instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) {
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
RBuffer *tbuf = r_buf_new ();
r_buf_set_bytes (tbuf, buf, sz);
struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf);
r_buf_free (tbuf);
return res ? res : NULL;
}
Commit Message: Fix #6829 oob write because of using wrong struct
CWE ID: CWE-119
|
static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) {
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
RBuffer *tbuf = r_buf_new ();
if (!tbuf) {
return NULL;
}
r_buf_set_bytes (tbuf, buf, sz);
struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf);
r_buf_free (tbuf);
return res ? res : NULL;
}
| 168,363
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
Commit Message: Fix build
Change-Id: I96a9c437eec53a285ac96794cc1ad0c8954b27e0
CWE ID: CWE-264
|
void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", (unsigned long)outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
| 174,157
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: MagickExport void *ResizeQuantumMemory(void *memory,const size_t count,
const size_t quantum)
{
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
{
memory=RelinquishMagickMemory(memory);
return((void *) NULL);
}
extent=count*quantum;
return(ResizeMagickMemory(memory,extent));
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119
|
MagickExport void *ResizeQuantumMemory(void *memory,const size_t count,
const size_t quantum)
{
size_t
extent;
if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
{
memory=RelinquishMagickMemory(memory);
return((void *) NULL);
}
extent=count*quantum;
return(ResizeMagickMemory(memory,extent));
}
| 168,545
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Layer::SetScrollOffset(gfx::Vector2d scroll_offset) {
DCHECK(IsPropertyChangeAllowed());
if (layer_tree_host()) {
scroll_offset = layer_tree_host()->DistributeScrollOffsetToViewports(
scroll_offset, this);
}
if (scroll_offset_ == scroll_offset)
return;
scroll_offset_ = scroll_offset;
SetNeedsCommit();
}
Commit Message: Removed pinch viewport scroll offset distribution
The associated change in Blink makes the pinch viewport a proper
ScrollableArea meaning the normal path for synchronizing layer scroll
offsets is used.
This is a 2 sided patch, the other CL:
https://codereview.chromium.org/199253002/
BUG=349941
Review URL: https://codereview.chromium.org/210543002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void Layer::SetScrollOffset(gfx::Vector2d scroll_offset) {
DCHECK(IsPropertyChangeAllowed());
if (scroll_offset_ == scroll_offset)
return;
scroll_offset_ = scroll_offset;
SetNeedsCommit();
}
| 171,198
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dns_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
n = dns_read_name(buffer, bufend, buffer + reader[1],
dest, dest_len - nb_bytes, offset);
if (n == 0)
goto err;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
Commit Message:
CWE ID: CWE-835
|
int dns_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset, unsigned int depth)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
if (depth++ > 100)
goto err;
n = dns_read_name(buffer, bufend, buffer + reader[1],
dest, dest_len - nb_bytes, offset, depth);
if (n == 0)
goto err;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
| 164,599
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: WebString WebPageSerializer::generateMetaCharsetDeclaration(const WebString& charset)
{
String charsetString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + static_cast<const String&>(charset) + "\">";
return charsetString;
}
Commit Message: Escape "--" in the page URL at page serialization
This patch makes page serializer to escape the page URL embed into a HTML
comment of result HTML[1] to avoid inserting text as HTML from URL by
introducing a static member function |PageSerialzier::markOfTheWebDeclaration()|
for sharing it between |PageSerialzier| and |WebPageSerialzier| classes.
[1] We use following format for serialized HTML:
saved from url=(${lengthOfURL})${URL}
BUG=503217
TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration
TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu
Review URL: https://codereview.chromium.org/1371323003
Cr-Commit-Position: refs/heads/master@{#351736}
CWE ID: CWE-20
|
WebString WebPageSerializer::generateMetaCharsetDeclaration(const WebString& charset)
{
// TODO(yosin) We should call |PageSerializer::metaCharsetDeclarationOf()|.
String charsetString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + static_cast<const String&>(charset) + "\">";
return charsetString;
}
| 171,788
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const Chapters::Edition* Chapters::GetEdition(int idx) const
{
if (idx < 0)
return NULL;
if (idx >= m_editions_count)
return NULL;
return m_editions + idx;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const Chapters::Edition* Chapters::GetEdition(int idx) const
const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size;
Edition* const editions = new (std::nothrow) Edition[size];
if (editions == NULL)
return false;
for (int idx = 0; idx < m_editions_count; ++idx) {
m_editions[idx].ShallowCopy(editions[idx]);
}
delete[] m_editions;
m_editions = editions;
m_editions_size = size;
return true;
}
| 174,310
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RenderWidgetHostViewAura::WasHidden() {
if (host_->is_hidden())
return;
host_->WasHidden();
released_front_lock_ = NULL;
if (ShouldReleaseFrontSurface() &&
host_->is_accelerated_compositing_active()) {
current_surface_ = 0;
UpdateExternalTexture();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
aura::RootWindow* root_window = window_->GetRootWindow();
if (root_window) {
HWND parent = root_window->GetAcceleratedWidget();
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(parent, HideWindowsCallback, lparam);
}
#endif
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostViewAura::WasHidden() {
if (host_->is_hidden())
return;
host_->WasHidden();
released_front_lock_ = NULL;
#if defined(OS_WIN)
aura::RootWindow* root_window = window_->GetRootWindow();
if (root_window) {
HWND parent = root_window->GetAcceleratedWidget();
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(parent, HideWindowsCallback, lparam);
}
#endif
}
| 171,388
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vnc_hextile_send_framebuffer_update(VncState *vs, int x,
int y, int w, int h)
{
int i, j;
int has_fg, has_bg;
uint8_t *last_fg, *last_bg;
VncDisplay *vd = vs->vd;
last_fg = (uint8_t *) g_malloc(vd->server->pf.bytes_per_pixel);
last_bg = (uint8_t *) g_malloc(vd->server->pf.bytes_per_pixel);
has_fg = has_bg = 0;
for (j = y; j < (y + h); j += 16) {
for (i = x; i < (x + w); i += 16) {
for (i = x; i < (x + w); i += 16) {
vs->hextile.send_tile(vs, i, j,
MIN(16, x + w - i), MIN(16, y + h - j),
last_bg, last_fg, &has_bg, &has_fg);
}
}
g_free(last_fg);
g_free(last_bg);
return 1;
}
void vnc_hextile_set_pixel_conversion(VncState *vs, int generic)
{
if (!generic) {
switch (vs->ds->surface->pf.bits_per_pixel) {
case 8:
vs->hextile.send_tile = send_hextile_tile_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_32;
break;
}
} else {
switch (vs->ds->surface->pf.bits_per_pixel) {
case 8:
vs->hextile.send_tile = send_hextile_tile_generic_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_generic_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_generic_32;
break;
}
}
}
}
Commit Message:
CWE ID: CWE-125
|
int vnc_hextile_send_framebuffer_update(VncState *vs, int x,
int y, int w, int h)
{
int i, j;
int has_fg, has_bg;
uint8_t *last_fg, *last_bg;
last_fg = (uint8_t *) g_malloc(VNC_SERVER_FB_BYTES);
last_bg = (uint8_t *) g_malloc(VNC_SERVER_FB_BYTES);
has_fg = has_bg = 0;
for (j = y; j < (y + h); j += 16) {
for (i = x; i < (x + w); i += 16) {
for (i = x; i < (x + w); i += 16) {
vs->hextile.send_tile(vs, i, j,
MIN(16, x + w - i), MIN(16, y + h - j),
last_bg, last_fg, &has_bg, &has_fg);
}
}
g_free(last_fg);
g_free(last_bg);
return 1;
}
void vnc_hextile_set_pixel_conversion(VncState *vs, int generic)
{
if (!generic) {
switch (VNC_SERVER_FB_BITS) {
case 8:
vs->hextile.send_tile = send_hextile_tile_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_32;
break;
}
} else {
switch (VNC_SERVER_FB_BITS) {
case 8:
vs->hextile.send_tile = send_hextile_tile_generic_8;
break;
case 16:
vs->hextile.send_tile = send_hextile_tile_generic_16;
break;
case 32:
vs->hextile.send_tile = send_hextile_tile_generic_32;
break;
}
}
}
}
| 165,459
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ResourceFetcher::DidLoadResourceFromMemoryCache(
unsigned long identifier,
Resource* resource,
const ResourceRequest& original_resource_request) {
ResourceRequest resource_request(resource->Url());
resource_request.SetFrameType(original_resource_request.GetFrameType());
resource_request.SetRequestContext(
original_resource_request.GetRequestContext());
Context().DispatchDidLoadResourceFromMemoryCache(identifier, resource_request,
resource->GetResponse());
Context().DispatchWillSendRequest(identifier, resource_request,
ResourceResponse() /* redirects */,
resource->Options().initiator_info);
Context().DispatchDidReceiveResponse(
identifier, resource->GetResponse(), resource_request.GetFrameType(),
resource_request.GetRequestContext(), resource,
FetchContext::ResourceResponseType::kFromMemoryCache);
if (resource->EncodedSize() > 0)
Context().DispatchDidReceiveData(identifier, 0, resource->EncodedSize());
Context().DispatchDidFinishLoading(
identifier, 0, 0, resource->GetResponse().DecodedBodyLength());
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
|
void ResourceFetcher::DidLoadResourceFromMemoryCache(
unsigned long identifier,
Resource* resource,
const ResourceRequest& original_resource_request) {
ResourceRequest resource_request(resource->Url());
resource_request.SetFrameType(original_resource_request.GetFrameType());
resource_request.SetRequestContext(
original_resource_request.GetRequestContext());
Context().DispatchDidLoadResourceFromMemoryCache(identifier, resource_request,
resource->GetResponse());
Context().DispatchWillSendRequest(
identifier, resource_request, ResourceResponse() /* redirects */,
resource->GetType(), resource->Options().initiator_info);
Context().DispatchDidReceiveResponse(
identifier, resource->GetResponse(), resource_request.GetFrameType(),
resource_request.GetRequestContext(), resource,
FetchContext::ResourceResponseType::kFromMemoryCache);
if (resource->EncodedSize() > 0)
Context().DispatchDidReceiveData(identifier, 0, resource->EncodedSize());
Context().DispatchDidFinishLoading(
identifier, 0, 0, resource->GetResponse().DecodedBodyLength());
}
| 172,478
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: rm_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) {
char * name = NULL;
int rtnVal = FALSE;
int rc;
bool found_cred;
CredentialWrapper * cred_wrapper = NULL;
char * owner = NULL;
const char * user;
ReliSock * socket = (ReliSock*)stream;
if (!socket->triedAuthentication()) {
CondorError errstack;
if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) {
dprintf (D_ALWAYS, "Unable to authenticate, qutting\n");
goto EXIT;
}
}
socket->decode();
if (!socket->code(name)) {
dprintf (D_ALWAYS, "Error receiving credential name\n");
goto EXIT;
}
user = socket->getFullyQualifiedUser();
dprintf (D_ALWAYS, "Authenticated as %s\n", user);
if (strchr (name, ':')) {
owner = strdup (name);
char * pColon = strchr (owner, ':');
*pColon = '\0';
sprintf (name, (char*)(pColon+sizeof(char)));
if (strcmp (owner, user) != 0) {
dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name);
if (!isSuperUser (user)) {
dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user);
goto EXIT;
} else {
dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user);
}
}
} else {
owner = strdup (user);
}
dprintf (D_ALWAYS, "Attempting to delete cred %s for user %s\n", name, owner);
found_cred=false;
credentials.Rewind();
while (credentials.Next(cred_wrapper)) {
if (cred_wrapper->cred->GetType() == X509_CREDENTIAL_TYPE) {
if ((strcmp(cred_wrapper->cred->GetName(), name) == 0) &&
(strcmp(cred_wrapper->cred->GetOwner(), owner) == 0)) {
credentials.DeleteCurrent();
found_cred=true;
break; // found it
}
}
}
if (found_cred) {
priv_state priv = set_root_priv();
unlink (cred_wrapper->GetStorageName());
SaveCredentialList();
set_priv(priv);
delete cred_wrapper;
dprintf (D_ALWAYS, "Removed credential %s for owner %s\n", name, owner);
} else {
dprintf (D_ALWAYS, "Unable to remove credential %s:%s (not found)\n", owner, name);
}
free (owner);
socket->encode();
rc = (found_cred)?CREDD_SUCCESS:CREDD_CREDENTIAL_NOT_FOUND;
socket->code(rc);
rtnVal = TRUE;
EXIT:
if (name != NULL) {
free (name);
}
return rtnVal;
}
Commit Message:
CWE ID: CWE-134
|
rm_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) {
char * name = NULL;
int rtnVal = FALSE;
int rc;
bool found_cred;
CredentialWrapper * cred_wrapper = NULL;
char * owner = NULL;
const char * user;
ReliSock * socket = (ReliSock*)stream;
if (!socket->triedAuthentication()) {
CondorError errstack;
if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) {
dprintf (D_ALWAYS, "Unable to authenticate, qutting\n");
goto EXIT;
}
}
socket->decode();
if (!socket->code(name)) {
dprintf (D_ALWAYS, "Error receiving credential name\n");
goto EXIT;
}
user = socket->getFullyQualifiedUser();
dprintf (D_ALWAYS, "Authenticated as %s\n", user);
if (strchr (name, ':')) {
owner = strdup (name);
char * pColon = strchr (owner, ':');
*pColon = '\0';
sprintf (name, "%s", (char*)(pColon+sizeof(char)));
if (strcmp (owner, user) != 0) {
dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name);
if (!isSuperUser (user)) {
dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user);
goto EXIT;
} else {
dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user);
}
}
} else {
owner = strdup (user);
}
dprintf (D_ALWAYS, "Attempting to delete cred %s for user %s\n", name, owner);
found_cred=false;
credentials.Rewind();
while (credentials.Next(cred_wrapper)) {
if (cred_wrapper->cred->GetType() == X509_CREDENTIAL_TYPE) {
if ((strcmp(cred_wrapper->cred->GetName(), name) == 0) &&
(strcmp(cred_wrapper->cred->GetOwner(), owner) == 0)) {
credentials.DeleteCurrent();
found_cred=true;
break; // found it
}
}
}
if (found_cred) {
priv_state priv = set_root_priv();
unlink (cred_wrapper->GetStorageName());
SaveCredentialList();
set_priv(priv);
delete cred_wrapper;
dprintf (D_ALWAYS, "Removed credential %s for owner %s\n", name, owner);
} else {
dprintf (D_ALWAYS, "Unable to remove credential %s:%s (not found)\n", owner, name);
}
free (owner);
socket->encode();
rc = (found_cred)?CREDD_SUCCESS:CREDD_CREDENTIAL_NOT_FOUND;
socket->code(rc);
rtnVal = TRUE;
EXIT:
if (name != NULL) {
free (name);
}
return rtnVal;
}
| 165,372
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool GestureProviderAura::OnTouchEvent(const TouchEvent& event) {
last_touch_event_flags_ = event.flags();
bool pointer_id_is_active = false;
for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) {
if (event.touch_id() != pointer_state_.GetPointerId(i))
continue;
pointer_id_is_active = true;
break;
}
if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) {
return false;
} else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) {
return false;
}
pointer_state_.OnTouch(event);
bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_);
pointer_state_.CleanupRemovedTouchPoints(event);
return result;
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
bool GestureProviderAura::OnTouchEvent(const TouchEvent& event) {
bool pointer_id_is_active = false;
for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) {
if (event.touch_id() != pointer_state_.GetPointerId(i))
continue;
pointer_id_is_active = true;
break;
}
if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) {
return false;
} else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) {
return false;
}
last_touch_event_flags_ = event.flags();
last_touch_event_latency_info_ = *event.latency();
pointer_state_.OnTouch(event);
bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_);
pointer_state_.CleanupRemovedTouchPoints(event);
return result;
}
| 171,205
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 destroy_super(struct super_block *s)
{
int i;
list_lru_destroy(&s->s_dentry_lru);
list_lru_destroy(&s->s_inode_lru);
#ifdef CONFIG_SMP
free_percpu(s->s_files);
#endif
for (i = 0; i < SB_FREEZE_LEVELS; i++)
percpu_counter_destroy(&s->s_writers.counter[i]);
security_sb_free(s);
WARN_ON(!list_empty(&s->s_mounts));
kfree(s->s_subtype);
kfree(s->s_options);
kfree_rcu(s, rcu);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-17
|
static void destroy_super(struct super_block *s)
{
int i;
list_lru_destroy(&s->s_dentry_lru);
list_lru_destroy(&s->s_inode_lru);
for (i = 0; i < SB_FREEZE_LEVELS; i++)
percpu_counter_destroy(&s->s_writers.counter[i]);
security_sb_free(s);
WARN_ON(!list_empty(&s->s_mounts));
kfree(s->s_subtype);
kfree(s->s_options);
kfree_rcu(s, rcu);
}
| 166,807
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
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: image_transform_ini_end(PNG_CONST image_transform *this,
transform_display *that)
{
UNUSED(this)
UNUSED(that)
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_ini_end(PNG_CONST image_transform *this,
image_transform_ini_end(const image_transform *this,
transform_display *that)
{
UNUSED(this)
UNUSED(that)
}
| 173,622
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UserActivityDetector::MaybeNotify() {
base::TimeTicks now = base::TimeTicks::Now();
if (last_observer_notification_time_.is_null() ||
(now - last_observer_notification_time_).InSecondsF() >=
kNotifyIntervalSec) {
FOR_EACH_OBSERVER(UserActivityObserver, observers_, OnUserActivity());
last_observer_notification_time_ = now;
}
}
Commit Message: ash: Make UserActivityDetector ignore synthetic mouse events
This may have been preventing us from suspending (e.g.
mouse event is synthesized in response to lock window being
shown so Chrome tells powerd that the user is active).
BUG=133419
TEST=added
Review URL: https://chromiumcodereview.appspot.com/10574044
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143437 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
|
void UserActivityDetector::MaybeNotify() {
base::TimeTicks now =
!now_for_test_.is_null() ? now_for_test_ : base::TimeTicks::Now();
if (last_observer_notification_time_.is_null() ||
(now - last_observer_notification_time_).InSecondsF() >=
kNotifyIntervalSec) {
FOR_EACH_OBSERVER(UserActivityObserver, observers_, OnUserActivity());
last_observer_notification_time_ = now;
}
}
| 170,719
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNCNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
(xmlIsNameChar(ctxt, c) && (c != ':'))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNCNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
(xmlIsNameChar(ctxt, c) && (c != ':'))) {
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
| 171,295
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const Cues* Segment::GetCues() const
{
return m_pCues;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const Cues* Segment::GetCues() const
| 174,301
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WasmCompileStreamingImpl(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
ScriptState* script_state = ScriptState::ForRelevantRealm(args);
v8::Local<v8::Function> compile_callback =
v8::Function::New(isolate, CompileFromResponseCallback);
V8SetReturnValue(args, ScriptPromise::Cast(script_state, args[0])
.Then(compile_callback)
.V8Value());
}
Commit Message: [wasm] Use correct bindings APIs
Use ScriptState::ForCurrentRealm in static methods, instead of
ForRelevantRealm().
Bug: chromium:788453
Change-Id: I63bd25e3f5a4e8d7cbaff945da8df0d71aa65527
Reviewed-on: https://chromium-review.googlesource.com/795096
Commit-Queue: Mircea Trofin <mtrofin@chromium.org>
Reviewed-by: Yuki Shiino <yukishiino@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#520174}
CWE ID: CWE-79
|
void WasmCompileStreamingImpl(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
ScriptState* script_state = ScriptState::ForCurrentRealm(args);
v8::Local<v8::Function> compile_callback =
v8::Function::New(isolate, CompileFromResponseCallback);
V8SetReturnValue(args, ScriptPromise::Cast(script_state, args[0])
.Then(compile_callback)
.V8Value());
}
| 172,939
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
return internalSetBitrateParams(
(const OMX_VIDEO_PARAM_BITRATETYPE *)params);
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcType->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mEntropyMode = 0;
if (OMX_TRUE == avcType->bEntropyCodingCABAC)
mEntropyMode = 1;
if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) &&
avcType->nPFrames) {
mBframes = avcType->nBFrames / avcType->nPFrames;
}
mIInterval = avcType->nPFrames + avcType->nBFrames;
if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode)
mDisableDeblkLevel = 4;
if (avcType->nRefFrames != 1
|| avcType->bUseHadamard != OMX_TRUE
|| avcType->nRefIdx10ActiveMinus1 != 0
|| avcType->nRefIdx11ActiveMinus1 != 0
|| avcType->bWeightedPPrediction != OMX_FALSE
|| avcType->bconstIpred != OMX_FALSE
|| avcType->bDirect8x8Inference != OMX_FALSE
|| avcType->bDirectSpatialTemporal != OMX_FALSE
|| avcType->nCabacInitIdc != 0) {
return OMX_ErrorUndefined;
}
if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *)params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
return internalSetBitrateParams(bitRate);
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params;
if (!isValidOMXParam(avcType)) {
return OMX_ErrorBadParameter;
}
if (avcType->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mEntropyMode = 0;
if (OMX_TRUE == avcType->bEntropyCodingCABAC)
mEntropyMode = 1;
if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) &&
avcType->nPFrames) {
mBframes = avcType->nBFrames / avcType->nPFrames;
}
mIInterval = avcType->nPFrames + avcType->nBFrames;
if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode)
mDisableDeblkLevel = 4;
if (avcType->nRefFrames != 1
|| avcType->bUseHadamard != OMX_TRUE
|| avcType->nRefIdx10ActiveMinus1 != 0
|| avcType->nRefIdx11ActiveMinus1 != 0
|| avcType->bWeightedPPrediction != OMX_FALSE
|| avcType->bconstIpred != OMX_FALSE
|| avcType->bDirect8x8Inference != OMX_FALSE
|| avcType->bDirectSpatialTemporal != OMX_FALSE
|| avcType->nCabacInitIdc != 0) {
return OMX_ErrorUndefined;
}
if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
| 174,201
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125
|
int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
| 169,278
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
*data = &iterator->current;
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
*data = &iterator->current;
}
| 167,070
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
ext4_xattr_put_super(struct super_block *sb)
| 169,995
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TabStripModelObserver::TabDetachedAt(TabContents* contents,
int index) {
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void TabStripModelObserver::TabDetachedAt(TabContents* contents,
void TabStripModelObserver::TabDetachedAt(WebContents* contents,
int index) {
}
| 171,518
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
struct sk_buff *skb;
int copied, error = -EINVAL;
if (sock->state != SS_CONNECTED)
return -ENOTCONN;
/* only handle MSG_DONTWAIT and MSG_PEEK */
if (flags & ~(MSG_DONTWAIT | MSG_PEEK))
return -EOPNOTSUPP;
vcc = ATM_SD(sock);
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags))
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);
if (!skb)
return error;
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (error)
return error;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc),
skb->truesize);
atm_return(vcc, skb->truesize);
}
skb_free_datagram(sk, skb);
return copied;
}
Commit Message: atm: update msg_namelen in vcc_recvmsg()
The current code does not fill the msg_name member in case it is set.
It also does not set the msg_namelen member to 0 and therefore makes
net/socket.c leak the local, uninitialized sockaddr_storage variable
to userland -- 128 bytes of kernel stack memory.
Fix that by simply setting msg_namelen to 0 as obviously nobody cared
about vcc_recvmsg() not filling the msg_name in case it was set.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
struct sk_buff *skb;
int copied, error = -EINVAL;
msg->msg_namelen = 0;
if (sock->state != SS_CONNECTED)
return -ENOTCONN;
/* only handle MSG_DONTWAIT and MSG_PEEK */
if (flags & ~(MSG_DONTWAIT | MSG_PEEK))
return -EOPNOTSUPP;
vcc = ATM_SD(sock);
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags))
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);
if (!skb)
return error;
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (error)
return error;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc),
skb->truesize);
atm_return(vcc, skb->truesize);
}
skb_free_datagram(sk, skb);
return copied;
}
| 166,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: static uint32_t color_string_to_rgba(const char *p, int len)
{
uint32_t ret = 0xFF000000;
const ColorEntry *entry;
char color_name[100];
if (*p == '#') {
p++;
len--;
if (len == 3) {
ret |= (hex_char_to_number(p[2]) << 4) |
(hex_char_to_number(p[1]) << 12) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 4) {
ret = (hex_char_to_number(p[3]) << 4) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 20) |
(hex_char_to_number(p[0]) << 28);
} else if (len == 6) {
ret |= hex_char_to_number(p[5]) |
(hex_char_to_number(p[4]) << 4) |
(hex_char_to_number(p[3]) << 8) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 16) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 8) {
ret = hex_char_to_number(p[7]) |
(hex_char_to_number(p[6]) << 4) |
(hex_char_to_number(p[5]) << 8) |
(hex_char_to_number(p[4]) << 12) |
(hex_char_to_number(p[3]) << 16) |
(hex_char_to_number(p[2]) << 20) |
(hex_char_to_number(p[1]) << 24) |
(hex_char_to_number(p[0]) << 28);
}
} else {
strncpy(color_name, p, len);
color_name[len] = '\0';
entry = bsearch(color_name,
color_table,
FF_ARRAY_ELEMS(color_table),
sizeof(ColorEntry),
color_table_compare);
if (!entry)
return ret;
ret = entry->rgb_color;
}
return ret;
}
Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues
Most of these were found through code review in response to
fixing 1466/clusterfuzz-testcase-minimized-5961584419536896
There is thus no testcase for most of this.
The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-119
|
static uint32_t color_string_to_rgba(const char *p, int len)
{
uint32_t ret = 0xFF000000;
const ColorEntry *entry;
char color_name[100];
len = FFMIN(FFMAX(len, 0), sizeof(color_name) - 1);
if (*p == '#') {
p++;
len--;
if (len == 3) {
ret |= (hex_char_to_number(p[2]) << 4) |
(hex_char_to_number(p[1]) << 12) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 4) {
ret = (hex_char_to_number(p[3]) << 4) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 20) |
(hex_char_to_number(p[0]) << 28);
} else if (len == 6) {
ret |= hex_char_to_number(p[5]) |
(hex_char_to_number(p[4]) << 4) |
(hex_char_to_number(p[3]) << 8) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 16) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 8) {
ret = hex_char_to_number(p[7]) |
(hex_char_to_number(p[6]) << 4) |
(hex_char_to_number(p[5]) << 8) |
(hex_char_to_number(p[4]) << 12) |
(hex_char_to_number(p[3]) << 16) |
(hex_char_to_number(p[2]) << 20) |
(hex_char_to_number(p[1]) << 24) |
(hex_char_to_number(p[0]) << 28);
}
} else {
strncpy(color_name, p, len);
color_name[len] = '\0';
entry = bsearch(color_name,
color_table,
FF_ARRAY_ELEMS(color_table),
sizeof(ColorEntry),
color_table_compare);
if (!entry)
return ret;
ret = entry->rgb_color;
}
return ret;
}
| 168,076
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void cJSON_Delete( cJSON *c )
{
cJSON *next;
while ( c ) {
next = c->next;
if ( ! ( c->type & cJSON_IsReference ) && c->child )
cJSON_Delete( c->child );
if ( ! ( c->type & cJSON_IsReference ) && c->valuestring )
cJSON_free( c->valuestring );
if ( c->string )
cJSON_free( c->string );
cJSON_free( c );
c = next;
}
}
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 <bmah@es.net>
CWE ID: CWE-119
|
void cJSON_Delete( cJSON *c )
void cJSON_Delete(cJSON *c)
{
cJSON *next;
while (c)
{
next=c->next;
if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string);
cJSON_free(c);
c=next;
}
}
| 167,281
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 http_connect(http_subtransport *t)
{
int error;
if (t->connected &&
http_should_keep_alive(&t->parser) &&
t->parse_finished)
return 0;
if (t->io) {
git_stream_close(t->io);
git_stream_free(t->io);
t->io = NULL;
t->connected = 0;
}
if (t->connection_data.use_ssl) {
error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
} else {
#ifdef GIT_CURL
error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#else
error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#endif
}
if (error < 0)
return error;
GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream");
apply_proxy_config(t);
error = git_stream_connect(t->io);
if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL &&
git_stream_is_encrypted(t->io)) {
git_cert *cert;
int is_valid;
if ((error = git_stream_certificate(&cert, t->io)) < 0)
return error;
giterr_clear();
is_valid = error != GIT_ECERTIFICATE;
error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload);
if (error < 0) {
if (!giterr_last())
giterr_set(GITERR_NET, "user cancelled certificate check");
return error;
}
}
if (error < 0)
return error;
t->connected = 1;
return 0;
}
Commit Message: http: check certificate validity before clobbering the error variable
CWE ID: CWE-284
|
static int http_connect(http_subtransport *t)
{
int error;
if (t->connected &&
http_should_keep_alive(&t->parser) &&
t->parse_finished)
return 0;
if (t->io) {
git_stream_close(t->io);
git_stream_free(t->io);
t->io = NULL;
t->connected = 0;
}
if (t->connection_data.use_ssl) {
error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
} else {
#ifdef GIT_CURL
error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#else
error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#endif
}
if (error < 0)
return error;
GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream");
apply_proxy_config(t);
error = git_stream_connect(t->io);
if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL &&
git_stream_is_encrypted(t->io)) {
git_cert *cert;
int is_valid = (error == GIT_OK);
if ((error = git_stream_certificate(&cert, t->io)) < 0)
return error;
giterr_clear();
error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload);
if (error < 0) {
if (!giterr_last())
giterr_set(GITERR_NET, "user cancelled certificate check");
return error;
}
}
if (error < 0)
return error;
t->connected = 1;
return 0;
}
| 168,526
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
Commit Message: Prevent arithmetic overflow on bounds check
CWE ID: CWE-125
|
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) > end - len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
| 170,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: Resource::~Resource() {
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
Resource::~Resource() {
ResourceTracker::Get()->ResourceDestroyed(this);
}
| 170,415
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GURL SanitizeFrontendURL(
const GURL& url,
const std::string& scheme,
const std::string& host,
const std::string& path,
bool allow_query) {
std::vector<std::string> query_parts;
if (allow_query) {
for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
std::string value = SanitizeFrontendQueryParam(it.GetKey(),
it.GetValue());
if (!value.empty()) {
query_parts.push_back(
base::StringPrintf("%s=%s", it.GetKey().c_str(), value.c_str()));
}
}
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
std::string constructed = base::StringPrintf("%s://%s%s%s",
scheme.c_str(), host.c_str(), path.c_str(), query.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
return result;
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
|
GURL SanitizeFrontendURL(
| 172,460
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (table->DeleteSecurityContext == NULL)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
return status;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476
|
SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name = NULL;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (table->DeleteSecurityContext == NULL)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
return status;
}
| 167,603
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
Commit Message: net: fix a kernel infoleak in x25 module
Stack object "dte_facilities" is allocated in x25_rx_call_request(),
which is supposed to be initialized in x25_negotiate_facilities.
However, 5 fields (8 bytes in total) are not initialized. This
object is then copied to userland via copy_to_user, thus infoleak
occurs.
Signed-off-by: Kangjie Lu <kjlu@gatech.edu>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
memset(dte, 0, sizeof(*dte));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
| 167,235
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox);
if (e) {
return e;
}
if (!((GF_DataInformationBox *)s)->dref) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n"));
((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);
}
return GF_OK;
}
Commit Message: prevent dref memleak on invalid input (#1183)
CWE ID: CWE-400
|
GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox);
if (e) {
return e;
}
if (!((GF_DataInformationBox *)s)->dref) {
GF_Box* dref;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n"));
dref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);
((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)dref;
gf_isom_box_add_for_dump_mode(s, dref);
}
return GF_OK;
}
| 169,759
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline int btif_hl_close_select_thread(void)
{
int result = 0;
char sig_on = btif_hl_signal_select_exit;
BTIF_TRACE_DEBUG("btif_hl_signal_select_exit");
result = send(signal_fds[1], &sig_on, sizeof(sig_on), 0);
if (btif_is_enabled())
{
/* Wait for the select_thread_id to exit if BT is still enabled
and only this profile getting cleaned up*/
if (select_thread_id != -1) {
pthread_join(select_thread_id, NULL);
select_thread_id = -1;
}
}
list_free(soc_queue);
return result;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static inline int btif_hl_close_select_thread(void)
{
int result = 0;
char sig_on = btif_hl_signal_select_exit;
BTIF_TRACE_DEBUG("btif_hl_signal_select_exit");
result = TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0));
if (btif_is_enabled())
{
/* Wait for the select_thread_id to exit if BT is still enabled
and only this profile getting cleaned up*/
if (select_thread_id != -1) {
pthread_join(select_thread_id, NULL);
select_thread_id = -1;
}
}
list_free(soc_queue);
return result;
}
| 173,439
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UkmPageLoadMetricsObserver::RecordTimingMetrics(
const page_load_metrics::mojom::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& info) {
ukm::builders::PageLoad builder(info.source_id);
bool is_user_initiated_navigation =
info.user_initiated_info.browser_initiated ||
timing.input_to_navigation_start;
builder.SetExperimental_Navigation_UserInitiated(
is_user_initiated_navigation);
if (timing.input_to_navigation_start) {
builder.SetExperimental_InputToNavigationStart(
timing.input_to_navigation_start.value().InMilliseconds());
}
if (timing.parse_timing->parse_start) {
builder.SetParseTiming_NavigationToParseStart(
timing.parse_timing->parse_start.value().InMilliseconds());
}
if (timing.document_timing->dom_content_loaded_event_start) {
builder.SetDocumentTiming_NavigationToDOMContentLoadedEventFired(
timing.document_timing->dom_content_loaded_event_start.value()
.InMilliseconds());
}
if (timing.document_timing->load_event_start) {
builder.SetDocumentTiming_NavigationToLoadEventFired(
timing.document_timing->load_event_start.value().InMilliseconds());
}
if (timing.paint_timing->first_paint) {
builder.SetPaintTiming_NavigationToFirstPaint(
timing.paint_timing->first_paint.value().InMilliseconds());
}
if (timing.paint_timing->first_contentful_paint) {
builder.SetPaintTiming_NavigationToFirstContentfulPaint(
timing.paint_timing->first_contentful_paint.value().InMilliseconds());
}
if (timing.paint_timing->first_meaningful_paint) {
builder.SetExperimental_PaintTiming_NavigationToFirstMeaningfulPaint(
timing.paint_timing->first_meaningful_paint.value().InMilliseconds());
}
if (timing.paint_timing->largest_image_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->largest_image_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLargestImagePaint(
timing.paint_timing->largest_image_paint.value().InMilliseconds());
}
if (timing.paint_timing->last_image_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->last_image_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLastImagePaint(
timing.paint_timing->last_image_paint.value().InMilliseconds());
}
if (timing.paint_timing->largest_text_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->largest_text_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLargestTextPaint(
timing.paint_timing->largest_text_paint.value().InMilliseconds());
}
if (timing.paint_timing->last_text_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->last_text_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLastTextPaint(
timing.paint_timing->last_text_paint.value().InMilliseconds());
}
base::Optional<base::TimeDelta> largest_content_paint_time;
uint64_t largest_content_paint_size;
AssignTimeAndSizeForLargestContentfulPaint(largest_content_paint_time,
largest_content_paint_size,
timing.paint_timing);
if (largest_content_paint_size > 0 &&
WasStartedInForegroundOptionalEventInForeground(
largest_content_paint_time, info)) {
builder.SetExperimental_PaintTiming_NavigationToLargestContentPaint(
largest_content_paint_time.value().InMilliseconds());
}
if (timing.interactive_timing->interactive) {
base::TimeDelta time_to_interactive =
timing.interactive_timing->interactive.value();
if (!timing.interactive_timing->first_invalidating_input ||
timing.interactive_timing->first_invalidating_input.value() >
time_to_interactive) {
builder.SetExperimental_NavigationToInteractive(
time_to_interactive.InMilliseconds());
}
}
if (timing.interactive_timing->first_input_delay) {
base::TimeDelta first_input_delay =
timing.interactive_timing->first_input_delay.value();
builder.SetInteractiveTiming_FirstInputDelay2(
first_input_delay.InMilliseconds());
}
if (timing.interactive_timing->first_input_timestamp) {
base::TimeDelta first_input_timestamp =
timing.interactive_timing->first_input_timestamp.value();
builder.SetInteractiveTiming_FirstInputTimestamp2(
first_input_timestamp.InMilliseconds());
}
if (timing.interactive_timing->longest_input_delay) {
base::TimeDelta longest_input_delay =
timing.interactive_timing->longest_input_delay.value();
builder.SetInteractiveTiming_LongestInputDelay2(
longest_input_delay.InMilliseconds());
}
if (timing.interactive_timing->longest_input_timestamp) {
base::TimeDelta longest_input_timestamp =
timing.interactive_timing->longest_input_timestamp.value();
builder.SetInteractiveTiming_LongestInputTimestamp2(
longest_input_timestamp.InMilliseconds());
}
builder.SetNet_CacheBytes(ukm::GetExponentialBucketMin(cache_bytes_, 1.3));
builder.SetNet_NetworkBytes(
ukm::GetExponentialBucketMin(network_bytes_, 1.3));
if (main_frame_timing_)
ReportMainResourceTimingMetrics(timing, &builder);
builder.Record(ukm::UkmRecorder::Get());
}
Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation.
Also refactor UkmPageLoadMetricsObserver to use this new boolean to
report the user initiated metric in RecordPageLoadExtraInfoMetrics, so
that it works correctly in the case when the page load failed.
Bug: 925104
Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff
Reviewed-on: https://chromium-review.googlesource.com/c/1450460
Commit-Queue: Annie Sullivan <sullivan@chromium.org>
Reviewed-by: Bryan McQuade <bmcquade@chromium.org>
Cr-Commit-Position: refs/heads/master@{#630870}
CWE ID: CWE-79
|
void UkmPageLoadMetricsObserver::RecordTimingMetrics(
const page_load_metrics::mojom::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& info) {
ukm::builders::PageLoad builder(info.source_id);
if (timing.input_to_navigation_start) {
builder.SetExperimental_InputToNavigationStart(
timing.input_to_navigation_start.value().InMilliseconds());
}
if (timing.parse_timing->parse_start) {
builder.SetParseTiming_NavigationToParseStart(
timing.parse_timing->parse_start.value().InMilliseconds());
}
if (timing.document_timing->dom_content_loaded_event_start) {
builder.SetDocumentTiming_NavigationToDOMContentLoadedEventFired(
timing.document_timing->dom_content_loaded_event_start.value()
.InMilliseconds());
}
if (timing.document_timing->load_event_start) {
builder.SetDocumentTiming_NavigationToLoadEventFired(
timing.document_timing->load_event_start.value().InMilliseconds());
}
if (timing.paint_timing->first_paint) {
builder.SetPaintTiming_NavigationToFirstPaint(
timing.paint_timing->first_paint.value().InMilliseconds());
}
if (timing.paint_timing->first_contentful_paint) {
builder.SetPaintTiming_NavigationToFirstContentfulPaint(
timing.paint_timing->first_contentful_paint.value().InMilliseconds());
}
if (timing.paint_timing->first_meaningful_paint) {
builder.SetExperimental_PaintTiming_NavigationToFirstMeaningfulPaint(
timing.paint_timing->first_meaningful_paint.value().InMilliseconds());
}
if (timing.paint_timing->largest_image_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->largest_image_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLargestImagePaint(
timing.paint_timing->largest_image_paint.value().InMilliseconds());
}
if (timing.paint_timing->last_image_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->last_image_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLastImagePaint(
timing.paint_timing->last_image_paint.value().InMilliseconds());
}
if (timing.paint_timing->largest_text_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->largest_text_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLargestTextPaint(
timing.paint_timing->largest_text_paint.value().InMilliseconds());
}
if (timing.paint_timing->last_text_paint.has_value() &&
WasStartedInForegroundOptionalEventInForeground(
timing.paint_timing->last_text_paint, info)) {
builder.SetExperimental_PaintTiming_NavigationToLastTextPaint(
timing.paint_timing->last_text_paint.value().InMilliseconds());
}
base::Optional<base::TimeDelta> largest_content_paint_time;
uint64_t largest_content_paint_size;
AssignTimeAndSizeForLargestContentfulPaint(largest_content_paint_time,
largest_content_paint_size,
timing.paint_timing);
if (largest_content_paint_size > 0 &&
WasStartedInForegroundOptionalEventInForeground(
largest_content_paint_time, info)) {
builder.SetExperimental_PaintTiming_NavigationToLargestContentPaint(
largest_content_paint_time.value().InMilliseconds());
}
if (timing.interactive_timing->interactive) {
base::TimeDelta time_to_interactive =
timing.interactive_timing->interactive.value();
if (!timing.interactive_timing->first_invalidating_input ||
timing.interactive_timing->first_invalidating_input.value() >
time_to_interactive) {
builder.SetExperimental_NavigationToInteractive(
time_to_interactive.InMilliseconds());
}
}
if (timing.interactive_timing->first_input_delay) {
base::TimeDelta first_input_delay =
timing.interactive_timing->first_input_delay.value();
builder.SetInteractiveTiming_FirstInputDelay2(
first_input_delay.InMilliseconds());
}
if (timing.interactive_timing->first_input_timestamp) {
base::TimeDelta first_input_timestamp =
timing.interactive_timing->first_input_timestamp.value();
builder.SetInteractiveTiming_FirstInputTimestamp2(
first_input_timestamp.InMilliseconds());
}
if (timing.interactive_timing->longest_input_delay) {
base::TimeDelta longest_input_delay =
timing.interactive_timing->longest_input_delay.value();
builder.SetInteractiveTiming_LongestInputDelay2(
longest_input_delay.InMilliseconds());
}
if (timing.interactive_timing->longest_input_timestamp) {
base::TimeDelta longest_input_timestamp =
timing.interactive_timing->longest_input_timestamp.value();
builder.SetInteractiveTiming_LongestInputTimestamp2(
longest_input_timestamp.InMilliseconds());
}
builder.SetNet_CacheBytes(ukm::GetExponentialBucketMin(cache_bytes_, 1.3));
builder.SetNet_NetworkBytes(
ukm::GetExponentialBucketMin(network_bytes_, 1.3));
if (main_frame_timing_)
ReportMainResourceTimingMetrics(timing, &builder);
builder.Record(ukm::UkmRecorder::Get());
}
| 172,497
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uipc_check_interrupt_locked(void)
{
if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set))
{
char sig_recv = 0;
recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
}
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static void uipc_check_interrupt_locked(void)
{
if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set))
{
char sig_recv = 0;
TEMP_FAILURE_RETRY(recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL));
}
}
| 173,496
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 m_authenticate(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
struct Client* acptr;
int first = 0;
char realhost[HOSTLEN + 3];
char *hoststr = (cli_sockhost(cptr) ? cli_sockhost(cptr) : cli_sock_ip(cptr));
if (!CapActive(cptr, CAP_SASL))
return 0;
if (parc < 2) /* have enough parameters? */
return need_more_params(cptr, "AUTHENTICATE");
if (strlen(parv[1]) > 400)
return send_reply(cptr, ERR_SASLTOOLONG);
if (IsSASLComplete(cptr))
return send_reply(cptr, ERR_SASLALREADY);
/* Look up the target server */
if (!(acptr = cli_saslagent(cptr))) {
if (strcmp(feature_str(FEAT_SASL_SERVER), "*"))
acptr = find_match_server((char *)feature_str(FEAT_SASL_SERVER));
else
acptr = NULL;
}
if (!acptr && strcmp(feature_str(FEAT_SASL_SERVER), "*"))
return send_reply(cptr, ERR_SASLFAIL, ": service unavailable");
/* If it's to us, do nothing; otherwise, forward the query */
if (acptr && IsMe(acptr))
return 0;
/* Generate an SASL session cookie if not already generated */
if (!cli_saslcookie(cptr)) {
do {
cli_saslcookie(cptr) = ircrandom() & 0x7fffffff;
} while (!cli_saslcookie(cptr));
first = 1;
}
if (strchr(hoststr, ':') != NULL)
ircd_snprintf(0, realhost, sizeof(realhost), "[%s]", hoststr);
else
ircd_strncpy(realhost, hoststr, sizeof(realhost));
if (acptr) {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S %s :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u H :%s@%s:%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u C :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
} else {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S %s :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u H :%s@%s:%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u C :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
}
if (!t_active(&cli_sasltimeout(cptr)))
timer_add(timer_init(&cli_sasltimeout(cptr)), sasl_timeout_callback, (void*) cptr,
TT_RELATIVE, feature_int(FEAT_SASL_TIMEOUT));
return 0;
}
Commit Message: Fix to prevent SASL security vulnerability
CWE ID: CWE-287
|
int m_authenticate(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
struct Client* acptr;
int first = 0;
char realhost[HOSTLEN + 3];
char *hoststr = (cli_sockhost(cptr) ? cli_sockhost(cptr) : cli_sock_ip(cptr));
if (!CapActive(cptr, CAP_SASL))
return 0;
if (parc < 2) /* have enough parameters? */
return need_more_params(cptr, "AUTHENTICATE");
if (strlen(parv[1]) > 400)
return send_reply(cptr, ERR_SASLTOOLONG);
if (IsSASLComplete(cptr))
return send_reply(cptr, ERR_SASLALREADY);
/* Look up the target server */
if (!(acptr = cli_saslagent(cptr))) {
if (strcmp(feature_str(FEAT_SASL_SERVER), "*"))
acptr = find_match_server((char *)feature_str(FEAT_SASL_SERVER));
else
acptr = NULL;
}
if (!acptr && strcmp(feature_str(FEAT_SASL_SERVER), "*"))
return send_reply(cptr, ERR_SASLFAIL, ": service unavailable");
/* If it's to us, do nothing; otherwise, forward the query */
if (acptr && IsMe(acptr))
return 0;
/* Generate an SASL session cookie if not already generated */
if (!cli_saslcookie(cptr)) {
do {
cli_saslcookie(cptr) = ircrandom() & 0x7fffffff;
} while (!cli_saslcookie(cptr));
first = 1;
}
if (strchr(hoststr, ':') != NULL)
ircd_snprintf(0, realhost, sizeof(realhost), "[%s]", hoststr);
else
ircd_strncpy(realhost, hoststr, sizeof(realhost));
if (acptr) {
if (first) {
if (*parv[1] == ':' || strchr(parv[1], ' '))
return exit_client(cptr, sptr, sptr, "Malformed AUTHENTICATE");
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S %s :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u H :%s@%s:%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u C :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
} else {
if (first) {
if (*parv[1] == ':' || strchr(parv[1], ' '))
return exit_client(cptr, sptr, sptr, "Malformed AUTHENTICATE");
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S %s :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u H :%s@%s:%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u C :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
}
if (!t_active(&cli_sasltimeout(cptr)))
timer_add(timer_init(&cli_sasltimeout(cptr)), sasl_timeout_callback, (void*) cptr,
TT_RELATIVE, feature_int(FEAT_SASL_TIMEOUT));
return 0;
}
| 168,813
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_MINIT_FUNCTION(spl_directory)
{
REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions);
memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone;
spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast;
spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info;
spl_ce_SplFileInfo->serialize = zend_class_serialize_deny;
spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny;
REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions);
zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator);
REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator);
spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS);
spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions);
REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator);
memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers));
spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check;
#ifdef HAVE_GLOB
REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions);
REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable);
#endif
REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions);
REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator);
REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV);
REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions);
return SUCCESS;
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
PHP_MINIT_FUNCTION(spl_directory)
{
REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions);
memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone;
spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast;
spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info;
spl_ce_SplFileInfo->serialize = zend_class_serialize_deny;
spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny;
REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions);
zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator);
REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator);
spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS);
spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions);
REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator);
memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers));
spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check;
#ifdef HAVE_GLOB
REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions);
REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable);
#endif
REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions);
REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator);
REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV);
REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions);
return SUCCESS;
}
| 167,026
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
PanicZ( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name,
face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%s': error 0x%04x", basename,
(FT_UShort)error_code );
break;
}
status.header = status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0,
status.header, display->fore_color );
sprintf( status.header_buffer, "at %g points, angle = %d",
status.ptsize/64.0, status.angle );
grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT,
status.header_buffer, display->fore_color );
grRefreshSurface( display->surface );
}
Commit Message:
CWE ID: CWE-119
|
write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
PanicZ( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer,
"%.50s %.50s (file `%.100s')", face->family_name,
face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%.100s': error 0x%04x", basename,
(FT_UShort)error_code );
break;
}
status.header = status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0,
status.header, display->fore_color );
sprintf( status.header_buffer, "at %g points, angle = %d",
status.ptsize/64.0, status.angle );
grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT,
status.header_buffer, display->fore_color );
grRefreshSurface( display->surface );
}
| 165,000
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uint64_t ReadBits(BitReader* reader, int num_bits) {
DCHECK_GE(reader->bits_available(), num_bits);
DCHECK((num_bits > 0) && (num_bits <= 64));
uint64_t value;
reader->ReadBits(num_bits, &value);
return value;
}
Commit Message: Cleanup media BitReader ReadBits() calls
Initialize temporary values, check return values.
Small tweaks to solution proposed by adtolbar@microsoft.com.
Bug: 929962
Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735
Reviewed-on: https://chromium-review.googlesource.com/c/1481085
Commit-Queue: Chrome Cunningham <chcunningham@chromium.org>
Reviewed-by: Dan Sanders <sandersd@chromium.org>
Cr-Commit-Position: refs/heads/master@{#634889}
CWE ID: CWE-200
|
static uint64_t ReadBits(BitReader* reader, int num_bits) {
DCHECK_GE(reader->bits_available(), num_bits);
DCHECK((num_bits > 0) && (num_bits <= 64));
uint64_t value = 0;
if (!reader->ReadBits(num_bits, &value))
return 0;
return value;
}
| 173,019
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);
sock_put(sk);
}
}
Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS
SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled
while packets are collected on the error queue.
So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags
is not enough to safely assume that the skb contains
OPT_STATS data.
Add a bit in sock_exterr_skb to indicate whether the
skb contains opt_stats data.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <zzoru007@gmail.com>
Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Signed-off-by: Willem de Bruijn <willemb@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-125
|
void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
sock_put(sk);
}
}
| 170,073
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Accelerator GetAccelerator(KeyboardCode code, int mask) {
return Accelerator(code, mask & (1 << 0), mask & (1 << 1), mask & (1 << 2));
}
Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans.
BUG=128242
R=ben@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10399085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
Accelerator GetAccelerator(KeyboardCode code, int mask) {
return Accelerator(code, mask);
}
| 170,907
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ixheaacd_shiftrountine_with_rnd_hq(WORD32 *qmf_real, WORD32 *qmf_imag,
WORD32 *filter_states, WORD32 len,
WORD32 shift) {
WORD32 *filter_states_rev = filter_states + len;
WORD32 treal, timag;
WORD32 j;
for (j = (len - 1); j >= 0; j -= 2) {
WORD32 r1, r2, i1, i2;
i2 = qmf_imag[j];
r2 = qmf_real[j];
r1 = *qmf_real++;
i1 = *qmf_imag++;
timag = ixheaacd_add32(i1, r1);
timag = (ixheaacd_shl32_sat(timag, shift));
filter_states_rev[j] = timag;
treal = ixheaacd_sub32(i2, r2);
treal = (ixheaacd_shl32_sat(treal, shift));
filter_states[j] = treal;
treal = ixheaacd_sub32(i1, r1);
treal = (ixheaacd_shl32_sat(treal, shift));
*filter_states++ = treal;
timag = ixheaacd_add32(i2, r2);
timag = (ixheaacd_shl32_sat(timag, shift));
*filter_states_rev++ = timag;
}
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787
|
VOID ixheaacd_shiftrountine_with_rnd_hq(WORD32 *qmf_real, WORD32 *qmf_imag,
WORD32 *filter_states, WORD32 len,
WORD32 shift) {
WORD32 *filter_states_rev = filter_states + len;
WORD32 treal, timag;
WORD32 j;
for (j = (len - 1); j >= 0; j -= 2) {
WORD32 r1, r2, i1, i2;
i2 = qmf_imag[j];
r2 = qmf_real[j];
r1 = *qmf_real++;
i1 = *qmf_imag++;
timag = ixheaacd_add32_sat(i1, r1);
timag = (ixheaacd_shl32_sat(timag, shift));
filter_states_rev[j] = timag;
treal = ixheaacd_sub32_sat(i2, r2);
treal = (ixheaacd_shl32_sat(treal, shift));
filter_states[j] = treal;
treal = ixheaacd_sub32_sat(i1, r1);
treal = (ixheaacd_shl32_sat(treal, shift));
*filter_states++ = treal;
timag = ixheaacd_add32_sat(i2, r2);
timag = (ixheaacd_shl32_sat(timag, shift));
*filter_states_rev++ = timag;
}
}
| 174,089
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: RenderFrameHostManager::RenderFrameHostManager(
FrameTreeNode* frame_tree_node,
RenderFrameHostDelegate* render_frame_delegate,
RenderWidgetHostDelegate* render_widget_delegate,
Delegate* delegate)
: frame_tree_node_(frame_tree_node),
delegate_(delegate),
render_frame_delegate_(render_frame_delegate),
render_widget_delegate_(render_widget_delegate),
interstitial_page_(nullptr),
weak_factory_(this) {
DCHECK(frame_tree_node_);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20
|
RenderFrameHostManager::RenderFrameHostManager(
FrameTreeNode* frame_tree_node,
RenderFrameHostDelegate* render_frame_delegate,
RenderWidgetHostDelegate* render_widget_delegate,
Delegate* delegate)
: frame_tree_node_(frame_tree_node),
delegate_(delegate),
render_frame_delegate_(render_frame_delegate),
render_widget_delegate_(render_widget_delegate),
weak_factory_(this) {
DCHECK(frame_tree_node_);
}
| 172,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: size_t CancelableFileOperation(Function operation,
HANDLE file,
BufferType* buffer,
size_t length,
WaitableEvent* io_event,
WaitableEvent* cancel_event,
CancelableSyncSocket* socket,
DWORD timeout_in_ms) {
ThreadRestrictions::AssertIOAllowed();
COMPILE_ASSERT(sizeof(buffer[0]) == sizeof(char), incorrect_buffer_type);
DCHECK_GT(length, 0u);
DCHECK_LE(length, kMaxMessageLength);
DCHECK_NE(file, SyncSocket::kInvalidHandle);
TimeTicks current_time, finish_time;
if (timeout_in_ms != INFINITE) {
current_time = TimeTicks::Now();
finish_time =
current_time + base::TimeDelta::FromMilliseconds(timeout_in_ms);
}
size_t count = 0;
do {
OVERLAPPED ol = { 0 };
ol.hEvent = io_event->handle();
const DWORD chunk = GetNextChunkSize(count, length);
DWORD len = 0;
const BOOL operation_ok = operation(
file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
if (!operation_ok) {
if (::GetLastError() == ERROR_IO_PENDING) {
HANDLE events[] = { io_event->handle(), cancel_event->handle() };
const int wait_result = WaitForMultipleObjects(
ARRAYSIZE_UNSAFE(events), events, FALSE,
timeout_in_ms == INFINITE ?
timeout_in_ms :
static_cast<DWORD>(
(finish_time - current_time).InMilliseconds()));
if (wait_result != WAIT_OBJECT_0 + 0) {
CancelIo(file);
}
if (!GetOverlappedResult(file, &ol, &len, TRUE))
len = 0;
if (wait_result == WAIT_OBJECT_0 + 1) {
DVLOG(1) << "Shutdown was signaled. Closing socket.";
socket->Close();
return count;
}
DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
} else {
break;
}
}
count += len;
if (len != chunk)
break;
if (timeout_in_ms != INFINITE && count < length)
current_time = base::TimeTicks::Now();
} while (count < length &&
(timeout_in_ms == INFINITE || current_time < finish_time));
return count;
}
Commit Message: Convert ARRAYSIZE_UNSAFE -> arraysize in base/.
R=thestig@chromium.org
BUG=423134
Review URL: https://codereview.chromium.org/656033009
Cr-Commit-Position: refs/heads/master@{#299835}
CWE ID: CWE-189
|
size_t CancelableFileOperation(Function operation,
HANDLE file,
BufferType* buffer,
size_t length,
WaitableEvent* io_event,
WaitableEvent* cancel_event,
CancelableSyncSocket* socket,
DWORD timeout_in_ms) {
ThreadRestrictions::AssertIOAllowed();
COMPILE_ASSERT(sizeof(buffer[0]) == sizeof(char), incorrect_buffer_type);
DCHECK_GT(length, 0u);
DCHECK_LE(length, kMaxMessageLength);
DCHECK_NE(file, SyncSocket::kInvalidHandle);
TimeTicks current_time, finish_time;
if (timeout_in_ms != INFINITE) {
current_time = TimeTicks::Now();
finish_time =
current_time + base::TimeDelta::FromMilliseconds(timeout_in_ms);
}
size_t count = 0;
do {
OVERLAPPED ol = { 0 };
ol.hEvent = io_event->handle();
const DWORD chunk = GetNextChunkSize(count, length);
DWORD len = 0;
const BOOL operation_ok = operation(
file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
if (!operation_ok) {
if (::GetLastError() == ERROR_IO_PENDING) {
HANDLE events[] = { io_event->handle(), cancel_event->handle() };
const int wait_result = WaitForMultipleObjects(
arraysize(events), events, FALSE,
timeout_in_ms == INFINITE ?
timeout_in_ms :
static_cast<DWORD>(
(finish_time - current_time).InMilliseconds()));
if (wait_result != WAIT_OBJECT_0 + 0) {
CancelIo(file);
}
if (!GetOverlappedResult(file, &ol, &len, TRUE))
len = 0;
if (wait_result == WAIT_OBJECT_0 + 1) {
DVLOG(1) << "Shutdown was signaled. Closing socket.";
socket->Close();
return count;
}
DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
} else {
break;
}
}
count += len;
if (len != chunk)
break;
if (timeout_in_ms != INFINITE && count < length)
current_time = base::TimeTicks::Now();
} while (count < length &&
(timeout_in_ms == INFINITE || current_time < finish_time));
return count;
}
| 171,163
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length )
{
static const size_t kMinPSIRSize = 12; // 4+2+1+1+4
this->DeleteExistingInfo();
this->fileParsed = true;
if ( length == 0 ) return;
XMP_Int64 psirOrigin = fileRef->Offset(); // Need this to determine the resource data offsets.
XMP_Int64 fileEnd = psirOrigin + length;
char nameBuffer [260]; // The name is a PString, at 1+255+1 including length and pad.
while ( fileRef->Offset() < fileEnd ) {
if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break; // Bad image resource.
XMP_Int64 thisRsrcPos = fileRef->Offset();
XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef );
XMP_Uns16 id = XIO::ReadUns16_BE ( fileRef );
XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef ); // ! The length for the Pascal string.
XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2!
if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break; // Bad image resource.
nameBuffer[0] = nameLen;
fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 ); // Include the pad byte, present for zero nameLen.
XMP_Uns32 dataLen = XIO::ReadUns32_BE ( fileRef );
XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total.
if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break; // Bad image resource.
XMP_Int64 thisDataPos = fileRef->Offset();
continue;
}
InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased );
InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id );
if ( rsrcPos == this->imgRsrcs.end() ) {
rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) );
} else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) {
rsrcPos->second = newInfo;
} else {
fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
continue;
}
InternalRsrcInfo* rsrcPtr = &rsrcPos->second;
rsrcPtr->origOffset = (XMP_Uns32)thisDataPos;
if ( nameLen > 0 ) {
rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen );
if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen ); // AUDIT: Safe, allocated enough bytes above.
}
if ( ! IsMetadataImgRsrc ( id ) ) {
fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
continue;
}
rsrcPtr->dataPtr = malloc ( dataTotal ); // ! Allocate after the IsMetadataImgRsrc check.
if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal );
}
Commit Message:
CWE ID: CWE-125
|
void PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length )
{
static const size_t kMinPSIRSize = 12; // 4+2+1+1+4
this->DeleteExistingInfo();
this->fileParsed = true;
if ( length == 0 ) return;
XMP_Int64 psirOrigin = fileRef->Offset(); // Need this to determine the resource data offsets.
XMP_Int64 fileEnd = psirOrigin + length;
char nameBuffer [260]; // The name is a PString, at 1+255+1 including length and pad.
while ( fileRef->Offset() < fileEnd ) {
if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break; // Bad image resource.
XMP_Int64 thisRsrcPos = fileRef->Offset();
XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef );
XMP_Uns16 id = XIO::ReadUns16_BE ( fileRef );
XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef ); // ! The length for the Pascal string.
XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2!
if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break; // Bad image resource.
nameBuffer[0] = nameLen;
fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 ); // Include the pad byte, present for zero nameLen.
XMP_Uns32 dataLen = XIO::ReadUns32_BE ( fileRef );
XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total.
// See bug https://bugs.freedesktop.org/show_bug.cgi?id=105204
// If dataLen is 0xffffffff, then dataTotal might be 0
// and therefor make the CheckFileSpace test pass.
if (dataTotal < dataLen) {
break;
}
if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break; // Bad image resource.
XMP_Int64 thisDataPos = fileRef->Offset();
continue;
}
InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased );
InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id );
if ( rsrcPos == this->imgRsrcs.end() ) {
rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) );
} else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) {
rsrcPos->second = newInfo;
} else {
fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
continue;
}
InternalRsrcInfo* rsrcPtr = &rsrcPos->second;
rsrcPtr->origOffset = (XMP_Uns32)thisDataPos;
if ( nameLen > 0 ) {
rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen );
if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen ); // AUDIT: Safe, allocated enough bytes above.
}
if ( ! IsMetadataImgRsrc ( id ) ) {
fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
continue;
}
rsrcPtr->dataPtr = malloc ( dataTotal ); // ! Allocate after the IsMetadataImgRsrc check.
if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal );
}
| 164,994
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LongOrNullAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "longOrNullAttribute");
int32_t cpp_value = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
bool is_null = IsUndefinedOrNull(v8_value);
impl->setLongOrNullAttribute(cpp_value, is_null);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <peria@chromium.org>
Commit-Queue: Yuki Shiino <yukishiino@chromium.org>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
|
static void LongOrNullAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "longOrNullAttribute");
bool is_null = IsUndefinedOrNull(v8_value);
int32_t cpp_value = is_null ? int32_t() : NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
impl->setLongOrNullAttribute(cpp_value, is_null);
}
| 172,305
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_recv_plaintext(int sock)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = 512;
buf = calloc(1, chunk_size);
while (1) {
errno = 0;
rc = read(sock, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
if (errno == EINTR || errno == EAGAIN) {
crm_trace("Retry: %d", (int)rc);
if (rc > 0) {
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
}
} else if (rc < 0) {
crm_perror(LOG_ERR, "Error receiving message: %d", (int)rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
return buf;
}
}
bail:
free(buf);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_recv_plaintext(int sock)
/*!
* \internal
* \brief Read bytes off non blocking socket.
*
* \param session - tls session to read
* \param max_size - max bytes allowed to read for buffer. 0 assumes no limit
*
* \note only use with NON-Blocking sockets. Should only be used after polling socket.
* This function will return once max_size is met, the socket read buffer
* is empty, or an error is encountered.
*
* \retval '\0' terminated buffer on success
*/
static char *
crm_recv_plaintext(int sock, size_t max_size, size_t *recv_len, int *disconnected)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = max_size ? max_size : 1024;
size_t buf_size = 0;
size_t read_size = 0;
if (sock <= 0) {
if (disconnected) {
*disconnected = 1;
}
goto done;
}
buf = calloc(1, chunk_size + 1);
buf_size = chunk_size;
while (TRUE) {
errno = 0;
read_size = buf_size - len;
/* automatically grow the buffer when needed if max_size is not set.*/
if (!max_size && (read_size < (chunk_size / 2))) {
buf_size += chunk_size;
crm_trace("Grow buffer by %d more bytes. buf is now %d bytes", (int)chunk_size, buf_size);
buf = realloc(buf, buf_size + 1);
CRM_ASSERT(buf != NULL);
read_size = buf_size - len;
}
rc = read(sock, buf + len, chunk_size);
if (rc > 0) {
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
len += rc;
/* always null terminate buffer, the +1 to alloc always allows for this.*/
buf[len] = '\0';
}
if (max_size && (max_size == read_size)) {
crm_trace("Buffer max read size %d met" , max_size);
goto done;
}
if (rc > 0) {
continue;
} else if (rc == 0) {
if (disconnected) {
*disconnected = 1;
}
crm_trace("EOF encoutered during read");
goto done;
}
/* process errors */
if (errno == EINTR) {
crm_trace("EINTER encoutered, retry socket read.");
} else if (errno == EAGAIN) {
crm_trace("non-blocking, exiting read on rc = %d", rc);
goto done;
} else if (errno <= 0) {
if (disconnected) {
*disconnected = 1;
}
crm_debug("Error receiving message: %d", (int)rc);
goto done;
}
}
done:
if (recv_len) {
*recv_len = len;
}
if (!len) {
free(buf);
buf = NULL;
}
return buf;
}
| 166,158
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SplitString(const std::wstring& str,
wchar_t c,
std::vector<std::wstring>* r) {
SplitStringT(str, c, true, r);
}
Commit Message: wstring: remove wstring version of SplitString
Retry of r84336.
BUG=23581
Review URL: http://codereview.chromium.org/6930047
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@84355 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void SplitString(const std::wstring& str,
| 170,555
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long ioctl_file_dedupe_range(struct file *file, void __user *arg)
{
struct file_dedupe_range __user *argp = arg;
struct file_dedupe_range *same = NULL;
int ret;
unsigned long size;
u16 count;
if (get_user(count, &argp->dest_count)) {
ret = -EFAULT;
goto out;
}
size = offsetof(struct file_dedupe_range __user, info[count]);
same = memdup_user(argp, size);
if (IS_ERR(same)) {
ret = PTR_ERR(same);
same = NULL;
goto out;
}
ret = vfs_dedupe_file_range(file, same);
if (ret)
goto out;
ret = copy_to_user(argp, same, size);
if (ret)
ret = -EFAULT;
out:
kfree(same);
return ret;
}
Commit Message: vfs: ioctl: prevent double-fetch in dedupe ioctl
This prevents a double-fetch from user space that can lead to to an
undersized allocation and heap overflow.
Fixes: 54dbc1517237 ("vfs: hoist the btrfs deduplication ioctl to the vfs")
Signed-off-by: Scott Bauer <sbauer@plzdonthack.me>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-119
|
static long ioctl_file_dedupe_range(struct file *file, void __user *arg)
{
struct file_dedupe_range __user *argp = arg;
struct file_dedupe_range *same = NULL;
int ret;
unsigned long size;
u16 count;
if (get_user(count, &argp->dest_count)) {
ret = -EFAULT;
goto out;
}
size = offsetof(struct file_dedupe_range __user, info[count]);
same = memdup_user(argp, size);
if (IS_ERR(same)) {
ret = PTR_ERR(same);
same = NULL;
goto out;
}
same->dest_count = count;
ret = vfs_dedupe_file_range(file, same);
if (ret)
goto out;
ret = copy_to_user(argp, same, size);
if (ret)
ret = -EFAULT;
out:
kfree(same);
return ret;
}
| 166,997
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
char *buf, int *len_ptr)
{
int len, iflags = 0;
struct file_list *flist;
uchar fnamecmp_type = FNAMECMP_FNAME;
int ndx;
read_loop:
while (1) {
ndx = read_ndx(f_in);
if (ndx >= 0)
break;
if (ndx == NDX_DONE)
return ndx;
if (ndx == NDX_DEL_STATS) {
read_del_stats(f_in);
if (am_sender && am_server)
write_del_stats(f_out);
continue;
}
if (!inc_recurse || am_sender) {
int last;
if (first_flist)
last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
else
last = -1;
rprintf(FERROR,
"Invalid file index: %d (%d - %d) [%s]\n",
ndx, NDX_DONE, last, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (ndx == NDX_FLIST_EOF) {
flist_eof = 1;
if (DEBUG_GTE(FLIST, 3))
rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
write_int(f_out, NDX_FLIST_EOF);
continue;
}
ndx = NDX_FLIST_OFFSET - ndx;
if (ndx < 0 || ndx >= dir_flist->used) {
ndx = NDX_FLIST_OFFSET - ndx;
rprintf(FERROR,
"Invalid dir index: %d (%d - %d) [%s]\n",
ndx, NDX_FLIST_OFFSET,
NDX_FLIST_OFFSET - dir_flist->used + 1,
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(FLIST, 2)) {
rprintf(FINFO, "[%s] receiving flist for dir %d\n",
who_am_i(), ndx);
}
/* Send all the data we read for this flist to the generator. */
start_flist_forward(ndx);
flist = recv_file_list(f_in, ndx);
flist->parent_ndx = ndx;
stop_flist_forward();
}
iflags = protocol_version >= 29 ? read_shortint(f_in)
: ITEM_TRANSFER | ITEM_MISSING_DATA;
/* Support the protocol-29 keep-alive style. */
if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
if (am_sender)
maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
goto read_loop;
}
flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
if (flist != cur_flist) {
cur_flist = flist;
if (am_sender) {
file_old_total = cur_flist->used;
for (flist = first_flist; flist != cur_flist; flist = flist->next)
file_old_total += flist->used;
}
}
if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
fnamecmp_type = read_byte(f_in);
*type_ptr = fnamecmp_type;
if (iflags & ITEM_XNAME_FOLLOWS) {
if (iflags & ITEM_XNAME_FOLLOWS) {
if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
exit_cleanup(RERR_PROTOCOL);
} else {
*buf = '\0';
len = -1;
rprintf(FERROR,
"received request to transfer non-regular file: %d [%s]\n",
ndx, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
}
*iflag_ptr = iflags;
return ndx;
}
Commit Message:
CWE ID:
|
int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
char *buf, int *len_ptr)
{
int len, iflags = 0;
struct file_list *flist;
uchar fnamecmp_type = FNAMECMP_FNAME;
int ndx;
read_loop:
while (1) {
ndx = read_ndx(f_in);
if (ndx >= 0)
break;
if (ndx == NDX_DONE)
return ndx;
if (ndx == NDX_DEL_STATS) {
read_del_stats(f_in);
if (am_sender && am_server)
write_del_stats(f_out);
continue;
}
if (!inc_recurse || am_sender) {
int last;
if (first_flist)
last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
else
last = -1;
rprintf(FERROR,
"Invalid file index: %d (%d - %d) [%s]\n",
ndx, NDX_DONE, last, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (ndx == NDX_FLIST_EOF) {
flist_eof = 1;
if (DEBUG_GTE(FLIST, 3))
rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
write_int(f_out, NDX_FLIST_EOF);
continue;
}
ndx = NDX_FLIST_OFFSET - ndx;
if (ndx < 0 || ndx >= dir_flist->used) {
ndx = NDX_FLIST_OFFSET - ndx;
rprintf(FERROR,
"Invalid dir index: %d (%d - %d) [%s]\n",
ndx, NDX_FLIST_OFFSET,
NDX_FLIST_OFFSET - dir_flist->used + 1,
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(FLIST, 2)) {
rprintf(FINFO, "[%s] receiving flist for dir %d\n",
who_am_i(), ndx);
}
/* Send all the data we read for this flist to the generator. */
start_flist_forward(ndx);
flist = recv_file_list(f_in, ndx);
flist->parent_ndx = ndx;
stop_flist_forward();
}
iflags = protocol_version >= 29 ? read_shortint(f_in)
: ITEM_TRANSFER | ITEM_MISSING_DATA;
/* Support the protocol-29 keep-alive style. */
if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
if (am_sender)
maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
goto read_loop;
}
flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
if (flist != cur_flist) {
cur_flist = flist;
if (am_sender) {
file_old_total = cur_flist->used;
for (flist = first_flist; flist != cur_flist; flist = flist->next)
file_old_total += flist->used;
}
}
if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
fnamecmp_type = read_byte(f_in);
*type_ptr = fnamecmp_type;
if (iflags & ITEM_XNAME_FOLLOWS) {
if (iflags & ITEM_XNAME_FOLLOWS) {
if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
exit_cleanup(RERR_PROTOCOL);
if (sanitize_paths) {
sanitize_path(buf, buf, "", 0, SP_DEFAULT);
len = strlen(buf);
}
} else {
*buf = '\0';
len = -1;
rprintf(FERROR,
"received request to transfer non-regular file: %d [%s]\n",
ndx, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
}
*iflag_ptr = iflags;
return ndx;
}
| 164,598
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole,
OnDidAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState,
OnUpdateUserActivationState)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking,
OnSetNeedsOcclusionTracking);
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame,
OnBubbleLogicalScrollInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess,
OnRenderFallbackContentInParentProcess)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <lowell@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Camille Lamy <clamy@chromium.org>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
|
bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState,
OnUpdateUserActivationState)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking,
OnSetNeedsOcclusionTracking);
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame,
OnBubbleLogicalScrollInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess,
OnRenderFallbackContentInParentProcess)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_END_MESSAGE_MAP()
return handled;
}
| 172,486
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
|
static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,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: exsltCryptoPopString (xmlXPathParserContextPtr ctxt, int nargs,
xmlChar ** str) {
int str_len = 0;
if ((nargs < 1) || (nargs > 2)) {
xmlXPathSetArityError (ctxt);
return 0;
}
*str = xmlXPathPopString (ctxt);
str_len = xmlUTF8Strlen (*str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (*str);
return 0;
}
return str_len;
}
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
|
exsltCryptoPopString (xmlXPathParserContextPtr ctxt, int nargs,
xmlChar ** str) {
int str_len = 0;
if ((nargs < 1) || (nargs > 2)) {
xmlXPathSetArityError (ctxt);
return 0;
}
*str = xmlXPathPopString (ctxt);
str_len = xmlStrlen (*str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (*str);
return 0;
}
return str_len;
}
| 173,286
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Parcel::readUtf8FromUtf16(std::string* str) const {
size_t utf16Size = 0;
const char16_t* src = readString16Inplace(&utf16Size);
if (!src) {
return UNEXPECTED_NULL;
}
if (utf16Size == 0u) {
str->clear();
return NO_ERROR;
}
ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size);
if (utf8Size < 0) {
return BAD_VALUE;
}
str->resize(utf8Size + 1);
utf16_to_utf8(src, utf16Size, &((*str)[0]));
str->resize(utf8Size);
return NO_ERROR;
}
Commit Message: Add bound checks to utf16_to_utf8
Bug: 29250543
Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a
(cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719)
CWE ID: CWE-119
|
status_t Parcel::readUtf8FromUtf16(std::string* str) const {
size_t utf16Size = 0;
const char16_t* src = readString16Inplace(&utf16Size);
if (!src) {
return UNEXPECTED_NULL;
}
if (utf16Size == 0u) {
str->clear();
return NO_ERROR;
}
// Allow for closing '\0'
ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1;
if (utf8Size < 1) {
return BAD_VALUE;
}
// spare byte around for the trailing null, we still pass the size including the trailing null
str->resize(utf8Size);
utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size);
str->resize(utf8Size - 1);
return NO_ERROR;
}
| 174,158
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 30 && rdesc[29] == 0x05 && rdesc[30] == 0x09) {
hid_info(hdev, "fixing up button/consumer in HID report descriptor\n");
rdesc[30] = 0x0c;
}
return rdesc;
}
Commit Message: HID: fix a couple of off-by-ones
There are a few very theoretical off-by-one bugs in report descriptor size
checking when performing a pre-parsing fixup. Fix those.
Cc: stable@vger.kernel.org
Reported-by: Ben Hawkes <hawkes@google.com>
Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-119
|
static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 31 && rdesc[29] == 0x05 && rdesc[30] == 0x09) {
hid_info(hdev, "fixing up button/consumer in HID report descriptor\n");
rdesc[30] = 0x0c;
}
return rdesc;
}
| 166,373
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __exit xfrm6_tunnel_fini(void)
{
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
xfrm6_tunnel_spi_fini();
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-362
|
static void __exit xfrm6_tunnel_fini(void)
{
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
}
| 165,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: const unsigned char* Track::GetCodecPrivate(size_t& size) const
{
size = m_info.codecPrivateSize;
return m_info.codecPrivate;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const unsigned char* Track::GetCodecPrivate(size_t& size) const
| 174,295
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SignatureUtil::CheckSignature(
const FilePath& file_path,
ClientDownloadRequest_SignatureInfo* signature_info) {
VLOG(2) << "Checking signature for " << file_path.value();
WINTRUST_FILE_INFO file_info;
file_info.cbStruct = sizeof(file_info);
file_info.pcwszFilePath = file_path.value().c_str();
file_info.hFile = NULL;
file_info.pgKnownSubject = NULL;
WINTRUST_DATA wintrust_data;
wintrust_data.cbStruct = sizeof(wintrust_data);
wintrust_data.pPolicyCallbackData = NULL;
wintrust_data.pSIPClientData = NULL;
wintrust_data.dwUIChoice = WTD_UI_NONE;
wintrust_data.fdwRevocationChecks = WTD_REVOKE_NONE;
wintrust_data.dwUnionChoice = WTD_CHOICE_FILE;
wintrust_data.pFile = &file_info;
wintrust_data.dwStateAction = WTD_STATEACTION_VERIFY;
wintrust_data.hWVTStateData = NULL;
wintrust_data.pwszURLReference = NULL;
wintrust_data.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
wintrust_data.dwUIContext = WTD_UICONTEXT_EXECUTE;
GUID policy_guid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
LONG result = WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid,
&wintrust_data);
CRYPT_PROVIDER_DATA* prov_data = WTHelperProvDataFromStateData(
wintrust_data.hWVTStateData);
if (prov_data) {
if (prov_data->csSigners > 0) {
signature_info->set_trusted(result == ERROR_SUCCESS);
}
for (DWORD i = 0; i < prov_data->csSigners; ++i) {
const CERT_CHAIN_CONTEXT* cert_chain_context =
prov_data->pasSigners[i].pChainContext;
for (DWORD j = 0; j < cert_chain_context->cChain; ++j) {
CERT_SIMPLE_CHAIN* simple_chain = cert_chain_context->rgpChain[j];
ClientDownloadRequest_CertificateChain* chain =
signature_info->add_certificate_chain();
for (DWORD k = 0; k < simple_chain->cElement; ++k) {
CERT_CHAIN_ELEMENT* element = simple_chain->rgpElement[k];
chain->add_element()->set_certificate(
element->pCertContext->pbCertEncoded,
element->pCertContext->cbCertEncoded);
}
}
}
wintrust_data.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid, &wintrust_data);
}
}
Commit Message: Fix null deref when walking cert chain.
BUG=109664
TEST=N/A
Review URL: http://codereview.chromium.org/9150013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@117080 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void SignatureUtil::CheckSignature(
const FilePath& file_path,
ClientDownloadRequest_SignatureInfo* signature_info) {
VLOG(2) << "Checking signature for " << file_path.value();
WINTRUST_FILE_INFO file_info;
file_info.cbStruct = sizeof(file_info);
file_info.pcwszFilePath = file_path.value().c_str();
file_info.hFile = NULL;
file_info.pgKnownSubject = NULL;
WINTRUST_DATA wintrust_data;
wintrust_data.cbStruct = sizeof(wintrust_data);
wintrust_data.pPolicyCallbackData = NULL;
wintrust_data.pSIPClientData = NULL;
wintrust_data.dwUIChoice = WTD_UI_NONE;
wintrust_data.fdwRevocationChecks = WTD_REVOKE_NONE;
wintrust_data.dwUnionChoice = WTD_CHOICE_FILE;
wintrust_data.pFile = &file_info;
wintrust_data.dwStateAction = WTD_STATEACTION_VERIFY;
wintrust_data.hWVTStateData = NULL;
wintrust_data.pwszURLReference = NULL;
wintrust_data.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
wintrust_data.dwUIContext = WTD_UICONTEXT_EXECUTE;
GUID policy_guid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
LONG result = WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid,
&wintrust_data);
CRYPT_PROVIDER_DATA* prov_data = WTHelperProvDataFromStateData(
wintrust_data.hWVTStateData);
if (prov_data) {
if (prov_data->csSigners > 0) {
signature_info->set_trusted(result == ERROR_SUCCESS);
}
for (DWORD i = 0; i < prov_data->csSigners; ++i) {
const CERT_CHAIN_CONTEXT* cert_chain_context =
prov_data->pasSigners[i].pChainContext;
if (!cert_chain_context)
break;
for (DWORD j = 0; j < cert_chain_context->cChain; ++j) {
CERT_SIMPLE_CHAIN* simple_chain = cert_chain_context->rgpChain[j];
ClientDownloadRequest_CertificateChain* chain =
signature_info->add_certificate_chain();
if (!simple_chain)
break;
for (DWORD k = 0; k < simple_chain->cElement; ++k) {
CERT_CHAIN_ELEMENT* element = simple_chain->rgpElement[k];
chain->add_element()->set_certificate(
element->pCertContext->pbCertEncoded,
element->pCertContext->cbCertEncoded);
}
}
}
wintrust_data.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid, &wintrust_data);
}
}
| 170,974
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc)
{
struct ib_cqe *cqe = wc->wr_cqe;
struct svc_rdma_op_ctxt *ctxt;
svc_rdma_send_wc_common_put(cq, wc, "write");
ctxt = container_of(cqe, struct svc_rdma_op_ctxt, cqe);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 0);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
void svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc)
| 168,184
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor(ui::Compositor*) {
if (current_surface_ || !host_->is_hidden())
return;
current_surface_in_use_by_compositor_ = false;
AdjustSurfaceProtection();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor(ui::Compositor*) {
| 171,385
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: jbig2_sd_list_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
Jbig2SymbolDict **dicts;
int n_dicts = jbig2_sd_count_referred(ctx, segment);
int dindex = 0;
dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_dicts);
if (dicts == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate referred list of symbol dictionaries");
return NULL;
}
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result &&
(((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) {
/* add this referred to symbol dictionary */
dicts[dindex++] = (Jbig2SymbolDict *) rsegment->result;
}
}
if (dindex != n_dicts) {
/* should never happen */
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "counted %d symbol dictionaries but built a list with %d.\n", n_dicts, dindex);
}
return (dicts);
}
Commit Message:
CWE ID: CWE-119
|
jbig2_sd_list_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
Jbig2SymbolDict **dicts;
uint32_t n_dicts = jbig2_sd_count_referred(ctx, segment);
uint32_t dindex = 0;
dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_dicts);
if (dicts == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate referred list of symbol dictionaries");
return NULL;
}
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result &&
(((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) {
/* add this referred to symbol dictionary */
dicts[dindex++] = (Jbig2SymbolDict *) rsegment->result;
}
}
if (dindex != n_dicts) {
/* should never happen */
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "counted %d symbol dictionaries but built a list with %d.\n", n_dicts, dindex);
}
return (dicts);
}
| 165,501
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern = (spl_filesystem_object*)object;
if (intern->oth_handler && intern->oth_handler->dtor) {
intern->oth_handler->dtor(intern TSRMLS_CC);
}
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->_path) {
efree(intern->_path);
}
if (intern->file_name) {
efree(intern->file_name);
}
switch(intern->type) {
case SPL_FS_INFO:
break;
case SPL_FS_DIR:
if (intern->u.dir.dirp) {
php_stream_close(intern->u.dir.dirp);
intern->u.dir.dirp = NULL;
}
if (intern->u.dir.sub_path) {
efree(intern->u.dir.sub_path);
}
break;
case SPL_FS_FILE:
if (intern->u.file.stream) {
if (intern->u.file.zcontext) {
/* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/
}
if (!intern->u.file.stream->is_persistent) {
php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE);
} else {
php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT);
}
if (intern->u.file.open_mode) {
efree(intern->u.file.open_mode);
}
if (intern->orig_path) {
efree(intern->orig_path);
}
}
spl_filesystem_file_free_line(intern TSRMLS_CC);
break;
}
{
zend_object_iterator *iterator;
iterator = (zend_object_iterator*)
spl_filesystem_object_to_iterator(intern);
if (iterator->data != NULL) {
iterator->data = NULL;
iterator->funcs->dtor(iterator TSRMLS_CC);
}
}
efree(object);
} /* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern = (spl_filesystem_object*)object;
if (intern->oth_handler && intern->oth_handler->dtor) {
intern->oth_handler->dtor(intern TSRMLS_CC);
}
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->_path) {
efree(intern->_path);
}
if (intern->file_name) {
efree(intern->file_name);
}
switch(intern->type) {
case SPL_FS_INFO:
break;
case SPL_FS_DIR:
if (intern->u.dir.dirp) {
php_stream_close(intern->u.dir.dirp);
intern->u.dir.dirp = NULL;
}
if (intern->u.dir.sub_path) {
efree(intern->u.dir.sub_path);
}
break;
case SPL_FS_FILE:
if (intern->u.file.stream) {
if (intern->u.file.zcontext) {
/* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/
}
if (!intern->u.file.stream->is_persistent) {
php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE);
} else {
php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT);
}
if (intern->u.file.open_mode) {
efree(intern->u.file.open_mode);
}
if (intern->orig_path) {
efree(intern->orig_path);
}
}
spl_filesystem_file_free_line(intern TSRMLS_CC);
break;
}
{
zend_object_iterator *iterator;
iterator = (zend_object_iterator*)
spl_filesystem_object_to_iterator(intern);
if (iterator->data != NULL) {
iterator->data = NULL;
iterator->funcs->dtor(iterator TSRMLS_CC);
}
}
efree(object);
} /* }}} */
| 167,083
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
init_get_bits8(&gb, buf, size);
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
}
Commit Message: avcodec/ac3_parser: Check init_get_bits8() for failure
Fixes: null pointer dereference
Fixes: ffmpeg_crash_6.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Reviewed-by: Paul B Mahol <onemda@gmail.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-476
|
int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
err = init_get_bits8(&gb, buf, size);
if (err < 0)
return AVERROR_INVALIDDATA;
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
}
| 169,158
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||
(inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK)))
return 1;
return 0;
}
Commit Message: nfs: always make sure page is up-to-date before extending a write to cover the entire page
We should always make sure the cached page is up-to-date when we're
determining whether we can extend a write to cover the full page -- even
if we've received a write delegation from the server.
Commit c7559663 added logic to skip this check if we have a write
delegation, which can lead to data corruption such as the following
scenario if client B receives a write delegation from the NFS server:
Client A:
# echo 123456789 > /mnt/file
Client B:
# echo abcdefghi >> /mnt/file
# cat /mnt/file
0�D0�abcdefghi
Just because we hold a write delegation doesn't mean that we've read in
the entire page contents.
Cc: <stable@vger.kernel.org> # v3.11+
Signed-off-by: Scott Mayhew <smayhew@redhat.com>
Signed-off-by: Trond Myklebust <trond.myklebust@primarydata.com>
CWE ID: CWE-20
|
static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (!nfs_write_pageuptodate(page, inode))
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK))
return 1;
return 0;
}
| 166,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: static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
struct snd_ctl_elem_value *control)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &control->id);
if (kctl == NULL) {
result = -ENOENT;
} else {
index_offset = snd_ctl_get_ioff(kctl, &control->id);
vd = &kctl->vd[index_offset];
if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||
kctl->put == NULL ||
(file && vd->owner && vd->owner != file)) {
result = -EPERM;
} else {
snd_ctl_build_ioff(&control->id, kctl, index_offset);
result = kctl->put(kctl, control);
}
if (result > 0) {
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&control->id);
return 0;
}
}
up_read(&card->controls_rwsem);
return result;
}
Commit Message: ALSA: control: Don't access controls outside of protected regions
A control that is visible on the card->controls list can be freed at any time.
This means we must not access any of its memory while not holding the
controls_rw_lock. Otherwise we risk a use after free access.
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Acked-by: Jaroslav Kysela <perex@perex.cz>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID:
|
static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
struct snd_ctl_elem_value *control)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &control->id);
if (kctl == NULL) {
result = -ENOENT;
} else {
index_offset = snd_ctl_get_ioff(kctl, &control->id);
vd = &kctl->vd[index_offset];
if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||
kctl->put == NULL ||
(file && vd->owner && vd->owner != file)) {
result = -EPERM;
} else {
snd_ctl_build_ioff(&control->id, kctl, index_offset);
result = kctl->put(kctl, control);
}
if (result > 0) {
struct snd_ctl_elem_id id = control->id;
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &id);
return 0;
}
}
up_read(&card->controls_rwsem);
return result;
}
| 166,293
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int main(int argc, char **argv) {
FILE *infile = NULL;
VpxVideoWriter *writer = NULL;
vpx_codec_ctx_t codec;
vpx_codec_enc_cfg_t cfg;
vpx_image_t raw;
vpx_codec_err_t res;
vpx_fixed_buf_t stats = {0};
VpxVideoInfo info = {0};
const VpxInterface *encoder = NULL;
int pass;
const int fps = 30; // TODO(dkovalev) add command line argument
const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
const char *const codec_arg = argv[1];
const char *const width_arg = argv[2];
const char *const height_arg = argv[3];
const char *const infile_arg = argv[4];
const char *const outfile_arg = argv[5];
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments.");
encoder = get_vpx_encoder_by_name(codec_arg);
if (!encoder)
die("Unsupported codec.");
info.codec_fourcc = encoder->fourcc;
info.time_base.numerator = 1;
info.time_base.denominator = fps;
info.frame_width = strtol(width_arg, NULL, 0);
info.frame_height = strtol(height_arg, NULL, 0);
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image", info.frame_width, info.frame_height);
}
writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing", outfile_arg);
printf("Using %s\n", vpx_codec_iface_name(encoder->interface()));
res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = bitrate;
for (pass = 0; pass < 2; ++pass) {
int frame_count = 0;
if (pass == 0) {
cfg.g_pass = VPX_RC_FIRST_PASS;
} else {
cfg.g_pass = VPX_RC_LAST_PASS;
cfg.rc_twopass_stats_in = stats;
}
if (!(infile = fopen(infile_arg, "rb")))
die("Failed to open %s for reading", infile_arg);
if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
while (vpx_img_read(&raw, infile)) {
++frame_count;
if (pass == 0) {
get_frame_stats(&codec, &raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY,
&stats);
} else {
encode_frame(&codec, &raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY,
writer);
}
}
if (pass == 0) {
get_frame_stats(&codec, NULL, frame_count, 1, 0, VPX_DL_BEST_QUALITY,
&stats);
} else {
printf("\n");
}
fclose(infile);
printf("Pass %d complete. Processed %d frames.\n", pass + 1, frame_count);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
}
vpx_img_free(&raw);
free(stats.buf);
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
int main(int argc, char **argv) {
FILE *infile = NULL;
int w, h;
vpx_codec_ctx_t codec;
vpx_codec_enc_cfg_t cfg;
vpx_image_t raw;
vpx_codec_err_t res;
vpx_fixed_buf_t stats;
const VpxInterface *encoder = NULL;
const int fps = 30; // TODO(dkovalev) add command line argument
const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
const char *const codec_arg = argv[1];
const char *const width_arg = argv[2];
const char *const height_arg = argv[3];
const char *const infile_arg = argv[4];
const char *const outfile_arg = argv[5];
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments.");
encoder = get_vpx_encoder_by_name(codec_arg);
if (!encoder)
die("Unsupported codec.");
w = strtol(width_arg, NULL, 0);
h = strtol(height_arg, NULL, 0);
if (w <= 0 || h <= 0 || (w % 2) != 0 || (h % 2) != 0)
die("Invalid frame size: %dx%d", w, h);
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, w, h, 1))
die("Failed to allocate image", w, h);
printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface()));
// Configuration
res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = w;
cfg.g_h = h;
cfg.g_timebase.num = 1;
cfg.g_timebase.den = fps;
cfg.rc_target_bitrate = bitrate;
if (!(infile = fopen(infile_arg, "rb")))
die("Failed to open %s for reading", infile_arg);
// Pass 0
cfg.g_pass = VPX_RC_FIRST_PASS;
stats = pass0(&raw, infile, encoder, &cfg);
// Pass 1
rewind(infile);
cfg.g_pass = VPX_RC_LAST_PASS;
cfg.rc_twopass_stats_in = stats;
pass1(&raw, infile, outfile_arg, encoder, &cfg);
free(stats.buf);
vpx_img_free(&raw);
fclose(infile);
return EXIT_SUCCESS;
}
| 174,493
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssl_check_for_safari(SSL *s, const unsigned char *data,
const unsigned char *limit)
{
unsigned short type, size;
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
};
/* The following is only present in TLS 1.2 */
static const unsigned char kSafariTLS12ExtensionsBlock[] = {
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
if (data >= (limit - 2))
return;
data += 2;
if (data > (limit - 4))
return;
n2s(data, type);
n2s(data, size);
if (type != TLSEXT_TYPE_server_name)
return;
if (data + size > limit)
return;
data += size;
if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
const size_t len1 = sizeof(kSafariExtensionsBlock);
const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
if (data + len1 + len2 != limit)
return;
if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
return;
if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
return;
} else {
const size_t len = sizeof(kSafariExtensionsBlock);
if (data + len != limit)
return;
if (memcmp(data, kSafariExtensionsBlock, len) != 0)
return;
}
s->s3->is_probably_safari = 1;
}
Commit Message:
CWE ID: CWE-190
|
static void ssl_check_for_safari(SSL *s, const unsigned char *data,
const unsigned char *limit)
{
unsigned short type, size;
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
};
/* The following is only present in TLS 1.2 */
static const unsigned char kSafariTLS12ExtensionsBlock[] = {
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
if (limit - data <= 2)
return;
data += 2;
if (limit - data < 4)
return;
n2s(data, type);
n2s(data, size);
if (type != TLSEXT_TYPE_server_name)
return;
if (limit - data < size)
return;
data += size;
if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
const size_t len1 = sizeof(kSafariExtensionsBlock);
const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
if (limit - data != (int)(len1 + len2))
return;
if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
return;
if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
return;
} else {
const size_t len = sizeof(kSafariExtensionsBlock);
if (limit - data != (int)(len))
return;
if (memcmp(data, kSafariExtensionsBlock, len) != 0)
return;
}
s->s3->is_probably_safari = 1;
}
| 165,202
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXListBoxOption::isEnabled() const {
if (!getNode())
return false;
if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
return false;
if (toElement(getNode())->hasAttribute(disabledAttr))
return false;
return true;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXListBoxOption::isEnabled() const {
if (!getNode())
return false;
if (equalIgnoringASCIICase(getAttribute(aria_disabledAttr), "true"))
return false;
if (toElement(getNode())->hasAttribute(disabledAttr))
return false;
return true;
}
| 171,907
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long Segment::CreateInstance(
IMkvReader* pReader,
long long pos,
Segment*& pSegment)
{
assert(pReader);
assert(pos >= 0);
pSegment = NULL;
long long total, available;
const long status = pReader->Length(&total, &available);
if (status < 0) //error
return status;
if (available < 0)
return -1;
if ((total >= 0) && (available > total))
return -1;
for (;;)
{
if ((total >= 0) && (pos >= total))
return E_FILE_FORMAT_INVALID;
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result) //error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return id;
pos += len; //consume ID
result = GetUIntLength(pReader, pos, len);
if (result) //error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return size;
pos += len; //consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (id == 0x08538067) //Segment ID
{
if (size == unknown_size)
size = -1;
else if (total < 0)
size = -1;
else if ((pos + size) > total)
size = -1;
pSegment = new (std::nothrow) Segment(
pReader,
idpos,
pos,
size);
if (pSegment == 0)
return -1; //generic error
return 0; //success
}
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + size) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
pos += size; //consume payload
}
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Segment::CreateInstance(
if (result < 0) // error
return result;
if (result > 0) // underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) // error
return id;
if (id == 0x0F43B675) // Cluster ID
break;
pos += len; // consume ID
if ((pos + 1) > available)
return (pos + 1);
// Read Size
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) // underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
const long long element_size = size + pos - element_start;
// Pos now points to start of payload
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
// We read EBML elements either in total or nothing at all.
if ((pos + size) > available)
return pos + size;
if (id == 0x0549A966) { // Segment Info ID
if (m_pInfo)
return E_FILE_FORMAT_INVALID;
m_pInfo = new (std::nothrow)
SegmentInfo(this, pos, size, element_start, element_size);
if (m_pInfo == NULL)
return -1;
const long status = m_pInfo->Parse();
if (status)
return status;
} else if (id == 0x0654AE6B) { // Tracks ID
if (m_pTracks)
return E_FILE_FORMAT_INVALID;
m_pTracks = new (std::nothrow)
Tracks(this, pos, size, element_start, element_size);
if (m_pTracks == NULL)
return -1;
const long status = m_pTracks->Parse();
| 174,259
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) {
if (error_)
return;
if (result == net::ERR_UPLOAD_FILE_CHANGED) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
} else if (result < 0) {
NotifyFailure(result);
return;
}
DCHECK_LT(index, blob_data_->items().size());
const BlobData::Item& item = blob_data_->items().at(index);
DCHECK(IsFileType(item.type()));
int64 item_length = static_cast<int64>(item.length());
if (item_length == -1)
item_length = result - item.offset();
DCHECK_LT(index, item_length_list_.size());
item_length_list_[index] = item_length;
total_size_ += item_length;
if (--pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
Commit Message: Avoid integer overflows in BlobURLRequestJob.
BUG=169685
Review URL: https://chromiumcodereview.appspot.com/12047012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
void BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) {
if (error_)
return;
if (result == net::ERR_UPLOAD_FILE_CHANGED) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
} else if (result < 0) {
NotifyFailure(result);
return;
}
DCHECK_LT(index, blob_data_->items().size());
const BlobData::Item& item = blob_data_->items().at(index);
DCHECK(IsFileType(item.type()));
uint64 file_length = result;
uint64 item_offset = item.offset();
uint64 item_length = item.length();
if (item_offset > file_length) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
}
uint64 max_length = file_length - item_offset;
if (item_length == static_cast<uint64>(-1)) {
item_length = max_length;
} else if (item_length > max_length) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
}
if (!AddItemLength(index, item_length))
return;
if (--pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
| 171,399
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */
{
if (intern->u.file.current_line) {
return intern->u.file.current_line_len == 0;
} else if (intern->u.file.current_zval) {
switch(Z_TYPE_P(intern->u.file.current_zval)) {
case IS_STRING:
return Z_STRLEN_P(intern->u.file.current_zval) == 0;
case IS_ARRAY:
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)
&& zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) {
zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData;
return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0;
}
return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0;
case IS_NULL:
return 1;
default:
return 0;
}
} else {
return 1;
}
}
/* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */
{
if (intern->u.file.current_line) {
return intern->u.file.current_line_len == 0;
} else if (intern->u.file.current_zval) {
switch(Z_TYPE_P(intern->u.file.current_zval)) {
case IS_STRING:
return Z_STRLEN_P(intern->u.file.current_zval) == 0;
case IS_ARRAY:
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)
&& zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) {
zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData;
return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0;
}
return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0;
case IS_NULL:
return 1;
default:
return 0;
}
} else {
return 1;
}
}
/* }}} */
| 167,074
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SendHandwritingStroke(const HandwritingStroke& stroke) {
if (!initialized_successfully_)
return;
chromeos::SendHandwritingStroke(input_method_status_connection_, stroke);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
virtual void SendHandwritingStroke(
const input_method::HandwritingStroke& stroke) {
if (!initialized_successfully_)
return;
ibus_controller_->SendHandwritingStroke(stroke);
}
| 170,504
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DebuggerFunction::InitAgentHost() {
if (debuggee_.tab_id) {
WebContents* web_contents = NULL;
bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id,
GetProfile(),
include_incognito(),
NULL,
NULL,
&web_contents,
NULL);
if (result && web_contents) {
if (content::HasWebUIScheme(web_contents->GetURL())) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kAttachToWebUIError,
web_contents->GetURL().scheme());
return false;
}
agent_host_ = DevToolsAgentHost::GetOrCreateFor(web_contents);
}
} else if (debuggee_.extension_id) {
ExtensionHost* extension_host =
ExtensionSystem::Get(GetProfile())
->process_manager()
->GetBackgroundHostForExtension(*debuggee_.extension_id);
if (extension_host) {
agent_host_ = DevToolsAgentHost::GetOrCreateFor(
extension_host->render_view_host());
}
} else if (debuggee_.target_id) {
agent_host_ = DevToolsAgentHost::GetForId(*debuggee_.target_id);
} else {
error_ = keys::kInvalidTargetError;
return false;
}
if (!agent_host_.get()) {
FormatErrorMessage(keys::kNoTargetError);
return false;
}
return true;
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool DebuggerFunction::InitAgentHost() {
const Extension* extension = GetExtension();
if (debuggee_.tab_id) {
WebContents* web_contents = NULL;
bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id,
GetProfile(),
include_incognito(),
NULL,
NULL,
&web_contents,
NULL);
if (result && web_contents) {
// TODO(rdevlin.cronin) This should definitely be GetLastCommittedURL().
GURL url = web_contents->GetVisibleURL();
if (PermissionsData::IsRestrictedUrl(url, url, extension, &error_))
return false;
agent_host_ = DevToolsAgentHost::GetOrCreateFor(web_contents);
}
} else if (debuggee_.extension_id) {
ExtensionHost* extension_host =
ExtensionSystem::Get(GetProfile())
->process_manager()
->GetBackgroundHostForExtension(*debuggee_.extension_id);
if (extension_host) {
if (PermissionsData::IsRestrictedUrl(extension_host->GetURL(),
extension_host->GetURL(),
extension,
&error_)) {
return false;
}
agent_host_ = DevToolsAgentHost::GetOrCreateFor(
extension_host->render_view_host());
}
} else if (debuggee_.target_id) {
agent_host_ = DevToolsAgentHost::GetForId(*debuggee_.target_id);
} else {
error_ = keys::kInvalidTargetError;
return false;
}
if (!agent_host_.get()) {
FormatErrorMessage(keys::kNoTargetError);
return false;
}
return true;
}
| 171,653
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
return;
}
for (i = 0; i < count; i++)
{
byte *record = namedata + 6 + i * 12;
int pid = u16(record + 0);
int eid = u16(record + 2);
int langid = u16(record + 4);
int nameid = u16(record + 6);
length = u16(record + 8);
offset = u16(record + 10);
/* Full font name or postscript name */
if (nameid == 4 || nameid == 6)
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
Commit Message:
CWE ID: CWE-119
|
xps_load_sfnt_name(xps_font_t *font, char *namep)
xps_load_sfnt_name(xps_font_t *font, char *namep, const int buflen)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
return;
}
for (i = 0; i < count; i++)
{
byte *record = namedata + 6 + i * 12;
int pid = u16(record + 0);
int eid = u16(record + 2);
int langid = u16(record + 4);
int nameid = u16(record + 6);
length = u16(record + 8);
offset = u16(record + 10);
length = length > buflen - 1 ? buflen - 1: length;
/* Full font name or postscript name */
if (nameid == 4 || nameid == 6)
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
| 164,785
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __local_bh_enable(unsigned int cnt)
{
lockdep_assert_irqs_disabled();
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_on(_RET_IP_);
preempt_count_sub(cnt);
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787
|
static void __local_bh_enable(unsigned int cnt)
{
lockdep_assert_irqs_disabled();
if (preempt_count() == cnt)
trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_on(_RET_IP_);
__preempt_count_sub(cnt);
}
| 169,184
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: UpdateLibrary* CrosLibrary::GetUpdateLibrary() {
return update_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
|
UpdateLibrary* CrosLibrary::GetUpdateLibrary() {
| 170,634
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static char *decode_text_string(const char *str, size_t str_len)
{
int idx, is_hex, is_utf16be, ascii_idx;
char *ascii, hex_buf[5] = {0};
is_hex = is_utf16be = idx = ascii_idx = 0;
/* Regular encoding */
if (str[0] == '(')
{
ascii = malloc(strlen(str) + 1);
strncpy(ascii, str, strlen(str) + 1);
return ascii;
}
else if (str[0] == '<')
{
is_hex = 1;
++idx;
}
/* Text strings can be either PDFDocEncoding or UTF-16BE */
if (is_hex && (str_len > 5) &&
(str[idx] == 'F') && (str[idx+1] == 'E') &&
(str[idx+2] == 'F') && (str[idx+3] == 'F'))
{
is_utf16be = 1;
idx += 4;
}
else
return NULL;
/* Now decode as hex */
ascii = malloc(str_len);
for ( ; idx<str_len; ++idx)
{
hex_buf[0] = str[idx++];
hex_buf[1] = str[idx++];
hex_buf[2] = str[idx++];
hex_buf[3] = str[idx];
ascii[ascii_idx++] = strtol(hex_buf, NULL, 16);
}
return ascii;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787
|
static char *decode_text_string(const char *str, size_t str_len)
{
int idx, is_hex, is_utf16be, ascii_idx;
char *ascii, hex_buf[5] = {0};
is_hex = is_utf16be = idx = ascii_idx = 0;
/* Regular encoding */
if (str[0] == '(')
{
ascii = safe_calloc(strlen(str) + 1);
strncpy(ascii, str, strlen(str) + 1);
return ascii;
}
else if (str[0] == '<')
{
is_hex = 1;
++idx;
}
/* Text strings can be either PDFDocEncoding or UTF-16BE */
if (is_hex && (str_len > 5) &&
(str[idx] == 'F') && (str[idx+1] == 'E') &&
(str[idx+2] == 'F') && (str[idx+3] == 'F'))
{
is_utf16be = 1;
idx += 4;
}
else
return NULL;
/* Now decode as hex */
ascii = safe_calloc(str_len);
for ( ; idx<str_len; ++idx)
{
hex_buf[0] = str[idx++];
hex_buf[1] = str[idx++];
hex_buf[2] = str[idx++];
hex_buf[3] = str[idx];
ascii[ascii_idx++] = strtol(hex_buf, NULL, 16);
}
return ascii;
}
| 169,566
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 digi_startup(struct usb_serial *serial)
{
struct digi_serial *serial_priv;
int ret;
serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL);
if (!serial_priv)
return -ENOMEM;
spin_lock_init(&serial_priv->ds_serial_lock);
serial_priv->ds_oob_port_num = serial->type->num_ports;
serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num];
ret = digi_port_init(serial_priv->ds_oob_port,
serial_priv->ds_oob_port_num);
if (ret) {
kfree(serial_priv);
return ret;
}
usb_set_serial_data(serial, serial_priv);
return 0;
}
Commit Message: USB: digi_acceleport: do sanity checking for the number of ports
The driver can be crashed with devices that expose crafted descriptors
with too few endpoints.
See: http://seclists.org/bugtraq/2016/Mar/61
Signed-off-by: Oliver Neukum <ONeukum@suse.com>
[johan: fix OOB endpoint check and add error messages ]
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID:
|
static int digi_startup(struct usb_serial *serial)
{
struct device *dev = &serial->interface->dev;
struct digi_serial *serial_priv;
int ret;
int i;
/* check whether the device has the expected number of endpoints */
if (serial->num_port_pointers < serial->type->num_ports + 1) {
dev_err(dev, "OOB endpoints missing\n");
return -ENODEV;
}
for (i = 0; i < serial->type->num_ports + 1 ; i++) {
if (!serial->port[i]->read_urb) {
dev_err(dev, "bulk-in endpoint missing\n");
return -ENODEV;
}
if (!serial->port[i]->write_urb) {
dev_err(dev, "bulk-out endpoint missing\n");
return -ENODEV;
}
}
serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL);
if (!serial_priv)
return -ENOMEM;
spin_lock_init(&serial_priv->ds_serial_lock);
serial_priv->ds_oob_port_num = serial->type->num_ports;
serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num];
ret = digi_port_init(serial_priv->ds_oob_port,
serial_priv->ds_oob_port_num);
if (ret) {
kfree(serial_priv);
return ret;
}
usb_set_serial_data(serial, serial_priv);
return 0;
}
| 167,357
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
{
get_page(buf->page);
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416
|
void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
{
return try_get_page(buf->page);
}
| 170,218
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: H264SwDecRet H264SwDecInit(H264SwDecInst *decInst, u32 noOutputReordering)
{
u32 rv = 0;
decContainer_t *pDecCont;
DEC_API_TRC("H264SwDecInit#");
/* check that right shift on negative numbers is performed signed */
/*lint -save -e* following check causes multiple lint messages */
if ( ((-1)>>1) != (-1) )
{
DEC_API_TRC("H264SwDecInit# ERROR: Right shift is not signed");
return(H264SWDEC_INITFAIL);
}
/*lint -restore */
if (decInst == NULL)
{
DEC_API_TRC("H264SwDecInit# ERROR: decInst == NULL");
return(H264SWDEC_PARAM_ERR);
}
pDecCont = (decContainer_t *)H264SwDecMalloc(sizeof(decContainer_t));
if (pDecCont == NULL)
{
DEC_API_TRC("H264SwDecInit# ERROR: Memory allocation failed");
return(H264SWDEC_MEMFAIL);
}
#ifdef H264DEC_TRACE
sprintf(pDecCont->str, "H264SwDecInit# decInst %p noOutputReordering %d",
(void*)decInst, noOutputReordering);
DEC_API_TRC(pDecCont->str);
#endif
rv = h264bsdInit(&pDecCont->storage, noOutputReordering);
if (rv != HANTRO_OK)
{
H264SwDecRelease(pDecCont);
return(H264SWDEC_MEMFAIL);
}
pDecCont->decStat = INITIALIZED;
pDecCont->picNumber = 0;
#ifdef H264DEC_TRACE
sprintf(pDecCont->str, "H264SwDecInit# OK: return %p", (void*)pDecCont);
DEC_API_TRC(pDecCont->str);
#endif
*decInst = (decContainer_t *)pDecCont;
return(H264SWDEC_OK);
}
Commit Message: h264dec: check for overflows when calculating allocation size.
Bug: 27855419
Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd
CWE ID: CWE-119
|
H264SwDecRet H264SwDecInit(H264SwDecInst *decInst, u32 noOutputReordering)
{
u32 rv = 0;
decContainer_t *pDecCont;
DEC_API_TRC("H264SwDecInit#");
/* check that right shift on negative numbers is performed signed */
/*lint -save -e* following check causes multiple lint messages */
if ( ((-1)>>1) != (-1) )
{
DEC_API_TRC("H264SwDecInit# ERROR: Right shift is not signed");
return(H264SWDEC_INITFAIL);
}
/*lint -restore */
if (decInst == NULL)
{
DEC_API_TRC("H264SwDecInit# ERROR: decInst == NULL");
return(H264SWDEC_PARAM_ERR);
}
pDecCont = (decContainer_t *)H264SwDecMalloc(sizeof(decContainer_t), 1);
if (pDecCont == NULL)
{
DEC_API_TRC("H264SwDecInit# ERROR: Memory allocation failed");
return(H264SWDEC_MEMFAIL);
}
#ifdef H264DEC_TRACE
sprintf(pDecCont->str, "H264SwDecInit# decInst %p noOutputReordering %d",
(void*)decInst, noOutputReordering);
DEC_API_TRC(pDecCont->str);
#endif
rv = h264bsdInit(&pDecCont->storage, noOutputReordering);
if (rv != HANTRO_OK)
{
H264SwDecRelease(pDecCont);
return(H264SWDEC_MEMFAIL);
}
pDecCont->decStat = INITIALIZED;
pDecCont->picNumber = 0;
#ifdef H264DEC_TRACE
sprintf(pDecCont->str, "H264SwDecInit# OK: return %p", (void*)pDecCont);
DEC_API_TRC(pDecCont->str);
#endif
*decInst = (decContainer_t *)pDecCont;
return(H264SWDEC_OK);
}
| 173,874
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int ssl3_get_new_session_ticket(SSL *s)
{
int ok, al, ret = 0, ticklen;
long n;
const unsigned char *p;
unsigned char *d;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_SESSION_TICKET_A,
SSL3_ST_CR_SESSION_TICKET_B,
SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
if (!ok)
return ((int)n);
if (n < 6) {
/* need at least ticket_lifetime_hint + ticket length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
p = d = (unsigned char *)s->init_msg;
n2l(p, s->session->tlsext_tick_lifetime_hint);
n2s(p, ticklen);
/* ticket_lifetime_hint + ticket_length + ticket */
if (ticklen + 6 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
OPENSSL_free(s->session->tlsext_tick);
s->session->tlsext_ticklen = 0;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick) {
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(s->session->tlsext_tick, p, ticklen);
s->session->tlsext_ticklen = ticklen;
/*
* There are two ways to detect a resumed ticket session. One is to set
* an appropriate session ID and then the server must return a match in
* ServerHello. This allows the normal client session ID matching to work
* and we know much earlier that the ticket has been accepted. The
* other way is to set zero length session ID when the ticket is
* presented and rely on the handshake to determine session resumption.
* We choose the former approach because this fits in with assumptions
* elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
* SHA256 is disabled) hash of the ticket.
*/
EVP_Digest(p, ticklen,
s->session->session_id, &s->session->session_id_length,
EVP_sha256(), NULL);
ret = 1;
return (ret);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
return (-1);
}
Commit Message: Fix race condition in NewSessionTicket
If a NewSessionTicket is received by a multi-threaded client when
attempting to reuse a previous ticket then a race condition can occur
potentially leading to a double free of the ticket data.
CVE-2015-1791
This also fixes RT#3808 where a session ID is changed for a session already
in the client session cache. Since the session ID is the key to the cache
this breaks the cache access.
Parts of this patch were inspired by this Akamai change:
https://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3
Reviewed-by: Rich Salz <rsalz@openssl.org>
CWE ID: CWE-362
|
int ssl3_get_new_session_ticket(SSL *s)
{
int ok, al, ret = 0, ticklen;
long n;
const unsigned char *p;
unsigned char *d;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_SESSION_TICKET_A,
SSL3_ST_CR_SESSION_TICKET_B,
SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
if (!ok)
return ((int)n);
if (n < 6) {
/* need at least ticket_lifetime_hint + ticket length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
p = d = (unsigned char *)s->init_msg;
if (s->session->session_id_length > 0) {
int i = s->session_ctx->session_cache_mode;
SSL_SESSION *new_sess;
/*
* We reused an existing session, so we need to replace it with a new
* one
*/
if (i & SSL_SESS_CACHE_CLIENT) {
/*
* Remove the old session from the cache
*/
if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
if (s->session_ctx->remove_session_cb != NULL)
s->session_ctx->remove_session_cb(s->session_ctx,
s->session);
} else {
/* We carry on if this fails */
SSL_CTX_remove_session(s->session_ctx, s->session);
}
}
if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto f_err;
}
SSL_SESSION_free(s->session);
s->session = new_sess;
}
n2l(p, s->session->tlsext_tick_lifetime_hint);
n2s(p, ticklen);
/* ticket_lifetime_hint + ticket_length + ticket */
if (ticklen + 6 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
OPENSSL_free(s->session->tlsext_tick);
s->session->tlsext_ticklen = 0;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick) {
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(s->session->tlsext_tick, p, ticklen);
s->session->tlsext_ticklen = ticklen;
/*
* There are two ways to detect a resumed ticket session. One is to set
* an appropriate session ID and then the server must return a match in
* ServerHello. This allows the normal client session ID matching to work
* and we know much earlier that the ticket has been accepted. The
* other way is to set zero length session ID when the ticket is
* presented and rely on the handshake to determine session resumption.
* We choose the former approach because this fits in with assumptions
* elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
* SHA256 is disabled) hash of the ticket.
*/
EVP_Digest(p, ticklen,
s->session->session_id, &s->session->session_id_length,
EVP_sha256(), NULL);
ret = 1;
return (ret);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
return (-1);
}
| 166,691
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(DirectoryIterator, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0');
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(DirectoryIterator, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0');
}
| 167,030
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: pax_decode_header (struct tar_sparse_file *file)
{
if (file->stat_info->sparse_major > 0)
{
uintmax_t u;
char nbuf[UINTMAX_STRSIZE_BOUND];
union block *blk;
char *p;
size_t i;
off_t start;
#define COPY_BUF(b,buf,src) do \
{ \
char *endp = b->buffer + BLOCKSIZE; \
char *dst = buf; \
do \
{ \
if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \
{ \
ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \
file->stat_info->orig_file_name)); \
return false; \
} \
if (src == endp) \
{ \
set_next_block_after (b); \
b = find_next_block (); \
src = b->buffer; \
endp = b->buffer + BLOCKSIZE; \
} \
while (*dst++ != '\n'); \
dst[-1] = 0; \
} while (0)
start = current_block_ordinal ();
set_next_block_after (current_header);
start = current_block_ordinal ();
set_next_block_after (current_header);
blk = find_next_block ();
p = blk->buffer;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))
}
file->stat_info->sparse_map_size = u;
file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,
sizeof (*file->stat_info->sparse_map));
file->stat_info->sparse_map_avail = 0;
for (i = 0; i < file->stat_info->sparse_map_size; i++)
{
struct sp_array sp;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.offset = u;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.numbytes = u;
sparse_add_map (file->stat_info, &sp);
}
set_next_block_after (blk);
file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);
}
return true;
}
Commit Message:
CWE ID: CWE-476
|
pax_decode_header (struct tar_sparse_file *file)
{
if (file->stat_info->sparse_major > 0)
{
uintmax_t u;
char nbuf[UINTMAX_STRSIZE_BOUND];
union block *blk;
char *p;
size_t i;
off_t start;
#define COPY_BUF(b,buf,src) do \
{ \
char *endp = b->buffer + BLOCKSIZE; \
char *dst = buf; \
do \
{ \
if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \
{ \
ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \
file->stat_info->orig_file_name)); \
return false; \
} \
if (src == endp) \
{ \
set_next_block_after (b); \
b = find_next_block (); \
if (!b) \
FATAL_ERROR ((0, 0, _("Unexpected EOF in archive"))); \
src = b->buffer; \
endp = b->buffer + BLOCKSIZE; \
} \
while (*dst++ != '\n'); \
dst[-1] = 0; \
} while (0)
start = current_block_ordinal ();
set_next_block_after (current_header);
start = current_block_ordinal ();
set_next_block_after (current_header);
blk = find_next_block ();
if (!blk)
FATAL_ERROR ((0, 0, _("Unexpected EOF in archive")));
p = blk->buffer;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))
}
file->stat_info->sparse_map_size = u;
file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,
sizeof (*file->stat_info->sparse_map));
file->stat_info->sparse_map_avail = 0;
for (i = 0; i < file->stat_info->sparse_map_size; i++)
{
struct sp_array sp;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.offset = u;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.numbytes = u;
sparse_add_map (file->stat_info, &sp);
}
set_next_block_after (blk);
file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);
}
return true;
}
| 164,776
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void NetworkHandler::ClearBrowserCache(
std::unique_ptr<ClearBrowserCacheCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
content::BrowsingDataRemover* remover =
content::BrowserContext::GetBrowsingDataRemover(
process_->GetBrowserContext());
remover->RemoveAndReply(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_CACHE,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
new DevtoolsClearCacheObserver(remover, std::move(callback)));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void NetworkHandler::ClearBrowserCache(
std::unique_ptr<ClearBrowserCacheCallback> callback) {
if (!browser_context_) {
callback->sendFailure(Response::InternalError());
return;
}
content::BrowsingDataRemover* remover =
content::BrowserContext::GetBrowsingDataRemover(browser_context_);
remover->RemoveAndReply(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_CACHE,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
new DevtoolsClearCacheObserver(remover, std::move(callback)));
}
| 172,752
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
if (val > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
return val;
}
Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258
CWE ID: CWE-125
|
read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
if (val > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
return val;
}
| 169,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: void usage()
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: pnm2png [options] <file>.<pnm> [<file>.png]\n");
fprintf (stderr, " or: ... | pnm2png [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -i[nterlace] write png-file with interlacing on\n");
fprintf (stderr, " -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
void usage()
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: pnm2png [options] <file>.<pnm> [<file>.png]\n");
fprintf (stderr, " or: ... | pnm2png [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -i[nterlace] write png-file with interlacing on\n");
fprintf (stderr,
" -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
| 173,726
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 svc_rdma_req_map *alloc_req_map(gfp_t flags)
{
struct svc_rdma_req_map *map;
map = kmalloc(sizeof(*map), flags);
if (map)
INIT_LIST_HEAD(&map->free);
return map;
}
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
|
static struct svc_rdma_req_map *alloc_req_map(gfp_t flags)
| 168,177
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE omx_vdec::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount;
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR:ETB Buffer is NULL");
return OMX_ErrorBadParameter;
}
if (!m_inp_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:ETB incorrect state operation, input port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
if (buffer->nInputPortIndex != OMX_CORE_INPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:ETB invalid port in header %u", (unsigned int)buffer->nInputPortIndex);
return OMX_ErrorBadPortIndex;
}
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
OMX_ERRORTYPE drmErr = iDivXDrmDecrypt->Decrypt(buffer);
if (drmErr != OMX_ErrorNone) {
DEBUG_PRINT_LOW("ERROR:iDivXDrmDecrypt->Decrypt %d", drmErr);
}
}
#endif //_ANDROID_
if (perf_flag) {
if (!latency) {
dec_time.stop();
latency = dec_time.processing_time_us();
dec_time.start();
}
}
if (arbitrary_bytes) {
nBufferIndex = buffer - m_inp_heap_ptr;
} else {
if (input_use_buffer == true) {
nBufferIndex = buffer - m_inp_heap_ptr;
m_inp_mem_ptr[nBufferIndex].nFilledLen = m_inp_heap_ptr[nBufferIndex].nFilledLen;
m_inp_mem_ptr[nBufferIndex].nTimeStamp = m_inp_heap_ptr[nBufferIndex].nTimeStamp;
m_inp_mem_ptr[nBufferIndex].nFlags = m_inp_heap_ptr[nBufferIndex].nFlags;
buffer = &m_inp_mem_ptr[nBufferIndex];
DEBUG_PRINT_LOW("Non-Arbitrary mode - buffer address is: malloc %p, pmem%p in Index %d, buffer %p of size %u",
&m_inp_heap_ptr[nBufferIndex], &m_inp_mem_ptr[nBufferIndex],nBufferIndex, buffer, (unsigned int)buffer->nFilledLen);
} else {
nBufferIndex = buffer - m_inp_mem_ptr;
}
}
if (nBufferIndex > drv_ctx.ip_buf.actualcount ) {
DEBUG_PRINT_ERROR("ERROR:ETB nBufferIndex is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
codec_config_flag = true;
DEBUG_PRINT_LOW("%s: codec_config buffer", __FUNCTION__);
}
DEBUG_PRINT_LOW("[ETB] BHdr(%p) pBuf(%p) nTS(%lld) nFL(%u)",
buffer, buffer->pBuffer, buffer->nTimeStamp, (unsigned int)buffer->nFilledLen);
if (arbitrary_bytes) {
post_event ((unsigned long)hComp,(unsigned long)buffer,
OMX_COMPONENT_GENERATE_ETB_ARBITRARY);
} else {
post_event ((unsigned long)hComp,(unsigned long)buffer,OMX_COMPONENT_GENERATE_ETB);
}
time_stamp_dts.insert_timestamp(buffer);
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID:
|
OMX_ERRORTYPE omx_vdec::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount;
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR:ETB Buffer is NULL");
return OMX_ErrorBadParameter;
}
if (!m_inp_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:ETB incorrect state operation, input port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
if (buffer->nInputPortIndex != OMX_CORE_INPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:ETB invalid port in header %u", (unsigned int)buffer->nInputPortIndex);
return OMX_ErrorBadPortIndex;
}
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
OMX_ERRORTYPE drmErr = iDivXDrmDecrypt->Decrypt(buffer);
if (drmErr != OMX_ErrorNone) {
DEBUG_PRINT_LOW("ERROR:iDivXDrmDecrypt->Decrypt %d", drmErr);
}
}
#endif //_ANDROID_
if (perf_flag) {
if (!latency) {
dec_time.stop();
latency = dec_time.processing_time_us();
dec_time.start();
}
}
if (arbitrary_bytes) {
nBufferIndex = buffer - m_inp_heap_ptr;
} else {
if (input_use_buffer == true) {
nBufferIndex = buffer - m_inp_heap_ptr;
m_inp_mem_ptr[nBufferIndex].nFilledLen = m_inp_heap_ptr[nBufferIndex].nFilledLen;
m_inp_mem_ptr[nBufferIndex].nTimeStamp = m_inp_heap_ptr[nBufferIndex].nTimeStamp;
m_inp_mem_ptr[nBufferIndex].nFlags = m_inp_heap_ptr[nBufferIndex].nFlags;
buffer = &m_inp_mem_ptr[nBufferIndex];
DEBUG_PRINT_LOW("Non-Arbitrary mode - buffer address is: malloc %p, pmem%p in Index %d, buffer %p of size %u",
&m_inp_heap_ptr[nBufferIndex], &m_inp_mem_ptr[nBufferIndex],nBufferIndex, buffer, (unsigned int)buffer->nFilledLen);
} else {
nBufferIndex = buffer - m_inp_mem_ptr;
}
}
if (nBufferIndex > drv_ctx.ip_buf.actualcount ) {
DEBUG_PRINT_ERROR("ERROR:ETB nBufferIndex is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
codec_config_flag = true;
DEBUG_PRINT_LOW("%s: codec_config buffer", __FUNCTION__);
}
DEBUG_PRINT_LOW("[ETB] BHdr(%p) pBuf(%p) nTS(%lld) nFL(%u)",
buffer, buffer->pBuffer, buffer->nTimeStamp, (unsigned int)buffer->nFilledLen);
if (arbitrary_bytes) {
post_event ((unsigned long)hComp,(unsigned long)buffer,
OMX_COMPONENT_GENERATE_ETB_ARBITRARY);
} else {
post_event ((unsigned long)hComp,(unsigned long)buffer,OMX_COMPONENT_GENERATE_ETB);
}
time_stamp_dts.insert_timestamp(buffer);
return OMX_ErrorNone;
}
| 173,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 long vbg_misc_device_ioctl(struct file *filp, unsigned int req,
unsigned long arg)
{
struct vbg_session *session = filp->private_data;
size_t returned_size, size;
struct vbg_ioctl_hdr hdr;
bool is_vmmdev_req;
int ret = 0;
void *buf;
if (copy_from_user(&hdr, (void *)arg, sizeof(hdr)))
return -EFAULT;
if (hdr.version != VBG_IOCTL_HDR_VERSION)
return -EINVAL;
if (hdr.size_in < sizeof(hdr) ||
(hdr.size_out && hdr.size_out < sizeof(hdr)))
return -EINVAL;
size = max(hdr.size_in, hdr.size_out);
if (_IOC_SIZE(req) && _IOC_SIZE(req) != size)
return -EINVAL;
if (size > SZ_16M)
return -E2BIG;
/*
* IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid
* the need for a bounce-buffer and another copy later on.
*/
is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) ||
req == VBG_IOCTL_VMMDEV_REQUEST_BIG;
if (is_vmmdev_req)
buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT);
else
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (copy_from_user(buf, (void *)arg, hdr.size_in)) {
ret = -EFAULT;
goto out;
}
if (hdr.size_in < size)
memset(buf + hdr.size_in, 0, size - hdr.size_in);
ret = vbg_core_ioctl(session, req, buf);
if (ret)
goto out;
returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out;
if (returned_size > size) {
vbg_debug("%s: too much output data %zu > %zu\n",
__func__, returned_size, size);
returned_size = size;
}
if (copy_to_user((void *)arg, buf, returned_size) != 0)
ret = -EFAULT;
out:
if (is_vmmdev_req)
vbg_req_free(buf, size);
else
kfree(buf);
return ret;
}
Commit Message: virt: vbox: Only copy_from_user the request-header once
In vbg_misc_device_ioctl(), the header of the ioctl argument is copied from
the userspace pointer 'arg' and saved to the kernel object 'hdr'. Then the
'version', 'size_in', and 'size_out' fields of 'hdr' are verified.
Before this commit, after the checks a buffer for the entire request would
be allocated and then all data including the verified header would be
copied from the userspace 'arg' pointer again.
Given that the 'arg' pointer resides in userspace, a malicious userspace
process can race to change the data pointed to by 'arg' between the two
copies. By doing so, the user can bypass the verifications on the ioctl
argument.
This commit fixes this by using the already checked copy of the header
to fill the header part of the allocated buffer and only copying the
remainder of the data from userspace.
Signed-off-by: Wenwen Wang <wang6495@umn.edu>
Reviewed-by: Hans de Goede <hdegoede@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-362
|
static long vbg_misc_device_ioctl(struct file *filp, unsigned int req,
unsigned long arg)
{
struct vbg_session *session = filp->private_data;
size_t returned_size, size;
struct vbg_ioctl_hdr hdr;
bool is_vmmdev_req;
int ret = 0;
void *buf;
if (copy_from_user(&hdr, (void *)arg, sizeof(hdr)))
return -EFAULT;
if (hdr.version != VBG_IOCTL_HDR_VERSION)
return -EINVAL;
if (hdr.size_in < sizeof(hdr) ||
(hdr.size_out && hdr.size_out < sizeof(hdr)))
return -EINVAL;
size = max(hdr.size_in, hdr.size_out);
if (_IOC_SIZE(req) && _IOC_SIZE(req) != size)
return -EINVAL;
if (size > SZ_16M)
return -E2BIG;
/*
* IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid
* the need for a bounce-buffer and another copy later on.
*/
is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) ||
req == VBG_IOCTL_VMMDEV_REQUEST_BIG;
if (is_vmmdev_req)
buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT);
else
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
*((struct vbg_ioctl_hdr *)buf) = hdr;
if (copy_from_user(buf + sizeof(hdr), (void *)arg + sizeof(hdr),
hdr.size_in - sizeof(hdr))) {
ret = -EFAULT;
goto out;
}
if (hdr.size_in < size)
memset(buf + hdr.size_in, 0, size - hdr.size_in);
ret = vbg_core_ioctl(session, req, buf);
if (ret)
goto out;
returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out;
if (returned_size > size) {
vbg_debug("%s: too much output data %zu > %zu\n",
__func__, returned_size, size);
returned_size = size;
}
if (copy_to_user((void *)arg, buf, returned_size) != 0)
ret = -EFAULT;
out:
if (is_vmmdev_req)
vbg_req_free(buf, size);
else
kfree(buf);
return ret;
}
| 169,188
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled)
{
zval *IM, *POINTS;
long NPOINTS, COL;
zval **var = NULL;
gdImagePtr im;
gdPointPtr points;
int npoints, col, nelem, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
npoints = NPOINTS;
col = COL;
nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS));
if (nelem < 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array");
RETURN_FALSE;
}
if (npoints <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points");
RETURN_FALSE;
}
if (nelem < npoints * 2) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2);
RETURN_FALSE;
}
points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0);
for (i = 0; i < npoints; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) {
SEPARATE_ZVAL((var));
convert_to_long(*var);
points[i].x = Z_LVAL_PP(var);
}
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) {
SEPARATE_ZVAL(var);
convert_to_long(*var);
points[i].y = Z_LVAL_PP(var);
}
}
if (filled) {
gdImageFilledPolygon(im, points, npoints, col);
} else {
gdImagePolygon(im, points, npoints, col);
}
efree(points);
RETURN_TRUE;
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189
|
static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled)
{
zval *IM, *POINTS;
long NPOINTS, COL;
zval **var = NULL;
gdImagePtr im;
gdPointPtr points;
int npoints, col, nelem, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
npoints = NPOINTS;
col = COL;
nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS));
if (nelem < 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array");
RETURN_FALSE;
}
if (npoints <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points");
RETURN_FALSE;
}
if (nelem < npoints * 2) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2);
RETURN_FALSE;
}
points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0);
for (i = 0; i < npoints; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) {
if (Z_TYPE_PP(var) != IS_LONG) {
zval lval;
lval = **var;
zval_copy_ctor(&lval);
convert_to_long(&lval);
points[i].x = Z_LVAL(lval);
} else {
points[i].x = Z_LVAL_PP(var);
}
}
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) {
if (Z_TYPE_PP(var) != IS_LONG) {
zval lval;
lval = **var;
zval_copy_ctor(&lval);
convert_to_long(&lval);
points[i].y = Z_LVAL(lval);
} else {
points[i].y = Z_LVAL_PP(var);
}
}
}
if (filled) {
gdImageFilledPolygon(im, points, npoints, col);
} else {
gdImagePolygon(im, points, npoints, col);
}
efree(points);
RETURN_TRUE;
}
| 166,431
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 QuicStreamHost::Finish() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(p2p_stream_);
p2p_stream_->Finish();
writeable_ = false;
if (!readable_ && !writeable_) {
Delete();
}
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <shampson@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
|
void QuicStreamHost::Finish() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(p2p_stream_);
std::vector<uint8_t> data;
p2p_stream_->WriteData(data, true);
writeable_ = false;
if (!readable_ && !writeable_) {
Delete();
}
}
| 172,269
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: zlib_run(struct zlib *zlib)
/* Like zlib_advance but also handles a stream of IDAT chunks. */
{
/* The 'extra_bytes' field is set by zlib_advance if there is extra
* compressed data in the chunk it handles (if it sees Z_STREAM_END before
* all the input data has been used.) This function uses the value to update
* the correct chunk length, so the problem should only ever be detected once
* for each chunk. zlib_advance outputs the error message, though see the
* IDAT specific check below.
*/
zlib->extra_bytes = 0;
if (zlib->idat != NULL)
{
struct IDAT_list *list = zlib->idat->idat_list_head;
struct IDAT_list *last = zlib->idat->idat_list_tail;
int skip = 0;
/* 'rewrite_offset' is the offset of the LZ data within the chunk, for
* IDAT it should be 0:
*/
assert(zlib->rewrite_offset == 0);
/* Process each IDAT_list in turn; the caller has left the stream
* positioned at the start of the first IDAT chunk data.
*/
for (;;)
{
const unsigned int count = list->count;
unsigned int i;
for (i = 0; i<count; ++i)
{
int rc;
if (skip > 0) /* Skip CRC and next IDAT header */
skip_12(zlib->file);
skip = 12; /* for the next time */
rc = zlib_advance(zlib, list->lengths[i]);
switch (rc)
{
case ZLIB_OK: /* keep going */
break;
case ZLIB_STREAM_END: /* stop */
/* There may be extra chunks; if there are and one of them is
* not zero length output the 'extra data' message. Only do
* this check if errors are being output.
*/
if (zlib->global->errors && zlib->extra_bytes == 0)
{
struct IDAT_list *check = list;
int j = i+1, jcount = count;
for (;;)
{
for (; j<jcount; ++j)
if (check->lengths[j] > 0)
{
chunk_message(zlib->chunk,
"extra compressed data");
goto end_check;
}
if (check == last)
break;
check = check->next;
jcount = check->count;
j = 0;
}
}
end_check:
/* Terminate the list at the current position, reducing the
* length of the last IDAT too if required.
*/
list->lengths[i] -= zlib->extra_bytes;
list->count = i+1;
zlib->idat->idat_list_tail = list;
/* FALL THROUGH */
default:
return rc;
}
}
/* At the end of the compressed data and Z_STREAM_END was not seen. */
if (list == last)
return ZLIB_OK;
list = list->next;
}
}
else
{
struct chunk *chunk = zlib->chunk;
int rc;
assert(zlib->rewrite_offset < chunk->chunk_length);
rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset);
/* The extra bytes in the chunk are handled now by adjusting the chunk
* length to exclude them; the zlib data is always stored at the end of
* the PNG chunk (although clearly this is not necessary.) zlib_advance
* has already output a warning message.
*/
chunk->chunk_length -= zlib->extra_bytes;
return rc;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
zlib_run(struct zlib *zlib)
/* Like zlib_advance but also handles a stream of IDAT chunks. */
{
/* The 'extra_bytes' field is set by zlib_advance if there is extra
* compressed data in the chunk it handles (if it sees Z_STREAM_END before
* all the input data has been used.) This function uses the value to update
* the correct chunk length, so the problem should only ever be detected once
* for each chunk. zlib_advance outputs the error message, though see the
* IDAT specific check below.
*/
zlib->extra_bytes = 0;
if (zlib->idat != NULL)
{
struct IDAT_list *list = zlib->idat->idat_list_head;
struct IDAT_list *last = zlib->idat->idat_list_tail;
int skip = 0;
/* 'rewrite_offset' is the offset of the LZ data within the chunk, for
* IDAT it should be 0:
*/
assert(zlib->rewrite_offset == 0);
/* Process each IDAT_list in turn; the caller has left the stream
* positioned at the start of the first IDAT chunk data.
*/
for (;;)
{
const unsigned int count = list->count;
unsigned int i;
for (i = 0; i<count; ++i)
{
int rc;
if (skip > 0) /* Skip CRC and next IDAT header */
skip_12(zlib->file);
skip = 12; /* for the next time */
rc = zlib_advance(zlib, list->lengths[i]);
switch (rc)
{
case ZLIB_OK: /* keep going */
break;
case ZLIB_STREAM_END: /* stop */
/* There may be extra chunks; if there are and one of them is
* not zero length output the 'extra data' message. Only do
* this check if errors are being output.
*/
if (zlib->global->errors && zlib->extra_bytes == 0)
{
struct IDAT_list *check = list;
int j = i+1, jcount = count;
for (;;)
{
for (; j<jcount; ++j)
if (check->lengths[j] > 0)
{
chunk_message(zlib->chunk,
"extra compressed data");
goto end_check;
}
if (check == last)
break;
check = check->next;
jcount = check->count;
j = 0;
}
}
end_check:
/* Terminate the list at the current position, reducing the
* length of the last IDAT too if required.
*/
list->lengths[i] -= zlib->extra_bytes;
list->count = i+1;
zlib->idat->idat_list_tail = list;
/* FALL THROUGH */
default:
return rc;
}
}
/* At the end of the compressed data and Z_STREAM_END was not seen. */
if (list == last)
return ZLIB_OK;
list = list->next;
}
}
else
{
struct chunk *chunk = zlib->chunk;
int rc;
assert(zlib->rewrite_offset < chunk->chunk_length);
rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset);
/* The extra bytes in the chunk are handled now by adjusting the chunk
* length to exclude them; the zlib data is always stored at the end of
* the PNG chunk (although clearly this is not necessary.) zlib_advance
* has already output a warning message.
*/
chunk->chunk_length -= zlib->extra_bytes;
return rc;
}
}
| 173,743
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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() {
url_util::AddStandardScheme("tabcontentstest");
old_browser_client_ = content::GetContentClient()->browser();
content::GetContentClient()->set_browser(&browser_client_);
RenderViewHostTestHarness::SetUp();
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
virtual void SetUp() {
url_util::AddStandardScheme("tabcontentstest");
old_client_ = content::GetContentClient();
content::SetContentClient(&client_);
old_browser_client_ = content::GetContentClient()->browser();
content::GetContentClient()->set_browser(&browser_client_);
RenderViewHostTestHarness::SetUp();
}
| 171,014
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IsIDNComponentSafe(base::StringPiece16 label) {
return g_idn_spoof_checker.Get().Check(label);
}
Commit Message: Block domain labels made of Cyrillic letters that look alike Latin
Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф.
BUG=683314
TEST=components_unittests --gtest_filter=U*IDN*
Review-Url: https://codereview.chromium.org/2683793010
Cr-Commit-Position: refs/heads/master@{#459226}
CWE ID: CWE-20
|
bool IsIDNComponentSafe(base::StringPiece16 label) {
bool IsIDNComponentSafe(base::StringPiece16 label, bool is_tld_ascii) {
return g_idn_spoof_checker.Get().Check(label, is_tld_ascii);
}
| 172,392
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: server_request_direct_streamlocal(void)
{
Channel *c = NULL;
char *target, *originator;
u_short originator_port;
target = packet_get_string(NULL);
originator = packet_get_string(NULL);
originator_port = packet_get_int();
packet_check_eom();
debug("server_request_direct_streamlocal: originator %s port %d, target %s",
originator, originator_port, target);
/* XXX fine grained permissions */
if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
!no_port_forwarding_flag && !options.disable_forwarding) {
c = channel_connect_to_path(target,
"direct-streamlocal@openssh.com", "direct-streamlocal");
} else {
logit("refused streamlocal port forward: "
"originator %s port %d, target %s",
originator, originator_port, target);
}
free(originator);
free(target);
return c;
}
Commit Message: disable Unix-domain socket forwarding when privsep is disabled
CWE ID: CWE-264
|
server_request_direct_streamlocal(void)
{
Channel *c = NULL;
char *target, *originator;
u_short originator_port;
target = packet_get_string(NULL);
originator = packet_get_string(NULL);
originator_port = packet_get_int();
packet_check_eom();
debug("server_request_direct_streamlocal: originator %s port %d, target %s",
originator, originator_port, target);
/* XXX fine grained permissions */
if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
!no_port_forwarding_flag && !options.disable_forwarding &&
use_privsep) {
c = channel_connect_to_path(target,
"direct-streamlocal@openssh.com", "direct-streamlocal");
} else {
logit("refused streamlocal port forward: "
"originator %s port %d, target %s",
originator, originator_port, target);
}
free(originator);
free(target);
return c;
}
| 168,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: static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125
|
static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,
++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
| 169,441
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const CuePoint* Cues::GetFirst() const {
if (m_cue_points == NULL)
return NULL;
if (m_count == 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
#endif
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[0];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
return pCP;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
const CuePoint* Cues::GetFirst() const {
if (m_cue_points == NULL || m_count == 0)
return NULL;
CuePoint* const* const pp = m_cue_points;
if (pp == NULL)
return NULL;
CuePoint* const pCP = pp[0];
if (pCP == NULL || pCP->GetTimeCode() < 0)
return NULL;
return pCP;
}
| 173,818
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ip6t_entry *)e);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
CWE ID: CWE-119
|
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ip6t_entry *)e);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
| 167,213
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.