instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcSendEvent(ClientPtr client) { WindowPtr pWin; WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ DeviceIntPtr dev = PickPointer(client); DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD); SpritePtr pSprite = dev->spriteInfo->sprite; REQUEST(xSendEventReq); REQUEST_SIZE_MATCH(xSendEventReq); /* libXext and other extension libraries may set the bit indicating * that this event came from a SendEvent request so remove it * since otherwise the event type may fail the range checks * and cause an invalid BadValue error to be returned. * * This is safe to do since we later add the SendEvent bit (0x80) * back in once we send the event to the client */ stuff->event.u.u.type &= ~(SEND_EVENT_BIT); /* The client's event type must be a core event type or one defined by an extension. */ if (!((stuff->event.u.u.type > X_Reply && stuff->event.u.u.type < LASTEvent) || (stuff->event.u.u.type >= EXTENSION_EVENT_BASE && stuff->event.u.u.type < (unsigned) lastEvent))) { client->errorValue = stuff->event.u.u.type; return BadValue; } if (stuff->event.u.u.type == ClientMessage && stuff->event.u.u.detail != 8 && stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) { } if (stuff->destination == PointerWindow) pWin = pSprite->win; else if (stuff->destination == InputFocus) { WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin; if (inputFocus == NoneWin) return Success; /* If the input focus is PointerRootWin, send the event to where the pointer is if possible, then perhaps propogate up to root. */ if (inputFocus == PointerRootWin) inputFocus = GetCurrentRootWindow(dev); if (IsParent(inputFocus, pSprite->win)) { effectiveFocus = inputFocus; pWin = pSprite->win; } else effectiveFocus = pWin = inputFocus; } else dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess); if (!pWin) return BadWindow; if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) { client->errorValue = stuff->propagate; return BadValue; } stuff->event.u.u.type |= SEND_EVENT_BIT; if (stuff->propagate) { for (; pWin; pWin = pWin->parent) { if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) return Success; if (DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab)) return Success; if (pWin == effectiveFocus) return Success; stuff->eventMask &= ~wDontPropagateMask(pWin); if (!stuff->eventMask) break; } } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab); return Success; } Commit Message: CWE ID: CWE-119
ProcSendEvent(ClientPtr client) { WindowPtr pWin; WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ DeviceIntPtr dev = PickPointer(client); DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD); SpritePtr pSprite = dev->spriteInfo->sprite; REQUEST(xSendEventReq); REQUEST_SIZE_MATCH(xSendEventReq); /* libXext and other extension libraries may set the bit indicating * that this event came from a SendEvent request so remove it * since otherwise the event type may fail the range checks * and cause an invalid BadValue error to be returned. * * This is safe to do since we later add the SendEvent bit (0x80) * back in once we send the event to the client */ stuff->event.u.u.type &= ~(SEND_EVENT_BIT); /* The client's event type must be a core event type or one defined by an extension. */ if (!((stuff->event.u.u.type > X_Reply && stuff->event.u.u.type < LASTEvent) || (stuff->event.u.u.type >= EXTENSION_EVENT_BASE && stuff->event.u.u.type < (unsigned) lastEvent))) { client->errorValue = stuff->event.u.u.type; return BadValue; } /* Generic events can have variable size, but SendEvent request holds exactly 32B of event data. */ if (stuff->event.u.u.type == GenericEvent) { client->errorValue = stuff->event.u.u.type; return BadValue; } if (stuff->event.u.u.type == ClientMessage && stuff->event.u.u.detail != 8 && stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) { } if (stuff->destination == PointerWindow) pWin = pSprite->win; else if (stuff->destination == InputFocus) { WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin; if (inputFocus == NoneWin) return Success; /* If the input focus is PointerRootWin, send the event to where the pointer is if possible, then perhaps propogate up to root. */ if (inputFocus == PointerRootWin) inputFocus = GetCurrentRootWindow(dev); if (IsParent(inputFocus, pSprite->win)) { effectiveFocus = inputFocus; pWin = pSprite->win; } else effectiveFocus = pWin = inputFocus; } else dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess); if (!pWin) return BadWindow; if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) { client->errorValue = stuff->propagate; return BadValue; } stuff->event.u.u.type |= SEND_EVENT_BIT; if (stuff->propagate) { for (; pWin; pWin = pWin->parent) { if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) return Success; if (DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab)) return Success; if (pWin == effectiveFocus) return Success; stuff->eventMask &= ~wDontPropagateMask(pWin); if (!stuff->eventMask) break; } } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab); return Success; }
164,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->pos + count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; } Commit Message: CWE ID: CWE-20
FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->size - stream->pos < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; }
164,986
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InternalWebIntentsDispatcherTest() { replied_ = 0; } Commit Message: Fix uninitialized member in ctor. [email protected] [email protected] BUG=none TEST=none Review URL: https://chromiumcodereview.appspot.com/10377180 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137606 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
InternalWebIntentsDispatcherTest() { InternalWebIntentsDispatcherTest() : replied_(0), notified_reply_type_(webkit_glue::WEB_INTENT_REPLY_INVALID) { }
170,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RendererSchedulerImpl::OnShutdownTaskQueue( const scoped_refptr<MainThreadTaskQueue>& task_queue) { if (main_thread_only().was_shutdown) return; if (task_queue_throttler_) task_queue_throttler_->ShutdownTaskQueue(task_queue.get()); if (task_runners_.erase(task_queue)) { switch (task_queue->queue_class()) { case MainThreadTaskQueue::QueueClass::kTimer: task_queue->RemoveTaskObserver( &main_thread_only().timer_task_cost_estimator); case MainThreadTaskQueue::QueueClass::kLoading: task_queue->RemoveTaskObserver( &main_thread_only().loading_task_cost_estimator); default: break; } } } Commit Message: [scheduler] Remove implicit fallthrough in switch Bail out early when a condition in the switch is fulfilled. This does not change behaviour due to RemoveTaskObserver being no-op when the task observer is not present in the list. [email protected] Bug: 177475 Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd Reviewed-on: https://chromium-review.googlesource.com/891187 Reviewed-by: Nico Weber <[email protected]> Commit-Queue: Alexander Timin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532649} CWE ID: CWE-119
void RendererSchedulerImpl::OnShutdownTaskQueue( const scoped_refptr<MainThreadTaskQueue>& task_queue) { if (main_thread_only().was_shutdown) return; if (task_queue_throttler_) task_queue_throttler_->ShutdownTaskQueue(task_queue.get()); if (task_runners_.erase(task_queue)) { switch (task_queue->queue_class()) { case MainThreadTaskQueue::QueueClass::kTimer: task_queue->RemoveTaskObserver( &main_thread_only().timer_task_cost_estimator); break; case MainThreadTaskQueue::QueueClass::kLoading: task_queue->RemoveTaskObserver( &main_thread_only().loading_task_cost_estimator); break; default: break; } } }
172,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 NsGetParameter(preproc_effect_t *effect, void *pParam, uint32_t *pValueSize, void *pValue) { int status = 0; return status; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int NsGetParameter(preproc_effect_t *effect, int NsGetParameter(preproc_effect_t *effect __unused, void *pParam __unused, uint32_t *pValueSize __unused, void *pValue __unused) { int status = 0; return status; }
173,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out, unsigned int *tag_out, size_t *taglen) { const u8 *p = *buf; size_t left = buflen, len; unsigned int cla, tag, i; if (left < 2) return SC_ERROR_INVALID_ASN1_OBJECT; *buf = NULL; if (*p == 0xff || *p == 0) { /* end of data reached */ *taglen = 0; *tag_out = SC_ASN1_TAG_EOC; return SC_SUCCESS; } /* parse tag byte(s) * Resulted tag is presented by integer that has not to be * confused with the 'tag number' part of ASN.1 tag. */ cla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED); tag = *p & SC_ASN1_TAG_PRIMITIVE; p++; left--; if (tag == SC_ASN1_TAG_PRIMITIVE) { /* high tag number */ size_t n = SC_ASN1_TAGNUM_SIZE - 1; /* search the last tag octet */ while (left-- != 0 && n != 0) { tag <<= 8; tag |= *p; if ((*p++ & 0x80) == 0) break; n--; } if (left == 0 || n == 0) /* either an invalid tag or it doesn't fit in * unsigned int */ return SC_ERROR_INVALID_ASN1_OBJECT; } /* parse length byte(s) */ len = *p & 0x7f; if (*p++ & 0x80) { unsigned int a = 0; if (len > 4 || len > left) return SC_ERROR_INVALID_ASN1_OBJECT; left -= len; for (i = 0; i < len; i++) { a <<= 8; a |= *p; p++; } len = a; } *cla_out = cla; *tag_out = tag; *taglen = len; *buf = p; if (len > left) return SC_ERROR_ASN1_END_OF_CONTENTS; return SC_SUCCESS; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
int sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out, unsigned int *tag_out, size_t *taglen) { const u8 *p = *buf; size_t left = buflen, len; unsigned int cla, tag, i; if (left < 2) return SC_ERROR_INVALID_ASN1_OBJECT; *buf = NULL; if (*p == 0xff || *p == 0) { /* end of data reached */ *taglen = 0; *tag_out = SC_ASN1_TAG_EOC; return SC_SUCCESS; } /* parse tag byte(s) * Resulted tag is presented by integer that has not to be * confused with the 'tag number' part of ASN.1 tag. */ cla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED); tag = *p & SC_ASN1_TAG_PRIMITIVE; p++; left--; if (tag == SC_ASN1_TAG_PRIMITIVE) { /* high tag number */ size_t n = SC_ASN1_TAGNUM_SIZE - 1; /* search the last tag octet */ while (left-- != 0 && n != 0) { tag <<= 8; tag |= *p; if ((*p++ & 0x80) == 0) break; n--; } if (left == 0 || n == 0) /* either an invalid tag or it doesn't fit in * unsigned int */ return SC_ERROR_INVALID_ASN1_OBJECT; } /* parse length byte(s) */ len = *p & 0x7f; if (*p++ & 0x80) { unsigned int a = 0; left--; if (len > 4 || len > left) return SC_ERROR_INVALID_ASN1_OBJECT; left -= len; for (i = 0; i < len; i++) { a <<= 8; a |= *p; p++; } len = a; } *cla_out = cla; *tag_out = tag; *taglen = len; *buf = p; if (len > left) return SC_ERROR_ASN1_END_OF_CONTENTS; return SC_SUCCESS; }
169,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> 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: mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 1); if (bp[hlen] & 0xf0) ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 2); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); } Commit Message: CVE-2017-13009/IPv6 mobility: Add a bounds check. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by the reporter(s). While we're at it: Add a comment giving the RFC for IPv6 mobility headers. Clean up some bounds checks to make it clearer what they're checking, by matching the subsequent EXTRACT_ calls or memcpy. For the binding update, if none of the flag bits are set, don't check the individual flag bits. CWE ID: CWE-125
mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK_16BITS(&bp[hlen]); if (bp[hlen] & 0xf0) { ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); } /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK_16BITS(&bp[hlen]); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); ND_TCHECK(mh->ip6m_data8[1]); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK_16BITS(&bp[hlen]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK_16BITS(&bp[hlen]); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(bp[hlen], 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); }
167,886
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric) { NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config); guint32 mtu = nm_ip4_config_get_mtu (config); int i; g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (config != NULL, FALSE); /* Addresses */ nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric); /* Routes */ { int count = nm_ip4_config_get_num_routes (config); GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count); const NMPlatformIP4Route *route; gboolean success; for (i = 0; i < count; i++) { route = nm_ip4_config_get_route (config, i); /* Don't add the route if it's more specific than one of the subnets * the device already has an IP address on. */ if ( route->gateway == 0 && nm_ip4_config_destination_is_direct (config, route->network, route->plen)) continue; g_array_append_vals (routes, route, 1); } success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes); g_array_unref (routes); return FALSE; } /* MTU */ if (mtu && mtu != nm_platform_link_get_mtu (ifindex)) nm_platform_link_set_mtu (ifindex, mtu); return TRUE; } Commit Message: CWE ID: CWE-20
nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric) { NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config); int i; g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (config != NULL, FALSE); /* Addresses */ nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric); /* Routes */ { int count = nm_ip4_config_get_num_routes (config); GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count); const NMPlatformIP4Route *route; gboolean success; for (i = 0; i < count; i++) { route = nm_ip4_config_get_route (config, i); /* Don't add the route if it's more specific than one of the subnets * the device already has an IP address on. */ if ( route->gateway == 0 && nm_ip4_config_destination_is_direct (config, route->network, route->plen)) continue; g_array_append_vals (routes, route, 1); } success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes); g_array_unref (routes); return FALSE; } return TRUE; }
164,815
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; void __user *p = (void __user *)arg; int error; SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, " "cmd=0x%x\n", disk->disk_name, cmd)); /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ error = scsi_nonblockable_ioctl(sdp, cmd, p, (mode & FMODE_NDELAY) != 0); if (!scsi_block_when_processing_errors(sdp) || !error) goto out; /* * Send SCSI addressing ioctls directly to mid level, send other * ioctls to block level and then onto mid level if they can't be * resolved. */ switch (cmd) { case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: error = scsi_ioctl(sdp, cmd, p); break; default: error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p); if (error != -ENOTTY) break; error = scsi_ioctl(sdp, cmd, p); break; } out: return error; } Commit Message: block: fail SCSI passthrough ioctls on partition devices Linux allows executing the SG_IO ioctl on a partition or LVM volume, and will pass the command to the underlying block device. This is well-known, but it is also a large security problem when (via Unix permissions, ACLs, SELinux or a combination thereof) a program or user needs to be granted access only to part of the disk. This patch lets partitions forward a small set of harmless ioctls; others are logged with printk so that we can see which ioctls are actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred. Of course it was being sent to a (partition on a) hard disk, so it would have failed with ENOTTY and the patch isn't changing anything in practice. Still, I'm treating it specially to avoid spamming the logs. In principle, this restriction should include programs running with CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and /dev/sdb, it still should not be able to read/write outside the boundaries of /dev/sda2 independent of the capabilities. However, for now programs with CAP_SYS_RAWIO will still be allowed to send the ioctls. Their actions will still be logged. This patch does not affect the non-libata IDE driver. That driver however already tests for bd != bd->bd_contains before issuing some ioctl; it could be restricted further to forbid these ioctls even for programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO. Cc: [email protected] Cc: Jens Axboe <[email protected]> Cc: James Bottomley <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> [ Make it also print the command name when warning - Linus ] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int sd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; void __user *p = (void __user *)arg; int error; SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, " "cmd=0x%x\n", disk->disk_name, cmd)); error = scsi_verify_blk_ioctl(bdev, cmd); if (error < 0) return error; /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ error = scsi_nonblockable_ioctl(sdp, cmd, p, (mode & FMODE_NDELAY) != 0); if (!scsi_block_when_processing_errors(sdp) || !error) goto out; /* * Send SCSI addressing ioctls directly to mid level, send other * ioctls to block level and then onto mid level if they can't be * resolved. */ switch (cmd) { case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: error = scsi_ioctl(sdp, cmd, p); break; default: error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p); if (error != -ENOTTY) break; error = scsi_ioctl(sdp, cmd, p); break; } out: return error; }
169,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: update_info_partition_on_linux_dmmp (Device *device) { const gchar *dm_name; const gchar* const *targets_type; const gchar* const *targets_params; gchar *params; gint linear_slave_major; gint linear_slave_minor; guint64 offset_sectors; Device *linear_slave; gchar *s; params = NULL; dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME"); if (dm_name == NULL) goto out; targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE"); if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0) goto out; goto out; params = decode_udev_encoded_string (targets_params[0]); if (sscanf (params, "%d:%d %" G_GUINT64_FORMAT, &linear_slave_major, &linear_slave_minor, &offset_sectors) != 3) goto out; linear_slave = daemon_local_find_by_dev (device->priv->daemon, makedev (linear_slave_major, linear_slave_minor)); if (linear_slave == NULL) goto out; if (!linear_slave->priv->device_is_linux_dmmp) goto out; /* The Partition* properties has been set as part of * update_info_partition() by reading UDISKS_PARTITION_* * properties.. so here we bascially just update the presentation * device file name and and whether the device is a drive. */ s = g_strdup_printf ("/dev/mapper/%s", dm_name); device_set_device_file_presentation (device, s); g_free (s); device_set_device_is_drive (device, FALSE); out: g_free (params); return TRUE; } Commit Message: CWE ID: CWE-200
update_info_partition_on_linux_dmmp (Device *device) { const gchar *dm_name; const gchar* const *targets_type; const gchar* const *targets_params; gchar *params; gint linear_slave_major; gint linear_slave_minor; guint64 offset_sectors; Device *linear_slave; gchar *s; params = NULL; dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME"); if (dm_name == NULL) goto out; targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE"); /* If we ever need this for other types than "linear", remember to update udisks-dm-export.c as well. */ if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0) goto out; goto out; params = decode_udev_encoded_string (targets_params[0]); if (sscanf (params, "%d:%d %" G_GUINT64_FORMAT, &linear_slave_major, &linear_slave_minor, &offset_sectors) != 3) goto out; linear_slave = daemon_local_find_by_dev (device->priv->daemon, makedev (linear_slave_major, linear_slave_minor)); if (linear_slave == NULL) goto out; if (!linear_slave->priv->device_is_linux_dmmp) goto out; /* The Partition* properties has been set as part of * update_info_partition() by reading UDISKS_PARTITION_* * properties.. so here we bascially just update the presentation * device file name and and whether the device is a drive. */ s = g_strdup_printf ("/dev/mapper/%s", dm_name); device_set_device_file_presentation (device, s); g_free (s); device_set_device_is_drive (device, FALSE); out: g_free (params); return TRUE; }
165,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 const SSL_METHOD *ssl23_get_client_method(int ver) { #ifndef OPENSSL_NO_SSL2 if (ver == SSL2_VERSION) return(SSLv2_client_method()); #endif if (ver == SSL3_VERSION) return(SSLv3_client_method()); else if (ver == TLS1_VERSION) return(TLSv1_client_method()); else if (ver == TLS1_1_VERSION) return(TLSv1_1_client_method()); else return(NULL); } Commit Message: CWE ID: CWE-310
static const SSL_METHOD *ssl23_get_client_method(int ver) { #ifndef OPENSSL_NO_SSL2 if (ver == SSL2_VERSION) return(SSLv2_client_method()); #endif #ifndef OPENSSL_NO_SSL3 if (ver == SSL3_VERSION) return(SSLv3_client_method()); #endif if (ver == TLS1_VERSION) return(TLSv1_client_method()); else if (ver == TLS1_1_VERSION) return(TLSv1_1_client_method()); else return(NULL); }
165,156
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MockPrinter::UpdateSettings(int cookie, PrintMsg_PrintPages_Params* params, const std::vector<int>& pages) { EXPECT_EQ(document_cookie_, cookie); params->Reset(); params->pages = pages; SetPrintParams(&(params->params)); printer_status_ = PRINTER_PRINTING; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MockPrinter::UpdateSettings(int cookie, PrintMsg_PrintPages_Params* params, const std::vector<int>& pages) { if (document_cookie_ == -1) { document_cookie_ = CreateDocumentCookie(); } params->Reset(); params->pages = pages; SetPrintParams(&(params->params)); printer_status_ = PRINTER_PRINTING; }
170,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jas_stream_pad(jas_stream_t *stream, int n, int c) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_putc(stream, c) == EOF) return n - m; } return n; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
int jas_stream_pad(jas_stream_t *stream, int n, int c) { int m; if (n < 0) { jas_deprecated("negative count for jas_stream_pad"); } m = n; for (m = n; m > 0; --m) { if (jas_stream_putc(stream, c) == EOF) return n - m; } return n; }
168,746
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bool unconditional(const struct arpt_arp *arp) { static const struct arpt_arp uncond; return memcmp(arp, &uncond, sizeof(uncond)) == 0; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
static inline bool unconditional(const struct arpt_arp *arp) static inline bool unconditional(const struct arpt_entry *e) { static const struct arpt_arp uncond; return e->target_offset == sizeof(struct arpt_entry) && memcmp(&e->arp, &uncond, sizeof(uncond)) == 0; }
167,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat) { struct file *file = kiocb->ki_filp; ssize_t ret = 0; switch (kiocb->ki_opcode) { case IOCB_CMD_PREAD: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITE: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PREADV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(READ, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITEV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(WRITE, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_FDSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fdsync; break; case IOCB_CMD_FSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fsync; break; default: dprintk("EINVAL: io_submit: no operation provided\n"); ret = -EINVAL; } if (!kiocb->ki_retry) return ret; return 0; } Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers We had for some reason overlooked the AIO interface, and it didn't use the proper rw_verify_area() helper function that checks (for example) mandatory locking on the file, and that the size of the access doesn't cause us to overflow the provided offset limits etc. Instead, AIO did just the security_file_permission() thing (that rw_verify_area() also does) directly. This fixes it to do all the proper helper functions, which not only means that now mandatory file locking works with AIO too, we can actually remove lines of code. Reported-by: Manish Honap <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID:
static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat) { struct file *file = kiocb->ki_filp; ssize_t ret = 0; switch (kiocb->ki_opcode) { case IOCB_CMD_PREAD: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf, kiocb->ki_left))) break; ret = aio_setup_single_vector(READ, file, kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITE: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf, kiocb->ki_left))) break; ret = aio_setup_single_vector(WRITE, file, kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PREADV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = aio_setup_vectored_rw(READ, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITEV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = aio_setup_vectored_rw(WRITE, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_FDSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fdsync; break; case IOCB_CMD_FSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fsync; break; default: dprintk("EINVAL: io_submit: no operation provided\n"); ret = -EINVAL; } if (!kiocb->ki_retry) return ret; return 0; }
167,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nfs4_close_prepare(struct rpc_task *task, void *data) { struct nfs4_closedata *calldata = data; struct nfs4_state *state = calldata->state; int clear_rd, clear_wr, clear_rdwr; if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0) return; clear_rd = clear_wr = clear_rdwr = 0; spin_lock(&state->owner->so_lock); /* Calculate the change in open mode */ if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { clear_rd |= test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags); clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { clear_wr |= test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags); clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags); } } spin_unlock(&state->owner->so_lock); if (!clear_rd && !clear_wr && !clear_rdwr) { /* Note: exit _without_ calling nfs4_close_done */ task->tk_action = NULL; return; } nfs_fattr_init(calldata->res.fattr); if (test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE]; calldata->arg.open_flags = FMODE_READ; } else if (test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE]; calldata->arg.open_flags = FMODE_WRITE; } calldata->timestamp = jiffies; rpc_call_start(task); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void nfs4_close_prepare(struct rpc_task *task, void *data) { struct nfs4_closedata *calldata = data; struct nfs4_state *state = calldata->state; int clear_rd, clear_wr, clear_rdwr; if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0) return; clear_rd = clear_wr = clear_rdwr = 0; spin_lock(&state->owner->so_lock); /* Calculate the change in open mode */ if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { clear_rd |= test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags); clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { clear_wr |= test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags); clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags); } } spin_unlock(&state->owner->so_lock); if (!clear_rd && !clear_wr && !clear_rdwr) { /* Note: exit _without_ calling nfs4_close_done */ task->tk_action = NULL; return; } nfs_fattr_init(calldata->res.fattr); if (test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE]; calldata->arg.fmode = FMODE_READ; } else if (test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE]; calldata->arg.fmode = FMODE_WRITE; } calldata->timestamp = jiffies; rpc_call_start(task); }
165,690
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc, void* pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags) { wStream* data_in; if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) { return CHANNEL_RC_OK; } if (dataFlags & CHANNEL_FLAG_FIRST) { if (drdynvc->data_in) Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = Stream_New(NULL, totalLength); } if (!(data_in = drdynvc->data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } if (!Stream_EnsureRemainingCapacity(data_in, (int) dataLength)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = NULL; return ERROR_INTERNAL_ERROR; } Stream_Write(data_in, pData, dataLength); if (dataFlags & CHANNEL_FLAG_LAST) { if (Stream_Capacity(data_in) != Stream_GetPosition(data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error"); return ERROR_INVALID_DATA; } drdynvc->data_in = NULL; Stream_SealLength(data_in); Stream_SetPosition(data_in, 0); if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*) data_in, NULL)) { WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!"); return ERROR_INTERNAL_ERROR; } } return CHANNEL_RC_OK; } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc, void* pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags) { wStream* data_in; if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) { return CHANNEL_RC_OK; } if (dataFlags & CHANNEL_FLAG_FIRST) { if (drdynvc->data_in) Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = Stream_New(NULL, totalLength); } if (!(data_in = drdynvc->data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } if (!Stream_EnsureRemainingCapacity(data_in, dataLength)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = NULL; return ERROR_INTERNAL_ERROR; } Stream_Write(data_in, pData, dataLength); if (dataFlags & CHANNEL_FLAG_LAST) { if (Stream_Capacity(data_in) != Stream_GetPosition(data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error"); return ERROR_INVALID_DATA; } drdynvc->data_in = NULL; Stream_SealLength(data_in); Stream_SetPosition(data_in, 0); if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*) data_in, NULL)) { WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!"); return ERROR_INTERNAL_ERROR; } } return CHANNEL_RC_OK; }
168,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: static int can_open_delegated(struct nfs_delegation *delegation, mode_t open_flags) { if ((delegation->type & open_flags) != open_flags) return 0; if (test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags)) return 0; nfs_mark_delegation_referenced(delegation); return 1; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static int can_open_delegated(struct nfs_delegation *delegation, mode_t open_flags) static int can_open_delegated(struct nfs_delegation *delegation, fmode_t fmode) { if ((delegation->type & fmode) != fmode) return 0; if (test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags)) return 0; nfs_mark_delegation_referenced(delegation); return 1; }
165,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xacct_add_tsk(struct taskstats *stats, struct task_struct *p) { /* convert pages-jiffies to Mbyte-usec */ stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB; stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB; if (p->mm) { /* adjust to KB unit */ stats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB; stats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB; } stats->read_char = p->rchar; stats->write_char = p->wchar; stats->read_syscalls = p->syscr; stats->write_syscalls = p->syscw; } Commit Message: [PATCH] xacct_add_tsk: fix pure theoretical ->mm use-after-free Paranoid fix. The task can free its ->mm after the 'if (p->mm)' check. Signed-off-by: Oleg Nesterov <[email protected]> Cc: Shailabh Nagar <[email protected]> Cc: Balbir Singh <[email protected]> Cc: Jay Lan <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
void xacct_add_tsk(struct taskstats *stats, struct task_struct *p) { struct mm_struct *mm; /* convert pages-jiffies to Mbyte-usec */ stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB; stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB; mm = get_task_mm(p); if (mm) { /* adjust to KB unit */ stats->hiwater_rss = mm->hiwater_rss * PAGE_SIZE / KB; stats->hiwater_vm = mm->hiwater_vm * PAGE_SIZE / KB; mmput(mm); } stats->read_char = p->rchar; stats->write_char = p->wchar; stats->read_syscalls = p->syscr; stats->write_syscalls = p->syscw; }
165,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: hb_buffer_clear (hb_buffer_t *buffer) { buffer->have_output = FALSE; buffer->have_positions = FALSE; buffer->len = 0; buffer->out_len = 0; buffer->i = 0; buffer->max_lig_id = 0; buffer->max_lig_id = 0; } Commit Message: CWE ID:
hb_buffer_clear (hb_buffer_t *buffer) { buffer->have_output = FALSE; buffer->have_positions = FALSE; buffer->in_error = FALSE; buffer->len = 0; buffer->out_len = 0; buffer->i = 0; buffer->max_lig_id = 0; buffer->max_lig_id = 0; }
164,772
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); header->nFilledLen = rangeLength; header->nOffset = rangeOffset; BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); buffer_meta->CopyToOMX(header); return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer); } Commit Message: IOMX: Add buffer range check to emptyBuffer Bug: 20634516 Change-Id: If351dbd573bb4aeb6968bfa33f6d407225bc752c (cherry picked from commit d971df0eb300356b3c995d533289216f43aa60de) CWE ID: CWE-119
status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); // rangeLength and rangeOffset must be a subset of the allocated data in the buffer. // corner case: we permit rangeOffset == end-of-buffer with rangeLength == 0. if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); buffer_meta->CopyToOMX(header); return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer); }
174,122
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Tar::ReadHeaders( void ) { FILE *in; TarHeader lHeader; TarRecord lRecord; unsigned int iBegData = 0; char buf_header[512]; in = fopen(mFilePath.fn_str(), "rb"); if(in == NULL) { wxLogFatalError(_("Error: File '%s' not found! Cannot read data."), mFilePath.c_str()); return 1; } wxString lDmodDizPath; mmDmodDescription = _T(""); mInstalledDmodDirectory = _T(""); int total_read = 0; while (true) { memset(&lHeader, 0, sizeof(TarHeader)); memset(&lRecord, 0, sizeof(TarRecord)); fread((char*)&lHeader.Name, 100, 1, in); fread((char*)&lHeader.Mode, 8, 1, in); fread((char*)&lHeader.Uid, 8, 1, in); fread((char*)&lHeader.Gid, 8, 1, in); fread((char*)&lHeader.Size, 12, 1, in); fread((char*)&lHeader.Mtime, 12, 1, in); fread((char*)&lHeader.Chksum, 8, 1, in); fread((char*)&lHeader.Linkflag, 1, 1, in); fread((char*)&lHeader.Linkname, 100, 1, in); fread((char*)&lHeader.Magic, 8, 1, in); fread((char*)&lHeader.Uname, 32, 1, in); fread((char*)&lHeader.Gname, 32, 1, in); fread((char*)&lHeader.Devmajor, 8, 1, in); fread((char*)&lHeader.Devminor, 8, 1, in); fread((char*)&lHeader.Padding, 167, 1, in); total_read += 512; if(!VerifyChecksum(&lHeader)) { wxLogFatalError(_("Error: This .dmod file has an invalid checksum! Cannot read file.")); return 1; } strncpy(lRecord.Name, lHeader.Name, 100); if (strcmp(lHeader.Name, "\xFF") == 0) continue; sscanf((const char*)&lHeader.Size, "%o", &lRecord.iFileSize); lRecord.iFilePosBegin = total_read; if(strcmp(lHeader.Name, "") == 0) { break; } wxString lPath(lRecord.Name, wxConvUTF8); wxString lPath(lRecord.Name, wxConvUTF8); if (mInstalledDmodDirectory.Length() == 0) { mInstalledDmodDirectory = lPath.SubString( 0, lPath.Find( '/' ) ); lDmodDizPath = mInstalledDmodDirectory + _T("dmod.diz"); lDmodDizPath.LowerCase(); } } else { int remaining = lRecord.iFileSize; char buf[BUFSIZ]; while (remaining > 0) { if (feof(in)) break; // TODO: error, unexpected end of file int nb_read = fread(buf, 1, (remaining > BUFSIZ) ? BUFSIZ : remaining, in); remaining -= nb_read; } } total_read += lRecord.iFileSize; TarRecords.push_back(lRecord); int padding_size = (512 - (total_read % 512)) % 512; fread(buf_header, 1, padding_size, in); total_read += padding_size; } Commit Message: CWE ID: CWE-22
int Tar::ReadHeaders( void ) { FILE *in; TarHeader lHeader; TarRecord lRecord; unsigned int iBegData = 0; char buf_header[512]; in = fopen(mFilePath.fn_str(), "rb"); if(in == NULL) { wxLogFatalError(_("Error: File '%s' not found! Cannot read data."), mFilePath.c_str()); return 1; } wxString lDmodDizPath; mmDmodDescription = _T(""); mInstalledDmodDirectory = _T(""); int total_read = 0; while (true) { memset(&lHeader, 0, sizeof(TarHeader)); memset(&lRecord, 0, sizeof(TarRecord)); fread((char*)&lHeader.Name, 100, 1, in); fread((char*)&lHeader.Mode, 8, 1, in); fread((char*)&lHeader.Uid, 8, 1, in); fread((char*)&lHeader.Gid, 8, 1, in); fread((char*)&lHeader.Size, 12, 1, in); fread((char*)&lHeader.Mtime, 12, 1, in); fread((char*)&lHeader.Chksum, 8, 1, in); fread((char*)&lHeader.Linkflag, 1, 1, in); fread((char*)&lHeader.Linkname, 100, 1, in); fread((char*)&lHeader.Magic, 8, 1, in); fread((char*)&lHeader.Uname, 32, 1, in); fread((char*)&lHeader.Gname, 32, 1, in); fread((char*)&lHeader.Devmajor, 8, 1, in); fread((char*)&lHeader.Devminor, 8, 1, in); fread((char*)&lHeader.Padding, 167, 1, in); total_read += 512; if(!VerifyChecksum(&lHeader)) { wxLogFatalError(_("Error: This .dmod file has an invalid checksum! Cannot read file.")); return 1; } strncpy(lRecord.Name, lHeader.Name, 100); if (strcmp(lHeader.Name, "\xFF") == 0) continue; sscanf((const char*)&lHeader.Size, "%o", &lRecord.iFileSize); lRecord.iFilePosBegin = total_read; if(strcmp(lHeader.Name, "") == 0) { break; } wxString lPath(lRecord.Name, wxConvUTF8); wxString lPath(lRecord.Name, wxConvUTF8); if (mInstalledDmodDirectory.Length() == 0) { // Security: ensure the D-Mod directory is non-empty wxString firstDir = GetFirstDir(lPath); if (firstDir.IsSameAs("", true) || firstDir.IsSameAs("..", true) || firstDir.IsSameAs("dink", true)) { wxLogError(_("Error: invalid D-Mod directory. Stopping.")); return 1; } mInstalledDmodDirectory = firstDir; lDmodDizPath = mInstalledDmodDirectory + _T("dmod.diz"); lDmodDizPath.LowerCase(); } } else { int remaining = lRecord.iFileSize; char buf[BUFSIZ]; while (remaining > 0) { if (feof(in)) break; // TODO: error, unexpected end of file int nb_read = fread(buf, 1, (remaining > BUFSIZ) ? BUFSIZ : remaining, in); remaining -= nb_read; } } total_read += lRecord.iFileSize; TarRecords.push_back(lRecord); int padding_size = (512 - (total_read % 512)) % 512; fread(buf_header, 1, padding_size, in); total_read += padding_size; }
165,347
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemNumberPtr comp = (xsltStyleItemNumberPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:number : compilation failed\n"); return; } if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; comp->numdata.doc = inst->doc; comp->numdata.node = inst; xsltNumberFormat(ctxt, &comp->numdata, node); } 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
xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemNumberPtr comp = (xsltStyleItemNumberPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathContextPtr xpctxt; xmlNsPtr *oldXPNamespaces; int oldXPNsNr; if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:number : compilation failed\n"); return; } if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; comp->numdata.doc = inst->doc; comp->numdata.node = inst; xpctxt = ctxt->xpathCtxt; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif xsltNumberFormat(ctxt, &comp->numdata, node); xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; }
173,329
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; } 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
unsigned long long Track::GetSeekPreRoll() const
174,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NodeIterator::NodeIterator(PassRefPtrWillBeRawPtr<Node> rootNode, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter) : NodeIteratorBase(rootNode, whatToShow, filter) , m_referenceNode(root(), true) { root()->document().attachNodeIterator(this); } Commit Message: Fix detached Attr nodes interaction with NodeIterator - Don't register NodeIterator to document when attaching to Attr node. -- NodeIterator is registered to its document to receive updateForNodeRemoval notifications. -- However it wouldn't make sense on Attr nodes, as they never have children. BUG=572537 Review URL: https://codereview.chromium.org/1577213003 Cr-Commit-Position: refs/heads/master@{#369687} CWE ID:
NodeIterator::NodeIterator(PassRefPtrWillBeRawPtr<Node> rootNode, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter) : NodeIteratorBase(rootNode, whatToShow, filter) , m_referenceNode(root(), true) { // If NodeIterator target is Attr node, don't subscribe for nodeWillBeRemoved, as it would never have child nodes. if (!root()->isAttributeNode()) root()->document().attachNodeIterator(this); }
172,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) csum = csum_sub(csum, csum_partial(skb_transport_header(skb) + tlen, offset, 0)); put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); } Commit Message: ip: fix IP_CHECKSUM handling The skbs processed by ip_cmsg_recv() are not guaranteed to be linear e.g. when sending UDP packets over loopback with MSGMORE. Using csum_partial() on [potentially] the whole skb len is dangerous; instead be on the safe side and use skb_checksum(). Thanks to syzkaller team to detect the issue and provide the reproducer. v1 -> v2: - move the variable declaration in a tighter scope Fixes: ad6f939ab193 ("ip: Add offset parameter to ip_cmsg_recv") Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Paolo Abeni <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) { int tend_off = skb_transport_offset(skb) + tlen; csum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0)); } put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); }
168,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ext4_invalidatepage(struct page *page, unsigned long offset) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); /* * If it's a full truncate we just forget about the pending dirtying */ if (offset == 0) ClearPageChecked(page); if (journal) jbd2_journal_invalidatepage(journal, page, offset); else block_invalidatepage(page, offset); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static void ext4_invalidatepage(struct page *page, unsigned long offset) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); /* * free any io_end structure allocated for buffers to be discarded */ if (ext4_should_dioread_nolock(page->mapping->host)) ext4_invalidatepage_free_endio(page, offset); /* * If it's a full truncate we just forget about the pending dirtying */ if (offset == 0) ClearPageChecked(page); if (journal) jbd2_journal_invalidatepage(journal, page, offset); else block_invalidatepage(page, offset); }
167,547
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintPreviewHandler::HandleGetPreview(const ListValue* args) { DCHECK_EQ(3U, args->GetSize()); scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args)); if (!settings.get()) return; int request_id = -1; if (!settings->GetInteger(printing::kPreviewRequestID, &request_id)) return; PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>( web_ui()->GetController()); print_preview_ui->OnPrintPreviewRequest(request_id); settings->SetString(printing::kPreviewUIAddr, print_preview_ui->GetPrintPreviewUIAddress()); ++regenerate_preview_request_count_; TabContents* initiator_tab = GetInitiatorTab(); if (!initiator_tab) { ReportUserActionHistogram(INITIATOR_TAB_CLOSED); print_preview_ui->OnClosePrintPreviewTab(); return; } bool display_header_footer = false; if (!settings->GetBoolean(printing::kSettingHeaderFooterEnabled, &display_header_footer)) { NOTREACHED(); } if (display_header_footer) { settings->SetString(printing::kSettingHeaderFooterTitle, initiator_tab->web_contents()->GetTitle()); std::string url; NavigationEntry* entry = initiator_tab->web_contents()->GetController().GetActiveEntry(); if (entry) url = entry->GetVirtualURL().spec(); settings->SetString(printing::kSettingHeaderFooterURL, url); } bool generate_draft_data = false; bool success = settings->GetBoolean(printing::kSettingGenerateDraftData, &generate_draft_data); DCHECK(success); if (!generate_draft_data) { double draft_page_count_double = -1; success = args->GetDouble(1, &draft_page_count_double); DCHECK(success); int draft_page_count = static_cast<int>(draft_page_count_double); bool preview_modifiable = false; success = args->GetBoolean(2, &preview_modifiable); DCHECK(success); if (draft_page_count != -1 && preview_modifiable && print_preview_ui->GetAvailableDraftPageCount() != draft_page_count) { settings->SetBoolean(printing::kSettingGenerateDraftData, true); } } VLOG(1) << "Print preview request start"; RenderViewHost* rvh = initiator_tab->web_contents()->GetRenderViewHost(); rvh->Send(new PrintMsg_PrintPreview(rvh->GetRoutingID(), *settings)); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewHandler::HandleGetPreview(const ListValue* args) { DCHECK_EQ(3U, args->GetSize()); scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args)); if (!settings.get()) return; int request_id = -1; if (!settings->GetInteger(printing::kPreviewRequestID, &request_id)) return; PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>( web_ui()->GetController()); print_preview_ui->OnPrintPreviewRequest(request_id); settings->SetInteger(printing::kPreviewUIID, print_preview_ui->GetIDForPrintPreviewUI()); ++regenerate_preview_request_count_; TabContents* initiator_tab = GetInitiatorTab(); if (!initiator_tab) { ReportUserActionHistogram(INITIATOR_TAB_CLOSED); print_preview_ui->OnClosePrintPreviewTab(); return; } bool display_header_footer = false; if (!settings->GetBoolean(printing::kSettingHeaderFooterEnabled, &display_header_footer)) { NOTREACHED(); } if (display_header_footer) { settings->SetString(printing::kSettingHeaderFooterTitle, initiator_tab->web_contents()->GetTitle()); std::string url; NavigationEntry* entry = initiator_tab->web_contents()->GetController().GetActiveEntry(); if (entry) url = entry->GetVirtualURL().spec(); settings->SetString(printing::kSettingHeaderFooterURL, url); } bool generate_draft_data = false; bool success = settings->GetBoolean(printing::kSettingGenerateDraftData, &generate_draft_data); DCHECK(success); if (!generate_draft_data) { double draft_page_count_double = -1; success = args->GetDouble(1, &draft_page_count_double); DCHECK(success); int draft_page_count = static_cast<int>(draft_page_count_double); bool preview_modifiable = false; success = args->GetBoolean(2, &preview_modifiable); DCHECK(success); if (draft_page_count != -1 && preview_modifiable && print_preview_ui->GetAvailableDraftPageCount() != draft_page_count) { settings->SetBoolean(printing::kSettingGenerateDraftData, true); } } VLOG(1) << "Print preview request start"; RenderViewHost* rvh = initiator_tab->web_contents()->GetRenderViewHost(); rvh->Send(new PrintMsg_PrintPreview(rvh->GetRoutingID(), *settings)); }
170,828
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t length; length=count*quantum; if ((count == 0) || (quantum != (length/count))) { errno=ENOMEM; return((MemoryInfo *) NULL); } memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); memory_info->length=length; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,length) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,length); if (memory_info->blob != NULL) memory_info->type=AlignedVirtualMemory; else RelinquishMagickResource(MemoryResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(MapResource,length) != MagickFalse)) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else RelinquishMagickResource(MapResource,length); } if (memory_info->blob == NULL) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file != -1) { if ((lseek(file,length-1,SEEK_SET) >= 0) && (write(file,"",1) == 1)) { memory_info->blob=MapBlob(file,IOMode,0,length); if (memory_info->blob != NULL) { memory_info->type=MapVirtualMemory; (void) AcquireMagickResource(MapResource,length); } } (void) close(file); } } if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(length); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); } Commit Message: CWE ID: CWE-189
MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t length; length=count*quantum; if ((count == 0) || (quantum != (length/count))) { errno=ENOMEM; return((MemoryInfo *) NULL); } memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); memory_info->length=length; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,length) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,length); if (memory_info->blob != NULL) memory_info->type=AlignedVirtualMemory; else RelinquishMagickResource(MemoryResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(MapResource,length) != MagickFalse)) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else RelinquishMagickResource(MapResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(DiskResource,length) != MagickFalse)) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file == -1) RelinquishMagickResource(DiskResource,length); else { if ((lseek(file,length-1,SEEK_SET) < 0) || (write(file,"",1) != 1)) RelinquishMagickResource(DiskResource,length); else { if (AcquireMagickResource(MapResource,length) == MagickFalse) RelinquishMagickResource(DiskResource,length); else { memory_info->blob=MapBlob(file,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else { RelinquishMagickResource(MapResource,length); RelinquishMagickResource(DiskResource,length); } } } (void) close(file); } } if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(length); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); }
168,859
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url, const FilePath& virtual_path, const FilePath& platform_path) { FilePath::StringType extension = virtual_path.Extension(); if (!extension.empty()) extension = extension.substr(1); // Strip leading ".". scoped_refptr<webkit_blob::ShareableFileReference> shareable_file = webkit_blob::ShareableFileReference::Get(platform_path); if (shareable_file && !ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id_, platform_path)) { ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( process_id_, platform_path); shareable_file->AddFinalReleaseCallback( base::Bind(&RevokeFilePermission, process_id_)); } std::string mime_type; net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); BlobData::Item item; item.SetToFilePathRange(platform_path, 0, -1, base::Time()); BlobStorageController* controller = blob_storage_context_->controller(); controller->StartBuildingBlob(blob_url); controller->AppendBlobDataItem(blob_url, item); controller->FinishBuildingBlob(blob_url, mime_type); blob_urls_.insert(blob_url.spec()); } Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files We also need to check the read permission and call GrantReadFile() for sandboxed files for CreateSnapshotFile(). BUG=162114 TEST=manual Review URL: https://codereview.chromium.org/11280231 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url, const FileSystemURL& url, const FilePath& platform_path) { FilePath::StringType extension = url.path().Extension(); if (!extension.empty()) extension = extension.substr(1); // Strip leading ".". scoped_refptr<webkit_blob::ShareableFileReference> shareable_file = webkit_blob::ShareableFileReference::Get(platform_path); if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id_, platform_path)) { // If the underlying file system implementation is returning a new // (likely temporary) snapshot file or the file is for sandboxed // filesystems it's ok to grant permission here. // (Note that we have also already checked if the renderer has the // read permission for this file in OnCreateSnapshotFile.) DCHECK(shareable_file || fileapi::SandboxMountPointProvider::CanHandleType(url.type())); ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( process_id_, platform_path); if (shareable_file) { // This will revoke all permissions for the file when the last ref // of the file is dropped (assuming it's ok). shareable_file->AddFinalReleaseCallback( base::Bind(&RevokeFilePermission, process_id_)); } } std::string mime_type; net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); BlobData::Item item; item.SetToFilePathRange(platform_path, 0, -1, base::Time()); BlobStorageController* controller = blob_storage_context_->controller(); controller->StartBuildingBlob(blob_url); controller->AppendBlobDataItem(blob_url, item); controller->FinishBuildingBlob(blob_url, mime_type); blob_urls_.insert(blob_url.spec()); }
171,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) { /* OpenSc Operation values for each command operation-type */ const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; const int ef_idx[8] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; const int efi_idx[8] = { /* internal EF used for RSA keys */ SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; u8 bValue; int i; int iKeyRef = 0; int iMethod; int iPinCount; int iOffset = 0; int iOperation; const int* p_idx; /* Check all sub-AC definitions within the total AC */ while (len > 1) { /* minimum length = 2 */ int iACLen = buf[iOffset] & 0x0F; iPinCount = -1; /* default no pin required */ iMethod = SC_AC_NONE; /* default no authentication required */ if (buf[iOffset] & 0X80) { /* AC in adaptive coding */ /* Evaluates only the command-byte, not the optional P1/P2/Option bytes */ int iParmLen = 1; /* command-byte is always present */ int iKeyLen = 0; /* Encryption key is optional */ if (buf[iOffset] & 0x20) iKeyLen++; if (buf[iOffset+1] & 0x40) iParmLen++; if (buf[iOffset+1] & 0x20) iParmLen++; if (buf[iOffset+1] & 0x10) iParmLen++; if (buf[iOffset+1] & 0x08) iParmLen++; /* Get KeyNumber if available */ if(iKeyLen) { int iSC = buf[iOffset+iACLen]; switch( (iSC>>5) & 0x03 ){ case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ } /* Get PinNumber if available */ if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ iMethod = SC_AC_CHV; } /* Convert SETCOS command to OpenSC command group */ switch(buf[iOffset+2]){ case 0x2A: /* crypto operation */ iOperation = SC_AC_OP_CRYPTO; break; case 0x46: /* key-generation operation */ iOperation = SC_AC_OP_UPDATE; break; default: iOperation = SC_AC_OP_SELECT; break; } sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef); } else { /* AC in simple coding */ /* Initial AC is treated as an operational AC */ /* Get specific Cmd groups for specified file-type */ switch (file->type) { case SC_FILE_TYPE_DF: /* DF */ p_idx = df_idx; break; case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ p_idx = efi_idx; break; default: /* EF */ p_idx = ef_idx; break; } /* Encryption key present ? */ iPinCount = iACLen - 1; if (buf[iOffset] & 0x20) { int iSC = buf[iOffset + iACLen]; switch( (iSC>>5) & 0x03 ) { case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ iPinCount--; /* one byte used for keyReference */ } /* Pin present ? */ if ( iPinCount > 0 ) { iKeyRef = buf[iOffset + 2]; /* pin ref */ iMethod = SC_AC_CHV; } /* Add AC for each command-operationType into OpenSc structure */ bValue = buf[iOffset + 1]; for (i = 0; i < 8; i++) { if((bValue & 1) && (p_idx[i] >= 0)) sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef); bValue >>= 1; } } /* Current field treated, get next AC sub-field */ iOffset += iACLen +1; /* AC + PTL-byte */ len -= iACLen +1; } } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) { /* OpenSc Operation values for each command operation-type */ const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; const int ef_idx[8] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; const int efi_idx[8] = { /* internal EF used for RSA keys */ SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; u8 bValue; int i; int iKeyRef = 0; int iMethod; int iPinCount; int iOffset = 0; int iOperation; const int* p_idx; /* Check all sub-AC definitions within the total AC */ while (len > 1) { /* minimum length = 2 */ int iACLen = buf[iOffset] & 0x0F; if ((size_t) iACLen > len) break; iPinCount = -1; /* default no pin required */ iMethod = SC_AC_NONE; /* default no authentication required */ if (buf[iOffset] & 0X80) { /* AC in adaptive coding */ /* Evaluates only the command-byte, not the optional P1/P2/Option bytes */ int iParmLen = 1; /* command-byte is always present */ int iKeyLen = 0; /* Encryption key is optional */ if (buf[iOffset] & 0x20) iKeyLen++; if (buf[iOffset+1] & 0x40) iParmLen++; if (buf[iOffset+1] & 0x20) iParmLen++; if (buf[iOffset+1] & 0x10) iParmLen++; if (buf[iOffset+1] & 0x08) iParmLen++; /* Get KeyNumber if available */ if(iKeyLen) { int iSC; if (len < 1+iACLen) break; iSC = buf[iOffset+iACLen]; switch( (iSC>>5) & 0x03 ){ case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ } /* Get PinNumber if available */ if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ if (len < 1+1+1+iParmLen) break; iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ iMethod = SC_AC_CHV; } /* Convert SETCOS command to OpenSC command group */ if (len < 1+2) break; switch(buf[iOffset+2]){ case 0x2A: /* crypto operation */ iOperation = SC_AC_OP_CRYPTO; break; case 0x46: /* key-generation operation */ iOperation = SC_AC_OP_UPDATE; break; default: iOperation = SC_AC_OP_SELECT; break; } sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef); } else { /* AC in simple coding */ /* Initial AC is treated as an operational AC */ /* Get specific Cmd groups for specified file-type */ switch (file->type) { case SC_FILE_TYPE_DF: /* DF */ p_idx = df_idx; break; case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ p_idx = efi_idx; break; default: /* EF */ p_idx = ef_idx; break; } /* Encryption key present ? */ iPinCount = iACLen - 1; if (buf[iOffset] & 0x20) { int iSC; if (len < 1 + iACLen) break; iSC = buf[iOffset + iACLen]; switch( (iSC>>5) & 0x03 ) { case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ iPinCount--; /* one byte used for keyReference */ } /* Pin present ? */ if ( iPinCount > 0 ) { if (len < 1 + 2) break; iKeyRef = buf[iOffset + 2]; /* pin ref */ iMethod = SC_AC_CHV; } /* Add AC for each command-operationType into OpenSc structure */ bValue = buf[iOffset + 1]; for (i = 0; i < 8; i++) { if((bValue & 1) && (p_idx[i] >= 0)) sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef); bValue >>= 1; } } /* Current field treated, get next AC sub-field */ iOffset += iACLen +1; /* AC + PTL-byte */ len -= iACLen +1; } }
169,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void silk_NLSF_stabilize( opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */ const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */ const opus_int L /* I Number of NLSF parameters in the input vector */ ) { opus_int i, I=0, k, loops; opus_int16 center_freq_Q15; opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15; /* This is necessary to ensure an output within range of a opus_int16 */ silk_assert( NDeltaMin_Q15[L] >= 1 ); for( loops = 0; loops < MAX_LOOPS; loops++ ) { /**************************/ /* Find smallest distance */ /**************************/ /* First element */ min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0]; I = 0; /* Middle elements */ for( i = 1; i <= L-1; i++ ) { diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = i; } } /* Last element */ diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = L; } /***************************************************/ /* Now check if the smallest distance non-negative */ /***************************************************/ if( min_diff_Q15 >= 0 ) { return; } if( I == 0 ) { /* Move away from lower limit */ NLSF_Q15[0] = NDeltaMin_Q15[0]; } else if( I == L) { /* Move away from higher limit */ NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L]; } else { /* Find the lower extreme for the location of the current center frequency */ min_center_Q15 = 0; for( k = 0; k < I; k++ ) { min_center_Q15 += NDeltaMin_Q15[k]; } min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Find the upper extreme for the location of the current center frequency */ max_center_Q15 = 1 << 15; for( k = L; k > I; k-- ) { max_center_Q15 -= NDeltaMin_Q15[k]; } max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Move apart, sorted by value, keeping the same center frequency */ center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ), min_center_Q15, max_center_Q15 ); NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 ); NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I]; } } /* Safe and simple fall back method, which is less ideal than the above */ if( loops == MAX_LOOPS ) { /* Insertion sort (fast for already almost sorted arrays): */ /* Best case: O(n) for an already sorted array */ /* Worst case: O(n^2) for an inversely sorted array */ silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L ); /* First NLSF should be no less than NDeltaMin[0] */ NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] ); /* Keep delta_min distance between the NLSFs */ for( i = 1; i < L; i++ ) NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); /* Last NLSF should be no higher than 1 - NDeltaMin[L] */ NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] ); /* Keep NDeltaMin distance between the NLSFs */ for( i = L-2; i >= 0; i-- ) NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] ); } } Commit Message: Ensure that NLSF cannot be negative when computing a min distance between them b/31607432 Signed-off-by: Jean-Marc Valin <[email protected]> (cherry picked from commit d9d5ac4027c5ee1da2ff1c6572ae3b35a845db19) CWE ID: CWE-190
void silk_NLSF_stabilize( opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */ const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */ const opus_int L /* I Number of NLSF parameters in the input vector */ ) { opus_int i, I=0, k, loops; opus_int16 center_freq_Q15; opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15; /* This is necessary to ensure an output within range of a opus_int16 */ silk_assert( NDeltaMin_Q15[L] >= 1 ); for( loops = 0; loops < MAX_LOOPS; loops++ ) { /**************************/ /* Find smallest distance */ /**************************/ /* First element */ min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0]; I = 0; /* Middle elements */ for( i = 1; i <= L-1; i++ ) { diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = i; } } /* Last element */ diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = L; } /***************************************************/ /* Now check if the smallest distance non-negative */ /***************************************************/ if( min_diff_Q15 >= 0 ) { return; } if( I == 0 ) { /* Move away from lower limit */ NLSF_Q15[0] = NDeltaMin_Q15[0]; } else if( I == L) { /* Move away from higher limit */ NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L]; } else { /* Find the lower extreme for the location of the current center frequency */ min_center_Q15 = 0; for( k = 0; k < I; k++ ) { min_center_Q15 += NDeltaMin_Q15[k]; } min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Find the upper extreme for the location of the current center frequency */ max_center_Q15 = 1 << 15; for( k = L; k > I; k-- ) { max_center_Q15 -= NDeltaMin_Q15[k]; } max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Move apart, sorted by value, keeping the same center frequency */ center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ), min_center_Q15, max_center_Q15 ); NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 ); NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I]; } } /* Safe and simple fall back method, which is less ideal than the above */ if( loops == MAX_LOOPS ) { /* Insertion sort (fast for already almost sorted arrays): */ /* Best case: O(n) for an already sorted array */ /* Worst case: O(n^2) for an inversely sorted array */ silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L ); /* First NLSF should be no less than NDeltaMin[0] */ NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] ); /* Keep delta_min distance between the NLSFs */ for( i = 1; i < L; i++ ) NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], silk_ADD_SAT16( NLSF_Q15[i-1], NDeltaMin_Q15[i] ) ); /* Last NLSF should be no higher than 1 - NDeltaMin[L] */ NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] ); /* Keep NDeltaMin distance between the NLSFs */ for( i = L-2; i >= 0; i-- ) NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] ); } }
174,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_cdtext_generic (void *p_user_data) { generic_img_private_t *p_env = p_user_data; uint8_t *p_cdtext_data = NULL; size_t len; if (!p_env) return NULL; if (p_env->b_cdtext_error) return NULL; if (NULL == p_env->cdtext) { p_cdtext_data = read_cdtext_generic (p_env); if (NULL != p_cdtext_data) { len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2; p_env->cdtext = cdtext_init(); if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) { p_env->b_cdtext_error = true; cdtext_destroy (p_env->cdtext); free(p_env->cdtext); p_env->cdtext = NULL; } } free(p_cdtext_data); } } Commit Message: CWE ID: CWE-415
get_cdtext_generic (void *p_user_data) { generic_img_private_t *p_env = p_user_data; uint8_t *p_cdtext_data = NULL; size_t len; if (!p_env) return NULL; if (p_env->b_cdtext_error) return NULL; if (NULL == p_env->cdtext) { p_cdtext_data = read_cdtext_generic (p_env); if (NULL != p_cdtext_data) { len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2; p_env->cdtext = cdtext_init(); if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) { p_env->b_cdtext_error = true; free(p_env->cdtext); p_env->cdtext = NULL; } } free(p_cdtext_data); } }
165,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool parse_reconnect(struct pool *pool, json_t *val) { char *sockaddr_url, *stratum_port, *tmp; char *url, *port, address[256]; if (opt_disable_client_reconnect) { applog(LOG_WARNING, "Stratum client.reconnect forbidden, aborting."); return false; } memset(address, 0, 255); url = (char *)json_string_value(json_array_get(val, 0)); if (!url) url = pool->sockaddr_url; port = (char *)json_string_value(json_array_get(val, 1)); if (!port) port = pool->stratum_port; sprintf(address, "%s:%s", url, port); if (!extract_sockaddr(address, &sockaddr_url, &stratum_port)) return false; applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address); clear_pool_work(pool); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); tmp = pool->sockaddr_url; pool->sockaddr_url = sockaddr_url; pool->stratum_url = pool->sockaddr_url; free(tmp); tmp = pool->stratum_port; pool->stratum_port = stratum_port; free(tmp); mutex_unlock(&pool->stratum_lock); if (!restart_stratum(pool)) { pool_failed(pool); return false; } return true; } Commit Message: stratum: parse_reconnect(): treat pool-sent URL as untrusted. Thanks to Mick Ayzenberg <[email protected]> for reminding that this existed and highlighting the offender. Also to Luke-jr for actually fixing this in bfgminer. :D CWE ID: CWE-119
static bool parse_reconnect(struct pool *pool, json_t *val) { if (opt_disable_client_reconnect) { applog(LOG_WARNING, "Stratum client.reconnect received but is disabled, not reconnecting."); return false; } char *url, *port, address[256]; char *sockaddr_url, *stratum_port, *tmp; /* Tempvars. */ url = (char *)json_string_value(json_array_get(val, 0)); if (!url) url = pool->sockaddr_url; port = (char *)json_string_value(json_array_get(val, 1)); if (!port) port = pool->stratum_port; snprintf(address, sizeof(address), "%s:%s", url, port); if (!extract_sockaddr(address, &sockaddr_url, &stratum_port)) return false; applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address); clear_pool_work(pool); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); tmp = pool->sockaddr_url; pool->sockaddr_url = sockaddr_url; pool->stratum_url = pool->sockaddr_url; free(tmp); tmp = pool->stratum_port; pool->stratum_port = stratum_port; free(tmp); mutex_unlock(&pool->stratum_lock); if (!restart_stratum(pool)) { pool_failed(pool); return false; } return true; }
169,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: construct_command_line(struct manager_ctx *manager, struct server *server) { static char cmd[BUF_SIZE]; char *method = manager->method; int i; build_config(working_dir, server); if (server->method) method = server->method; memset(cmd, 0, BUF_SIZE); snprintf(cmd, BUF_SIZE, "%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf", executable, method, manager->manager_address, working_dir, server->port, working_dir, server->port); if (manager->acl != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl); } if (manager->timeout != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout); } #ifdef HAVE_SETRLIMIT if (manager->nofile) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile); } #endif if (manager->user != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user); } if (manager->verbose) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -v"); } if (server->mode == NULL && manager->mode == UDP_ONLY) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -U"); } if (server->mode == NULL && manager->mode == TCP_AND_UDP) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -u"); } if (server->fast_open[0] == 0 && manager->fast_open) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --fast-open"); } if (manager->ipv6first) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -6"); } if (manager->mtu) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu); } if (server->plugin == NULL && manager->plugin) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin \"%s\"", manager->plugin); } if (server->plugin_opts == NULL && manager->plugin_opts) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin-opts \"%s\"", manager->plugin_opts); } for (i = 0; i < manager->nameserver_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]); } for (i = 0; i < manager->host_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]); } { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --reuse-port"); } if (verbose) { LOGI("cmd: %s", cmd); } return cmd; } Commit Message: Fix #1734 CWE ID: CWE-78
construct_command_line(struct manager_ctx *manager, struct server *server) { static char cmd[BUF_SIZE]; int i; int port; port = atoi(server->port); build_config(working_dir, manager, server); memset(cmd, 0, BUF_SIZE); snprintf(cmd, BUF_SIZE, "%s --manager-address %s -f %s/.shadowsocks_%d.pid -c %s/.shadowsocks_%d.conf", executable, manager->manager_address, working_dir, port, working_dir, port); if (manager->acl != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl); } if (manager->timeout != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout); } #ifdef HAVE_SETRLIMIT if (manager->nofile) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile); } #endif if (manager->user != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user); } if (manager->verbose) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -v"); } if (server->mode == NULL && manager->mode == UDP_ONLY) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -U"); } if (server->mode == NULL && manager->mode == TCP_AND_UDP) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -u"); } if (server->fast_open[0] == 0 && manager->fast_open) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --fast-open"); } if (manager->ipv6first) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -6"); } if (manager->mtu) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu); } if (server->plugin == NULL && manager->plugin) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin \"%s\"", manager->plugin); } if (server->plugin_opts == NULL && manager->plugin_opts) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin-opts \"%s\"", manager->plugin_opts); } for (i = 0; i < manager->nameserver_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]); } for (i = 0; i < manager->host_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]); } { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --reuse-port"); } if (verbose) { LOGI("cmd: %s", cmd); } return cmd; }
167,714
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: display_log(struct display *dp, error_level level, const char *fmt, ...) /* 'level' is as above, fmt is a stdio style format string. This routine * does not return if level is above LIBPNG_WARNING */ { dp->results |= 1U << level; if (level > (error_level)(dp->options & LEVEL_MASK)) { const char *lp; va_list ap; switch (level) { case INFORMATION: lp = "information"; break; case LIBPNG_WARNING: lp = "warning(libpng)"; break; case APP_WARNING: lp = "warning(pngimage)"; break; case APP_FAIL: lp = "error(continuable)"; break; case LIBPNG_ERROR: lp = "error(libpng)"; break; case LIBPNG_BUG: lp = "bug(libpng)"; break; case APP_ERROR: lp = "error(pngimage)"; break; case USER_ERROR: lp = "error(user)"; break; case INTERNAL_ERROR: /* anything unexpected is an internal error: */ case VERBOSE: case WARNINGS: case ERRORS: case QUIET: default: lp = "bug(pngimage)"; break; } fprintf(stderr, "%s: %s: %s", dp->filename != NULL ? dp->filename : "<stdin>", lp, dp->operation); if (dp->transforms != 0) { int tr = dp->transforms; if (is_combo(tr)) fprintf(stderr, "(0x%x)", tr); else fprintf(stderr, "(%s)", transform_name(tr)); } fprintf(stderr, ": "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); } /* else do not output any message */ /* Errors cause this routine to exit to the fail code */ if (level > APP_FAIL || (level > ERRORS && !(dp->options & CONTINUE))) longjmp(dp->error_return, level); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
display_log(struct display *dp, error_level level, const char *fmt, ...) /* 'level' is as above, fmt is a stdio style format string. This routine * does not return if level is above LIBPNG_WARNING */ { dp->results |= 1U << level; if (level > (error_level)(dp->options & LEVEL_MASK)) { const char *lp; va_list ap; switch (level) { case INFORMATION: lp = "information"; break; case LIBPNG_WARNING: lp = "warning(libpng)"; break; case APP_WARNING: lp = "warning(pngimage)"; break; case APP_FAIL: lp = "error(continuable)"; break; case LIBPNG_ERROR: lp = "error(libpng)"; break; case LIBPNG_BUG: lp = "bug(libpng)"; break; case APP_ERROR: lp = "error(pngimage)"; break; case USER_ERROR: lp = "error(user)"; break; case INTERNAL_ERROR: /* anything unexpected is an internal error: */ case VERBOSE: case WARNINGS: case ERRORS: case QUIET: default: lp = "bug(pngimage)"; break; } fprintf(stderr, "%s: %s: %s", dp->filename != NULL ? dp->filename : "<stdin>", lp, dp->operation); if (dp->transforms != 0) { int tr = dp->transforms; if (is_combo(tr)) { if (dp->options & LIST_COMBOS) { int trx = tr; fprintf(stderr, "("); if (trx) { int start = 0; while (trx) { int trz = trx & -trx; if (start) fprintf(stderr, "+"); fprintf(stderr, "%s", transform_name(trz)); start = 1; trx &= ~trz; } } else fprintf(stderr, "-"); fprintf(stderr, ")"); } else fprintf(stderr, "(0x%x)", tr); } else fprintf(stderr, "(%s)", transform_name(tr)); } fprintf(stderr, ": "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); } /* else do not output any message */ /* Errors cause this routine to exit to the fail code */ if (level > APP_FAIL || (level > ERRORS && !(dp->options & CONTINUE))) longjmp(dp->error_return, level); }
173,588
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out) { void **out = (void **)_out; struct asn1_data *data = asn1_init(mem_ctx); struct dsdb_openldap_dereference_result_control *control; struct dsdb_openldap_dereference_result **r = NULL; int i = 0; if (!data) return false; control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) return false; if (!asn1_load(data, in)) { return false; } control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } while (asn1_tag_remaining(data) > 0) { r = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2); if (!r) { return false; } r[i] = talloc_zero(r, struct dsdb_openldap_dereference_result); if (!r[i]) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } asn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute); asn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn); if (asn1_peek_tag(data, ASN1_CONTEXT(0))) { if (!asn1_start_tag(data, ASN1_CONTEXT(0))) { return false; } ldap_decode_attribs_bare(r, data, &r[i]->attributes, &r[i]->num_attributes); if (!asn1_end_tag(data)) { return false; } } if (!asn1_end_tag(data)) { return false; } i++; r[i] = NULL; } if (!asn1_end_tag(data)) { return false; } control->attributes = r; *out = control; return true; } Commit Message: CWE ID: CWE-399
static bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out) { void **out = (void **)_out; struct asn1_data *data = asn1_init(mem_ctx); struct dsdb_openldap_dereference_result_control *control; struct dsdb_openldap_dereference_result **r = NULL; int i = 0; if (!data) return false; control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) return false; if (!asn1_load(data, in)) { return false; } control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } while (asn1_tag_remaining(data) > 0) { r = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2); if (!r) { return false; } r[i] = talloc_zero(r, struct dsdb_openldap_dereference_result); if (!r[i]) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } asn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute); asn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn); if (asn1_peek_tag(data, ASN1_CONTEXT(0))) { if (!asn1_start_tag(data, ASN1_CONTEXT(0))) { return false; } if (!ldap_decode_attribs_bare(r, data, &r[i]->attributes, &r[i]->num_attributes)) { return false; } if (!asn1_end_tag(data)) { return false; } } if (!asn1_end_tag(data)) { return false; } i++; r[i] = NULL; } if (!asn1_end_tag(data)) { return false; } control->attributes = r; *out = control; return true; }
164,595
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file) { struct comedi_devinfo devinfo; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_subdevice *read_subdev = comedi_get_read_subdevice(dev_file_info); struct comedi_subdevice *write_subdev = comedi_get_write_subdevice(dev_file_info); memset(&devinfo, 0, sizeof(devinfo)); /* fill devinfo structure */ devinfo.version_code = COMEDI_VERSION_CODE; devinfo.n_subdevs = dev->n_subdevices; memcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN); memcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN); if (read_subdev) devinfo.read_subdevice = read_subdev - dev->subdevices; else devinfo.read_subdevice = -1; if (write_subdev) devinfo.write_subdevice = write_subdev - dev->subdevices; else devinfo.write_subdevice = -1; if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo))) return -EFAULT; return 0; } Commit Message: staging: comedi: fix infoleak to userspace driver_name and board_name are pointers to strings, not buffers of size COMEDI_NAMELEN. Copying COMEDI_NAMELEN bytes of a string containing less than COMEDI_NAMELEN-1 bytes would leak some unrelated bytes. Signed-off-by: Vasiliy Kulikov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200
static int do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file) { struct comedi_devinfo devinfo; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_subdevice *read_subdev = comedi_get_read_subdevice(dev_file_info); struct comedi_subdevice *write_subdev = comedi_get_write_subdevice(dev_file_info); memset(&devinfo, 0, sizeof(devinfo)); /* fill devinfo structure */ devinfo.version_code = COMEDI_VERSION_CODE; devinfo.n_subdevs = dev->n_subdevices; strlcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN); strlcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN); if (read_subdev) devinfo.read_subdevice = read_subdev - dev->subdevices; else devinfo.read_subdevice = -1; if (write_subdev) devinfo.write_subdevice = write_subdev - dev->subdevices; else devinfo.write_subdevice = -1; if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo))) return -EFAULT; return 0; }
166,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltCopyNamespaceList(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNsPtr cur) { xmlNsPtr ret = NULL, tmp; xmlNsPtr p = NULL,q; if (cur == NULL) return(NULL); if (cur->type != XML_NAMESPACE_DECL) return(NULL); /* * One can add namespaces only on element nodes */ if ((node != NULL) && (node->type != XML_ELEMENT_NODE)) node = NULL; while (cur != NULL) { if (cur->type != XML_NAMESPACE_DECL) break; /* * Avoid duplicating namespace declarations in the tree if * a matching declaration is in scope. */ if (node != NULL) { if ((node->ns != NULL) && (xmlStrEqual(node->ns->prefix, cur->prefix)) && (xmlStrEqual(node->ns->href, cur->href))) { cur = cur->next; continue; } tmp = xmlSearchNs(node->doc, node, cur->prefix); if ((tmp != NULL) && (xmlStrEqual(tmp->href, cur->href))) { cur = cur->next; continue; } } #ifdef XSLT_REFACTORED /* * Namespace exclusion and ns-aliasing is performed at * compilation-time in the refactored code. */ q = xmlNewNs(node, cur->href, cur->prefix); if (p == NULL) { ret = p = q; } else { p->next = q; p = q; } #else /* * TODO: Remove this if the refactored code gets enabled. */ if (!xmlStrEqual(cur->href, XSLT_NAMESPACE)) { const xmlChar *URI; /* TODO apply cascading */ URI = (const xmlChar *) xmlHashLookup(ctxt->style->nsAliases, cur->href); if (URI == UNDEFINED_DEFAULT_NS) continue; if (URI != NULL) { q = xmlNewNs(node, URI, cur->prefix); } else { q = xmlNewNs(node, cur->href, cur->prefix); } if (p == NULL) { ret = p = q; } else { p->next = q; p = q; } } #endif cur = cur->next; } return(ret); } 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
xsltCopyNamespaceList(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNsPtr cur) { xmlNsPtr ret = NULL, tmp; xmlNsPtr p = NULL,q; if (cur == NULL) return(NULL); if (cur->type != XML_NAMESPACE_DECL) return(NULL); /* * One can add namespaces only on element nodes */ if ((node != NULL) && (node->type != XML_ELEMENT_NODE)) node = NULL; while (cur != NULL) { if (cur->type != XML_NAMESPACE_DECL) break; /* * Avoid duplicating namespace declarations in the tree if * a matching declaration is in scope. */ if (node != NULL) { if ((node->ns != NULL) && (xmlStrEqual(node->ns->prefix, cur->prefix)) && (xmlStrEqual(node->ns->href, cur->href))) { cur = cur->next; continue; } tmp = xmlSearchNs(node->doc, node, cur->prefix); if ((tmp != NULL) && (xmlStrEqual(tmp->href, cur->href))) { cur = cur->next; continue; } } #ifdef XSLT_REFACTORED /* * Namespace exclusion and ns-aliasing is performed at * compilation-time in the refactored code. */ q = xmlNewNs(node, cur->href, cur->prefix); if (p == NULL) { ret = p = q; } else { p->next = q; p = q; } #else /* * TODO: Remove this if the refactored code gets enabled. */ if (!xmlStrEqual(cur->href, XSLT_NAMESPACE)) { const xmlChar *URI; /* TODO apply cascading */ URI = (const xmlChar *) xmlHashLookup(ctxt->style->nsAliases, cur->href); if (URI == UNDEFINED_DEFAULT_NS) { cur = cur->next; continue; } if (URI != NULL) { q = xmlNewNs(node, URI, cur->prefix); } else { q = xmlNewNs(node, cur->href, cur->prefix); } if (p == NULL) { ret = p = q; } else { p->next = q; p = q; } } #endif cur = cur->next; } return(ret); }
173,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: ContentUtilityClient* ShellMainDelegate::CreateContentUtilityClient() { utility_client_.reset(new ShellContentUtilityClient); return utility_client_.get(); } Commit Message: Fix content_shell with network service enabled not loading pages. This regressed in my earlier cl r528763. This is a reland of r547221. Bug: 833612 Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b Reviewed-on: https://chromium-review.googlesource.com/1064702 Reviewed-by: Jay Civelli <[email protected]> Commit-Queue: John Abd-El-Malek <[email protected]> Cr-Commit-Position: refs/heads/master@{#560011} CWE ID: CWE-264
ContentUtilityClient* ShellMainDelegate::CreateContentUtilityClient() { utility_client_.reset(new ShellContentUtilityClient(is_browsertest_)); return utility_client_.get(); }
172,120
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintJobWorker::GetSettingsWithUI( int document_page_count, bool has_selection, bool is_scripted) { DCHECK_CURRENTLY_ON(BrowserThread::UI); #if defined(OS_ANDROID) if (is_scripted) { PrintingContextDelegate* printing_context_delegate = static_cast<PrintingContextDelegate*>(printing_context_delegate_.get()); content::WebContents* web_contents = printing_context_delegate->GetWebContents(); TabAndroid* tab = web_contents ? TabAndroid::FromWebContents(web_contents) : nullptr; if (tab) tab->SetPendingPrint(); } #endif printing_context_->AskUserForSettings( document_page_count, has_selection, is_scripted, base::Bind(&PostOnOwnerThread, make_scoped_refptr(owner_), base::Bind(&PrintJobWorker::GetSettingsDone, weak_factory_.GetWeakPtr()))); } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20
void PrintJobWorker::GetSettingsWithUI( int document_page_count, bool has_selection, bool is_scripted) { DCHECK_CURRENTLY_ON(BrowserThread::UI); PrintingContextDelegate* printing_context_delegate = static_cast<PrintingContextDelegate*>(printing_context_delegate_.get()); content::WebContents* web_contents = printing_context_delegate->GetWebContents(); #if defined(OS_ANDROID) if (is_scripted) { TabAndroid* tab = web_contents ? TabAndroid::FromWebContents(web_contents) : nullptr; if (tab) tab->SetPendingPrint(); } #endif // Running a dialog causes an exit to webpage-initiated fullscreen. // http://crbug.com/728276 if (web_contents->IsFullscreenForCurrentTab()) web_contents->ExitFullscreen(true); printing_context_->AskUserForSettings( document_page_count, has_selection, is_scripted, base::Bind(&PostOnOwnerThread, make_scoped_refptr(owner_), base::Bind(&PrintJobWorker::GetSettingsDone, weak_factory_.GetWeakPtr()))); }
172,313
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Frame* ReuseExistingWindow(LocalFrame& active_frame, LocalFrame& lookup_frame, const AtomicString& frame_name, NavigationPolicy policy, const KURL& destination_url) { if (!frame_name.IsEmpty() && !EqualIgnoringASCIICase(frame_name, "_blank") && policy == kNavigationPolicyIgnore) { if (Frame* frame = lookup_frame.FindFrameForNavigation( frame_name, active_frame, destination_url)) { if (!EqualIgnoringASCIICase(frame_name, "_self")) { if (Page* page = frame->GetPage()) { if (page == active_frame.GetPage()) page->GetFocusController().SetFocusedFrame(frame); else page->GetChromeClient().Focus(); } } return frame; } } return nullptr; } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
static Frame* ReuseExistingWindow(LocalFrame& active_frame, LocalFrame& lookup_frame, const AtomicString& frame_name, NavigationPolicy policy, const KURL& destination_url) { if (!frame_name.IsEmpty() && !EqualIgnoringASCIICase(frame_name, "_blank") && policy == kNavigationPolicyIgnore) { if (Frame* frame = lookup_frame.FindFrameForNavigation( frame_name, active_frame, destination_url)) { if (!EqualIgnoringASCIICase(frame_name, "_self")) { if (Page* page = frame->GetPage()) { if (page == active_frame.GetPage()) page->GetFocusController().SetFocusedFrame(frame); else page->GetChromeClient().Focus(&active_frame); } } return frame; } } return nullptr; }
172,725
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 save_text_if_changed(const char *name, const char *new_value) { /* a text value can't be change if the file is not loaded */ /* returns NULL if the name is not found; otherwise nonzero */ if (!g_hash_table_lookup(g_loaded_texts, name)) return; const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : ""; if (!old_value) old_value = ""; if (strcmp(new_value, old_value) != 0) { struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); if (dd) dd_save_text(dd, name, new_value); dd_close(dd); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); } } Commit Message: wizard: fix save users changes after reviewing dump dir files If the user reviewed the dump dir's files during reporting the crash, the changes was thrown away and original data was passed to the bugzilla bug report. report-gtk saves the first text view buffer and then reloads data from the reported problem directory, which causes that the changes made to those text views are thrown away. Function save_text_if_changed(), except of saving text, also reload the files from dump dir and update gui state from the dump dir. The commit moves the reloading and updating gui functions away from this function. Related to rhbz#1270235 Signed-off-by: Matej Habrnal <[email protected]> CWE ID: CWE-200
static void save_text_if_changed(const char *name, const char *new_value) { /* a text value can't be change if the file is not loaded */ /* returns NULL if the name is not found; otherwise nonzero */ if (!g_hash_table_lookup(g_loaded_texts, name)) return; const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : ""; if (!old_value) old_value = ""; if (strcmp(new_value, old_value) != 0) { struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); if (dd) dd_save_text(dd, name, new_value); dd_close(dd); } }
166,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXNodeObject::hasContentEditableAttributeSet() const { const AtomicString& contentEditableValue = getAttribute(contenteditableAttr); if (contentEditableValue.isNull()) return false; return contentEditableValue.isEmpty() || equalIgnoringCase(contentEditableValue, "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 AXNodeObject::hasContentEditableAttributeSet() const { const AtomicString& contentEditableValue = getAttribute(contenteditableAttr); if (contentEditableValue.isNull()) return false; return contentEditableValue.isEmpty() || equalIgnoringASCIICase(contentEditableValue, "true"); }
171,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderView::RenderView(RenderThreadBase* render_thread, gfx::NativeViewId parent_hwnd, int32 opener_id, const RendererPreferences& renderer_prefs, const WebPreferences& webkit_prefs, SharedRenderViewCounter* counter, int32 routing_id, int64 session_storage_namespace_id, const string16& frame_name) : RenderWidget(render_thread, WebKit::WebPopupTypeNone), webkit_preferences_(webkit_prefs), send_content_state_immediately_(false), enabled_bindings_(0), send_preferred_size_changes_(false), is_loading_(false), navigation_gesture_(NavigationGestureUnknown), opened_by_user_gesture_(true), opener_suppressed_(false), page_id_(-1), last_page_id_sent_to_browser_(-1), history_list_offset_(-1), history_list_length_(0), target_url_status_(TARGET_NONE), ALLOW_THIS_IN_INITIALIZER_LIST(pepper_delegate_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(accessibility_method_factory_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(cookie_jar_(this)), geolocation_dispatcher_(NULL), speech_input_dispatcher_(NULL), device_orientation_dispatcher_(NULL), accessibility_ack_pending_(false), p2p_socket_dispatcher_(NULL), session_storage_namespace_id_(session_storage_namespace_id) { routing_id_ = routing_id; if (opener_id != MSG_ROUTING_NONE) opener_id_ = opener_id; webwidget_ = WebView::create(this); if (counter) { shared_popup_counter_ = counter; shared_popup_counter_->data++; decrement_shared_popup_at_destruction_ = true; } else { shared_popup_counter_ = new SharedRenderViewCounter(0); decrement_shared_popup_at_destruction_ = false; } notification_provider_ = new NotificationProvider(this); render_thread_->AddRoute(routing_id_, this); AddRef(); if (opener_id == MSG_ROUTING_NONE) { did_show_ = true; CompleteInit(parent_hwnd); } g_view_map.Get().insert(std::make_pair(webview(), this)); webkit_preferences_.Apply(webview()); webview()->initializeMainFrame(this); if (!frame_name.empty()) webview()->mainFrame()->setName(frame_name); webview()->settings()->setMinimumTimerInterval( is_hidden() ? webkit_glue::kBackgroundTabTimerInterval : webkit_glue::kForegroundTabTimerInterval); OnSetRendererPrefs(renderer_prefs); host_window_ = parent_hwnd; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableAccessibility)) WebAccessibilityCache::enableAccessibility(); #if defined(ENABLE_P2P_APIS) p2p_socket_dispatcher_ = new P2PSocketDispatcher(this); #endif new MHTMLGenerator(this); if (command_line.HasSwitch(switches::kEnableMediaStream)) { media_stream_impl_ = new MediaStreamImpl( RenderThread::current()->video_capture_impl_manager()); } content::GetContentClient()->renderer()->RenderViewCreated(this); } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
RenderView::RenderView(RenderThreadBase* render_thread, gfx::NativeViewId parent_hwnd, int32 opener_id, const RendererPreferences& renderer_prefs, const WebPreferences& webkit_prefs, SharedRenderViewCounter* counter, int32 routing_id, int64 session_storage_namespace_id, const string16& frame_name) : RenderWidget(render_thread, WebKit::WebPopupTypeNone), webkit_preferences_(webkit_prefs), send_content_state_immediately_(false), enabled_bindings_(0), send_preferred_size_changes_(false), is_loading_(false), navigation_gesture_(NavigationGestureUnknown), opened_by_user_gesture_(true), opener_suppressed_(false), page_id_(-1), last_page_id_sent_to_browser_(-1), history_list_offset_(-1), history_list_length_(0), target_url_status_(TARGET_NONE), ALLOW_THIS_IN_INITIALIZER_LIST(pepper_delegate_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(accessibility_method_factory_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(cookie_jar_(this)), geolocation_dispatcher_(NULL), speech_input_dispatcher_(NULL), device_orientation_dispatcher_(NULL), accessibility_ack_pending_(false), p2p_socket_dispatcher_(NULL), session_storage_namespace_id_(session_storage_namespace_id) { routing_id_ = routing_id; if (opener_id != MSG_ROUTING_NONE) opener_id_ = opener_id; webwidget_ = WebView::create(this); if (counter) { shared_popup_counter_ = counter; shared_popup_counter_->data++; decrement_shared_popup_at_destruction_ = true; } else { shared_popup_counter_ = new SharedRenderViewCounter(0); decrement_shared_popup_at_destruction_ = false; } notification_provider_ = new NotificationProvider(this); render_thread_->AddRoute(routing_id_, this); AddRef(); if (opener_id == MSG_ROUTING_NONE) { did_show_ = true; CompleteInit(parent_hwnd); } g_view_map.Get().insert(std::make_pair(webview(), this)); webkit_preferences_.Apply(webview()); webview()->initializeMainFrame(this); if (!frame_name.empty()) webview()->mainFrame()->setName(frame_name); webview()->settings()->setMinimumTimerInterval( is_hidden() ? webkit_glue::kBackgroundTabTimerInterval : webkit_glue::kForegroundTabTimerInterval); OnSetRendererPrefs(renderer_prefs); host_window_ = parent_hwnd; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableAccessibility)) WebAccessibilityCache::enableAccessibility(); #if defined(ENABLE_P2P_APIS) p2p_socket_dispatcher_ = new P2PSocketDispatcher(this); #endif new MHTMLGenerator(this); new DevToolsAgent(this); if (command_line.HasSwitch(switches::kEnableMediaStream)) { media_stream_impl_ = new MediaStreamImpl( RenderThread::current()->video_capture_impl_manager()); } content::GetContentClient()->renderer()->RenderViewCreated(this); }
170,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FramePktHook(const vpx_codec_cx_pkt_t *pkt) { if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) { } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
174,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LayoutSVGContainer::layout() { ASSERT(needsLayout()); LayoutAnalyzer::Scope analyzer(*this); calcViewport(); bool updatedTransform = calculateLocalTransform(); m_didScreenScaleFactorChange = updatedTransform || SVGLayoutSupport::screenScaleFactorChanged(parent()); determineIfLayoutSizeChanged(); bool layoutSizeChanged = element()->hasRelativeLengths() && SVGLayoutSupport::layoutSizeOfNearestViewportChanged(this); SVGLayoutSupport::layoutChildren(firstChild(), false, m_didScreenScaleFactorChange, layoutSizeChanged); if (everHadLayout() && needsLayout()) SVGResourcesCache::clientLayoutChanged(this); if (m_needsBoundariesUpdate || updatedTransform) { updateCachedBoundaries(); m_needsBoundariesUpdate = false; LayoutSVGModelObject::setNeedsBoundariesUpdate(); } ASSERT(!m_needsBoundariesUpdate); clearNeedsLayout(); } Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers Currently, SVG containers in the LayoutObject hierarchy force layout of their children if the transform changes. The main reason for this is to trigger paint invalidation of the subtree. In some cases - changes to the scale factor - there are other reasons to trigger layout, like computing a new scale factor for <text> or re-layout nodes with non-scaling stroke. Compute a "scale-factor change" in addition to the "transform change" already computed, then use this new signal to determine if layout should be forced for the subtree. Trigger paint invalidation using the LayoutObject flags instead. The downside to this is that paint invalidation will walk into "hidden" containers which rarely require repaint (since they are not technically visible). This will hopefully be rectified in a follow-up CL. For the testcase from 603850, this essentially eliminates the cost of layout (from ~350ms to ~0ms on authors machine; layout cost is related to text metrics recalculation), bumping frame rate significantly. BUG=603956,603850 Review-Url: https://codereview.chromium.org/1996543002 Cr-Commit-Position: refs/heads/master@{#400950} CWE ID:
void LayoutSVGContainer::layout() { ASSERT(needsLayout()); LayoutAnalyzer::Scope analyzer(*this); calcViewport(); TransformChange transformChange = calculateLocalTransform(); m_didScreenScaleFactorChange = transformChange == TransformChange::Full || SVGLayoutSupport::screenScaleFactorChanged(parent()); determineIfLayoutSizeChanged(); bool layoutSizeChanged = element()->hasRelativeLengths() && SVGLayoutSupport::layoutSizeOfNearestViewportChanged(this); SVGLayoutSupport::layoutChildren(firstChild(), false, m_didScreenScaleFactorChange, layoutSizeChanged); if (everHadLayout() && needsLayout()) SVGResourcesCache::clientLayoutChanged(this); if (m_needsBoundariesUpdate || transformChange != TransformChange::None) { updateCachedBoundaries(); m_needsBoundariesUpdate = false; LayoutSVGModelObject::setNeedsBoundariesUpdate(); } ASSERT(!m_needsBoundariesUpdate); clearNeedsLayout(); }
171,664
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MockRenderThread::RemoveRoute(int32 routing_id) { EXPECT_EQ(routing_id_, routing_id); widget_ = NULL; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MockRenderThread::RemoveRoute(int32 routing_id) { // We may hear this for views created from OnMsgCreateWindow as well, // in which case we don't want to track the new widget. if (routing_id_ == routing_id) widget_ = NULL; }
171,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); }
172,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *, infop, int, options, struct rusage __user *, ru) { struct rusage r; struct waitid_info info = {.status = 0}; long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL); int signo = 0; if (err > 0) { signo = SIGCHLD; err = 0; } if (!err) { if (ru && copy_to_user(ru, &r, sizeof(struct rusage))) return -EFAULT; } if (!infop) return err; user_access_begin(); unsafe_put_user(signo, &infop->si_signo, Efault); unsafe_put_user(0, &infop->si_errno, Efault); unsafe_put_user(info.cause, &infop->si_code, Efault); unsafe_put_user(info.pid, &infop->si_pid, Efault); unsafe_put_user(info.uid, &infop->si_uid, Efault); unsafe_put_user(info.status, &infop->si_status, Efault); user_access_end(); return err; Efault: user_access_end(); return -EFAULT; } Commit Message: fix infoleak in waitid(2) kernel_waitid() can return a PID, an error or 0. rusage is filled in the first case and waitid(2) rusage should've been copied out exactly in that case, *not* whenever kernel_waitid() has not returned an error. Compat variant shares that braino; none of kernel_wait4() callers do, so the below ought to fix it. Reported-and-tested-by: Alexander Potapenko <[email protected]> Fixes: ce72a16fa705 ("wait4(2)/waitid(2): separate copying rusage to userland") Cc: [email protected] # v4.13 Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-200
SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *, infop, int, options, struct rusage __user *, ru) { struct rusage r; struct waitid_info info = {.status = 0}; long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL); int signo = 0; if (err > 0) { signo = SIGCHLD; err = 0; if (ru && copy_to_user(ru, &r, sizeof(struct rusage))) return -EFAULT; } if (!infop) return err; user_access_begin(); unsafe_put_user(signo, &infop->si_signo, Efault); unsafe_put_user(0, &infop->si_errno, Efault); unsafe_put_user(info.cause, &infop->si_code, Efault); unsafe_put_user(info.pid, &infop->si_pid, Efault); unsafe_put_user(info.uid, &infop->si_uid, Efault); unsafe_put_user(info.status, &infop->si_status, Efault); user_access_end(); return err; Efault: user_access_end(); return -EFAULT; }
167,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: OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; } Commit Message: DO NOT MERGE - libstagefright: check requested memory size before allocation for SoftMPEG4Encoder and SoftVPXEncoder. Bug: 25812794 Change-Id: I96dc74734380d462583f6efa33d09946f9532809 (cherry picked from commit 87f8cbb223ee516803dbb99699320c2484cbf3ba) (cherry picked from commit 0462975291796e414891e04bcec9da993914e458) CWE ID: CWE-119
OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = NULL; if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) { ALOGE("b/25812794, Buffer size is too big."); return OMX_ErrorBadParameter; } mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; }
173,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::TrackPosition* CuePoint::Find(const Track* pTrack) const { assert(pTrack); const long long n = pTrack->GetNumber(); const TrackPosition* i = m_track_positions; const TrackPosition* const j = i + m_track_positions_count; while (i != j) { const TrackPosition& p = *i++; if (p.m_track == n) return &p; } return NULL; //no matching track number found } 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 CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const const long long n = pTrack->GetNumber(); const TrackPosition* i = m_track_positions; const TrackPosition* const j = i + m_track_positions_count; while (i != j) { const TrackPosition& p = *i++; if (p.m_track == n) return &p; } return NULL; // no matching track number found }
174,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 int mem_write(jas_stream_obj_t *obj, char *buf, int cnt) { int n; int ret; jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newbufsize; long newpos; assert(buf); assert(cnt >= 0); JAS_DBGLOG(100, ("mem_write(%p, %p, %d)\n", obj, buf, cnt)); newpos = m->pos_ + cnt; if (newpos > m->bufsize_ && m->growable_) { newbufsize = m->bufsize_; while (newbufsize < newpos) { newbufsize <<= 1; assert(newbufsize >= 0); } JAS_DBGLOG(100, ("mem_write resizing from %d to %z\n", m->bufsize_, newbufsize)); JAS_DBGLOG(100, ("mem_write resizing from %d to %ul\n", m->bufsize_, JAS_CAST(unsigned long, newbufsize))); if (mem_resize(m, newbufsize)) { return -1; } } if (m->pos_ > m->len_) { /* The current position is beyond the end of the file, so pad the file to the current position with zeros. */ n = JAS_MIN(m->pos_, m->bufsize_) - m->len_; if (n > 0) { memset(&m->buf_[m->len_], 0, n); m->len_ += n; } if (m->pos_ != m->len_) { /* The buffer is not big enough. */ return 0; } } n = m->bufsize_ - m->pos_; ret = JAS_MIN(n, cnt); if (ret > 0) { memcpy(&m->buf_[m->pos_], buf, ret); m->pos_ += ret; } if (m->pos_ > m->len_) { m->len_ = m->pos_; } assert(ret == cnt); return ret; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt) { size_t n; int ret; jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; size_t newbufsize; size_t newpos; assert(buf); assert(cnt >= 0); JAS_DBGLOG(100, ("mem_write(%p, %p, %d)\n", obj, buf, cnt)); newpos = m->pos_ + cnt; if (newpos > m->bufsize_ && m->growable_) { newbufsize = m->bufsize_; while (newbufsize < newpos) { //newbufsize <<= 1; if (!jas_safe_size_mul(newbufsize, 2, &newbufsize)) { JAS_DBGLOG(100, ("new buffer size would cause overflow\n")); return -1; } } JAS_DBGLOG(100, ("mem_write resizing from %d to %zu\n", m->bufsize_, newbufsize)); assert(newbufsize > 0); if (mem_resize(m, newbufsize)) { return -1; } } if (m->pos_ > m->len_) { /* The current position is beyond the end of the file, so pad the file to the current position with zeros. */ n = JAS_MIN(m->pos_, m->bufsize_) - m->len_; if (n > 0) { memset(&m->buf_[m->len_], 0, n); m->len_ += n; } if (m->pos_ != m->len_) { /* The buffer is not big enough. */ return 0; } } n = m->bufsize_ - m->pos_; ret = JAS_MIN(n, cnt); if (ret > 0) { memcpy(&m->buf_[m->pos_], buf, ret); m->pos_ += ret; } if (m->pos_ > m->len_) { m->len_ = m->pos_; } assert(ret == cnt); return ret; }
168,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: static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK); len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE) { return -1; } qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ uint32_t len2 = off + len - 4096; uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; } } return 0; } Commit Message: CWE ID: CWE-20
static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp, xfers = 0; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK); len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE) { return -1; } qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ uint32_t len2 = off + len - 4096; uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; xfers++; } } return xfers ? 0 : -1; }
165,279
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_send_plaintext(int sock, xmlNode * msg) { char *xml_text = dump_xml_unformatted(msg); if (xml_text != NULL) { int rc = 0; char *unsent = xml_text; int len = strlen(xml_text); len++; /* null char */ crm_trace("Message on socket %d: size=%d", sock, len); retry: rc = write(sock, unsent, len); if (rc < 0) { switch (errno) { case EINTR: case EAGAIN: crm_trace("Retry"); goto retry; default: crm_perror(LOG_ERR, "Could only write %d of the remaining %d bytes", rc, len); break; } } else if (rc < len) { crm_trace("Only sent %d of %d remaining bytes", rc, len); len -= rc; unsent += rc; goto retry; } else { crm_trace("Sent %d bytes: %.100s", rc, xml_text); } } free(xml_text); return NULL; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_send_plaintext(int sock, xmlNode * msg) static int crm_send_plaintext(int sock, const char *buf, size_t len) { int rc = 0; const char *unsent = buf; int total_send; if (buf == NULL) { return -1; } total_send = len; crm_trace("Message on socket %d: size=%d", sock, len); retry: rc = write(sock, unsent, len); if (rc < 0) { switch (errno) { case EINTR: case EAGAIN: crm_trace("Retry"); goto retry; default: crm_perror(LOG_ERR, "Could only write %d of the remaining %d bytes", rc, (int) len); break; } } else if (rc < len) { crm_trace("Only sent %d of %d remaining bytes", rc, len); len -= rc; unsent += rc; goto retry; } else { crm_trace("Sent %d bytes: %.100s", rc, buf); } return rc < 0 ? rc : total_send; }
166,160
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext) { SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl); info->num_memslots = NUM_MEMSLOTS; info->num_memslots_groups = NUM_MEMSLOTS_GROUPS; info->internal_groupslot_id = 0; info->qxl_ram_size = ssd->bufsize; info->n_surfaces = ssd->num_surfaces; } Commit Message: CWE ID: CWE-200
static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext) { SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl); info->num_memslots = NUM_MEMSLOTS; info->num_memslots_groups = NUM_MEMSLOTS_GROUPS; info->internal_groupslot_id = 0; info->qxl_ram_size = 16 * 1024 * 1024; info->n_surfaces = ssd->num_surfaces; }
165,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CURLcode Curl_close(struct Curl_easy *data) { struct Curl_multi *m; if(!data) return CURLE_OK; Curl_expire_clear(data); /* shut off timers */ m = data->multi; if(m) /* This handle is still part of a multi handle, take care of this first and detach this handle from there. */ curl_multi_remove_handle(data->multi, data); if(data->multi_easy) /* when curl_easy_perform() is used, it creates its own multi handle to use and this is the one */ curl_multi_cleanup(data->multi_easy); /* Destroy the timeout list that is held in the easy handle. It is /normally/ done by curl_multi_remove_handle() but this is "just in case" */ Curl_llist_destroy(&data->state.timeoutlist, NULL); data->magic = 0; /* force a clear AFTER the possibly enforced removal from the multi handle, since that function uses the magic field! */ if(data->state.rangestringalloc) free(data->state.range); /* freed here just in case DONE wasn't called */ Curl_free_request_state(data); /* Close down all open SSL info and sessions */ Curl_ssl_close_all(data); Curl_safefree(data->state.first_host); Curl_safefree(data->state.scratch); Curl_ssl_free_certinfo(data); /* Cleanup possible redirect junk */ free(data->req.newurl); data->req.newurl = NULL; if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } data->change.referer = NULL; Curl_up_free(data); Curl_safefree(data->state.buffer); Curl_safefree(data->state.headerbuff); Curl_safefree(data->state.ulbuf); Curl_flush_cookies(data, 1); Curl_digest_cleanup(data); Curl_safefree(data->info.contenttype); Curl_safefree(data->info.wouldredirect); /* this destroys the channel and we cannot use it anymore after this */ Curl_resolver_cleanup(data->state.resolver); Curl_http2_cleanup_dependencies(data); Curl_convert_close(data); /* No longer a dirty share, if it exists */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* destruct wildcard structures if it is needed */ Curl_wildcard_dtor(&data->wildcard); Curl_freeset(data); free(data); return CURLE_OK; } Commit Message: Curl_close: clear data->multi_easy on free to avoid use-after-free Regression from b46cfbc068 (7.59.0) CVE-2018-16840 Reported-by: Brian Carpenter (Geeknik Labs) Bug: https://curl.haxx.se/docs/CVE-2018-16840.html CWE ID: CWE-416
CURLcode Curl_close(struct Curl_easy *data) { struct Curl_multi *m; if(!data) return CURLE_OK; Curl_expire_clear(data); /* shut off timers */ m = data->multi; if(m) /* This handle is still part of a multi handle, take care of this first and detach this handle from there. */ curl_multi_remove_handle(data->multi, data); if(data->multi_easy) { /* when curl_easy_perform() is used, it creates its own multi handle to use and this is the one */ curl_multi_cleanup(data->multi_easy); data->multi_easy = NULL; } /* Destroy the timeout list that is held in the easy handle. It is /normally/ done by curl_multi_remove_handle() but this is "just in case" */ Curl_llist_destroy(&data->state.timeoutlist, NULL); data->magic = 0; /* force a clear AFTER the possibly enforced removal from the multi handle, since that function uses the magic field! */ if(data->state.rangestringalloc) free(data->state.range); /* freed here just in case DONE wasn't called */ Curl_free_request_state(data); /* Close down all open SSL info and sessions */ Curl_ssl_close_all(data); Curl_safefree(data->state.first_host); Curl_safefree(data->state.scratch); Curl_ssl_free_certinfo(data); /* Cleanup possible redirect junk */ free(data->req.newurl); data->req.newurl = NULL; if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } data->change.referer = NULL; Curl_up_free(data); Curl_safefree(data->state.buffer); Curl_safefree(data->state.headerbuff); Curl_safefree(data->state.ulbuf); Curl_flush_cookies(data, 1); Curl_digest_cleanup(data); Curl_safefree(data->info.contenttype); Curl_safefree(data->info.wouldredirect); /* this destroys the channel and we cannot use it anymore after this */ Curl_resolver_cleanup(data->state.resolver); Curl_http2_cleanup_dependencies(data); Curl_convert_close(data); /* No longer a dirty share, if it exists */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* destruct wildcard structures if it is needed */ Curl_wildcard_dtor(&data->wildcard); Curl_freeset(data); free(data); return CURLE_OK; }
169,030
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context) { uint8_t tmp = 0; asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context)); asn1_read_uint8(data, &tmp); if (tmp == 0xFF) { *v = true; } else { *v = false; } asn1_end_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context) { uint8_t tmp = 0; if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context))) return false; *v = false; if (!asn1_read_uint8(data, &tmp)) return false; if (tmp == 0xFF) { *v = true; } return asn1_end_tag(data); }
164,584
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FLACParser::FLACParser( const sp<DataSource> &dataSource, const sp<MetaData> &fileMetadata, const sp<MetaData> &trackMetadata) : mDataSource(dataSource), mFileMetadata(fileMetadata), mTrackMetadata(trackMetadata), mInitCheck(false), mMaxBufferSize(0), mGroup(NULL), mCopy(copyTrespass), mDecoder(NULL), mCurrentPos(0LL), mEOF(false), mStreamInfoValid(false), mWriteRequested(false), mWriteCompleted(false), mWriteBuffer(NULL), mErrorStatus((FLAC__StreamDecoderErrorStatus) -1) { ALOGV("FLACParser::FLACParser"); memset(&mStreamInfo, 0, sizeof(mStreamInfo)); memset(&mWriteHeader, 0, sizeof(mWriteHeader)); mInitCheck = init(); } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
FLACParser::FLACParser( const sp<DataSource> &dataSource, const sp<MetaData> &fileMetadata, const sp<MetaData> &trackMetadata) : mDataSource(dataSource), mFileMetadata(fileMetadata), mTrackMetadata(trackMetadata), mInitCheck(false), mMaxBufferSize(0), mGroup(NULL), mCopy(copyTrespass), mDecoder(NULL), mCurrentPos(0LL), mEOF(false), mStreamInfoValid(false), mWriteRequested(false), mWriteCompleted(false), mErrorStatus((FLAC__StreamDecoderErrorStatus) -1) { ALOGV("FLACParser::FLACParser"); memset(&mStreamInfo, 0, sizeof(mStreamInfo)); memset(&mWriteHeader, 0, sizeof(mWriteHeader)); mInitCheck = init(); }
174,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: xmlParseNmtoken(xmlParserCtxtPtr ctxt) { xmlChar buf[XML_MAX_NAMELEN + 5]; int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNmToken++; #endif GROW; c = CUR_CHAR(l); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } COPY_BUF(l,buf,len,c); NEXTL(l); c = CUR_CHAR(l); if (len >= XML_MAX_NAMELEN) { /* * Okay someone managed to make a huge token, so he's ready to pay * for the processing speed. */ xmlChar *buffer; int max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } if (len + 10 > max) { xmlChar *tmp; max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } COPY_BUF(l,buffer,len,c); NEXTL(l); c = CUR_CHAR(l); } buffer[len] = 0; return(buffer); } } if (len == 0) return(NULL); return(xmlStrndup(buf, 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
xmlParseNmtoken(xmlParserCtxtPtr ctxt) { xmlChar buf[XML_MAX_NAMELEN + 5]; int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNmToken++; #endif GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } COPY_BUF(l,buf,len,c); NEXTL(l); c = CUR_CHAR(l); if (len >= XML_MAX_NAMELEN) { /* * Okay someone managed to make a huge token, so he's ready to pay * for the processing speed. */ xmlChar *buffer; int max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buffer); return(NULL); } } if (len + 10 > max) { xmlChar *tmp; max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } COPY_BUF(l,buffer,len,c); NEXTL(l); c = CUR_CHAR(l); } buffer[len] = 0; return(buffer); } } if (len == 0) return(NULL); return(xmlStrndup(buf, len)); }
171,298
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 gboolean netscreen_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) { gint64 offset; int pkt_len; char line[NETSCREEN_LINE_LENGTH]; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; gboolean cap_dir; char cap_dst[13]; /* Find the next packet */ offset = netscreen_seek_next_packet(wth, err, err_info, line); if (offset < 0) return FALSE; /* Parse the header */ pkt_len = parse_netscreen_rec_hdr(&wth->phdr, line, cap_int, &cap_dir, cap_dst, err, err_info); if (pkt_len == -1) return FALSE; /* Convert the ASCII hex dump to binary data, and fill in some struct wtap_pkthdr fields */ if (!parse_netscreen_hex_dump(wth->fh, pkt_len, cap_int, cap_dst, &wth->phdr, wth->frame_buffer, err, err_info)) return FALSE; /* * If the per-file encapsulation isn't known, set it to this * packet's encapsulation. * * If it *is* known, and it isn't this packet's encapsulation, * set it to WTAP_ENCAP_PER_PACKET, as this file doesn't * have a single encapsulation for all packets in the file. */ if (wth->file_encap == WTAP_ENCAP_UNKNOWN) wth->file_encap = wth->phdr.pkt_encap; else { if (wth->file_encap != wth->phdr.pkt_encap) wth->file_encap = WTAP_ENCAP_PER_PACKET; } *data_offset = offset; return TRUE; } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12396 Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f Reviewed-on: https://code.wireshark.org/review/15176 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20
static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) { gint64 offset; char line[NETSCREEN_LINE_LENGTH]; /* Find the next packet */ offset = netscreen_seek_next_packet(wth, err, err_info, line); if (offset < 0) return FALSE; /* Parse the header and convert the ASCII hex dump to binary data */ if (!parse_netscreen_packet(wth->fh, &wth->phdr, wth->frame_buffer, line, err, err_info)) return FALSE; /* * If the per-file encapsulation isn't known, set it to this * packet's encapsulation. * * If it *is* known, and it isn't this packet's encapsulation, * set it to WTAP_ENCAP_PER_PACKET, as this file doesn't * have a single encapsulation for all packets in the file. */ if (wth->file_encap == WTAP_ENCAP_UNKNOWN) wth->file_encap = wth->phdr.pkt_encap; else { if (wth->file_encap != wth->phdr.pkt_encap) wth->file_encap = WTAP_ENCAP_PER_PACKET; } *data_offset = offset; return TRUE; }
167,146
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len) { jas_stream_t *in; jas_iccprof_t *prof; if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len))) goto error; if (!(prof = jas_iccprof_load(in))) goto error; jas_stream_close(in); return prof; error: if (in) jas_stream_close(in); return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len) jas_iccprof_t *jas_iccprof_createfrombuf(jas_uchar *buf, int len) { jas_stream_t *in; jas_iccprof_t *prof; if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len))) goto error; if (!(prof = jas_iccprof_load(in))) goto error; jas_stream_close(in); return prof; error: if (in) jas_stream_close(in); return 0; }
168,688
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct dst_entry *inet_csk_route_req(struct sock *sk, const struct request_sock *req) { struct rtable *rt; const struct inet_request_sock *ireq = inet_rsk(req); struct ip_options *opt = inet_rsk(req)->opt; struct net *net = sock_net(sk); struct flowi4 fl4; flowi4_init_output(&fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), (opt && opt->srr) ? opt->faddr : ireq->rmt_addr, ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport); security_req_classify_flow(req, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) goto no_route; if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway) goto route_err; return &rt->dst; route_err: ip_rt_put(rt); no_route: IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES); return NULL; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
struct dst_entry *inet_csk_route_req(struct sock *sk, const struct request_sock *req) { struct rtable *rt; const struct inet_request_sock *ireq = inet_rsk(req); struct ip_options_rcu *opt = inet_rsk(req)->opt; struct net *net = sock_net(sk); struct flowi4 fl4; flowi4_init_output(&fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), (opt && opt->opt.srr) ? opt->opt.faddr : ireq->rmt_addr, ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport); security_req_classify_flow(req, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) goto no_route; if (opt && opt->opt.is_strictroute && rt->rt_dst != rt->rt_gateway) goto route_err; return &rt->dst; route_err: ip_rt_put(rt); no_route: IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES); return NULL; }
165,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 int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *sigalg, ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey)) /* Carry on */ return 2; return -1; } Commit Message: CWE ID:
static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *sigalg, ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) { /* Carry on */ return 2; } return -1; }
164,820
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_end(struct zlib *zlib) { /* Output the summary line now; this ensures a summary line always gets * output regardless of the manner of exit. */ if (!zlib->global->quiet) { if (zlib->ok_bits < 16) /* stream was read ok */ { const char *reason; if (zlib->cksum) reason = "CHK"; /* checksum error */ else if (zlib->ok_bits > zlib->file_bits) reason = "TFB"; /* fixing a too-far-back error */ else if (zlib->ok_bits == zlib->file_bits) reason = "OK "; else reason = "OPT"; /* optimizing window bits */ /* SUMMARY FORMAT (for a successful zlib inflate): * * IDAT reason flevel file-bits ok-bits compressed uncompressed file */ type_name(zlib->chunk->chunk_type, stdout); printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits, zlib->ok_bits); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits, stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } else { /* This is a zlib read error; the chunk will be skipped. For an IDAT * stream this will also cause a fatal read error (via stop()). * * SUMMARY FORMAT: * * IDAT SKP flevel file-bits z-rc compressed message file * * z-rc is the zlib failure code; message is the error message with * spaces replaced by '-'. The compressed byte count indicates where * in the zlib stream the error occured. */ type_name(zlib->chunk->chunk_type, stdout); printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits, zlib_rc(zlib)); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } } if (zlib->state >= 0) { zlib->rc = inflateEnd(&zlib->z); if (zlib->rc != Z_OK) zlib_message(zlib, 1/*unexpected*/); } CLEAR(*zlib); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
zlib_end(struct zlib *zlib) { /* Output the summary line now; this ensures a summary line always gets * output regardless of the manner of exit. */ if (!zlib->global->quiet) { if (zlib->ok_bits < 16) /* stream was read ok */ { const char *reason; if (zlib->cksum) reason = "CHK"; /* checksum error */ else if (zlib->ok_bits > zlib->file_bits) reason = "TFB"; /* fixing a too-far-back error */ else if (zlib->ok_bits == zlib->file_bits) reason = "OK "; else reason = "OPT"; /* optimizing window bits */ /* SUMMARY FORMAT (for a successful zlib inflate): * * IDAT reason flevel file-bits ok-bits compressed uncompressed file */ type_name(zlib->chunk->chunk_type, stdout); printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits, zlib->ok_bits); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits, stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } else { /* This is a zlib read error; the chunk will be skipped. For an IDAT * stream this will also cause a fatal read error (via stop()). * * SUMMARY FORMAT: * * IDAT SKP flevel file-bits z-rc compressed message file * * z-rc is the zlib failure code; message is the error message with * spaces replaced by '-'. The compressed byte count indicates where * in the zlib stream the error occurred. */ type_name(zlib->chunk->chunk_type, stdout); printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits, zlib_rc(zlib)); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } } if (zlib->state >= 0) { zlib->rc = inflateEnd(&zlib->z); if (zlib->rc != Z_OK) zlib_message(zlib, 1/*unexpected*/); } CLEAR(*zlib); }
173,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InstalledBubbleContent(Browser* browser, const Extension* extension, ExtensionInstalledBubble::BubbleType type, SkBitmap* icon, ExtensionInstalledBubble* bubble) : browser_(browser), extension_id_(extension->id()), bubble_(bubble), type_(type), info_(NULL) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont); gfx::Size size(icon->width(), icon->height()); if (size.width() > kIconSize || size.height() > kIconSize) size = gfx::Size(kIconSize, kIconSize); icon_ = new views::ImageView(); icon_->SetImageSize(size); icon_->SetImage(*icon); AddChildView(icon_); string16 extension_name = UTF8ToUTF16(extension->name()); base::i18n::AdjustStringForLocaleDirection(&extension_name); heading_ = new views::Label(l10n_util::GetStringFUTF16( IDS_EXTENSION_INSTALLED_HEADING, extension_name, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME))); heading_->SetFont(rb.GetFont(ResourceBundle::MediumFont)); heading_->SetMultiLine(true); heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(heading_); switch (type_) { case ExtensionInstalledBubble::PAGE_ACTION: { info_ = new views::Label(l10n_util::GetStringUTF16( IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO)); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); break; } case ExtensionInstalledBubble::OMNIBOX_KEYWORD: { info_ = new views::Label(l10n_util::GetStringFUTF16( IDS_EXTENSION_INSTALLED_OMNIBOX_KEYWORD_INFO, UTF8ToUTF16(extension->omnibox_keyword()))); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); break; } case ExtensionInstalledBubble::APP: { views::Link* link = new views::Link( l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_APP_INFO)); link->set_listener(this); manage_ = link; manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); break; } default: break; } if (type_ != ExtensionInstalledBubble::APP) { manage_ = new views::Label( l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_MANAGE_INFO)); manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); } close_button_ = new views::ImageButton(this); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetBitmapNamed(IDR_CLOSE_BAR)); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetBitmapNamed(IDR_CLOSE_BAR_H)); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetBitmapNamed(IDR_CLOSE_BAR_P)); AddChildView(close_button_); } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
InstalledBubbleContent(Browser* browser, const Extension* extension, ExtensionInstalledBubble::BubbleType type, SkBitmap* icon, ExtensionInstalledBubble* bubble) : browser_(browser), extension_id_(extension->id()), bubble_(bubble), type_(type), info_(NULL) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont); gfx::Size size(icon->width(), icon->height()); if (size.width() > kIconSize || size.height() > kIconSize) size = gfx::Size(kIconSize, kIconSize); icon_ = new views::ImageView(); icon_->SetImageSize(size); icon_->SetImage(*icon); AddChildView(icon_); string16 extension_name = UTF8ToUTF16(extension->name()); base::i18n::AdjustStringForLocaleDirection(&extension_name); heading_ = new views::Label(l10n_util::GetStringFUTF16( IDS_EXTENSION_INSTALLED_HEADING, extension_name)); heading_->SetFont(rb.GetFont(ResourceBundle::MediumFont)); heading_->SetMultiLine(true); heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(heading_); switch (type_) { case ExtensionInstalledBubble::PAGE_ACTION: { info_ = new views::Label(l10n_util::GetStringUTF16( IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO)); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); break; } case ExtensionInstalledBubble::OMNIBOX_KEYWORD: { info_ = new views::Label(l10n_util::GetStringFUTF16( IDS_EXTENSION_INSTALLED_OMNIBOX_KEYWORD_INFO, UTF8ToUTF16(extension->omnibox_keyword()))); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); break; } case ExtensionInstalledBubble::APP: { views::Link* link = new views::Link( l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_APP_INFO)); link->set_listener(this); manage_ = link; manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); break; } default: break; } if (type_ != ExtensionInstalledBubble::APP) { manage_ = new views::Label( l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_MANAGE_INFO)); manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); } close_button_ = new views::ImageButton(this); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetBitmapNamed(IDR_CLOSE_BAR)); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetBitmapNamed(IDR_CLOSE_BAR_H)); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetBitmapNamed(IDR_CLOSE_BAR_P)); AddChildView(close_button_); }
170,984
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg) { struct vivid_dev *dev = (struct vivid_dev *)info->par; switch (cmd) { case FBIOGET_VBLANK: { struct fb_vblank vblank; vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT | FB_VBLANK_HAVE_VSYNC; vblank.count = 0; vblank.vcount = 0; vblank.hcount = 0; if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank))) return -EFAULT; return 0; } default: dprintk(dev, 1, "Unknown ioctl %08x\n", cmd); return -EINVAL; } return 0; } Commit Message: [media] media/vivid-osd: fix info leak in ioctl The vivid_fb_ioctl() code fails to initialize the 16 _reserved bytes of struct fb_vblank after the ->hcount member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <[email protected]> Signed-off-by: Hans Verkuil <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-200
static int vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg) { struct vivid_dev *dev = (struct vivid_dev *)info->par; switch (cmd) { case FBIOGET_VBLANK: { struct fb_vblank vblank; memset(&vblank, 0, sizeof(vblank)); vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT | FB_VBLANK_HAVE_VSYNC; vblank.count = 0; vblank.vcount = 0; vblank.hcount = 0; if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank))) return -EFAULT; return 0; } default: dprintk(dev, 1, "Unknown ioctl %08x\n", cmd); return -EINVAL; } return 0; }
166,575
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigateOnUIThread( const GURL& url, const std::vector<GURL> url_chain, const Referrer& referrer, bool has_user_gesture, const ResourceRequestInfo::WebContentsGetter& wc_getter) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = wc_getter.Run(); if (web_contents) { NavigationController::LoadURLParams params(url); params.has_user_gesture = has_user_gesture; params.referrer = referrer; params.redirect_chain = url_chain; web_contents->GetController().LoadURLWithParams(params); } } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
void NavigateOnUIThread( void NavigateOnUIThread(const GURL& url, const std::vector<GURL> url_chain, const Referrer& referrer, bool has_user_gesture, const ResourceRequestInfo::WebContentsGetter& wc_getter, int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = wc_getter.Run(); if (web_contents) { NavigationController::LoadURLParams params(url); params.has_user_gesture = has_user_gesture; params.referrer = referrer; params.redirect_chain = url_chain; params.frame_tree_node_id = frame_tree_node_id; web_contents->GetController().LoadURLWithParams(params); } }
173,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc) { uint32* wp = (uint32*) cp0; tmsize_t wc = cc / 4; horDiff32(tif, cp0, cc); TIFFSwabArrayOfLong(wp, wc); } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc) { uint32* wp = (uint32*) cp0; tmsize_t wc = cc / 4; if( !horDiff32(tif, cp0, cc) ) return 0; TIFFSwabArrayOfLong(wp, wc); return 1; }
166,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mptsas_process_scsi_io_request(MPTSASState *s, MPIMsgSCSIIORequest *scsi_io, hwaddr addr) { MPTSASRequest *req; MPIMsgSCSIIOReply reply; SCSIDevice *sdev; int status; mptsas_fix_scsi_io_endianness(scsi_io); trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID, scsi_io->LUN[1], scsi_io->DataLength); status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID, scsi_io->LUN, &sdev); if (status) { goto bad; } req = g_new(MPTSASRequest, 1); QTAILQ_INSERT_TAIL(&s->pending, req, next); req->scsi_io = *scsi_io; req->dev = s; status = mptsas_build_sgl(s, req, addr); if (status) { goto free_bad; } if (req->qsg.size < scsi_io->DataLength) { trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength, req->qsg.size); status = MPI_IOCSTATUS_INVALID_SGL; goto free_bad; } req->sreq = scsi_req_new(sdev, scsi_io->MsgContext, scsi_io->LUN[1], scsi_io->CDB, req); if (req->sreq->cmd.xfer > scsi_io->DataLength) { goto overrun; } switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) { case MPI_SCSIIO_CONTROL_NODATATRANSFER: if (req->sreq->cmd.mode != SCSI_XFER_NONE) { goto overrun; } break; case MPI_SCSIIO_CONTROL_WRITE: if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) { goto overrun; } break; case MPI_SCSIIO_CONTROL_READ: if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) { goto overrun; } break; } if (scsi_req_enqueue(req->sreq)) { scsi_req_continue(req->sreq); } return 0; overrun: trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer, scsi_io->DataLength); status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN; free_bad: mptsas_free_request(req); bad: memset(&reply, 0, sizeof(reply)); reply.TargetID = scsi_io->TargetID; reply.Bus = scsi_io->Bus; reply.MsgLength = sizeof(reply) / 4; reply.Function = scsi_io->Function; reply.CDBLength = scsi_io->CDBLength; reply.SenseBufferLength = scsi_io->SenseBufferLength; reply.MsgContext = scsi_io->MsgContext; reply.SCSIState = MPI_SCSI_STATE_NO_SCSI_STATUS; reply.IOCStatus = status; mptsas_fix_scsi_io_reply_endianness(&reply); mptsas_reply(s, (MPIDefaultReply *)&reply); return 0; } Commit Message: CWE ID: CWE-787
static int mptsas_process_scsi_io_request(MPTSASState *s, MPIMsgSCSIIORequest *scsi_io, hwaddr addr) { MPTSASRequest *req; MPIMsgSCSIIOReply reply; SCSIDevice *sdev; int status; mptsas_fix_scsi_io_endianness(scsi_io); trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID, scsi_io->LUN[1], scsi_io->DataLength); status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID, scsi_io->LUN, &sdev); if (status) { goto bad; } req = g_new0(MPTSASRequest, 1); QTAILQ_INSERT_TAIL(&s->pending, req, next); req->scsi_io = *scsi_io; req->dev = s; status = mptsas_build_sgl(s, req, addr); if (status) { goto free_bad; } if (req->qsg.size < scsi_io->DataLength) { trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength, req->qsg.size); status = MPI_IOCSTATUS_INVALID_SGL; goto free_bad; } req->sreq = scsi_req_new(sdev, scsi_io->MsgContext, scsi_io->LUN[1], scsi_io->CDB, req); if (req->sreq->cmd.xfer > scsi_io->DataLength) { goto overrun; } switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) { case MPI_SCSIIO_CONTROL_NODATATRANSFER: if (req->sreq->cmd.mode != SCSI_XFER_NONE) { goto overrun; } break; case MPI_SCSIIO_CONTROL_WRITE: if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) { goto overrun; } break; case MPI_SCSIIO_CONTROL_READ: if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) { goto overrun; } break; } if (scsi_req_enqueue(req->sreq)) { scsi_req_continue(req->sreq); } return 0; overrun: trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer, scsi_io->DataLength); status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN; free_bad: mptsas_free_request(req); bad: memset(&reply, 0, sizeof(reply)); reply.TargetID = scsi_io->TargetID; reply.Bus = scsi_io->Bus; reply.MsgLength = sizeof(reply) / 4; reply.Function = scsi_io->Function; reply.CDBLength = scsi_io->CDBLength; reply.SenseBufferLength = scsi_io->SenseBufferLength; reply.MsgContext = scsi_io->MsgContext; reply.SCSIState = MPI_SCSI_STATE_NO_SCSI_STATUS; reply.IOCStatus = status; mptsas_fix_scsi_io_reply_endianness(&reply); mptsas_reply(s, (MPIDefaultReply *)&reply); return 0; }
164,928
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintingMessageFilter::OnUpdatePrintSettings( int document_cookie, const DictionaryValue& job_settings, IPC::Message* reply_msg) { scoped_refptr<printing::PrinterQuery> printer_query; print_job_manager_->PopPrinterQuery(document_cookie, &printer_query); if (printer_query.get()) { CancelableTask* task = NewRunnableMethod( this, &PrintingMessageFilter::OnUpdatePrintSettingsReply, printer_query, reply_msg); printer_query->SetSettings(job_settings, task); } } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintingMessageFilter::OnUpdatePrintSettings( int document_cookie, const DictionaryValue& job_settings, IPC::Message* reply_msg) { scoped_refptr<printing::PrinterQuery> printer_query; if (!print_job_manager_->printing_enabled()) { // Reply with NULL query. OnUpdatePrintSettingsReply(printer_query, reply_msg); return; } print_job_manager_->PopPrinterQuery(document_cookie, &printer_query); if (!printer_query.get()) printer_query = new printing::PrinterQuery; CancelableTask* task = NewRunnableMethod( this, &PrintingMessageFilter::OnUpdatePrintSettingsReply, printer_query, reply_msg); printer_query->SetSettings(job_settings, task); }
170,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dpcm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; const uint8_t *buf_end = buf + buf_size; DPCMContext *s = avctx->priv_data; int out = 0, ret; int predictor[2]; int ch = 0; int stereo = s->channels - 1; int16_t *output_samples; /* calculate output size */ switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: case CODEC_ID_XAN_DPCM: out = buf_size - 2 * s->channels; break; case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) out = buf_size * 2; else out = buf_size; break; } if (out <= 0) { av_log(avctx, AV_LOG_ERROR, "packet is too small\n"); return AVERROR(EINVAL); } /* get output buffer */ s->frame.nb_samples = out / s->channels; if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; } output_samples = (int16_t *)s->frame.data[0]; switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: buf += 6; if (stereo) { predictor[1] = (int16_t)(bytestream_get_byte(&buf) << 8); predictor[0] = (int16_t)(bytestream_get_byte(&buf) << 8); } else { predictor[0] = (int16_t)bytestream_get_le16(&buf); } /* decode the samples */ while (buf < buf_end) { predictor[ch] += s->roq_square_array[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_INTERPLAY_DPCM: buf += 6; /* skip over the stream mask and stream length */ for (ch = 0; ch < s->channels; ch++) { predictor[ch] = (int16_t)bytestream_get_le16(&buf); *output_samples++ = predictor[ch]; } ch = 0; while (buf < buf_end) { predictor[ch] += interplay_delta_table[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_XAN_DPCM: { int shift[2] = { 4, 4 }; for (ch = 0; ch < s->channels; ch++) predictor[ch] = (int16_t)bytestream_get_le16(&buf); ch = 0; while (buf < buf_end) { uint8_t n = *buf++; int16_t diff = (n & 0xFC) << 8; if ((n & 0x03) == 3) shift[ch]++; else shift[ch] -= (2 * (n & 3)); /* saturate the shifter to a lower limit of 0 */ if (shift[ch] < 0) shift[ch] = 0; diff >>= shift[ch]; predictor[ch] += diff; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; } case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) { uint8_t *output_samples_u8 = s->frame.data[0]; while (buf < buf_end) { uint8_t n = *buf++; s->sample[0] += s->sol_table[n >> 4]; s->sample[0] = av_clip_uint8(s->sample[0]); *output_samples_u8++ = s->sample[0]; s->sample[stereo] += s->sol_table[n & 0x0F]; s->sample[stereo] = av_clip_uint8(s->sample[stereo]); *output_samples_u8++ = s->sample[stereo]; } } else { while (buf < buf_end) { uint8_t n = *buf++; if (n & 0x80) s->sample[ch] -= sol_table_16[n & 0x7F]; else s->sample[ch] += sol_table_16[n & 0x7F]; s->sample[ch] = av_clip_int16(s->sample[ch]); *output_samples++ = s->sample[ch]; /* toggle channel */ ch ^= stereo; } } break; } *got_frame_ptr = 1; *(AVFrame *)data = s->frame; return buf_size; } Commit Message: CWE ID: CWE-119
static int dpcm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; const uint8_t *buf_end = buf + buf_size; DPCMContext *s = avctx->priv_data; int out = 0, ret; int predictor[2]; int ch = 0; int stereo = s->channels - 1; int16_t *output_samples; if (stereo && (buf_size & 1)) { buf_size--; buf_end--; } /* calculate output size */ switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: case CODEC_ID_XAN_DPCM: out = buf_size - 2 * s->channels; break; case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) out = buf_size * 2; else out = buf_size; break; } if (out <= 0) { av_log(avctx, AV_LOG_ERROR, "packet is too small\n"); return AVERROR(EINVAL); } /* get output buffer */ s->frame.nb_samples = out / s->channels; if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; } output_samples = (int16_t *)s->frame.data[0]; switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: buf += 6; if (stereo) { predictor[1] = (int16_t)(bytestream_get_byte(&buf) << 8); predictor[0] = (int16_t)(bytestream_get_byte(&buf) << 8); } else { predictor[0] = (int16_t)bytestream_get_le16(&buf); } /* decode the samples */ while (buf < buf_end) { predictor[ch] += s->roq_square_array[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_INTERPLAY_DPCM: buf += 6; /* skip over the stream mask and stream length */ for (ch = 0; ch < s->channels; ch++) { predictor[ch] = (int16_t)bytestream_get_le16(&buf); *output_samples++ = predictor[ch]; } ch = 0; while (buf < buf_end) { predictor[ch] += interplay_delta_table[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_XAN_DPCM: { int shift[2] = { 4, 4 }; for (ch = 0; ch < s->channels; ch++) predictor[ch] = (int16_t)bytestream_get_le16(&buf); ch = 0; while (buf < buf_end) { uint8_t n = *buf++; int16_t diff = (n & 0xFC) << 8; if ((n & 0x03) == 3) shift[ch]++; else shift[ch] -= (2 * (n & 3)); /* saturate the shifter to a lower limit of 0 */ if (shift[ch] < 0) shift[ch] = 0; diff >>= shift[ch]; predictor[ch] += diff; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; } case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) { uint8_t *output_samples_u8 = s->frame.data[0]; while (buf < buf_end) { uint8_t n = *buf++; s->sample[0] += s->sol_table[n >> 4]; s->sample[0] = av_clip_uint8(s->sample[0]); *output_samples_u8++ = s->sample[0]; s->sample[stereo] += s->sol_table[n & 0x0F]; s->sample[stereo] = av_clip_uint8(s->sample[stereo]); *output_samples_u8++ = s->sample[stereo]; } } else { while (buf < buf_end) { uint8_t n = *buf++; if (n & 0x80) s->sample[ch] -= sol_table_16[n & 0x7F]; else s->sample[ch] += sol_table_16[n & 0x7F]; s->sample[ch] = av_clip_int16(s->sample[ch]); *output_samples++ = s->sample[ch]; /* toggle channel */ ch ^= stereo; } } break; } *got_frame_ptr = 1; *(AVFrame *)data = s->frame; return buf_size; }
165,241
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 u_int mp_dss_len(const struct mp_dss *m, int csum) { u_int len; len = 4; if (m->flags & MP_DSS_A) { /* Ack present - 4 or 8 octets */ len += (m->flags & MP_DSS_a) ? 8 : 4; } if (m->flags & MP_DSS_M) { /* * Data Sequence Number (DSN), Subflow Sequence Number (SSN), * Data-Level Length present, and Checksum possibly present. * All but the Checksum are 10 bytes if the m flag is * clear (4-byte DSN) and 14 bytes if the m flag is set * (8-byte DSN). */ len += (m->flags & MP_DSS_m) ? 14 : 10; /* * The Checksum is present only if negotiated. */ if (csum) len += 2; } return len; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
static u_int mp_dss_len(const struct mp_dss *m, int csum)
167,836
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size) { ssize_t ret; guint watch; assert(qemu_in_coroutine()); /* Negotiation are always in main loop. */ watch = qio_channel_add_watch(ioc, G_IO_IN, nbd_negotiate_continue, qemu_coroutine_self(), NULL); ret = nbd_read(ioc, buffer, size, NULL); g_source_remove(watch); return ret; } Commit Message: CWE ID: CWE-20
static int nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size)
165,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); }
167,033
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { RemoveInterstitialObservers(old_contents); AddInterstitialObservers(new_contents->web_contents()); } 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 BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { RemoveInterstitialObservers(old_contents->web_contents()); AddInterstitialObservers(new_contents->web_contents()); }
171,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e, const char *hookname, const char **chainname, const char **comment, unsigned int *rulenum) { const struct xt_standard_target *t = (void *)ip6t_get_target_c(s); if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) { /* Head of user chain: ERROR target with chainname */ *chainname = t->target.data; (*rulenum) = 0; } else if (s == e) { (*rulenum)++; if (s->target_offset == sizeof(struct ip6t_entry) && strcmp(t->target.u.kernel.target->name, XT_STANDARD_TARGET) == 0 && t->verdict < 0 && unconditional(&s->ipv6)) { /* Tail of chains: STANDARD target (return/policy) */ *comment = *chainname == hookname ? comments[NF_IP6_TRACE_COMMENT_POLICY] : comments[NF_IP6_TRACE_COMMENT_RETURN]; } return 1; } else (*rulenum)++; return 0; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e, const char *hookname, const char **chainname, const char **comment, unsigned int *rulenum) { const struct xt_standard_target *t = (void *)ip6t_get_target_c(s); if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) { /* Head of user chain: ERROR target with chainname */ *chainname = t->target.data; (*rulenum) = 0; } else if (s == e) { (*rulenum)++; if (unconditional(s) && strcmp(t->target.u.kernel.target->name, XT_STANDARD_TARGET) == 0 && t->verdict < 0) { /* Tail of chains: STANDARD target (return/policy) */ *comment = *chainname == hookname ? comments[NF_IP6_TRACE_COMMENT_POLICY] : comments[NF_IP6_TRACE_COMMENT_RETURN]; } return 1; } else (*rulenum)++; return 0; }
167,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::Display::Display() { } 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
Chapters::Display::Display()
174,263
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WallpaperManager::OnWallpaperDecoded( const AccountId& account_id, const wallpaper::WallpaperInfo& info, bool update_wallpaper, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT_ASYNC_END0("ui", "LoadAndDecodeWallpaper", this); if (user_image->image().isNull()) { wallpaper::WallpaperInfo default_info( "", wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetUserWallpaperInfo(account_id, default_info, true); if (update_wallpaper) DoSetDefaultWallpaper(account_id, std::move(on_finish)); return; } wallpaper_cache_[account_id].second = user_image->image(); if (update_wallpaper) SetWallpaper(user_image->image(), info); } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200
void WallpaperManager::OnWallpaperDecoded( const AccountId& account_id, const wallpaper::WallpaperInfo& info, bool update_wallpaper, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT_ASYNC_END0("ui", "LoadAndDecodeWallpaper", this); if (user_image->image().isNull()) { wallpaper::WallpaperInfo default_info( "", wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetUserWallpaperInfo(account_id, default_info, true); DoSetDefaultWallpaper(account_id, update_wallpaper, std::move(on_finish)); return; } wallpaper_cache_[account_id].second = user_image->image(); if (update_wallpaper) SetWallpaper(user_image->image(), info); }
171,968
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void pdf_load_pages_kids(FILE *fp, pdf_t *pdf) { int i, id, dummy; char *buf, *c; long start, sz; start = ftell(fp); /* Load all kids for all xref tables (versions) */ for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0)) { fseek(fp, pdf->xrefs[i].start, SEEK_SET); while (SAFE_F(fp, (fgetc(fp) != 't'))) ; /* Iterate to trailer */ /* Get root catalog */ sz = pdf->xrefs[i].end - ftell(fp); buf = malloc(sz + 1); SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n"); buf[sz] = '\0'; if (!(c = strstr(buf, "/Root"))) { free(buf); continue; } /* Jump to catalog (root) */ id = atoi(c + strlen("/Root") + 1); free(buf); buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy); if (!buf || !(c = strstr(buf, "/Pages"))) { free(buf); continue; } /* Start at the first Pages obj and get kids */ id = atoi(c + strlen("/Pages") + 1); load_kids(fp, id, &pdf->xrefs[i]); free(buf); } } fseek(fp, start, SEEK_SET); } 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
void pdf_load_pages_kids(FILE *fp, pdf_t *pdf) { int i, id, dummy; char *buf, *c; long start, sz; start = ftell(fp); /* Load all kids for all xref tables (versions) */ for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0)) { fseek(fp, pdf->xrefs[i].start, SEEK_SET); while (SAFE_F(fp, (fgetc(fp) != 't'))) ; /* Iterate to trailer */ /* Get root catalog */ sz = pdf->xrefs[i].end - ftell(fp); buf = safe_calloc(sz + 1); SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n"); buf[sz] = '\0'; if (!(c = strstr(buf, "/Root"))) { free(buf); continue; } /* Jump to catalog (root) */ id = atoi(c + strlen("/Root") + 1); free(buf); buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy); if (!buf || !(c = strstr(buf, "/Pages"))) { free(buf); continue; } /* Start at the first Pages obj and get kids */ id = atoi(c + strlen("/Pages") + 1); load_kids(fp, id, &pdf->xrefs[i]); free(buf); } } fseek(fp, start, SEEK_SET); }
169,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cg_getattr(const char *path, struct stat *sb) { struct timespec now; struct fuse_context *fc = fuse_get_context(); char * cgdir = NULL; char *fpath = NULL, *path1, *path2; struct cgfs_files *k = NULL; const char *cgroup; const char *controller = NULL; int ret = -ENOENT; if (!fc) return -EIO; memset(sb, 0, sizeof(struct stat)); if (clock_gettime(CLOCK_REALTIME, &now) < 0) return -EINVAL; sb->st_uid = sb->st_gid = 0; sb->st_atim = sb->st_mtim = sb->st_ctim = now; sb->st_size = 0; if (strcmp(path, "/cgroup") == 0) { sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { path1 = "/"; path2 = cgdir; } else { path1 = cgdir; path2 = fpath; } /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys. * Then check that caller's cgroup is under path if fpath is a child * cgroup, or cgdir if fpath is a file */ if (is_child_cgroup(controller, path1, path2)) { if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00555; sb->st_nlink = 2; ret = 0; goto out; } if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) { ret = -EACCES; goto out; } sb->st_mode = S_IFDIR | 00755; k = cgfs_get_key(controller, cgroup, "tasks"); if (!k) { sb->st_uid = sb->st_gid = 0; } else { sb->st_uid = k->uid; sb->st_gid = k->gid; } free_key(k); sb->st_nlink = 2; ret = 0; goto out; } if ((k = cgfs_get_key(controller, path1, path2)) != NULL) { sb->st_mode = S_IFREG | k->mode; sb->st_nlink = 1; sb->st_uid = k->uid; sb->st_gid = k->gid; sb->st_size = 0; free_key(k); if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) { ret = -EACCES; goto out; } ret = 0; } out: free(cgdir); return ret; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static int cg_getattr(const char *path, struct stat *sb) { struct timespec now; struct fuse_context *fc = fuse_get_context(); char * cgdir = NULL; char *fpath = NULL, *path1, *path2; struct cgfs_files *k = NULL; const char *cgroup; const char *controller = NULL; int ret = -ENOENT; if (!fc) return -EIO; memset(sb, 0, sizeof(struct stat)); if (clock_gettime(CLOCK_REALTIME, &now) < 0) return -EINVAL; sb->st_uid = sb->st_gid = 0; sb->st_atim = sb->st_mtim = sb->st_ctim = now; sb->st_size = 0; if (strcmp(path, "/cgroup") == 0) { sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { path1 = "/"; path2 = cgdir; } else { path1 = cgdir; path2 = fpath; } /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys. * Then check that caller's cgroup is under path if fpath is a child * cgroup, or cgdir if fpath is a file */ if (is_child_cgroup(controller, path1, path2)) { if (!caller_may_see_dir(fc->pid, controller, cgroup)) { ret = -ENOENT; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00555; sb->st_nlink = 2; ret = 0; goto out; } if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) { ret = -EACCES; goto out; } sb->st_mode = S_IFDIR | 00755; k = cgfs_get_key(controller, cgroup, "tasks"); if (!k) { sb->st_uid = sb->st_gid = 0; } else { sb->st_uid = k->uid; sb->st_gid = k->gid; } free_key(k); sb->st_nlink = 2; ret = 0; goto out; } if ((k = cgfs_get_key(controller, path1, path2)) != NULL) { sb->st_mode = S_IFREG | k->mode; sb->st_nlink = 1; sb->st_uid = k->uid; sb->st_gid = k->gid; sb->st_size = 0; free_key(k); if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) { ret = -EACCES; goto out; } ret = 0; } out: free(cgdir); return ret; }
166,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tmsize_t stride = sp->stride; uint16 *wp = (uint16*) cp0; tmsize_t wc = cc/2; assert((cc%(2*stride))==0); if (wc > stride) { wc -= stride; wp += wc - 1; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--) wc -= stride; } while (wc > 0); } } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tmsize_t stride = sp->stride; uint16 *wp = (uint16*) cp0; tmsize_t wc = cc/2; if((cc%(2*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "horDiff8", "%s", "(cc%(2*stride))!=0"); return 0; } if (wc > stride) { wc -= stride; wp += wc - 1; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--) wc -= stride; } while (wc > 0); } return 1; }
166,885
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int packet_do_bind(struct sock *sk, const char *name, int ifindex, __be16 proto) { struct packet_sock *po = pkt_sk(sk); struct net_device *dev_curr; __be16 proto_curr; bool need_rehook; struct net_device *dev = NULL; int ret = 0; bool unlisted = false; if (po->fanout) return -EINVAL; lock_sock(sk); spin_lock(&po->bind_lock); rcu_read_lock(); if (name) { dev = dev_get_by_name_rcu(sock_net(sk), name); if (!dev) { ret = -ENODEV; goto out_unlock; } } else if (ifindex) { dev = dev_get_by_index_rcu(sock_net(sk), ifindex); if (!dev) { ret = -ENODEV; goto out_unlock; } } if (dev) dev_hold(dev); proto_curr = po->prot_hook.type; dev_curr = po->prot_hook.dev; need_rehook = proto_curr != proto || dev_curr != dev; if (need_rehook) { if (po->running) { rcu_read_unlock(); __unregister_prot_hook(sk, true); rcu_read_lock(); dev_curr = po->prot_hook.dev; if (dev) unlisted = !dev_get_by_index_rcu(sock_net(sk), dev->ifindex); } po->num = proto; po->prot_hook.type = proto; if (unlikely(unlisted)) { dev_put(dev); po->prot_hook.dev = NULL; po->ifindex = -1; packet_cached_dev_reset(po); } else { po->prot_hook.dev = dev; po->ifindex = dev ? dev->ifindex : 0; packet_cached_dev_assign(po, dev); } } if (dev_curr) dev_put(dev_curr); if (proto == 0 || !need_rehook) goto out_unlock; if (!unlisted && (!dev || (dev->flags & IFF_UP))) { register_prot_hook(sk); } else { sk->sk_err = ENETDOWN; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_error_report(sk); } out_unlock: rcu_read_unlock(); spin_unlock(&po->bind_lock); release_sock(sk); return ret; } Commit Message: packet: in packet_do_bind, test fanout with bind_lock held Once a socket has po->fanout set, it remains a member of the group until it is destroyed. The prot_hook must be constant and identical across sockets in the group. If fanout_add races with packet_do_bind between the test of po->fanout and taking the lock, the bind call may make type or dev inconsistent with that of the fanout group. Hold po->bind_lock when testing po->fanout to avoid this race. I had to introduce artificial delay (local_bh_enable) to actually observe the race. Fixes: dc99f600698d ("packet: Add fanout support.") Signed-off-by: Willem de Bruijn <[email protected]> Reviewed-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int packet_do_bind(struct sock *sk, const char *name, int ifindex, __be16 proto) { struct packet_sock *po = pkt_sk(sk); struct net_device *dev_curr; __be16 proto_curr; bool need_rehook; struct net_device *dev = NULL; int ret = 0; bool unlisted = false; lock_sock(sk); spin_lock(&po->bind_lock); rcu_read_lock(); if (po->fanout) { ret = -EINVAL; goto out_unlock; } if (name) { dev = dev_get_by_name_rcu(sock_net(sk), name); if (!dev) { ret = -ENODEV; goto out_unlock; } } else if (ifindex) { dev = dev_get_by_index_rcu(sock_net(sk), ifindex); if (!dev) { ret = -ENODEV; goto out_unlock; } } if (dev) dev_hold(dev); proto_curr = po->prot_hook.type; dev_curr = po->prot_hook.dev; need_rehook = proto_curr != proto || dev_curr != dev; if (need_rehook) { if (po->running) { rcu_read_unlock(); __unregister_prot_hook(sk, true); rcu_read_lock(); dev_curr = po->prot_hook.dev; if (dev) unlisted = !dev_get_by_index_rcu(sock_net(sk), dev->ifindex); } po->num = proto; po->prot_hook.type = proto; if (unlikely(unlisted)) { dev_put(dev); po->prot_hook.dev = NULL; po->ifindex = -1; packet_cached_dev_reset(po); } else { po->prot_hook.dev = dev; po->ifindex = dev ? dev->ifindex : 0; packet_cached_dev_assign(po, dev); } } if (dev_curr) dev_put(dev_curr); if (proto == 0 || !need_rehook) goto out_unlock; if (!unlisted && (!dev || (dev->flags & IFF_UP))) { register_prot_hook(sk); } else { sk->sk_err = ENETDOWN; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_error_report(sk); } out_unlock: rcu_read_unlock(); spin_unlock(&po->bind_lock); release_sock(sk); return ret; }
167,717
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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: ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin() : speech_synthesizer_(NULL), paused_(false) { CoCreateInstance( CLSID_SpVoice, NULL, CLSCTX_SERVER, IID_ISpVoice, reinterpret_cast<void**>(&speech_synthesizer_)); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin() : speech_synthesizer_(NULL), paused_(false) { CoCreateInstance( CLSID_SpVoice, NULL, CLSCTX_SERVER, IID_ISpVoice, reinterpret_cast<void**>(&speech_synthesizer_)); if (speech_synthesizer_) { ULONGLONG event_mask = SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_TTS_BOOKMARK) | SPFEI(SPEI_WORD_BOUNDARY) | SPFEI(SPEI_SENTENCE_BOUNDARY) | SPFEI(SPEI_END_INPUT_STREAM); speech_synthesizer_->SetInterest(event_mask, event_mask); speech_synthesizer_->SetNotifyCallbackFunction( ExtensionTtsPlatformImplWin::SpeechEventCallback, 0, 0); } }
170,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::SetPinCode(const std::string& pincode) { if (!agent_.get() || pincode_callback_.is_null()) return; pincode_callback_.Run(SUCCESS, pincode); pincode_callback_.Reset(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::SetPinCode(const std::string& pincode) { if (!pairing_context_.get()) return; pairing_context_->SetPinCode(pincode); }
171,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr=val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); }
169,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: htc_request_check_host_hdr(struct http *hp) { int u; int seen_host = 0; for (u = HTTP_HDR_FIRST; u < hp->nhd; u++) { if (hp->hd[u].b == NULL) continue; AN(hp->hd[u].b); AN(hp->hd[u].e); if (http_IsHdr(&hp->hd[u], H_Host)) { if (seen_host) { return (400); } seen_host = 1; } } return (0); } Commit Message: Check for duplicate Content-Length headers in requests If a duplicate CL header is in the request, we fail the request with a 400 (Bad Request) Fix a test case that was sending duplicate CL by misstake and would not fail because of that. CWE ID:
htc_request_check_host_hdr(struct http *hp) htc_request_check_hdrs(struct sess *sp, struct http *hp) { int u; int seen_host = 0; int seen_cl = 0; for (u = HTTP_HDR_FIRST; u < hp->nhd; u++) { if (hp->hd[u].b == NULL) continue; AN(hp->hd[u].b); AN(hp->hd[u].e); if (http_IsHdr(&hp->hd[u], H_Host)) { if (seen_host) { WSP(sp, SLT_Error, "Duplicated Host header"); return (400); } seen_host = 1; } if (http_IsHdr(&hp->hd[u], H_Content_Length)) { if (seen_cl) { WSP(sp, SLT_Error, "Duplicated Content-Length header"); return (400); } seen_cl = 1; } } return (0); }
167,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: ServiceManagerContext::ServiceManagerContext() { service_manager::mojom::ServiceRequest packaged_services_request; if (service_manager::ServiceManagerIsRemote()) { auto invitation = mojo::edk::IncomingBrokerClientInvitation::AcceptFromCommandLine( mojo::edk::TransportProtocol::kLegacy); packaged_services_request = service_manager::GetServiceRequestFromCommandLine(invitation.get()); } else { std::unique_ptr<BuiltinManifestProvider> manifest_provider = base::MakeUnique<BuiltinManifestProvider>(); static const struct ManifestInfo { const char* name; int resource_id; } kManifests[] = { {mojom::kBrowserServiceName, IDR_MOJO_CONTENT_BROWSER_MANIFEST}, {mojom::kGpuServiceName, IDR_MOJO_CONTENT_GPU_MANIFEST}, {mojom::kPackagedServicesServiceName, IDR_MOJO_CONTENT_PACKAGED_SERVICES_MANIFEST}, {mojom::kPluginServiceName, IDR_MOJO_CONTENT_PLUGIN_MANIFEST}, {mojom::kRendererServiceName, IDR_MOJO_CONTENT_RENDERER_MANIFEST}, {mojom::kUtilityServiceName, IDR_MOJO_CONTENT_UTILITY_MANIFEST}, {catalog::mojom::kServiceName, IDR_MOJO_CATALOG_MANIFEST}, }; for (size_t i = 0; i < arraysize(kManifests); ++i) { manifest_provider->AddServiceManifest(kManifests[i].name, kManifests[i].resource_id); } for (const auto& manifest : GetContentClient()->browser()->GetExtraServiceManifests()) { manifest_provider->AddServiceManifest(manifest.name, manifest.resource_id); } in_process_context_ = new InProcessServiceManagerContext; service_manager::mojom::ServicePtr packaged_services_service; packaged_services_request = mojo::MakeRequest(&packaged_services_service); in_process_context_->Start(packaged_services_service.PassInterface(), std::move(manifest_provider)); } packaged_services_connection_ = ServiceManagerConnection::Create( std::move(packaged_services_request), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); service_manager::mojom::ServicePtr root_browser_service; ServiceManagerConnection::SetForProcess(ServiceManagerConnection::Create( mojo::MakeRequest(&root_browser_service), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO))); auto* browser_connection = ServiceManagerConnection::GetForProcess(); service_manager::mojom::PIDReceiverPtr pid_receiver; packaged_services_connection_->GetConnector()->StartService( service_manager::Identity(mojom::kBrowserServiceName, service_manager::mojom::kRootUserID), std::move(root_browser_service), mojo::MakeRequest(&pid_receiver)); pid_receiver->SetPID(base::GetCurrentProcId()); service_manager::EmbeddedServiceInfo device_info; #if defined(OS_ANDROID) JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaGlobalRef<jobject> java_nfc_delegate; java_nfc_delegate.Reset(Java_ContentNfcDelegate_create(env)); DCHECK(!java_nfc_delegate.is_null()); device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), base::Bind(&WakeLockContextHost::GetNativeViewForContext), std::move(java_nfc_delegate)); #else device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); #endif device_info.task_runner = base::ThreadTaskRunnerHandle::Get(); packaged_services_connection_->AddEmbeddedService(device::mojom::kServiceName, device_info); if (base::FeatureList::IsEnabled(features::kGlobalResourceCoordinator)) { service_manager::EmbeddedServiceInfo resource_coordinator_info; resource_coordinator_info.factory = base::Bind(&resource_coordinator::ResourceCoordinatorService::Create); packaged_services_connection_->AddEmbeddedService( resource_coordinator::mojom::kServiceName, resource_coordinator_info); } ContentBrowserClient::StaticServiceMap services; GetContentClient()->browser()->RegisterInProcessServices(&services); for (const auto& entry : services) { packaged_services_connection_->AddEmbeddedService(entry.first, entry.second); } g_io_thread_connector.Get() = browser_connection->GetConnector()->Clone(); ContentBrowserClient::OutOfProcessServiceMap out_of_process_services; GetContentClient()->browser()->RegisterOutOfProcessServices( &out_of_process_services); out_of_process_services[data_decoder::mojom::kServiceName] = { base::ASCIIToUTF16("Data Decoder Service"), SANDBOX_TYPE_UTILITY}; bool network_service_enabled = base::FeatureList::IsEnabled(features::kNetworkService); if (network_service_enabled) { out_of_process_services[content::mojom::kNetworkServiceName] = { base::ASCIIToUTF16("Network Service"), SANDBOX_TYPE_NETWORK}; } if (base::FeatureList::IsEnabled(video_capture::kMojoVideoCapture)) { out_of_process_services[video_capture::mojom::kServiceName] = { base::ASCIIToUTF16("Video Capture Service"), SANDBOX_TYPE_NO_SANDBOX}; } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_UTILITY_PROCESS) out_of_process_services[media::mojom::kMediaServiceName] = { base::ASCIIToUTF16("Media Service"), SANDBOX_TYPE_NO_SANDBOX}; #endif for (const auto& service : out_of_process_services) { packaged_services_connection_->AddServiceRequestHandler( service.first, base::Bind(&StartServiceInUtilityProcess, service.first, service.second.first, service.second.second)); } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_GPU_PROCESS) packaged_services_connection_->AddServiceRequestHandler( media::mojom::kMediaServiceName, base::Bind(&StartServiceInGpuProcess, media::mojom::kMediaServiceName)); #endif packaged_services_connection_->AddServiceRequestHandler( shape_detection::mojom::kServiceName, base::Bind(&StartServiceInGpuProcess, shape_detection::mojom::kServiceName)); packaged_services_connection_->Start(); RegisterCommonBrowserInterfaces(browser_connection); browser_connection->Start(); if (network_service_enabled) { browser_connection->GetConnector()->StartService( mojom::kNetworkServiceName); } } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
ServiceManagerContext::ServiceManagerContext() { service_manager::mojom::ServiceRequest packaged_services_request; if (service_manager::ServiceManagerIsRemote()) { auto invitation = mojo::edk::IncomingBrokerClientInvitation::AcceptFromCommandLine( mojo::edk::TransportProtocol::kLegacy); packaged_services_request = service_manager::GetServiceRequestFromCommandLine(invitation.get()); } else { std::unique_ptr<BuiltinManifestProvider> manifest_provider = base::MakeUnique<BuiltinManifestProvider>(); static const struct ManifestInfo { const char* name; int resource_id; } kManifests[] = { {mojom::kBrowserServiceName, IDR_MOJO_CONTENT_BROWSER_MANIFEST}, {mojom::kGpuServiceName, IDR_MOJO_CONTENT_GPU_MANIFEST}, {mojom::kPackagedServicesServiceName, IDR_MOJO_CONTENT_PACKAGED_SERVICES_MANIFEST}, {mojom::kPluginServiceName, IDR_MOJO_CONTENT_PLUGIN_MANIFEST}, {mojom::kRendererServiceName, IDR_MOJO_CONTENT_RENDERER_MANIFEST}, {mojom::kUtilityServiceName, IDR_MOJO_CONTENT_UTILITY_MANIFEST}, {catalog::mojom::kServiceName, IDR_MOJO_CATALOG_MANIFEST}, }; for (size_t i = 0; i < arraysize(kManifests); ++i) { manifest_provider->AddServiceManifest(kManifests[i].name, kManifests[i].resource_id); } for (const auto& manifest : GetContentClient()->browser()->GetExtraServiceManifests()) { manifest_provider->AddServiceManifest(manifest.name, manifest.resource_id); } in_process_context_ = new InProcessServiceManagerContext; service_manager::mojom::ServicePtr packaged_services_service; packaged_services_request = mojo::MakeRequest(&packaged_services_service); in_process_context_->Start(packaged_services_service.PassInterface(), std::move(manifest_provider)); } packaged_services_connection_ = ServiceManagerConnection::Create( std::move(packaged_services_request), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); service_manager::mojom::ServicePtr root_browser_service; ServiceManagerConnection::SetForProcess(ServiceManagerConnection::Create( mojo::MakeRequest(&root_browser_service), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO))); auto* browser_connection = ServiceManagerConnection::GetForProcess(); service_manager::mojom::PIDReceiverPtr pid_receiver; packaged_services_connection_->GetConnector()->StartService( service_manager::Identity(mojom::kBrowserServiceName, service_manager::mojom::kRootUserID), std::move(root_browser_service), mojo::MakeRequest(&pid_receiver)); pid_receiver->SetPID(base::GetCurrentProcId()); service_manager::EmbeddedServiceInfo device_info; #if defined(OS_ANDROID) JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaGlobalRef<jobject> java_nfc_delegate; java_nfc_delegate.Reset(Java_ContentNfcDelegate_create(env)); DCHECK(!java_nfc_delegate.is_null()); device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), base::Bind(&WakeLockContextHost::GetNativeViewForContext), std::move(java_nfc_delegate)); #else device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); #endif device_info.task_runner = base::ThreadTaskRunnerHandle::Get(); packaged_services_connection_->AddEmbeddedService(device::mojom::kServiceName, device_info); if (base::FeatureList::IsEnabled(features::kGlobalResourceCoordinator)) { service_manager::EmbeddedServiceInfo resource_coordinator_info; resource_coordinator_info.factory = base::Bind(&resource_coordinator::ResourceCoordinatorService::Create); packaged_services_connection_->AddEmbeddedService( resource_coordinator::mojom::kServiceName, resource_coordinator_info); } ContentBrowserClient::StaticServiceMap services; GetContentClient()->browser()->RegisterInProcessServices(&services); for (const auto& entry : services) { packaged_services_connection_->AddEmbeddedService(entry.first, entry.second); } g_io_thread_connector.Get() = browser_connection->GetConnector()->Clone(); ContentBrowserClient::OutOfProcessServiceMap out_of_process_services; GetContentClient()->browser()->RegisterOutOfProcessServices( &out_of_process_services); out_of_process_services[data_decoder::mojom::kServiceName] = { base::ASCIIToUTF16("Data Decoder Service"), SANDBOX_TYPE_UTILITY}; bool network_service_enabled = base::FeatureList::IsEnabled(features::kNetworkService); if (network_service_enabled) { out_of_process_services[content::mojom::kNetworkServiceName] = { base::ASCIIToUTF16("Network Service"), SANDBOX_TYPE_NETWORK}; } if (base::FeatureList::IsEnabled(video_capture::kMojoVideoCapture)) { out_of_process_services[video_capture::mojom::kServiceName] = { base::ASCIIToUTF16("Video Capture Service"), SANDBOX_TYPE_NO_SANDBOX}; } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_UTILITY_PROCESS) out_of_process_services[media::mojom::kMediaServiceName] = { base::ASCIIToUTF16("Media Service"), SANDBOX_TYPE_UTILITY}; #endif #if BUILDFLAG(ENABLE_STANDALONE_CDM_SERVICE) out_of_process_services[media::mojom::kCdmServiceName] = { base::ASCIIToUTF16("Content Decryption Module Service"), SANDBOX_TYPE_NO_SANDBOX}; #endif for (const auto& service : out_of_process_services) { packaged_services_connection_->AddServiceRequestHandler( service.first, base::Bind(&StartServiceInUtilityProcess, service.first, service.second.first, service.second.second)); } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_GPU_PROCESS) packaged_services_connection_->AddServiceRequestHandler( media::mojom::kMediaServiceName, base::Bind(&StartServiceInGpuProcess, media::mojom::kMediaServiceName)); #endif packaged_services_connection_->AddServiceRequestHandler( shape_detection::mojom::kServiceName, base::Bind(&StartServiceInGpuProcess, shape_detection::mojom::kServiceName)); packaged_services_connection_->Start(); RegisterCommonBrowserInterfaces(browser_connection); browser_connection->Start(); if (network_service_enabled) { browser_connection->GetConnector()->StartService( mojom::kNetworkServiceName); } }
171,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: void Cues::PreloadCuePoint( long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2*cue_points_size; CuePoint** const qq = new CuePoint*[n]; CuePoint** q = qq; //beginning of target CuePoint** p = m_cue_points; //beginning of source CuePoint** const pp = p + m_preload_count; //end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Cues::PreloadCuePoint( continue; } assert(m_preload_count > 0); CuePoint* const pCP = m_cue_points[m_count]; assert(pCP); assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) return false; pCP->Load(pReader); ++m_count; --m_preload_count; m_pos += size; // consume payload assert(m_pos <= stop); return true; // yes, we loaded a cue point } // return (m_pos < stop); return false; // no, we did not load a cue point }
174,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PrintPreviewUI::~PrintPreviewUI() { print_preview_data_service()->RemoveEntry(preview_ui_addr_str_); g_print_preview_request_id_map.Get().Erase(preview_ui_addr_str_); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
PrintPreviewUI::~PrintPreviewUI() { print_preview_data_service()->RemoveEntry(id_); g_print_preview_request_id_map.Get().Erase(id_); g_print_preview_ui_id_map.Get().Remove(id_); }
170,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), re->flags | RE_FLAGS_SCAN, NULL, NULL); } Commit Message: Fix issue #646 (#648) * Fix issue #646 and some edge cases with wide regexps using \b and \B * Rename function IS_WORD_CHAR to _yr_re_is_word_char CWE ID: CWE-125
int yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), 0, re->flags | RE_FLAGS_SCAN, NULL, NULL); }
168,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) return -EMSGSIZE; return 0; } Commit Message: net: fix infoleak in rtnetlink The stack object “map” has a total size of 32 bytes. Its last 4 bytes are padding generated by compiler. These padding bytes are not initialized and sent out via “nla_put”. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev) { struct rtnl_link_ifmap map; memset(&map, 0, sizeof(map)); map.mem_start = dev->mem_start; map.mem_end = dev->mem_end; map.base_addr = dev->base_addr; map.irq = dev->irq; map.dma = dev->dma; map.port = dev->if_port; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) return -EMSGSIZE; return 0; }
167,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt) { int rc; ctxt->dst.type = OP_REG; ctxt->dst.addr.reg = &ctxt->_eip; ctxt->dst.bytes = ctxt->op_bytes; rc = emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rsp_increment(ctxt, ctxt->src.val); return X86EMUL_CONTINUE; } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long eip; rc = emulate_pop(ctxt, &eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_near(ctxt, eip); if (rc != X86EMUL_CONTINUE) return rc; rsp_increment(ctxt, ctxt->src.val); return X86EMUL_CONTINUE; }
169,914
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BackgroundLoaderOffliner::StartSnapshot() { if (!pending_request_.get()) { DVLOG(1) << "Pending request was cleared during delay."; return; } DCHECK(is_low_bar_met_) << "Minimum quality must have been reached before saving a snapshot"; AddLoadingSignal("Snapshotting"); SavePageRequest request(*pending_request_.get()); if (page_load_state_ != SUCCESS) { Offliner::RequestStatus status; switch (page_load_state_) { case RETRIABLE_NET_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_NET_ERROR; break; case RETRIABLE_HTTP_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_HTTP_ERROR; break; case NONRETRIABLE: status = Offliner::RequestStatus::LOADING_FAILED_NO_RETRY; break; default: NOTREACHED(); status = Offliner::RequestStatus::LOADING_FAILED; } std::move(completion_callback_).Run(request, status); ResetState(); return; } content::WebContents* web_contents( content::WebContentsObserver::web_contents()); Offliner::RequestStatus loaded_page_error = CanSavePageInBackground(web_contents); if (loaded_page_error != Offliner::RequestStatus::UNKNOWN) { std::move(completion_callback_).Run(request, loaded_page_error); ResetState(); return; } save_state_ = SAVING; RequestStats& image_stats = stats_[ResourceDataType::IMAGE]; RequestStats& css_stats = stats_[ResourceDataType::TEXT_CSS]; RequestStats& xhr_stats = stats_[ResourceDataType::XHR]; bool image_complete = (image_stats.requested == image_stats.completed); bool css_complete = (css_stats.requested == css_stats.completed); bool xhr_complete = (xhr_stats.requested == xhr_stats.completed); RecordResourceCompletionUMA(image_complete, css_complete, xhr_complete); if (IsOfflinePagesLoadSignalCollectingEnabled()) { signal_data_.SetDouble("StartedImages", image_stats.requested); signal_data_.SetDouble("CompletedImages", image_stats.completed); signal_data_.SetDouble("StartedCSS", css_stats.requested); signal_data_.SetDouble("CompletedCSS", css_stats.completed); signal_data_.SetDouble("StartedXHR", xhr_stats.requested); signal_data_.SetDouble("CompletedXHR", xhr_stats.completed); std::string headers = base::StringPrintf( "%s\r\n%s\r\n\r\n", kContentTransferEncodingBinary, kXHeaderForSignals); std::string body; base::JSONWriter::Write(signal_data_, &body); std::string content_type = kContentType; std::string content_location = base::StringPrintf( "cid:signal-data-%" PRId64 "@mhtml.blink", request.request_id()); content::MHTMLExtraParts* extra_parts = content::MHTMLExtraParts::FromWebContents(web_contents); DCHECK(extra_parts); if (extra_parts != nullptr) { extra_parts->AddExtraMHTMLPart(content_type, content_location, headers, body); } } std::unique_ptr<OfflinePageArchiver> archiver(new OfflinePageMHTMLArchiver()); OfflinePageModel::SavePageParams params; params.url = web_contents->GetLastCommittedURL(); params.client_id = request.client_id(); params.proposed_offline_id = request.request_id(); params.is_background = true; params.use_page_problem_detectors = true; params.request_origin = request.request_origin(); if (!request.original_url().is_empty()) params.original_url = request.original_url(); else if (params.url != request.url()) params.original_url = request.url(); offline_page_model_->SavePage( params, std::move(archiver), web_contents, base::Bind(&BackgroundLoaderOffliner::OnPageSaved, weak_ptr_factory_.GetWeakPtr())); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <[email protected]> Reviewed-by: Steven Holte <[email protected]> Commit-Queue: Peter Williamson <[email protected]> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119
void BackgroundLoaderOffliner::StartSnapshot() { if (!pending_request_.get()) { DVLOG(1) << "Pending request was cleared during delay."; return; } DCHECK(is_low_bar_met_) << "Minimum quality must have been reached before saving a snapshot"; AddLoadingSignal("Snapshotting"); SavePageRequest request(*pending_request_.get()); if (page_load_state_ != SUCCESS) { Offliner::RequestStatus status; switch (page_load_state_) { case RETRIABLE_NET_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_NET_ERROR; break; case RETRIABLE_HTTP_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_HTTP_ERROR; break; case NONRETRIABLE: status = Offliner::RequestStatus::LOADING_FAILED_NO_RETRY; break; default: NOTREACHED(); status = Offliner::RequestStatus::LOADING_FAILED; } std::move(completion_callback_).Run(request, status); ResetState(); return; } content::WebContents* web_contents( content::WebContentsObserver::web_contents()); Offliner::RequestStatus loaded_page_error = CanSavePageInBackground(web_contents); if (loaded_page_error != Offliner::RequestStatus::UNKNOWN) { std::move(completion_callback_).Run(request, loaded_page_error); ResetState(); return; } save_state_ = SAVING; RequestStats& image_stats = stats_[ResourceDataType::IMAGE]; RequestStats& css_stats = stats_[ResourceDataType::TEXT_CSS]; RequestStats& xhr_stats = stats_[ResourceDataType::XHR]; if (IsOfflinePagesLoadSignalCollectingEnabled()) { signal_data_.SetDouble("StartedImages", image_stats.requested); signal_data_.SetDouble("CompletedImages", image_stats.completed); signal_data_.SetDouble("StartedCSS", css_stats.requested); signal_data_.SetDouble("CompletedCSS", css_stats.completed); signal_data_.SetDouble("StartedXHR", xhr_stats.requested); signal_data_.SetDouble("CompletedXHR", xhr_stats.completed); std::string headers = base::StringPrintf( "%s\r\n%s\r\n\r\n", kContentTransferEncodingBinary, kXHeaderForSignals); std::string body; base::JSONWriter::Write(signal_data_, &body); std::string content_type = kContentType; std::string content_location = base::StringPrintf( "cid:signal-data-%" PRId64 "@mhtml.blink", request.request_id()); content::MHTMLExtraParts* extra_parts = content::MHTMLExtraParts::FromWebContents(web_contents); DCHECK(extra_parts); if (extra_parts != nullptr) { extra_parts->AddExtraMHTMLPart(content_type, content_location, headers, body); } } std::unique_ptr<OfflinePageArchiver> archiver(new OfflinePageMHTMLArchiver()); OfflinePageModel::SavePageParams params; params.url = web_contents->GetLastCommittedURL(); params.client_id = request.client_id(); params.proposed_offline_id = request.request_id(); params.is_background = true; params.use_page_problem_detectors = true; params.request_origin = request.request_origin(); if (!request.original_url().is_empty()) params.original_url = request.original_url(); else if (params.url != request.url()) params.original_url = request.url(); offline_page_model_->SavePage( params, std::move(archiver), web_contents, base::Bind(&BackgroundLoaderOffliner::OnPageSaved, weak_ptr_factory_.GetWeakPtr())); }
172,484
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DownloadFileManager::CompleteDownload(DownloadId global_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!ContainsKey(downloads_, global_id)) return; DownloadFile* download_file = downloads_[global_id]; VLOG(20) << " " << __FUNCTION__ << "()" << " id = " << global_id << " download_file = " << download_file->DebugString(); download_file->Detach(); EraseDownload(global_id); } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void DownloadFileManager::CompleteDownload(DownloadId global_id) { void DownloadFileManager::CompleteDownload( DownloadId global_id, const base::Closure& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!ContainsKey(downloads_, global_id)) return; DownloadFile* download_file = downloads_[global_id]; VLOG(20) << " " << __FUNCTION__ << "()" << " id = " << global_id << " download_file = " << download_file->DebugString(); // Done here on Windows so that anti-virus scanners invoked by // the attachment service actually see the data; see // http://crbug.com/127999. // Done here for mac because we only want to do this once; see // http://crbug.com/13120 for details. // Other platforms don't currently do source annotation. download_file->AnnotateWithSourceInformation(); download_file->Detach(); EraseDownload(global_id); // Notify our caller we've let it go. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); }
170,876
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct page *follow_page_pte(struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, unsigned int flags, struct dev_pagemap **pgmap) { struct mm_struct *mm = vma->vm_mm; struct page *page; spinlock_t *ptl; pte_t *ptep, pte; retry: if (unlikely(pmd_bad(*pmd))) return no_page_table(vma, flags); ptep = pte_offset_map_lock(mm, pmd, address, &ptl); pte = *ptep; if (!pte_present(pte)) { swp_entry_t entry; /* * KSM's break_ksm() relies upon recognizing a ksm page * even while it is being migrated, so for that case we * need migration_entry_wait(). */ if (likely(!(flags & FOLL_MIGRATION))) goto no_page; if (pte_none(pte)) goto no_page; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto no_page; pte_unmap_unlock(ptep, ptl); migration_entry_wait(mm, pmd, address); goto retry; } if ((flags & FOLL_NUMA) && pte_protnone(pte)) goto no_page; if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) { pte_unmap_unlock(ptep, ptl); return NULL; } page = vm_normal_page(vma, address, pte); if (!page && pte_devmap(pte) && (flags & FOLL_GET)) { /* * Only return device mapping pages in the FOLL_GET case since * they are only valid while holding the pgmap reference. */ *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap); if (*pgmap) page = pte_page(pte); else goto no_page; } else if (unlikely(!page)) { if (flags & FOLL_DUMP) { /* Avoid special (like zero) pages in core dumps */ page = ERR_PTR(-EFAULT); goto out; } if (is_zero_pfn(pte_pfn(pte))) { page = pte_page(pte); } else { int ret; ret = follow_pfn_pte(vma, address, ptep, flags); page = ERR_PTR(ret); goto out; } } if (flags & FOLL_SPLIT && PageTransCompound(page)) { int ret; get_page(page); pte_unmap_unlock(ptep, ptl); lock_page(page); ret = split_huge_page(page); unlock_page(page); put_page(page); if (ret) return ERR_PTR(ret); goto retry; } if (flags & FOLL_GET) get_page(page); if (flags & FOLL_TOUCH) { if ((flags & FOLL_WRITE) && !pte_dirty(pte) && !PageDirty(page)) set_page_dirty(page); /* * pte_mkyoung() would be more correct here, but atomic care * is needed to avoid losing the dirty bit: it is easier to use * mark_page_accessed(). */ mark_page_accessed(page); } if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) { /* Do not mlock pte-mapped THP */ if (PageTransCompound(page)) goto out; /* * The preliminary mapping check is mainly to avoid the * pointless overhead of lock_page on the ZERO_PAGE * which might bounce very badly if there is contention. * * If the page is already locked, we don't need to * handle it now - vmscan will handle it later if and * when it attempts to reclaim the page. */ if (page->mapping && trylock_page(page)) { lru_add_drain(); /* push cached pages to LRU */ /* * Because we lock page here, and migration is * blocked by the pte's page reference, and we * know the page is still mapped, we don't even * need to check for file-cache page truncation. */ mlock_vma_page(page); unlock_page(page); } } out: pte_unmap_unlock(ptep, ptl); return page; no_page: pte_unmap_unlock(ptep, ptl); if (!pte_none(pte)) return NULL; return no_page_table(vma, flags); } 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
static struct page *follow_page_pte(struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, unsigned int flags, struct dev_pagemap **pgmap) { struct mm_struct *mm = vma->vm_mm; struct page *page; spinlock_t *ptl; pte_t *ptep, pte; retry: if (unlikely(pmd_bad(*pmd))) return no_page_table(vma, flags); ptep = pte_offset_map_lock(mm, pmd, address, &ptl); pte = *ptep; if (!pte_present(pte)) { swp_entry_t entry; /* * KSM's break_ksm() relies upon recognizing a ksm page * even while it is being migrated, so for that case we * need migration_entry_wait(). */ if (likely(!(flags & FOLL_MIGRATION))) goto no_page; if (pte_none(pte)) goto no_page; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto no_page; pte_unmap_unlock(ptep, ptl); migration_entry_wait(mm, pmd, address); goto retry; } if ((flags & FOLL_NUMA) && pte_protnone(pte)) goto no_page; if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) { pte_unmap_unlock(ptep, ptl); return NULL; } page = vm_normal_page(vma, address, pte); if (!page && pte_devmap(pte) && (flags & FOLL_GET)) { /* * Only return device mapping pages in the FOLL_GET case since * they are only valid while holding the pgmap reference. */ *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap); if (*pgmap) page = pte_page(pte); else goto no_page; } else if (unlikely(!page)) { if (flags & FOLL_DUMP) { /* Avoid special (like zero) pages in core dumps */ page = ERR_PTR(-EFAULT); goto out; } if (is_zero_pfn(pte_pfn(pte))) { page = pte_page(pte); } else { int ret; ret = follow_pfn_pte(vma, address, ptep, flags); page = ERR_PTR(ret); goto out; } } if (flags & FOLL_SPLIT && PageTransCompound(page)) { int ret; get_page(page); pte_unmap_unlock(ptep, ptl); lock_page(page); ret = split_huge_page(page); unlock_page(page); put_page(page); if (ret) return ERR_PTR(ret); goto retry; } if (flags & FOLL_GET) { if (unlikely(!try_get_page(page))) { page = ERR_PTR(-ENOMEM); goto out; } } if (flags & FOLL_TOUCH) { if ((flags & FOLL_WRITE) && !pte_dirty(pte) && !PageDirty(page)) set_page_dirty(page); /* * pte_mkyoung() would be more correct here, but atomic care * is needed to avoid losing the dirty bit: it is easier to use * mark_page_accessed(). */ mark_page_accessed(page); } if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) { /* Do not mlock pte-mapped THP */ if (PageTransCompound(page)) goto out; /* * The preliminary mapping check is mainly to avoid the * pointless overhead of lock_page on the ZERO_PAGE * which might bounce very badly if there is contention. * * If the page is already locked, we don't need to * handle it now - vmscan will handle it later if and * when it attempts to reclaim the page. */ if (page->mapping && trylock_page(page)) { lru_add_drain(); /* push cached pages to LRU */ /* * Because we lock page here, and migration is * blocked by the pte's page reference, and we * know the page is still mapped, we don't even * need to check for file-cache page truncation. */ mlock_vma_page(page); unlock_page(page); } } out: pte_unmap_unlock(ptep, ptl); return page; no_page: pte_unmap_unlock(ptep, ptl); if (!pte_none(pte)) return NULL; return no_page_table(vma, flags); }
170,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void set_roi_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { unsigned int i; vpx_roi_map_t roi = {0}; roi.rows = (cfg->g_h + 15) / 16; roi.cols = (cfg->g_w + 15) / 16; roi.delta_q[0] = 0; roi.delta_q[1] = -2; roi.delta_q[2] = -4; roi.delta_q[3] = -6; roi.delta_lf[0] = 0; roi.delta_lf[1] = 1; roi.delta_lf[2] = 2; roi.delta_lf[3] = 3; roi.static_threshold[0] = 1500; roi.static_threshold[1] = 1000; roi.static_threshold[2] = 500; roi.static_threshold[3] = 0; roi.roi_map = (uint8_t *)malloc(roi.rows * roi.cols); for (i = 0; i < roi.rows * roi.cols; ++i) roi.roi_map[i] = i % 4; if (vpx_codec_control(codec, VP8E_SET_ROI_MAP, &roi)) die_codec(codec, "Failed to set ROI map"); free(roi.roi_map); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void set_roi_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { unsigned int i; vpx_roi_map_t roi; memset(&roi, 0, sizeof(roi)); roi.rows = (cfg->g_h + 15) / 16; roi.cols = (cfg->g_w + 15) / 16; roi.delta_q[0] = 0; roi.delta_q[1] = -2; roi.delta_q[2] = -4; roi.delta_q[3] = -6; roi.delta_lf[0] = 0; roi.delta_lf[1] = 1; roi.delta_lf[2] = 2; roi.delta_lf[3] = 3; roi.static_threshold[0] = 1500; roi.static_threshold[1] = 1000; roi.static_threshold[2] = 500; roi.static_threshold[3] = 0; roi.roi_map = (uint8_t *)malloc(roi.rows * roi.cols); for (i = 0; i < roi.rows * roi.cols; ++i) roi.roi_map[i] = i % 4; if (vpx_codec_control(codec, VP8E_SET_ROI_MAP, &roi)) die_codec(codec, "Failed to set ROI map"); free(roi.roi_map); }
174,484
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); view->AcceleratedSurfaceBuffersSwapped(params, host_id_); } 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 [email protected] 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 GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, params.surface_handle, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); view->AcceleratedSurfaceBuffersSwapped(params, host_id_); }
171,357