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: void NetworkHandler::GetAllCookies( std::unique_ptr<GetAllCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } scoped_refptr<CookieRetriever> retriever = new CookieRetriever(std::move(callback)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &CookieRetriever::RetrieveAllCookiesOnIO, retriever, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::GetAllCookies( std::unique_ptr<GetAllCookiesCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } scoped_refptr<CookieRetriever> retriever = new CookieRetriever(std::move(callback)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &CookieRetriever::RetrieveAllCookiesOnIO, retriever, base::Unretained(storage_partition_->GetURLRequestContext()))); }
172,756
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK)) { /* Not a tunnel packet, just a pseudo packet */ p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); } Commit Message: teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736. CWE ID: CWE-20
Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK) || (proto == DECODE_TUNNEL_IPV6_TEREDO && (p->flags & PKT_IS_INVALID))) { /* Not a (valid) tunnel packet */ SCLogDebug("tunnel packet is invalid"); p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); }
169,479
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; struct user_struct *user; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; user = get_current_user(); if (unlikely(atomic_read(&user->inotify_devs) >= inotify_max_user_instances)) { ret = -EMFILE; goto out_free_uid; } /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(user, inotify_max_queued_events); if (IS_ERR(group)) { ret = PTR_ERR(group); goto out_free_uid; } atomic_inc(&user->inotify_devs); ret = anon_inode_getfd("inotify", &inotify_fops, group, O_RDONLY | flags); if (ret >= 0) return ret; atomic_dec(&user->inotify_devs); out_free_uid: free_uid(user); return ret; } Commit Message: inotify: stop kernel memory leak on file creation failure If inotify_init is unable to allocate a new file for the new inotify group we leak the new group. This patch drops the reference on the group on file allocation failure. Reported-by: Vegard Nossum <[email protected]> cc: [email protected] Signed-off-by: Eric Paris <[email protected]> CWE ID: CWE-399
SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; struct user_struct *user; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; user = get_current_user(); if (unlikely(atomic_read(&user->inotify_devs) >= inotify_max_user_instances)) { ret = -EMFILE; goto out_free_uid; } /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(user, inotify_max_queued_events); if (IS_ERR(group)) { ret = PTR_ERR(group); goto out_free_uid; } atomic_inc(&user->inotify_devs); ret = anon_inode_getfd("inotify", &inotify_fops, group, O_RDONLY | flags); if (ret >= 0) return ret; fsnotify_put_group(group); atomic_dec(&user->inotify_devs); out_free_uid: free_uid(user); return ret; }
165,908
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *FLTGetIsLikeComparisonCommonExpression(FilterEncodingNode *psFilterNode) { const size_t bufferSize = 1024; char szBuffer[1024]; char szTmp[256]; char *pszValue = NULL; const char *pszWild = NULL; const char *pszSingle = NULL; const char *pszEscape = NULL; int bCaseInsensitive = 0; FEPropertyIsLike* propIsLike; int nLength=0, i=0, iTmp=0; if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode || !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue) return NULL; propIsLike = (FEPropertyIsLike *)psFilterNode->pOther; pszWild = propIsLike->pszWildCard; pszSingle = propIsLike->pszSingleChar; pszEscape = propIsLike->pszEscapeChar; bCaseInsensitive = propIsLike->bCaseInsensitive; if (!pszWild || strlen(pszWild) == 0 || !pszSingle || strlen(pszSingle) == 0 || !pszEscape || strlen(pszEscape) == 0) return NULL; /* -------------------------------------------------------------------- */ /* Use operand with regular expressions. */ /* -------------------------------------------------------------------- */ szBuffer[0] = '\0'; sprintf(szTmp, "%s", "(\"["); szTmp[4] = '\0'; strlcat(szBuffer, szTmp, bufferSize); /* attribute */ strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; /* #3521 */ if (bCaseInsensitive == 1) sprintf(szTmp, "%s", "]\" ~* \""); else sprintf(szTmp, "%s", "]\" ~ \""); szTmp[7] = '\0'; strlcat(szBuffer, szTmp, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; pszValue = psFilterNode->psRightNode->pszValue; nLength = strlen(pszValue); iTmp =0; if (nLength > 0 && pszValue[0] != pszWild[0] && pszValue[0] != pszSingle[0] && pszValue[0] != pszEscape[0]) { szTmp[iTmp]= '^'; iTmp++; } for (i=0; i<nLength; i++) { if (pszValue[i] != pszWild[0] && pszValue[i] != pszSingle[0] && pszValue[i] != pszEscape[0]) { szTmp[iTmp] = pszValue[i]; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszSingle[0]) { szTmp[iTmp] = '.'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszEscape[0]) { szTmp[iTmp] = '\\'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszWild[0]) { szTmp[iTmp++] = '.'; szTmp[iTmp++] = '*'; szTmp[iTmp] = '\0'; } } szTmp[iTmp] = '"'; szTmp[++iTmp] = '\0'; strlcat(szBuffer, szTmp, bufferSize); strlcat(szBuffer, ")", bufferSize); return msStrdup(szBuffer); } Commit Message: security fix (patch by EvenR) CWE ID: CWE-119
char *FLTGetIsLikeComparisonCommonExpression(FilterEncodingNode *psFilterNode) { const size_t bufferSize = 1024; char szBuffer[1024]; char szTmp[256]; char *pszValue = NULL; const char *pszWild = NULL; const char *pszSingle = NULL; const char *pszEscape = NULL; int bCaseInsensitive = 0; FEPropertyIsLike* propIsLike; int nLength=0, i=0, iTmp=0; if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode || !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue) return NULL; propIsLike = (FEPropertyIsLike *)psFilterNode->pOther; pszWild = propIsLike->pszWildCard; pszSingle = propIsLike->pszSingleChar; pszEscape = propIsLike->pszEscapeChar; bCaseInsensitive = propIsLike->bCaseInsensitive; if (!pszWild || strlen(pszWild) == 0 || !pszSingle || strlen(pszSingle) == 0 || !pszEscape || strlen(pszEscape) == 0) return NULL; /* -------------------------------------------------------------------- */ /* Use operand with regular expressions. */ /* -------------------------------------------------------------------- */ szBuffer[0] = '\0'; sprintf(szTmp, "%s", "(\"["); szTmp[4] = '\0'; strlcat(szBuffer, szTmp, bufferSize); /* attribute */ strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; /* #3521 */ if (bCaseInsensitive == 1) sprintf(szTmp, "%s", "]\" ~* \""); else sprintf(szTmp, "%s", "]\" ~ \""); szTmp[7] = '\0'; strlcat(szBuffer, szTmp, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; pszValue = psFilterNode->psRightNode->pszValue; nLength = strlen(pszValue); if( 1 + 2 * nLength + 1 + 1 >= sizeof(szTmp) ) return NULL; iTmp =0; if (nLength > 0 && pszValue[0] != pszWild[0] && pszValue[0] != pszSingle[0] && pszValue[0] != pszEscape[0]) { szTmp[iTmp]= '^'; iTmp++; } for (i=0; i<nLength; i++) { if (pszValue[i] != pszWild[0] && pszValue[i] != pszSingle[0] && pszValue[i] != pszEscape[0]) { szTmp[iTmp] = pszValue[i]; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszSingle[0]) { szTmp[iTmp] = '.'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszEscape[0]) { szTmp[iTmp] = '\\'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszWild[0]) { szTmp[iTmp++] = '.'; szTmp[iTmp++] = '*'; szTmp[iTmp] = '\0'; } } szTmp[iTmp] = '"'; szTmp[++iTmp] = '\0'; strlcat(szBuffer, szTmp, bufferSize); strlcat(szBuffer, ")", bufferSize); return msStrdup(szBuffer); }
168,400
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; if (cmd & 0x01) off = *delta++; if (cmd & 0x02) off |= *delta++ << 8UL; if (cmd & 0x04) off |= *delta++ << 16UL; if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL); if (cmd & 0x10) len = *delta++; if (cmd & 0x20) len |= *delta++ << 8UL; if (cmd & 0x40) len |= *delta++ << 16UL; if (!len) len = 0x10000; if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; } Commit Message: delta: fix out-of-bounds read of delta When computing the offset and length of the delta base, we repeatedly increment the `delta` pointer without checking whether we have advanced past its end already, which can thus result in an out-of-bounds read. Fix this by repeatedly checking whether we have reached the end. Add a test which would cause Valgrind to produce an error. Reported-by: Riccardo Schirone <[email protected]> Test-provided-by: Riccardo Schirone <[email protected]> CWE ID: CWE-125
int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
169,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeWebContentsDelegateAndroid::AddNewContents( WebContents* source, WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { DCHECK_NE(disposition, SAVE_TO_DISK); DCHECK_NE(disposition, CURRENT_TAB); TabHelpers::AttachTabHelpers(new_contents); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = GetJavaDelegate(env); AddWebContentsResult add_result = ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE; if (!obj.is_null()) { ScopedJavaLocalRef<jobject> jsource; if (source) jsource = source->GetJavaWebContents(); ScopedJavaLocalRef<jobject> jnew_contents; if (new_contents) jnew_contents = new_contents->GetJavaWebContents(); add_result = static_cast<AddWebContentsResult>( Java_ChromeWebContentsDelegateAndroid_addNewContents( env, obj.obj(), jsource.obj(), jnew_contents.obj(), static_cast<jint>(disposition), NULL, user_gesture)); } if (was_blocked) *was_blocked = !(add_result == ADD_WEB_CONTENTS_RESULT_PROCEED); if (add_result == ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE) delete new_contents; } Commit Message: Revert "Load web contents after tab is created." This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d. BUG=432562 [email protected],[email protected],[email protected] Review URL: https://codereview.chromium.org/894003005 Cr-Commit-Position: refs/heads/master@{#314469} CWE ID: CWE-399
void ChromeWebContentsDelegateAndroid::AddNewContents( WebContents* source, WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { DCHECK_NE(disposition, SAVE_TO_DISK); DCHECK_NE(disposition, CURRENT_TAB); TabHelpers::AttachTabHelpers(new_contents); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = GetJavaDelegate(env); bool handled = false; if (!obj.is_null()) { ScopedJavaLocalRef<jobject> jsource; if (source) jsource = source->GetJavaWebContents(); ScopedJavaLocalRef<jobject> jnew_contents; if (new_contents) jnew_contents = new_contents->GetJavaWebContents(); handled = Java_ChromeWebContentsDelegateAndroid_addNewContents( env, obj.obj(), jsource.obj(), jnew_contents.obj(), static_cast<jint>(disposition), NULL, user_gesture); } if (was_blocked) *was_blocked = !handled; if (!handled) delete new_contents; }
171,137
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif } 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
PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_) { print_dialog_ = create_dialog_func_(this); print_dialog_->AddRefToDialog(); } if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif }
170,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN; dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG)); dma_addr_t real_prdt_len = prdt_len; uint8_t *prdt; uint8_t *prdt; int i; int r = 0; int sum = 0; int off_idx = -1; int off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; if (prdt_len < real_prdt_len) { DPRINTF(ad->port_no, "mapped less than expected\n"); r = -1; goto out; } /* Get entries in the PRDT, init a qemu sglist accordingly */ if (sglist_alloc_hint > 0) { AHCI_SG *tbl = (AHCI_SG *)prdt; sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; break; } sum += tbl_entry_size; } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; } } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } } out: dma_memory_unmap(ad->hba->as, prdt, prdt_len, DMA_DIRECTION_TO_DEVICE, prdt_len); /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } Commit Message: CWE ID: CWE-399
static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int32_t offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN; dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG)); dma_addr_t real_prdt_len = prdt_len; uint8_t *prdt; uint8_t *prdt; int i; int r = 0; uint64_t sum = 0; int off_idx = -1; int64_t off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); /* * Note: AHCI PRDT can describe up to 256GiB. SATA/ATA only support * transactions of up to 32MiB as of ATA8-ACS3 rev 1b, assuming a * 512 byte sector size. We limit the PRDT in this implementation to * a reasonably large 2GiB, which can accommodate the maximum transfer * request for sector sizes up to 32K. */ if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; if (prdt_len < real_prdt_len) { DPRINTF(ad->port_no, "mapped less than expected\n"); r = -1; goto out; } /* Get entries in the PRDT, init a qemu sglist accordingly */ if (sglist_alloc_hint > 0) { AHCI_SG *tbl = (AHCI_SG *)prdt; sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; break; } sum += tbl_entry_size; } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; } } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %"PRId64"\n", __func__, off_idx, off_pos); r = -1; goto out; qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } } out: dma_memory_unmap(ad->hba->as, prdt, prdt_len, DMA_DIRECTION_TO_DEVICE, prdt_len); /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); if (sglist->size > INT32_MAX) { error_report("AHCI Physical Region Descriptor Table describes " "more than 2 GiB.\n"); qemu_sglist_destroy(sglist); r = -1; goto out; } }
164,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dev_forward_skb(struct net_device *dev, struct sk_buff *skb) { skb_orphan(skb); if (!(dev->flags & IFF_UP)) return NET_RX_DROP; if (skb->len > (dev->mtu + dev->hard_header_len)) return NET_RX_DROP; skb_set_dev(skb, dev); skb->tstamp.tv64 = 0; skb->pkt_type = PACKET_HOST; skb->protocol = eth_type_trans(skb, dev); return netif_rx(skb); } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
int dev_forward_skb(struct net_device *dev, struct sk_buff *skb) { skb_orphan(skb); if (!(dev->flags & IFF_UP) || (skb->len > (dev->mtu + dev->hard_header_len))) { kfree_skb(skb); return NET_RX_DROP; } skb_set_dev(skb, dev); skb->tstamp.tv64 = 0; skb->pkt_type = PACKET_HOST; skb->protocol = eth_type_trans(skb, dev); return netif_rx(skb); }
166,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int NaClIPCAdapter::TakeClientFileDescriptor() { return io_thread_data_.channel_->TakeClientFileDescriptor(); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
int NaClIPCAdapter::TakeClientFileDescriptor() {
170,731
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, offsetGet) { char *fname, *error; size_t fname_len; zval zfname; phar_entry_info *entry; zend_string *sfname; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } /* security is 0 here so that we can get a better error message than "entry doesn't exist" */ if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:""); } else { if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } if (entry->is_temp_dir) { efree(entry->filename); efree(entry); } sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname); ZVAL_NEW_STR(&zfname, sfname); spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname); zval_ptr_dtor(&zfname); } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetGet) { char *fname, *error; size_t fname_len; zval zfname; phar_entry_info *entry; zend_string *sfname; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } /* security is 0 here so that we can get a better error message than "entry doesn't exist" */ if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:""); } else { if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } if (entry->is_temp_dir) { efree(entry->filename); efree(entry); } sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname); ZVAL_NEW_STR(&zfname, sfname); spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname); zval_ptr_dtor(&zfname); } }
165,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hashtable_set(hashtable_t *hashtable, const char *key, size_t serial, json_t *value) { pair_t *pair; bucket_t *bucket; size_t hash, index; /* rehash if the load ratio exceeds 1 */ if(hashtable->size >= num_buckets(hashtable)) if(hashtable_do_rehash(hashtable)) return -1; hash = hash_str(key); index = hash % num_buckets(hashtable); bucket = &hashtable->buckets[index]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(pair) { json_decref(pair->value); pair->value = value; } else { /* offsetof(...) returns the size of pair_t without the last, flexible member. This way, the correct amount is allocated. */ pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1); if(!pair) return -1; pair->hash = hash; pair->serial = serial; strcpy(pair->key, key); pair->value = value; list_init(&pair->list); insert_to_bucket(hashtable, bucket, &pair->list); hashtable->size++; } return 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
int hashtable_set(hashtable_t *hashtable, const char *key, size_t serial, json_t *value) { pair_t *pair; bucket_t *bucket; size_t hash, index; /* rehash if the load ratio exceeds 1 */ if(hashtable->size >= hashsize(hashtable->order)) if(hashtable_do_rehash(hashtable)) return -1; hash = hash_str(key); index = hash & hashmask(hashtable->order); bucket = &hashtable->buckets[index]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(pair) { json_decref(pair->value); pair->value = value; } else { /* offsetof(...) returns the size of pair_t without the last, flexible member. This way, the correct amount is allocated. */ pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1); if(!pair) return -1; pair->hash = hash; pair->serial = serial; strcpy(pair->key, key); pair->value = value; list_init(&pair->list); insert_to_bucket(hashtable, bucket, &pair->list); hashtable->size++; } return 0; }
166,533
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } Commit Message: ccpp: open file for dump_fd_info with O_EXCL To avoid possible races. Related: #1211835 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59
static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "wx"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; }
170,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ServiceWorkerHandler::ServiceWorkerHandler() : DevToolsDomainHandler(ServiceWorker::Metainfo::domainName), enabled_(false), process_(nullptr), weak_factory_(this) {} Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
ServiceWorkerHandler::ServiceWorkerHandler() : DevToolsDomainHandler(ServiceWorker::Metainfo::domainName), enabled_(false), browser_context_(nullptr), storage_partition_(nullptr), weak_factory_(this) {}
172,768
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp) { int pad = 0, ret, i, neg; unsigned char *p, *n, pb = 0; if (a == NULL) return (0); neg = a->type & V_ASN1_NEG; if (a->length == 0) ret = 1; else { ret = a->length; i = a->data[0]; if (!neg && (i > 127)) { pad = 1; pb = 0; pad = 1; pb = 0xFF; } else if (i == 128) { /* * Special case: if any other bytes non zero we pad: * otherwise we don't. */ for (i = 1; i < a->length; i++) if (a->data[i]) { pad = 1; pb = 0xFF; break; } } } ret += pad; } Commit Message: CWE ID: CWE-119
int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp) { int pad = 0, ret, i, neg; unsigned char *p, *n, pb = 0; if (a == NULL) return (0); neg = a->type & V_ASN1_NEG; if (a->length == 0) ret = 1; else { ret = a->length; i = a->data[0]; if (ret == 1 && i == 0) neg = 0; if (!neg && (i > 127)) { pad = 1; pb = 0; pad = 1; pb = 0xFF; } else if (i == 128) { /* * Special case: if any other bytes non zero we pad: * otherwise we don't. */ for (i = 1; i < a->length; i++) if (a->data[i]) { pad = 1; pb = 0xFF; break; } } } ret += pad; }
165,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool nodeHasRole(Node* node, const String& role) { if (!node || !node->isElementNode()) return false; return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role); } 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 nodeHasRole(Node* node, const String& role) { if (!node || !node->isElementNode()) return false; return equalIgnoringASCIICase(toElement(node)->getAttribute(roleAttr), role); }
171,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_parse_islice_data_cavlc(dec_struct_t * ps_dec, dec_slice_params_t * ps_slice, UWORD16 u2_first_mb_in_slice) { UWORD8 uc_more_data_flag; UWORD8 u1_num_mbs, u1_mb_idx; dec_mb_info_t *ps_cur_mb_info; deblk_mb_t *ps_cur_deblk_mb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; WORD16 i2_cur_mb_addr; UWORD8 u1_mbaff; UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb; WORD32 ret = OK; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mbaff = ps_slice->u1_mbaff_frame_flag; /* initializations */ u1_mb_idx = ps_dec->u1_mb_idx; u1_num_mbs = u1_mb_idx; uc_more_data_flag = 1; i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff; do { UWORD8 u1_mb_type; ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) { ret = ERROR_MB_ADDRESS_T; break; } ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_mb_info->u1_end_of_slice = 0; /***************************************************************/ /* Get the required information for decoding of MB */ /* mb_x, mb_y , neighbour availablity, */ /***************************************************************/ ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0); /***************************************************************/ /* Set the deblocking parameters for this MB */ /***************************************************************/ ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; if(ps_dec->u4_app_disable_deblk_frm == 0) ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type | D_INTRA_MB; /**************************************************************/ /* Macroblock Layer Begins, Decode the u1_mb_type */ /**************************************************************/ { UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst; UWORD32 u4_word, u4_ldz, u4_temp; /***************************************************************/ /* Find leading zeros in next 32 bits */ /***************************************************************/ NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf); u4_ldz = CLZ(u4_word); /* Flush the ps_bitstrm */ u4_bitstream_offset += (u4_ldz + 1); /* Read the suffix from the ps_bitstrm */ u4_word = 0; if(u4_ldz) GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf, u4_ldz); *pu4_bitstrm_ofst = u4_bitstream_offset; u4_temp = ((1 << u4_ldz) + u4_word - 1); if(u4_temp > 25) return ERROR_MB_TYPE; u1_mb_type = u4_temp; } ps_cur_mb_info->u1_mb_type = u1_mb_type; COPYTHECONTEXT("u1_mb_type", u1_mb_type); /**************************************************************/ /* Parse Macroblock data */ /**************************************************************/ if(25 == u1_mb_type) { /* I_PCM_MB */ ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB; ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs); if(ret != OK) return ret; ps_cur_deblk_mb->u1_mb_qp = 0; } else { ret = ih264d_parse_imb_cavlc(ps_dec, ps_cur_mb_info, u1_num_mbs, u1_mb_type); if(ret != OK) return ret; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; } if(u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm); /* Store the colocated information */ { mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4); mv_pred_t s_mvPred = { { 0, 0, 0, 0 }, { -1, -1 }, 0, 0}; ih264d_rep_mv_colz(ps_dec, &s_mvPred, ps_mv_nmb_start, 0, (UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1), 4, 4); } /*if num _cores is set to 3,compute bs will be done in another thread*/ if(ps_dec->u4_num_cores < 3) { if(ps_dec->u4_app_disable_deblk_frm == 0) ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info, (UWORD16)(u1_num_mbs >> u1_mbaff)); } u1_num_mbs++; /****************************************************************/ /* Check for End Of Row */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || (!uc_more_data_flag); ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag); /*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d", ps_slice->i4_poc >> ps_slice->u1_field_pic_flag, ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb)); H264_DEC_DEBUG_PRINT("u1_tfr_n_mb || (!uc_more_data_flag): %d", u1_tfr_n_mb || (!uc_more_data_flag));*/ if(u1_tfr_n_mb || (!uc_more_data_flag)) { if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } while(uc_more_data_flag); ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - (u2_first_mb_in_slice << u1_mbaff); return ret; } Commit Message: Fix in returning end of bitstream error for MBAFF In case of MBAFF streams, slices should terminate on even MB boundary. If bytes are exhausted with odd number of MBs decoded for MBAff, then treat that as error. Bug: 33933140 Change-Id: Ifc26b66ff8ebdb3aec5c0d6c512e4cac3f54c5b7 CWE ID:
WORD32 ih264d_parse_islice_data_cavlc(dec_struct_t * ps_dec, dec_slice_params_t * ps_slice, UWORD16 u2_first_mb_in_slice) { UWORD8 uc_more_data_flag; UWORD8 u1_num_mbs, u1_mb_idx; dec_mb_info_t *ps_cur_mb_info; deblk_mb_t *ps_cur_deblk_mb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; WORD16 i2_cur_mb_addr; UWORD8 u1_mbaff; UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb; WORD32 ret = OK; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mbaff = ps_slice->u1_mbaff_frame_flag; /* initializations */ u1_mb_idx = ps_dec->u1_mb_idx; u1_num_mbs = u1_mb_idx; uc_more_data_flag = 1; i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff; do { UWORD8 u1_mb_type; ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) { ret = ERROR_MB_ADDRESS_T; break; } ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_mb_info->u1_end_of_slice = 0; /***************************************************************/ /* Get the required information for decoding of MB */ /* mb_x, mb_y , neighbour availablity, */ /***************************************************************/ ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0); /***************************************************************/ /* Set the deblocking parameters for this MB */ /***************************************************************/ ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; if(ps_dec->u4_app_disable_deblk_frm == 0) ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type | D_INTRA_MB; /**************************************************************/ /* Macroblock Layer Begins, Decode the u1_mb_type */ /**************************************************************/ { UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst; UWORD32 u4_word, u4_ldz, u4_temp; /***************************************************************/ /* Find leading zeros in next 32 bits */ /***************************************************************/ NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf); u4_ldz = CLZ(u4_word); /* Flush the ps_bitstrm */ u4_bitstream_offset += (u4_ldz + 1); /* Read the suffix from the ps_bitstrm */ u4_word = 0; if(u4_ldz) GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf, u4_ldz); *pu4_bitstrm_ofst = u4_bitstream_offset; u4_temp = ((1 << u4_ldz) + u4_word - 1); if(u4_temp > 25) return ERROR_MB_TYPE; u1_mb_type = u4_temp; } ps_cur_mb_info->u1_mb_type = u1_mb_type; COPYTHECONTEXT("u1_mb_type", u1_mb_type); /**************************************************************/ /* Parse Macroblock data */ /**************************************************************/ if(25 == u1_mb_type) { /* I_PCM_MB */ ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB; ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs); if(ret != OK) return ret; ps_cur_deblk_mb->u1_mb_qp = 0; } else { ret = ih264d_parse_imb_cavlc(ps_dec, ps_cur_mb_info, u1_num_mbs, u1_mb_type); if(ret != OK) return ret; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; } if(u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); if(!uc_more_data_flag && (0 == (i2_cur_mb_addr & 1))) { return ERROR_EOB_FLUSHBITS_T; } } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm); /* Store the colocated information */ { mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4); mv_pred_t s_mvPred = { { 0, 0, 0, 0 }, { -1, -1 }, 0, 0}; ih264d_rep_mv_colz(ps_dec, &s_mvPred, ps_mv_nmb_start, 0, (UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1), 4, 4); } /*if num _cores is set to 3,compute bs will be done in another thread*/ if(ps_dec->u4_num_cores < 3) { if(ps_dec->u4_app_disable_deblk_frm == 0) ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info, (UWORD16)(u1_num_mbs >> u1_mbaff)); } u1_num_mbs++; /****************************************************************/ /* Check for End Of Row */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || (!uc_more_data_flag); ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag); /*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d", ps_slice->i4_poc >> ps_slice->u1_field_pic_flag, ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb)); H264_DEC_DEBUG_PRINT("u1_tfr_n_mb || (!uc_more_data_flag): %d", u1_tfr_n_mb || (!uc_more_data_flag));*/ if(u1_tfr_n_mb || (!uc_more_data_flag)) { if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } while(uc_more_data_flag); ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - (u2_first_mb_in_slice << u1_mbaff); return ret; }
174,045
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int msr_open(struct inode *inode, struct file *file) { unsigned int cpu; struct cpuinfo_x86 *c; cpu = iminor(file->f_path.dentry->d_inode); if (cpu >= nr_cpu_ids || !cpu_online(cpu)) return -ENXIO; /* No such CPU */ c = &cpu_data(cpu); if (!cpu_has(c, X86_FEATURE_MSR)) return -EIO; /* MSR not supported */ return 0; } Commit Message: x86/msr: Add capabilities check At the moment the MSR driver only relies upon file system checks. This means that anything as root with any capability set can write to MSRs. Historically that wasn't very interesting but on modern processors the MSRs are such that writing to them provides several ways to execute arbitary code in kernel space. Sample code and documentation on doing this is circulating and MSR attacks are used on Windows 64bit rootkits already. In the Linux case you still need to be able to open the device file so the impact is fairly limited and reduces the security of some capability and security model based systems down towards that of a generic "root owns the box" setup. Therefore they should require CAP_SYS_RAWIO to prevent an elevation of capabilities. The impact of this is fairly minimal on most setups because they don't have heavy use of capabilities. Those using SELinux, SMACK or AppArmor rules might want to consider if their rulesets on the MSR driver could be tighter. Signed-off-by: Alan Cox <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Horses <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
static int msr_open(struct inode *inode, struct file *file) { unsigned int cpu; struct cpuinfo_x86 *c; if (!capable(CAP_SYS_RAWIO)) return -EPERM; cpu = iminor(file->f_path.dentry->d_inode); if (cpu >= nr_cpu_ids || !cpu_online(cpu)) return -ENXIO; /* No such CPU */ c = &cpu_data(cpu); if (!cpu_has(c, X86_FEATURE_MSR)) return -EIO; /* MSR not supported */ return 0; }
166,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TextureManager::TextureInfo::ValidForTexture( GLint face, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type) const { size_t face_index = GLTargetToFaceIndex(face); if (level >= 0 && face_index < level_infos_.size() && static_cast<size_t>(level) < level_infos_[face_index].size()) { const LevelInfo& info = level_infos_[GLTargetToFaceIndex(face)][level]; GLint right; GLint top; return SafeAdd(xoffset, width, &right) && SafeAdd(yoffset, height, &top) && xoffset >= 0 && yoffset >= 0 && right <= info.width && top <= info.height && format == info.internal_format && type == info.type; } return false; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
bool TextureManager::TextureInfo::ValidForTexture( GLint face, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type) const { size_t face_index = GLTargetToFaceIndex(face); if (level >= 0 && face_index < level_infos_.size() && static_cast<size_t>(level) < level_infos_[face_index].size()) { const LevelInfo& info = level_infos_[GLTargetToFaceIndex(face)][level]; int32 right; int32 top; return SafeAddInt32(xoffset, width, &right) && SafeAddInt32(yoffset, height, &top) && xoffset >= 0 && yoffset >= 0 && right <= info.width && top <= info.height && format == info.internal_format && type == info.type; } return false; }
170,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: bool PrintDialogGtk::UpdateSettings(const DictionaryValue& settings, const printing::PageRanges& ranges) { bool collate; int color; bool landscape; bool print_to_pdf; int copies; int duplex_mode; std::string device_name; if (!settings.GetBoolean(printing::kSettingLandscape, &landscape) || !settings.GetBoolean(printing::kSettingCollate, &collate) || !settings.GetInteger(printing::kSettingColor, &color) || !settings.GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf) || !settings.GetInteger(printing::kSettingDuplexMode, &duplex_mode) || !settings.GetInteger(printing::kSettingCopies, &copies) || !settings.GetString(printing::kSettingDeviceName, &device_name)) { return false; } if (!print_to_pdf) { scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList); printer_ = printer_list->GetPrinterWithName(device_name.c_str()); if (printer_) { g_object_ref(printer_); gtk_print_settings_set_printer(gtk_settings_, gtk_printer_get_name(printer_)); } gtk_print_settings_set_n_copies(gtk_settings_, copies); gtk_print_settings_set_collate(gtk_settings_, collate); const char* color_mode; switch (color) { case printing::COLOR: color_mode = kColor; break; case printing::CMYK: color_mode = kCMYK; break; default: color_mode = kGrayscale; break; } gtk_print_settings_set(gtk_settings_, kCUPSColorModel, color_mode); if (duplex_mode != printing::UNKNOWN_DUPLEX_MODE) { const char* cups_duplex_mode = NULL; switch (duplex_mode) { case printing::LONG_EDGE: cups_duplex_mode = kDuplexNoTumble; break; case printing::SHORT_EDGE: cups_duplex_mode = kDuplexTumble; break; case printing::SIMPLEX: cups_duplex_mode = kDuplexNone; break; default: // UNKNOWN_DUPLEX_MODE NOTREACHED(); break; } gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode); } } gtk_print_settings_set_orientation( gtk_settings_, landscape ? GTK_PAGE_ORIENTATION_LANDSCAPE : GTK_PAGE_ORIENTATION_PORTRAIT); InitPrintSettings(ranges); return true; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool PrintDialogGtk::UpdateSettings(const DictionaryValue& settings, const printing::PageRanges& ranges) { bool collate; int color; bool landscape; bool print_to_pdf; int copies; int duplex_mode; std::string device_name; if (!settings.GetBoolean(printing::kSettingLandscape, &landscape) || !settings.GetBoolean(printing::kSettingCollate, &collate) || !settings.GetInteger(printing::kSettingColor, &color) || !settings.GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf) || !settings.GetInteger(printing::kSettingDuplexMode, &duplex_mode) || !settings.GetInteger(printing::kSettingCopies, &copies) || !settings.GetString(printing::kSettingDeviceName, &device_name)) { return false; } if (!gtk_settings_) gtk_settings_ = gtk_print_settings_new(); if (!print_to_pdf) { scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList); printer_ = printer_list->GetPrinterWithName(device_name.c_str()); if (printer_) { g_object_ref(printer_); gtk_print_settings_set_printer(gtk_settings_, gtk_printer_get_name(printer_)); if (!page_setup_) { page_setup_ = gtk_printer_get_default_page_size(printer_); } } if (!page_setup_) page_setup_ = gtk_page_setup_new(); gtk_print_settings_set_n_copies(gtk_settings_, copies); gtk_print_settings_set_collate(gtk_settings_, collate); const char* color_mode; switch (color) { case printing::COLOR: color_mode = kColor; break; case printing::CMYK: color_mode = kCMYK; break; default: color_mode = kGrayscale; break; } gtk_print_settings_set(gtk_settings_, kCUPSColorModel, color_mode); if (duplex_mode != printing::UNKNOWN_DUPLEX_MODE) { const char* cups_duplex_mode = NULL; switch (duplex_mode) { case printing::LONG_EDGE: cups_duplex_mode = kDuplexNoTumble; break; case printing::SHORT_EDGE: cups_duplex_mode = kDuplexTumble; break; case printing::SIMPLEX: cups_duplex_mode = kDuplexNone; break; default: // UNKNOWN_DUPLEX_MODE NOTREACHED(); break; } gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode); } } gtk_print_settings_set_orientation( gtk_settings_, landscape ? GTK_PAGE_ORIENTATION_LANDSCAPE : GTK_PAGE_ORIENTATION_PORTRAIT); InitPrintSettings(ranges); return true; }
170,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PluginModule::InstanceDeleted(PluginInstance* instance) { if (out_of_process_proxy_.get()) out_of_process_proxy_->RemoveInstance(instance->pp_instance()); instances_.erase(instance); if (nacl_ipc_proxy_) { out_of_process_proxy_.reset(); reserve_instance_id_ = NULL; } } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PluginModule::InstanceDeleted(PluginInstance* instance) { if (out_of_process_proxy_.get()) out_of_process_proxy_->RemoveInstance(instance->pp_instance()); instances_.erase(instance); }
170,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 av_cold int rl2_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVStream *st; unsigned int frame_count; unsigned int audio_frame_counter = 0; unsigned int video_frame_counter = 0; unsigned int back_size; unsigned short sound_rate; unsigned short rate; unsigned short channels; unsigned short def_sound_size; unsigned int signature; unsigned int pts_den = 11025; /* video only case */ unsigned int pts_num = 1103; unsigned int* chunk_offset = NULL; int* chunk_size = NULL; int* audio_size = NULL; int i; int ret = 0; avio_skip(pb,4); /* skip FORM tag */ back_size = avio_rl32(pb); /**< get size of the background frame */ signature = avio_rb32(pb); avio_skip(pb, 4); /* data size */ frame_count = avio_rl32(pb); /* disallow back_sizes and frame_counts that may lead to overflows later */ if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t)) return AVERROR_INVALIDDATA; avio_skip(pb, 2); /* encoding method */ sound_rate = avio_rl16(pb); rate = avio_rl16(pb); channels = avio_rl16(pb); def_sound_size = avio_rl16(pb); /** setup video stream */ st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RL2; st->codecpar->codec_tag = 0; /* no fourcc */ st->codecpar->width = 320; st->codecpar->height = 200; /** allocate and fill extradata */ st->codecpar->extradata_size = EXTRADATA1_SIZE; if(signature == RLV3_TAG && back_size > 0) st->codecpar->extradata_size += back_size; if(ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); /** setup audio stream if present */ if(sound_rate){ if (!channels || channels > 42) { av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels); return AVERROR_INVALIDDATA; } pts_num = def_sound_size; pts_den = rate; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_PCM_U8; st->codecpar->codec_tag = 1; st->codecpar->channels = channels; st->codecpar->bits_per_coded_sample = 8; st->codecpar->sample_rate = rate; st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample; st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8; avpriv_set_pts_info(st,32,1,rate); } avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den); chunk_size = av_malloc(frame_count * sizeof(uint32_t)); audio_size = av_malloc(frame_count * sizeof(uint32_t)); chunk_offset = av_malloc(frame_count * sizeof(uint32_t)); if(!chunk_size || !audio_size || !chunk_offset){ av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return AVERROR(ENOMEM); } /** read offset and size tables */ for(i=0; i < frame_count;i++) chunk_size[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) chunk_offset[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) audio_size[i] = avio_rl32(pb) & 0xFFFF; /** build the sample index */ for(i=0;i<frame_count;i++){ if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){ ret = AVERROR_INVALIDDATA; break; } if(sound_rate && audio_size[i]){ av_add_index_entry(s->streams[1], chunk_offset[i], audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME); audio_frame_counter += audio_size[i] / channels; } av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i], video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME); ++video_frame_counter; } av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return ret; } Commit Message: avformat/rl2: Fix DoS due to lack of eof check Fixes: loop.rl2 Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static av_cold int rl2_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVStream *st; unsigned int frame_count; unsigned int audio_frame_counter = 0; unsigned int video_frame_counter = 0; unsigned int back_size; unsigned short sound_rate; unsigned short rate; unsigned short channels; unsigned short def_sound_size; unsigned int signature; unsigned int pts_den = 11025; /* video only case */ unsigned int pts_num = 1103; unsigned int* chunk_offset = NULL; int* chunk_size = NULL; int* audio_size = NULL; int i; int ret = 0; avio_skip(pb,4); /* skip FORM tag */ back_size = avio_rl32(pb); /**< get size of the background frame */ signature = avio_rb32(pb); avio_skip(pb, 4); /* data size */ frame_count = avio_rl32(pb); /* disallow back_sizes and frame_counts that may lead to overflows later */ if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t)) return AVERROR_INVALIDDATA; avio_skip(pb, 2); /* encoding method */ sound_rate = avio_rl16(pb); rate = avio_rl16(pb); channels = avio_rl16(pb); def_sound_size = avio_rl16(pb); /** setup video stream */ st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RL2; st->codecpar->codec_tag = 0; /* no fourcc */ st->codecpar->width = 320; st->codecpar->height = 200; /** allocate and fill extradata */ st->codecpar->extradata_size = EXTRADATA1_SIZE; if(signature == RLV3_TAG && back_size > 0) st->codecpar->extradata_size += back_size; if(ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); /** setup audio stream if present */ if(sound_rate){ if (!channels || channels > 42) { av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels); return AVERROR_INVALIDDATA; } pts_num = def_sound_size; pts_den = rate; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_PCM_U8; st->codecpar->codec_tag = 1; st->codecpar->channels = channels; st->codecpar->bits_per_coded_sample = 8; st->codecpar->sample_rate = rate; st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample; st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8; avpriv_set_pts_info(st,32,1,rate); } avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den); chunk_size = av_malloc(frame_count * sizeof(uint32_t)); audio_size = av_malloc(frame_count * sizeof(uint32_t)); chunk_offset = av_malloc(frame_count * sizeof(uint32_t)); if(!chunk_size || !audio_size || !chunk_offset){ av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return AVERROR(ENOMEM); } /** read offset and size tables */ for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; chunk_size[i] = avio_rl32(pb); } for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; chunk_offset[i] = avio_rl32(pb); } for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; audio_size[i] = avio_rl32(pb) & 0xFFFF; } /** build the sample index */ for(i=0;i<frame_count;i++){ if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){ ret = AVERROR_INVALIDDATA; break; } if(sound_rate && audio_size[i]){ av_add_index_entry(s->streams[1], chunk_offset[i], audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME); audio_frame_counter += audio_size[i] / channels; } av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i], video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME); ++video_frame_counter; } av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return ret; }
167,776
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jas_seq2d_output(jas_matrix_t *matrix, FILE *out) { #define MAXLINELEN 80 int i; int j; jas_seqent_t x; char buf[MAXLINELEN + 1]; char sbuf[MAXLINELEN + 1]; int n; fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix), jas_seq2d_ystart(matrix)); fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix), jas_matrix_numrows(matrix)); buf[0] = '\0'; for (i = 0; i < jas_matrix_numrows(matrix); ++i) { for (j = 0; j < jas_matrix_numcols(matrix); ++j) { x = jas_matrix_get(matrix, i, j); sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "", JAS_CAST(long, x)); n = JAS_CAST(int, strlen(buf)); if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } strcat(buf, sbuf); if (j == jas_matrix_numcols(matrix) - 1) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } } } fputs(buf, out); 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
int jas_seq2d_output(jas_matrix_t *matrix, FILE *out) { #define MAXLINELEN 80 jas_matind_t i; jas_matind_t j; jas_seqent_t x; char buf[MAXLINELEN + 1]; char sbuf[MAXLINELEN + 1]; int n; fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix), jas_seq2d_ystart(matrix)); fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix), jas_matrix_numrows(matrix)); buf[0] = '\0'; for (i = 0; i < jas_matrix_numrows(matrix); ++i) { for (j = 0; j < jas_matrix_numcols(matrix); ++j) { x = jas_matrix_get(matrix, i, j); sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "", JAS_CAST(long, x)); n = JAS_CAST(int, strlen(buf)); if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } strcat(buf, sbuf); if (j == jas_matrix_numcols(matrix) - 1) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } } } fputs(buf, out); return 0; }
168,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __init trap_init(void) { int i; #ifdef CONFIG_EISA void __iomem *p = early_ioremap(0x0FFFD9, 4); if (readl(p) == 'E' + ('I'<<8) + ('S'<<16) + ('A'<<24)) EISA_bus = 1; early_iounmap(p, 4); #endif set_intr_gate(X86_TRAP_DE, divide_error); set_intr_gate_ist(X86_TRAP_NMI, &nmi, NMI_STACK); /* int4 can be called from all */ set_system_intr_gate(X86_TRAP_OF, &overflow); set_intr_gate(X86_TRAP_BR, bounds); set_intr_gate(X86_TRAP_UD, invalid_op); set_intr_gate(X86_TRAP_NM, device_not_available); #ifdef CONFIG_X86_32 set_task_gate(X86_TRAP_DF, GDT_ENTRY_DOUBLEFAULT_TSS); #else set_intr_gate_ist(X86_TRAP_DF, &double_fault, DOUBLEFAULT_STACK); #endif set_intr_gate(X86_TRAP_OLD_MF, coprocessor_segment_overrun); set_intr_gate(X86_TRAP_TS, invalid_TSS); set_intr_gate(X86_TRAP_NP, segment_not_present); set_intr_gate_ist(X86_TRAP_SS, &stack_segment, STACKFAULT_STACK); set_intr_gate(X86_TRAP_GP, general_protection); set_intr_gate(X86_TRAP_SPURIOUS, spurious_interrupt_bug); set_intr_gate(X86_TRAP_MF, coprocessor_error); set_intr_gate(X86_TRAP_AC, alignment_check); #ifdef CONFIG_X86_MCE set_intr_gate_ist(X86_TRAP_MC, &machine_check, MCE_STACK); #endif set_intr_gate(X86_TRAP_XF, simd_coprocessor_error); /* Reserve all the builtin and the syscall vector: */ for (i = 0; i < FIRST_EXTERNAL_VECTOR; i++) set_bit(i, used_vectors); #ifdef CONFIG_IA32_EMULATION set_system_intr_gate(IA32_SYSCALL_VECTOR, ia32_syscall); set_bit(IA32_SYSCALL_VECTOR, used_vectors); #endif #ifdef CONFIG_X86_32 set_system_trap_gate(SYSCALL_VECTOR, &system_call); set_bit(SYSCALL_VECTOR, used_vectors); #endif /* * Set the IDT descriptor to a fixed read-only location, so that the * "sidt" instruction will not leak the location of the kernel, and * to defend the IDT against arbitrary memory write vulnerabilities. * It will be reloaded in cpu_init() */ __set_fixmap(FIX_RO_IDT, __pa_symbol(idt_table), PAGE_KERNEL_RO); idt_descr.address = fix_to_virt(FIX_RO_IDT); /* * Should be a barrier for any external CPU state: */ cpu_init(); x86_init.irqs.trap_init(); #ifdef CONFIG_X86_64 memcpy(&debug_idt_table, &idt_table, IDT_ENTRIES * 16); set_nmi_gate(X86_TRAP_DB, &debug); set_nmi_gate(X86_TRAP_BP, &int3); #endif } Commit Message: x86_64, traps: Stop using IST for #SS On a 32-bit kernel, this has no effect, since there are no IST stacks. On a 64-bit kernel, #SS can only happen in user code, on a failed iret to user space, a canonical violation on access via RSP or RBP, or a genuine stack segment violation in 32-bit kernel code. The first two cases don't need IST, and the latter two cases are unlikely fatal bugs, and promoting them to double faults would be fine. This fixes a bug in which the espfix64 code mishandles a stack segment violation. This saves 4k of memory per CPU and a tiny bit of code. Signed-off-by: Andy Lutomirski <[email protected]> Reviewed-by: Thomas Gleixner <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
void __init trap_init(void) { int i; #ifdef CONFIG_EISA void __iomem *p = early_ioremap(0x0FFFD9, 4); if (readl(p) == 'E' + ('I'<<8) + ('S'<<16) + ('A'<<24)) EISA_bus = 1; early_iounmap(p, 4); #endif set_intr_gate(X86_TRAP_DE, divide_error); set_intr_gate_ist(X86_TRAP_NMI, &nmi, NMI_STACK); /* int4 can be called from all */ set_system_intr_gate(X86_TRAP_OF, &overflow); set_intr_gate(X86_TRAP_BR, bounds); set_intr_gate(X86_TRAP_UD, invalid_op); set_intr_gate(X86_TRAP_NM, device_not_available); #ifdef CONFIG_X86_32 set_task_gate(X86_TRAP_DF, GDT_ENTRY_DOUBLEFAULT_TSS); #else set_intr_gate_ist(X86_TRAP_DF, &double_fault, DOUBLEFAULT_STACK); #endif set_intr_gate(X86_TRAP_OLD_MF, coprocessor_segment_overrun); set_intr_gate(X86_TRAP_TS, invalid_TSS); set_intr_gate(X86_TRAP_NP, segment_not_present); set_intr_gate(X86_TRAP_SS, stack_segment); set_intr_gate(X86_TRAP_GP, general_protection); set_intr_gate(X86_TRAP_SPURIOUS, spurious_interrupt_bug); set_intr_gate(X86_TRAP_MF, coprocessor_error); set_intr_gate(X86_TRAP_AC, alignment_check); #ifdef CONFIG_X86_MCE set_intr_gate_ist(X86_TRAP_MC, &machine_check, MCE_STACK); #endif set_intr_gate(X86_TRAP_XF, simd_coprocessor_error); /* Reserve all the builtin and the syscall vector: */ for (i = 0; i < FIRST_EXTERNAL_VECTOR; i++) set_bit(i, used_vectors); #ifdef CONFIG_IA32_EMULATION set_system_intr_gate(IA32_SYSCALL_VECTOR, ia32_syscall); set_bit(IA32_SYSCALL_VECTOR, used_vectors); #endif #ifdef CONFIG_X86_32 set_system_trap_gate(SYSCALL_VECTOR, &system_call); set_bit(SYSCALL_VECTOR, used_vectors); #endif /* * Set the IDT descriptor to a fixed read-only location, so that the * "sidt" instruction will not leak the location of the kernel, and * to defend the IDT against arbitrary memory write vulnerabilities. * It will be reloaded in cpu_init() */ __set_fixmap(FIX_RO_IDT, __pa_symbol(idt_table), PAGE_KERNEL_RO); idt_descr.address = fix_to_virt(FIX_RO_IDT); /* * Should be a barrier for any external CPU state: */ cpu_init(); x86_init.irqs.trap_init(); #ifdef CONFIG_X86_64 memcpy(&debug_idt_table, &idt_table, IDT_ENTRIES * 16); set_nmi_gate(X86_TRAP_DB, &debug); set_nmi_gate(X86_TRAP_BP, &int3); #endif }
166,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Chapters::Display* Chapters::Atom::GetDisplay(int index) const { if (index < 0) return NULL; if (index >= m_displays_count) return NULL; return m_displays + index; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Chapters::Display* Chapters::Atom::GetDisplay(int index) const
174,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE + sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; } Commit Message: Fix buffer size checking Yes, this means we've re-introduced CVE-2005-3534. Sigh. CWE ID: CWE-119
int mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE - sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; }
165,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: make_transform_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, png_byte PNG_CONST bit_depth, unsigned int palette_number, int interlace_type, png_const_charp name) { context(ps, fault); check_interlace_type(interlace_type); Try { png_infop pi; png_structp pp = set_store_for_write(ps, &pi, name); png_uint_32 h; /* In the event of a problem return control to the Catch statement below * to do the clean up - it is not possible to 'return' directly from a Try * block. */ if (pp == NULL) Throw ps; h = transform_height(pp, colour_type, bit_depth); png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth), h, bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); #ifdef PNG_TEXT_SUPPORTED # if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED) # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt # else # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE # endif { static char key[] = "image name"; /* must be writeable */ size_t pos; png_text text; char copy[FILE_NAME_SIZE]; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; /* Yuck: the text must be writable! */ pos = safecat(copy, sizeof copy, 0, ps->wname); text.text = copy; text.text_length = pos; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/); png_write_info(pp, pi); if (png_get_rowbytes(pp, pi) != transform_rowsize(pp, colour_type, bit_depth)) png_error(pp, "row size incorrect"); else { /* Somewhat confusingly this must be called *after* png_write_info * because if it is called before, the information in *pp has not been * updated to reflect the interlaced image. */ int npasses = png_set_interlace_handling(pp); int pass; if (npasses != npasses_from_interlace_type(pp, interlace_type)) png_error(pp, "write: png_set_interlace_handling failed"); for (pass=0; pass<npasses; ++pass) { png_uint_32 y; for (y=0; y<h; ++y) { png_byte buffer[TRANSFORM_ROWMAX]; transform_row(pp, buffer, colour_type, bit_depth, y); png_write_row(pp, buffer); } } } #ifdef PNG_TEXT_SUPPORTED { static char key[] = "end marker"; static char comment[] = "end"; png_text text; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; text.text = comment; text.text_length = (sizeof comment)-1; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif png_write_end(pp, pi); /* And store this under the appropriate id, then clean up. */ store_storefile(ps, FILEID(colour_type, bit_depth, palette_number, interlace_type, 0, 0, 0)); store_write_reset(ps); } Catch(fault) { /* Use the png_store returned by the exception. This may help the compiler * because 'ps' is not used in this branch of the setjmp. Note that fault * and ps will always be the same value. */ store_write_reset(fault); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
make_transform_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, make_transform_image(png_store* const ps, png_byte const colour_type, png_byte const bit_depth, unsigned int palette_number, int interlace_type, png_const_charp name) { context(ps, fault); check_interlace_type(interlace_type); Try { png_infop pi; png_structp pp = set_store_for_write(ps, &pi, name); png_uint_32 h, w; /* In the event of a problem return control to the Catch statement below * to do the clean up - it is not possible to 'return' directly from a Try * block. */ if (pp == NULL) Throw ps; w = transform_width(pp, colour_type, bit_depth); h = transform_height(pp, colour_type, bit_depth); png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); #ifdef PNG_TEXT_SUPPORTED # if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED) # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt # else # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE # endif { static char key[] = "image name"; /* must be writeable */ size_t pos; png_text text; char copy[FILE_NAME_SIZE]; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; /* Yuck: the text must be writable! */ pos = safecat(copy, sizeof copy, 0, ps->wname); text.text = copy; text.text_length = pos; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/); # ifdef PNG_WRITE_tRNS_SUPPORTED else if (palette_number) set_random_tRNS(pp, pi, colour_type, bit_depth); # endif png_write_info(pp, pi); if (png_get_rowbytes(pp, pi) != transform_rowsize(pp, colour_type, bit_depth)) png_error(pp, "transform row size incorrect"); else { /* Somewhat confusingly this must be called *after* png_write_info * because if it is called before, the information in *pp has not been * updated to reflect the interlaced image. */ int npasses = set_write_interlace_handling(pp, interlace_type); int pass; if (npasses != npasses_from_interlace_type(pp, interlace_type)) png_error(pp, "write: png_set_interlace_handling failed"); for (pass=0; pass<npasses; ++pass) { png_uint_32 y; /* do_own_interlace is a pre-defined boolean (a #define) which is * set if we have to work out the interlaced rows here. */ for (y=0; y<h; ++y) { png_byte buffer[TRANSFORM_ROWMAX]; transform_row(pp, buffer, colour_type, bit_depth, y); # if do_own_interlace /* If do_own_interlace *and* the image is interlaced we need a * reduced interlace row; this may be reduced to empty. */ if (interlace_type == PNG_INTERLACE_ADAM7) { /* The row must not be written if it doesn't exist, notice * that there are two conditions here, either the row isn't * ever in the pass or the row would be but isn't wide * enough to contribute any pixels. In fact the wPass test * can be used to skip the whole y loop in this case. */ if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(w, pass) > 0) interlace_row(buffer, buffer, bit_size(pp, colour_type, bit_depth), w, pass, 0/*data always bigendian*/); else continue; } # endif /* do_own_interlace */ png_write_row(pp, buffer); } } } #ifdef PNG_TEXT_SUPPORTED { static char key[] = "end marker"; static char comment[] = "end"; png_text text; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; text.text = comment; text.text_length = (sizeof comment)-1; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif png_write_end(pp, pi); /* And store this under the appropriate id, then clean up. */ store_storefile(ps, FILEID(colour_type, bit_depth, palette_number, interlace_type, 0, 0, 0)); store_write_reset(ps); } Catch(fault) { /* Use the png_store returned by the exception. This may help the compiler * because 'ps' is not used in this branch of the setjmp. Note that fault * and ps will always be the same value. */ store_write_reset(fault); } }
173,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cifs_find_smb_ses(struct TCP_Server_Info *server, char *username) { struct list_head *tmp; struct cifsSesInfo *ses; write_lock(&cifs_tcp_ses_lock); list_for_each(tmp, &server->smb_ses_list) { ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list); if (strncmp(ses->userName, username, MAX_USERNAME_SIZE)) continue; ++ses->ses_count; write_unlock(&cifs_tcp_ses_lock); return ses; } write_unlock(&cifs_tcp_ses_lock); return NULL; } Commit Message: cifs: clean up cifs_find_smb_ses (try #2) This patch replaces the earlier patch by the same name. The only difference is that MAX_PASSWORD_SIZE has been increased to attempt to match the limits that windows enforces. Do a better job of matching sessions by authtype. Matching by username for a Kerberos session is incorrect, and anonymous sessions need special handling. Also, in the case where we do match by username, we also need to match by password. That ensures that someone else doesn't "borrow" an existing session without needing to know the password. Finally, passwords can be longer than 16 bytes. Bump MAX_PASSWORD_SIZE to 512 to match the size that the userspace mount helper allows. Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-264
cifs_find_smb_ses(struct TCP_Server_Info *server, char *username) cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb_vol *vol) { struct cifsSesInfo *ses; write_lock(&cifs_tcp_ses_lock); list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) { switch (server->secType) { case Kerberos: if (vol->linux_uid != ses->linux_uid) continue; break; default: /* anything else takes username/password */ if (strncmp(ses->userName, vol->username, MAX_USERNAME_SIZE)) continue; if (strlen(vol->username) != 0 && strncmp(ses->password, vol->password, MAX_PASSWORD_SIZE)) continue; } ++ses->ses_count; write_unlock(&cifs_tcp_ses_lock); return ses; } write_unlock(&cifs_tcp_ses_lock); return NULL; }
166,229
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAMR::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 0) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (!isConfigured()) { amrParams->nBitRate = 0; amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused; } else { amrParams->nBitRate = 0; amrParams->eAMRBandMode = mMode == MODE_NARROW ? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->nChannels = 1; pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->nSamplingRate = (mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAMR::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 0) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (!isConfigured()) { amrParams->nBitRate = 0; amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused; } else { amrParams->nBitRate = 0; amrParams->eAMRBandMode = mMode == MODE_NARROW ? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->nChannels = 1; pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->nSamplingRate = (mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,192
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ape_read_header(AVFormatContext * s, AVFormatParameters * ap) { AVIOContext *pb = s->pb; APEContext *ape = s->priv_data; AVStream *st; uint32_t tag; int i; int total_blocks; int64_t pts; /* TODO: Skip any leading junk such as id3v2 tags */ ape->junklength = 0; tag = avio_rl32(pb); if (tag != MKTAG('M', 'A', 'C', ' ')) return -1; ape->fileversion = avio_rl16(pb); if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) { av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10); return -1; } if (ape->fileversion >= 3980) { ape->padding1 = avio_rl16(pb); ape->descriptorlength = avio_rl32(pb); ape->headerlength = avio_rl32(pb); ape->seektablelength = avio_rl32(pb); ape->wavheaderlength = avio_rl32(pb); ape->audiodatalength = avio_rl32(pb); ape->audiodatalength_high = avio_rl32(pb); ape->wavtaillength = avio_rl32(pb); avio_read(pb, ape->md5, 16); /* Skip any unknown bytes at the end of the descriptor. This is for future compatibility */ if (ape->descriptorlength > 52) avio_seek(pb, ape->descriptorlength - 52, SEEK_CUR); /* Read header data */ ape->compressiontype = avio_rl16(pb); ape->formatflags = avio_rl16(pb); ape->blocksperframe = avio_rl32(pb); ape->finalframeblocks = avio_rl32(pb); ape->totalframes = avio_rl32(pb); ape->bps = avio_rl16(pb); ape->channels = avio_rl16(pb); ape->samplerate = avio_rl32(pb); } else { ape->descriptorlength = 0; ape->headerlength = 32; ape->compressiontype = avio_rl16(pb); ape->formatflags = avio_rl16(pb); ape->channels = avio_rl16(pb); ape->samplerate = avio_rl32(pb); ape->wavheaderlength = avio_rl32(pb); ape->wavtaillength = avio_rl32(pb); ape->totalframes = avio_rl32(pb); ape->finalframeblocks = avio_rl32(pb); if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { avio_seek(pb, 4, SEEK_CUR); /* Skip the peak level */ ape->headerlength += 4; } if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { ape->seektablelength = avio_rl32(pb); ape->headerlength += 4; ape->seektablelength *= sizeof(int32_t); } else ape->seektablelength = ape->totalframes * sizeof(int32_t); if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT) ape->bps = 8; else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT) ape->bps = 24; else ape->bps = 16; if (ape->fileversion >= 3950) ape->blocksperframe = 73728 * 4; else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000)) ape->blocksperframe = 73728; else ape->blocksperframe = 9216; /* Skip any stored wav header */ if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) avio_seek(pb, ape->wavheaderlength, SEEK_CUR); } if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes); return -1; } ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame)); if(!ape->frames) return AVERROR(ENOMEM); ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength; ape->currentframe = 0; ape->totalsamples = ape->finalframeblocks; if (ape->totalframes > 1) ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1); if (ape->seektablelength > 0) { ape->seektable = av_malloc(ape->seektablelength); for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++) ape->seektable[i] = avio_rl32(pb); } ape->frames[0].pos = ape->firstframe; ape->frames[0].nblocks = ape->blocksperframe; ape->frames[0].skip = 0; for (i = 1; i < ape->totalframes; i++) { ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe; ape->frames[i].nblocks = ape->blocksperframe; ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos; ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3; } ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4; ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks; for (i = 0; i < ape->totalframes; i++) { if(ape->frames[i].skip){ ape->frames[i].pos -= ape->frames[i].skip; ape->frames[i].size += ape->frames[i].skip; } ape->frames[i].size = (ape->frames[i].size + 3) & ~3; } ape_dumpinfo(s, ape); /* try to read APE tags */ if (!url_is_streamed(pb)) { ff_ape_parse_tag(s); avio_seek(pb, 0, SEEK_SET); } av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype); /* now we are ready: build format streams */ st = av_new_stream(s, 0); if (!st) return -1; total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks; st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = CODEC_ID_APE; st->codec->codec_tag = MKTAG('A', 'P', 'E', ' '); st->codec->channels = ape->channels; st->codec->sample_rate = ape->samplerate; st->codec->bits_per_coded_sample = ape->bps; st->codec->frame_size = MAC_SUBFRAME_SIZE; st->nb_frames = ape->totalframes; st->start_time = 0; st->duration = total_blocks / MAC_SUBFRAME_SIZE; av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate); st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE); st->codec->extradata_size = APE_EXTRADATA_SIZE; AV_WL16(st->codec->extradata + 0, ape->fileversion); AV_WL16(st->codec->extradata + 2, ape->compressiontype); AV_WL16(st->codec->extradata + 4, ape->formatflags); pts = 0; for (i = 0; i < ape->totalframes; i++) { ape->frames[i].pts = pts; av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME); pts += ape->blocksperframe / MAC_SUBFRAME_SIZE; } return 0; } Commit Message: Do not attempt to decode APE file with no frames This fixes invalid reads/writes with this sample: http://packetstorm.linuxsecurity.com/1103-exploits/vlc105-dos.txt CWE ID: CWE-399
static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) { AVIOContext *pb = s->pb; APEContext *ape = s->priv_data; AVStream *st; uint32_t tag; int i; int total_blocks; int64_t pts; /* TODO: Skip any leading junk such as id3v2 tags */ ape->junklength = 0; tag = avio_rl32(pb); if (tag != MKTAG('M', 'A', 'C', ' ')) return -1; ape->fileversion = avio_rl16(pb); if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) { av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10); return -1; } if (ape->fileversion >= 3980) { ape->padding1 = avio_rl16(pb); ape->descriptorlength = avio_rl32(pb); ape->headerlength = avio_rl32(pb); ape->seektablelength = avio_rl32(pb); ape->wavheaderlength = avio_rl32(pb); ape->audiodatalength = avio_rl32(pb); ape->audiodatalength_high = avio_rl32(pb); ape->wavtaillength = avio_rl32(pb); avio_read(pb, ape->md5, 16); /* Skip any unknown bytes at the end of the descriptor. This is for future compatibility */ if (ape->descriptorlength > 52) avio_seek(pb, ape->descriptorlength - 52, SEEK_CUR); /* Read header data */ ape->compressiontype = avio_rl16(pb); ape->formatflags = avio_rl16(pb); ape->blocksperframe = avio_rl32(pb); ape->finalframeblocks = avio_rl32(pb); ape->totalframes = avio_rl32(pb); ape->bps = avio_rl16(pb); ape->channels = avio_rl16(pb); ape->samplerate = avio_rl32(pb); } else { ape->descriptorlength = 0; ape->headerlength = 32; ape->compressiontype = avio_rl16(pb); ape->formatflags = avio_rl16(pb); ape->channels = avio_rl16(pb); ape->samplerate = avio_rl32(pb); ape->wavheaderlength = avio_rl32(pb); ape->wavtaillength = avio_rl32(pb); ape->totalframes = avio_rl32(pb); ape->finalframeblocks = avio_rl32(pb); if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { avio_seek(pb, 4, SEEK_CUR); /* Skip the peak level */ ape->headerlength += 4; } if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { ape->seektablelength = avio_rl32(pb); ape->headerlength += 4; ape->seektablelength *= sizeof(int32_t); } else ape->seektablelength = ape->totalframes * sizeof(int32_t); if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT) ape->bps = 8; else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT) ape->bps = 24; else ape->bps = 16; if (ape->fileversion >= 3950) ape->blocksperframe = 73728 * 4; else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000)) ape->blocksperframe = 73728; else ape->blocksperframe = 9216; /* Skip any stored wav header */ if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) avio_seek(pb, ape->wavheaderlength, SEEK_CUR); } if(!ape->totalframes){ av_log(s, AV_LOG_ERROR, "No frames in the file!\n"); return AVERROR(EINVAL); } if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes); return -1; } ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame)); if(!ape->frames) return AVERROR(ENOMEM); ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength; ape->currentframe = 0; ape->totalsamples = ape->finalframeblocks; if (ape->totalframes > 1) ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1); if (ape->seektablelength > 0) { ape->seektable = av_malloc(ape->seektablelength); for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++) ape->seektable[i] = avio_rl32(pb); } ape->frames[0].pos = ape->firstframe; ape->frames[0].nblocks = ape->blocksperframe; ape->frames[0].skip = 0; for (i = 1; i < ape->totalframes; i++) { ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe; ape->frames[i].nblocks = ape->blocksperframe; ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos; ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3; } ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4; ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks; for (i = 0; i < ape->totalframes; i++) { if(ape->frames[i].skip){ ape->frames[i].pos -= ape->frames[i].skip; ape->frames[i].size += ape->frames[i].skip; } ape->frames[i].size = (ape->frames[i].size + 3) & ~3; } ape_dumpinfo(s, ape); /* try to read APE tags */ if (!url_is_streamed(pb)) { ff_ape_parse_tag(s); avio_seek(pb, 0, SEEK_SET); } av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype); /* now we are ready: build format streams */ st = av_new_stream(s, 0); if (!st) return -1; total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks; st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = CODEC_ID_APE; st->codec->codec_tag = MKTAG('A', 'P', 'E', ' '); st->codec->channels = ape->channels; st->codec->sample_rate = ape->samplerate; st->codec->bits_per_coded_sample = ape->bps; st->codec->frame_size = MAC_SUBFRAME_SIZE; st->nb_frames = ape->totalframes; st->start_time = 0; st->duration = total_blocks / MAC_SUBFRAME_SIZE; av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate); st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE); st->codec->extradata_size = APE_EXTRADATA_SIZE; AV_WL16(st->codec->extradata + 0, ape->fileversion); AV_WL16(st->codec->extradata + 2, ape->compressiontype); AV_WL16(st->codec->extradata + 4, ape->formatflags); pts = 0; for (i = 0; i < ape->totalframes; i++) { ape->frames[i].pts = pts; av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME); pts += ape->blocksperframe / MAC_SUBFRAME_SIZE; } return 0; }
165,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: content::WebUIDataSource* CreateOobeUIDataSource( const base::DictionaryValue& localized_strings, const std::string& display_type) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->AddLocalizedStrings(localized_strings); source->SetJsonPath(kStringsJSPath); if (display_type == OobeUI::kOobeDisplay) { source->SetDefaultResource(IDR_OOBE_HTML); source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_OOBE_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_OOBE_JS); } else { source->SetDefaultResource(IDR_LOGIN_HTML); source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_LOGIN_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_LOGIN_JS); } source->AddResourcePath(kPolymerConfigJSPath, IDR_POLYMER_CONFIG_JS); source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyFrameSrc( base::StringPrintf( "frame-src chrome://terms/ %s/;", extensions::kGaiaAuthExtensionOrigin)); source->OverrideContentSecurityPolicyObjectSrc("object-src *;"); bool is_webview_signin_enabled = StartupUtils::IsWebviewSigninEnabled(); source->AddResourcePath("gaia_auth_host.js", is_webview_signin_enabled ? IDR_GAIA_AUTH_AUTHENTICATOR_JS : IDR_GAIA_AUTH_HOST_JS); source->AddResourcePath(kEnrollmentHTMLPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_HTML : IDR_OOBE_ENROLLMENT_HTML); source->AddResourcePath(kEnrollmentCSSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_CSS : IDR_OOBE_ENROLLMENT_CSS); source->AddResourcePath(kEnrollmentJSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_JS : IDR_OOBE_ENROLLMENT_JS); if (display_type == OobeUI::kOobeDisplay) { source->AddResourcePath("Roboto-Thin.ttf", IDR_FONT_ROBOTO_THIN); source->AddResourcePath("Roboto-Light.ttf", IDR_FONT_ROBOTO_LIGHT); source->AddResourcePath("Roboto-Regular.ttf", IDR_FONT_ROBOTO_REGULAR); source->AddResourcePath("Roboto-Medium.ttf", IDR_FONT_ROBOTO_MEDIUM); source->AddResourcePath("Roboto-Bold.ttf", IDR_FONT_ROBOTO_BOLD); } return source; } Commit Message: One polymer_config.js to rule them all. [email protected],[email protected],[email protected] BUG=425626 Review URL: https://codereview.chromium.org/1224783005 Cr-Commit-Position: refs/heads/master@{#337882} CWE ID: CWE-399
content::WebUIDataSource* CreateOobeUIDataSource( const base::DictionaryValue& localized_strings, const std::string& display_type) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->AddLocalizedStrings(localized_strings); source->SetJsonPath(kStringsJSPath); if (display_type == OobeUI::kOobeDisplay) { source->SetDefaultResource(IDR_OOBE_HTML); source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_OOBE_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_OOBE_JS); } else { source->SetDefaultResource(IDR_LOGIN_HTML); source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_LOGIN_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_LOGIN_JS); } source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyFrameSrc( base::StringPrintf( "frame-src chrome://terms/ %s/;", extensions::kGaiaAuthExtensionOrigin)); source->OverrideContentSecurityPolicyObjectSrc("object-src *;"); bool is_webview_signin_enabled = StartupUtils::IsWebviewSigninEnabled(); source->AddResourcePath("gaia_auth_host.js", is_webview_signin_enabled ? IDR_GAIA_AUTH_AUTHENTICATOR_JS : IDR_GAIA_AUTH_HOST_JS); source->AddResourcePath(kEnrollmentHTMLPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_HTML : IDR_OOBE_ENROLLMENT_HTML); source->AddResourcePath(kEnrollmentCSSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_CSS : IDR_OOBE_ENROLLMENT_CSS); source->AddResourcePath(kEnrollmentJSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_JS : IDR_OOBE_ENROLLMENT_JS); if (display_type == OobeUI::kOobeDisplay) { source->AddResourcePath("Roboto-Thin.ttf", IDR_FONT_ROBOTO_THIN); source->AddResourcePath("Roboto-Light.ttf", IDR_FONT_ROBOTO_LIGHT); source->AddResourcePath("Roboto-Regular.ttf", IDR_FONT_ROBOTO_REGULAR); source->AddResourcePath("Roboto-Medium.ttf", IDR_FONT_ROBOTO_MEDIUM); source->AddResourcePath("Roboto-Bold.ttf", IDR_FONT_ROBOTO_BOLD); } return source; }
171,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error) { if (strcmp (incoming, "/org/freedesktop/DBus/GLib/Tests/MyTestObject")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid incoming object"); return FALSE; } *outgoing = "/org/freedesktop/DBus/GLib/Tests/MyTestObject2"; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error)
165,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { q = (const uint8_t *)(const void *) ((const char *)(const void *)p + CDF_GETUINT32(p, (i << 1) + 1)) - 2 * sizeof(uint32_t); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, CDF_GETUINT32(p, (i << 1) + 1))); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } Commit Message: Fix bounds checks again. CWE ID: CWE-119
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; }
165,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResourceTracker::CleanupInstanceData(PP_Instance instance, bool delete_instance) { DLOG_IF(ERROR, !CheckIdType(instance, PP_ID_TYPE_INSTANCE)) << instance << " is not a PP_Instance."; InstanceMap::iterator found = instance_map_.find(instance); if (found == instance_map_.end()) { NOTREACHED(); return; } InstanceData& data = *found->second; ResourceSet::iterator cur_res = data.resources.begin(); while (cur_res != data.resources.end()) { ResourceMap::iterator found_resource = live_resources_.find(*cur_res); if (found_resource == live_resources_.end()) { NOTREACHED(); } else { Resource* resource = found_resource->second.first; resource->LastPluginRefWasDeleted(true); live_resources_.erase(*cur_res); } ResourceSet::iterator current = cur_res++; data.resources.erase(current); } DCHECK(data.resources.empty()); VarSet::iterator cur_var = data.object_vars.begin(); while (cur_var != data.object_vars.end()) { VarSet::iterator current = cur_var++; PP_Var object_pp_var; object_pp_var.type = PP_VARTYPE_OBJECT; object_pp_var.value.as_id = *current; scoped_refptr<ObjectVar> object_var(ObjectVar::FromPPVar(object_pp_var)); if (object_var.get()) object_var->InstanceDeleted(); live_vars_.erase(*current); data.object_vars.erase(*current); } DCHECK(data.object_vars.empty()); if (delete_instance) instance_map_.erase(found); } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ResourceTracker::CleanupInstanceData(PP_Instance instance, bool delete_instance) { DLOG_IF(ERROR, !CheckIdType(instance, PP_ID_TYPE_INSTANCE)) << instance << " is not a PP_Instance."; InstanceMap::iterator found = instance_map_.find(instance); if (found == instance_map_.end()) { NOTREACHED(); return; } InstanceData& data = *found->second; ResourceSet::iterator cur_res = data.ref_resources.begin(); while (cur_res != data.ref_resources.end()) { ResourceMap::iterator found_resource = live_resources_.find(*cur_res); if (found_resource == live_resources_.end()) { NOTREACHED(); } else { Resource* resource = found_resource->second.first; resource->LastPluginRefWasDeleted(); live_resources_.erase(*cur_res); } ResourceSet::iterator current = cur_res++; data.ref_resources.erase(current); } DCHECK(data.ref_resources.empty()); VarSet::iterator cur_var = data.object_vars.begin(); while (cur_var != data.object_vars.end()) { VarSet::iterator current = cur_var++; PP_Var object_pp_var; object_pp_var.type = PP_VARTYPE_OBJECT; object_pp_var.value.as_id = *current; scoped_refptr<ObjectVar> object_var(ObjectVar::FromPPVar(object_pp_var)); if (object_var.get()) object_var->InstanceDeleted(); live_vars_.erase(*current); data.object_vars.erase(*current); } DCHECK(data.object_vars.empty()); // Clear any resources that still reference this instance. for (std::set<Resource*>::iterator res = data.assoc_resources.begin(); res != data.assoc_resources.end(); ++res) (*res)->ClearInstance(); data.assoc_resources.clear(); if (delete_instance) instance_map_.erase(found); }
170,417
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltFuncFunctionComp (xsltStylesheetPtr style, xmlNodePtr inst) { xmlChar *name, *prefix; xmlNsPtr ns; xmlHashTablePtr data; exsltFuncFunctionData *func; if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE)) return; { xmlChar *qname; qname = xmlGetProp(inst, (const xmlChar *) "name"); name = xmlSplitQName2 (qname, &prefix); xmlFree(qname); } if ((name == NULL) || (prefix == NULL)) { xsltGenericError(xsltGenericErrorContext, "func:function: not a QName\n"); if (name != NULL) xmlFree(name); return; } /* namespace lookup */ ns = xmlSearchNs (inst->doc, inst, prefix); if (ns == NULL) { xsltGenericError(xsltGenericErrorContext, "func:function: undeclared prefix %s\n", prefix); xmlFree(name); xmlFree(prefix); return; } xmlFree(prefix); xsltParseTemplateContent(style, inst); /* * Create function data */ func = exsltFuncNewFunctionData(); func->content = inst->children; while (IS_XSLT_ELEM(func->content) && IS_XSLT_NAME(func->content, "param")) { func->content = func->content->next; func->nargs++; } /* * Register the function data such that it can be retrieved * by exslFuncFunctionFunction */ #ifdef XSLT_REFACTORED /* * Ensure that the hash table will be stored in the *current* * stylesheet level in order to correctly evaluate the * import precedence. */ data = (xmlHashTablePtr) xsltStyleStylesheetLevelGetExtData(style, EXSLT_FUNCTIONS_NAMESPACE); #else data = (xmlHashTablePtr) xsltStyleGetExtData (style, EXSLT_FUNCTIONS_NAMESPACE); #endif if (data == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionComp: no stylesheet data\n"); xmlFree(name); return; } if (xmlHashAddEntry2 (data, ns->href, name, func) < 0) { xsltTransformError(NULL, style, inst, "Failed to register function {%s}%s\n", ns->href, name); style->errors++; } else { xsltGenericDebug(xsltGenericDebugContext, "exsltFuncFunctionComp: register {%s}%s\n", ns->href, name); } xmlFree(name); } 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
exsltFuncFunctionComp (xsltStylesheetPtr style, xmlNodePtr inst) { xmlChar *name, *prefix; xmlNsPtr ns; xmlHashTablePtr data; exsltFuncFunctionData *func; if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE)) return; { xmlChar *qname; qname = xmlGetProp(inst, (const xmlChar *) "name"); name = xmlSplitQName2 (qname, &prefix); xmlFree(qname); } if ((name == NULL) || (prefix == NULL)) { xsltGenericError(xsltGenericErrorContext, "func:function: not a QName\n"); if (name != NULL) xmlFree(name); return; } /* namespace lookup */ ns = xmlSearchNs (inst->doc, inst, prefix); if (ns == NULL) { xsltGenericError(xsltGenericErrorContext, "func:function: undeclared prefix %s\n", prefix); xmlFree(name); xmlFree(prefix); return; } xmlFree(prefix); xsltParseTemplateContent(style, inst); /* * Create function data */ func = exsltFuncNewFunctionData(); if (func == NULL) { xmlFree(name); return; } func->content = inst->children; while (IS_XSLT_ELEM(func->content) && IS_XSLT_NAME(func->content, "param")) { func->content = func->content->next; func->nargs++; } /* * Register the function data such that it can be retrieved * by exslFuncFunctionFunction */ #ifdef XSLT_REFACTORED /* * Ensure that the hash table will be stored in the *current* * stylesheet level in order to correctly evaluate the * import precedence. */ data = (xmlHashTablePtr) xsltStyleStylesheetLevelGetExtData(style, EXSLT_FUNCTIONS_NAMESPACE); #else data = (xmlHashTablePtr) xsltStyleGetExtData (style, EXSLT_FUNCTIONS_NAMESPACE); #endif if (data == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionComp: no stylesheet data\n"); xmlFree(name); return; } if (xmlHashAddEntry2 (data, ns->href, name, func) < 0) { xsltTransformError(NULL, style, inst, "Failed to register function {%s}%s\n", ns->href, name); style->errors++; } else { xsltGenericDebug(xsltGenericDebugContext, "exsltFuncFunctionComp: register {%s}%s\n", ns->href, name); } xmlFree(name); }
173,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: key_ref_t key_create_or_update(key_ref_t keyring_ref, const char *type, const char *description, const void *payload, size_t plen, key_perm_t perm, unsigned long flags) { struct keyring_index_key index_key = { .description = description, }; struct key_preparsed_payload prep; struct assoc_array_edit *edit; const struct cred *cred = current_cred(); struct key *keyring, *key = NULL; key_ref_t key_ref; int ret; /* look up the key type to see if it's one of the registered kernel * types */ index_key.type = key_type_lookup(type); if (IS_ERR(index_key.type)) { key_ref = ERR_PTR(-ENODEV); goto error; } key_ref = ERR_PTR(-EINVAL); if (!index_key.type->match || !index_key.type->instantiate || (!index_key.description && !index_key.type->preparse)) goto error_put_type; keyring = key_ref_to_ptr(keyring_ref); key_check(keyring); key_ref = ERR_PTR(-ENOTDIR); if (keyring->type != &key_type_keyring) goto error_put_type; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = index_key.type->def_datalen; prep.trusted = flags & KEY_ALLOC_TRUSTED; prep.expiry = TIME_T_MAX; if (index_key.type->preparse) { ret = index_key.type->preparse(&prep); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } if (!index_key.description) index_key.description = prep.description; key_ref = ERR_PTR(-EINVAL); if (!index_key.description) goto error_free_prep; } index_key.desc_len = strlen(index_key.description); key_ref = ERR_PTR(-EPERM); if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags)) goto error_free_prep; flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0; ret = __key_link_begin(keyring, &index_key, &edit); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } /* if we're going to allocate a new key, we're going to have * to modify the keyring */ ret = key_permission(keyring_ref, KEY_NEED_WRITE); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_link_end; } /* if it's possible to update this type of key, search for an existing * key of the same type and description in the destination keyring and * update that instead if possible */ if (index_key.type->update) { key_ref = find_key_to_update(keyring_ref, &index_key); if (key_ref) goto found_matching_key; } /* if the client doesn't provide, decide on the permissions we want */ if (perm == KEY_PERM_UNDEF) { perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (index_key.type->read) perm |= KEY_POS_READ; if (index_key.type == &key_type_keyring || index_key.type->update) perm |= KEY_POS_WRITE; } /* allocate a new key */ key = key_alloc(index_key.type, index_key.description, cred->fsuid, cred->fsgid, cred, perm, flags); if (IS_ERR(key)) { key_ref = ERR_CAST(key); goto error_link_end; } /* instantiate it and link it into the target keyring */ ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit); if (ret < 0) { key_put(key); key_ref = ERR_PTR(ret); goto error_link_end; } key_ref = make_key_ref(key, is_key_possessed(keyring_ref)); error_link_end: __key_link_end(keyring, &index_key, edit); error_free_prep: if (index_key.type->preparse) index_key.type->free_preparse(&prep); error_put_type: key_type_put(index_key.type); error: return key_ref; found_matching_key: /* we found a matching key, so we're going to try to update it * - we can drop the locks first as we have the key pinned */ __key_link_end(keyring, &index_key, edit); key_ref = __key_update(key_ref, &prep); goto error_free_prep; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]> CWE ID: CWE-476
key_ref_t key_create_or_update(key_ref_t keyring_ref, const char *type, const char *description, const void *payload, size_t plen, key_perm_t perm, unsigned long flags) { struct keyring_index_key index_key = { .description = description, }; struct key_preparsed_payload prep; struct assoc_array_edit *edit; const struct cred *cred = current_cred(); struct key *keyring, *key = NULL; key_ref_t key_ref; int ret; /* look up the key type to see if it's one of the registered kernel * types */ index_key.type = key_type_lookup(type); if (IS_ERR(index_key.type)) { key_ref = ERR_PTR(-ENODEV); goto error; } key_ref = ERR_PTR(-EINVAL); if (!index_key.type->instantiate || (!index_key.description && !index_key.type->preparse)) goto error_put_type; keyring = key_ref_to_ptr(keyring_ref); key_check(keyring); key_ref = ERR_PTR(-ENOTDIR); if (keyring->type != &key_type_keyring) goto error_put_type; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = index_key.type->def_datalen; prep.trusted = flags & KEY_ALLOC_TRUSTED; prep.expiry = TIME_T_MAX; if (index_key.type->preparse) { ret = index_key.type->preparse(&prep); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } if (!index_key.description) index_key.description = prep.description; key_ref = ERR_PTR(-EINVAL); if (!index_key.description) goto error_free_prep; } index_key.desc_len = strlen(index_key.description); key_ref = ERR_PTR(-EPERM); if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags)) goto error_free_prep; flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0; ret = __key_link_begin(keyring, &index_key, &edit); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } /* if we're going to allocate a new key, we're going to have * to modify the keyring */ ret = key_permission(keyring_ref, KEY_NEED_WRITE); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_link_end; } /* if it's possible to update this type of key, search for an existing * key of the same type and description in the destination keyring and * update that instead if possible */ if (index_key.type->update) { key_ref = find_key_to_update(keyring_ref, &index_key); if (key_ref) goto found_matching_key; } /* if the client doesn't provide, decide on the permissions we want */ if (perm == KEY_PERM_UNDEF) { perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (index_key.type->read) perm |= KEY_POS_READ; if (index_key.type == &key_type_keyring || index_key.type->update) perm |= KEY_POS_WRITE; } /* allocate a new key */ key = key_alloc(index_key.type, index_key.description, cred->fsuid, cred->fsgid, cred, perm, flags); if (IS_ERR(key)) { key_ref = ERR_CAST(key); goto error_link_end; } /* instantiate it and link it into the target keyring */ ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit); if (ret < 0) { key_put(key); key_ref = ERR_PTR(ret); goto error_link_end; } key_ref = make_key_ref(key, is_key_possessed(keyring_ref)); error_link_end: __key_link_end(keyring, &index_key, edit); error_free_prep: if (index_key.type->preparse) index_key.type->free_preparse(&prep); error_put_type: key_type_put(index_key.type); error: return key_ref; found_matching_key: /* we found a matching key, so we're going to try to update it * - we can drop the locks first as we have the key pinned */ __key_link_end(keyring, &index_key, edit); key_ref = __key_update(key_ref, &prep); goto error_free_prep; }
168,439
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync( content::CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kUnconnected || gpu_channel_->state() == GpuChannelHost::kConnected) return GetGpuChannel(); gpu_channel_ = NULL; } int client_id = 0; IPC::ChannelHandle channel_handle; base::ProcessHandle renderer_process_for_gpu; content::GPUInfo gpu_info; if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch, &client_id, &channel_handle, &renderer_process_for_gpu, &gpu_info)) || channel_handle.name.empty() || #if defined(OS_POSIX) channel_handle.socket.fd == -1 || #endif renderer_process_for_gpu == base::kNullProcessHandle) { gpu_channel_ = NULL; return NULL; } gpu_channel_ = new GpuChannelHost(this, 0, client_id); gpu_channel_->set_gpu_info(gpu_info); content::GetContentClient()->SetGpuInfo(gpu_info); gpu_channel_->Connect(channel_handle, renderer_process_for_gpu); return GetGpuChannel(); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync( content::CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kUnconnected || gpu_channel_->state() == GpuChannelHost::kConnected) return GetGpuChannel(); gpu_channel_ = NULL; } int client_id = 0; IPC::ChannelHandle channel_handle; content::GPUInfo gpu_info; if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch, &client_id, &channel_handle, &gpu_info)) || #if defined(OS_POSIX) channel_handle.socket.fd == -1 || #endif channel_handle.name.empty()) { gpu_channel_ = NULL; return NULL; } gpu_channel_ = new GpuChannelHost(this, 0, client_id); gpu_channel_->set_gpu_info(gpu_info); content::GetContentClient()->SetGpuInfo(gpu_info); gpu_channel_->Connect(channel_handle); return GetGpuChannel(); }
170,954
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateInt( int64_t num ) { cJSON *item = cJSON_New_Item(); if ( item ) { item->type = cJSON_Number; item->valuefloat = num; item->valueint = num; } return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateInt( int64_t num )
167,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: standard_row_validate(standard_display *dp, png_const_structp pp, int iImage, int iDisplay, png_uint_32 y) { int where; png_byte std[STANDARD_ROWMAX]; /* The row must be pre-initialized to the magic number here for the size * tests to pass: */ memset(std, 178, sizeof std); standard_row(pp, std, dp->id, y); /* At the end both the 'row' and 'display' arrays should end up identical. * In earlier passes 'row' will be partially filled in, with only the pixels * that have been read so far, but 'display' will have those pixels * replicated to fill the unread pixels while reading an interlaced image. #if PNG_LIBPNG_VER < 10506 * The side effect inside the libpng sequential reader is that the 'row' * array retains the correct values for unwritten pixels within the row * bytes, while the 'display' array gets bits off the end of the image (in * the last byte) trashed. Unfortunately in the progressive reader the * row bytes are always trashed, so we always do a pixel_cmp here even though * a memcmp of all cbRow bytes will succeed for the sequential reader. #endif */ if (iImage >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iImage, y)[where-1]); png_error(pp, msg); } #if PNG_LIBPNG_VER < 10506 /* In this case use pixel_cmp because we need to compare a partial * byte at the end of the row if the row is not an exact multiple * of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is * changed to match!) */ #endif if (iDisplay >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iDisplay, y)[where-1]); png_error(pp, msg); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
standard_row_validate(standard_display *dp, png_const_structp pp, int iImage, int iDisplay, png_uint_32 y) { int where; png_byte std[STANDARD_ROWMAX]; /* The row must be pre-initialized to the magic number here for the size * tests to pass: */ memset(std, 178, sizeof std); standard_row(pp, std, dp->id, y); /* At the end both the 'row' and 'display' arrays should end up identical. * In earlier passes 'row' will be partially filled in, with only the pixels * that have been read so far, but 'display' will have those pixels * replicated to fill the unread pixels while reading an interlaced image. */ if (iImage >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iImage, y)[where-1]); png_error(pp, msg); } if (iDisplay >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iDisplay, y)[where-1]); png_error(pp, msg); } }
173,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[8] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, 8); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; }
169,053
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m, const struct iovec *iv, unsigned long total_len, size_t count, int noblock) { struct sk_buff *skb; struct macvlan_dev *vlan; unsigned long len = total_len; int err; struct virtio_net_hdr vnet_hdr = { 0 }; int vnet_hdr_len = 0; int copylen; bool zerocopy = false; if (q->flags & IFF_VNET_HDR) { vnet_hdr_len = q->vnet_hdr_sz; err = -EINVAL; if (len < vnet_hdr_len) goto err; len -= vnet_hdr_len; err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0, sizeof(vnet_hdr)); if (err < 0) goto err; if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 > vnet_hdr.hdr_len) vnet_hdr.hdr_len = vnet_hdr.csum_start + vnet_hdr.csum_offset + 2; err = -EINVAL; if (vnet_hdr.hdr_len > len) goto err; } err = -EINVAL; if (unlikely(len < ETH_HLEN)) goto err; if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) zerocopy = true; if (zerocopy) { /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest buffer is mapped from userspace. */ copylen = vnet_hdr.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen, vnet_hdr.hdr_len, noblock, &err); if (!skb) goto err; if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len, len); if (err) goto err_kfree; skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_header(skb); skb->protocol = eth_hdr(skb)->h_proto; if (vnet_hdr_len) { err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr); if (err) goto err_kfree; } rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = m->msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } if (vlan) macvlan_start_xmit(skb, vlan->dev); else kfree_skb(skb); rcu_read_unlock_bh(); return total_len; err_kfree: kfree_skb(skb); err: rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); if (vlan) vlan->dev->stats.tx_dropped++; rcu_read_unlock_bh(); return err; } Commit Message: macvtap: zerocopy: validate vectors before building skb There're several reasons that the vectors need to be validated: - Return error when caller provides vectors whose num is greater than UIO_MAXIOV. - Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS. - Return error when userspace provides vectors whose total length may exceed - MAX_SKB_FRAGS * PAGE_SIZE. Signed-off-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> CWE ID: CWE-119
static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m, const struct iovec *iv, unsigned long total_len, size_t count, int noblock) { struct sk_buff *skb; struct macvlan_dev *vlan; unsigned long len = total_len; int err; struct virtio_net_hdr vnet_hdr = { 0 }; int vnet_hdr_len = 0; int copylen = 0; bool zerocopy = false; if (q->flags & IFF_VNET_HDR) { vnet_hdr_len = q->vnet_hdr_sz; err = -EINVAL; if (len < vnet_hdr_len) goto err; len -= vnet_hdr_len; err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0, sizeof(vnet_hdr)); if (err < 0) goto err; if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 > vnet_hdr.hdr_len) vnet_hdr.hdr_len = vnet_hdr.csum_start + vnet_hdr.csum_offset + 2; err = -EINVAL; if (vnet_hdr.hdr_len > len) goto err; } err = -EINVAL; if (unlikely(len < ETH_HLEN)) goto err; err = -EMSGSIZE; if (unlikely(count > UIO_MAXIOV)) goto err; if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) zerocopy = true; if (zerocopy) { /* Userspace may produce vectors with count greater than * MAX_SKB_FRAGS, so we need to linearize parts of the skb * to let the rest of data to be fit in the frags. */ if (count > MAX_SKB_FRAGS) { copylen = iov_length(iv, count - MAX_SKB_FRAGS); if (copylen < vnet_hdr_len) copylen = 0; else copylen -= vnet_hdr_len; } /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest buffer is mapped from userspace. */ if (copylen < vnet_hdr.hdr_len) copylen = vnet_hdr.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen, vnet_hdr.hdr_len, noblock, &err); if (!skb) goto err; if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len, len); if (err) goto err_kfree; skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_header(skb); skb->protocol = eth_hdr(skb)->h_proto; if (vnet_hdr_len) { err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr); if (err) goto err_kfree; } rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = m->msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } if (vlan) macvlan_start_xmit(skb, vlan->dev); else kfree_skb(skb); rcu_read_unlock_bh(); return total_len; err_kfree: kfree_skb(skb); err: rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); if (vlan) vlan->dev->stats.tx_dropped++; rcu_read_unlock_bh(); return err; }
166,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssize_t readAt(off64_t offset, void *buffer, size_t size) { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); data.writeInt64(offset); data.writeInt32(size); status_t err = remote()->transact(READ_AT, data, &reply); if (err != OK) { ALOGE("remote readAt failed"); return UNKNOWN_ERROR; } int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } int32_t len = reply.readInt32(); if (len > 0) { memcpy(buffer, mMemory->pointer(), len); } return len; } Commit Message: Add some sanity checks Bug: 19400722 Change-Id: Ib3afdf73fd4647eeea5721c61c8b72dbba0647f6 CWE ID: CWE-119
virtual ssize_t readAt(off64_t offset, void *buffer, size_t size) { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); data.writeInt64(offset); data.writeInt32(size); status_t err = remote()->transact(READ_AT, data, &reply); if (err != OK) { ALOGE("remote readAt failed"); return UNKNOWN_ERROR; } int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } size_t len = reply.readInt32(); if (len > size) { ALOGE("requested %zu, got %zu", size, len); return ERROR_OUT_OF_RANGE; } if (len > mMemory->size()) { ALOGE("got %zu, but memory has %zu", len, mMemory->size()); return ERROR_OUT_OF_RANGE; } memcpy(buffer, mMemory->pointer(), len); return len; }
173,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { SEPARATE_ZVAL(var2); convert_to_double(*var2); matrix[i][j] = (float)Z_DVAL_PP(var2); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { if (Z_TYPE_PP(var2) != IS_DOUBLE) { zval dval; dval = **var; zval_copy_ctor(&dval); convert_to_double(&dval); matrix[i][j] = (float)Z_DVAL(dval); } else { matrix[i][j] = (float)Z_DVAL_PP(var2); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } }
166,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssl_get_prev_session(SSL *s, unsigned char *session_id, int len, const unsigned char *limit) { /* This is used only by servers. */ SSL_SESSION *ret = NULL; int fatal = 0; int try_session_cache = 1; #ifndef OPENSSL_NO_TLSEXT int r; #endif if (session_id + len > limit) { fatal = 1; goto err; } if (len == 0) try_session_cache = 0; #ifndef OPENSSL_NO_TLSEXT /* sets s->tlsext_ticket_expected */ r = tls1_process_ticket(s, session_id, len, limit, &ret); switch (r) { case -1: /* Error during processing */ fatal = 1; goto err; case 0: /* No ticket found */ case 1: /* Zero length ticket found */ break; /* Ok to carry on processing session id. */ case 2: /* Ticket found but not decrypted. */ case 3: /* Ticket decrypted, *ret has been set. */ try_session_cache = 0; break; default: abort(); } #endif if (try_session_cache && ret == NULL && !(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) { SSL_SESSION data; data.ssl_version = s->version; data.session_id_length = len; if (len == 0) return 0; memcpy(data.session_id, session_id, len); CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data); if (ret != NULL) { /* don't allow other threads to steal it: */ CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); } CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); if (ret == NULL) s->session_ctx->stats.sess_miss++; } if (try_session_cache && ret == NULL && s->session_ctx->get_session_cb != NULL) { int copy = 1; if ((ret = s->session_ctx->get_session_cb(s, session_id, len, &copy))) { s->session_ctx->stats.sess_cb_hit++; /* * Increment reference count now if the session callback asks us * to do so (note that if the session structures returned by the * callback are shared between threads, it must handle the * reference count itself [i.e. copy == 0], or things won't be * thread-safe). */ if (copy) CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); /* * Add the externally cached session to the internal cache as * well if and only if we are supposed to. */ if (! (s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE)) /* * The following should not return 1, otherwise, things are * very strange */ SSL_CTX_add_session(s->session_ctx, ret); } } if (ret == NULL) goto err; /* Now ret is non-NULL and we own one of its reference counts. */ if (ret->sid_ctx_length != s->sid_ctx_length || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) { /* * We have the session requested by the client, but we don't want to * use it in this context. */ goto err; /* treat like cache miss */ } if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) { /* * We can't be sure if this session is being used out of context, * which is especially important for SSL_VERIFY_PEER. The application * should have used SSL[_CTX]_set_session_id_context. For this error * case, we generate an error instead of treating the event like a * cache miss (otherwise it would be easy for applications to * effectively disable the session cache by accident without anyone * noticing). */ SSLerr(SSL_F_SSL_GET_PREV_SESSION, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED); fatal = 1; goto err; } if (ret->cipher == NULL) { unsigned char buf[5], *p; unsigned long l; p = buf; l = ret->cipher_id; l2n(l, p); if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR) ret->cipher = ssl_get_cipher_by_char(s, &(buf[2])); else ret->cipher = ssl_get_cipher_by_char(s, &(buf[1])); if (ret->cipher == NULL) goto err; } if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */ s->session_ctx->stats.sess_timeout++; if (try_session_cache) { /* session was from the cache, so remove it */ SSL_CTX_remove_session(s->session_ctx, ret); } goto err; } s->session_ctx->stats.sess_hit++; if (s->session != NULL) SSL_SESSION_free(s->session); s->session = ret; s->verify_result = s->session->verify_result; return 1; err: if (ret != NULL) { SSL_SESSION_free(ret); #ifndef OPENSSL_NO_TLSEXT if (!try_session_cache) { /* * The session was from a ticket, so we should issue a ticket for * the new session */ s->tlsext_ticket_expected = 1; } #endif } if (fatal) return -1; else return 0; } Commit Message: CWE ID: CWE-190
int ssl_get_prev_session(SSL *s, unsigned char *session_id, int len, const unsigned char *limit) { /* This is used only by servers. */ SSL_SESSION *ret = NULL; int fatal = 0; int try_session_cache = 1; #ifndef OPENSSL_NO_TLSEXT int r; #endif if (limit - session_id < len) { fatal = 1; goto err; } if (len == 0) try_session_cache = 0; #ifndef OPENSSL_NO_TLSEXT /* sets s->tlsext_ticket_expected */ r = tls1_process_ticket(s, session_id, len, limit, &ret); switch (r) { case -1: /* Error during processing */ fatal = 1; goto err; case 0: /* No ticket found */ case 1: /* Zero length ticket found */ break; /* Ok to carry on processing session id. */ case 2: /* Ticket found but not decrypted. */ case 3: /* Ticket decrypted, *ret has been set. */ try_session_cache = 0; break; default: abort(); } #endif if (try_session_cache && ret == NULL && !(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) { SSL_SESSION data; data.ssl_version = s->version; data.session_id_length = len; if (len == 0) return 0; memcpy(data.session_id, session_id, len); CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data); if (ret != NULL) { /* don't allow other threads to steal it: */ CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); } CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); if (ret == NULL) s->session_ctx->stats.sess_miss++; } if (try_session_cache && ret == NULL && s->session_ctx->get_session_cb != NULL) { int copy = 1; if ((ret = s->session_ctx->get_session_cb(s, session_id, len, &copy))) { s->session_ctx->stats.sess_cb_hit++; /* * Increment reference count now if the session callback asks us * to do so (note that if the session structures returned by the * callback are shared between threads, it must handle the * reference count itself [i.e. copy == 0], or things won't be * thread-safe). */ if (copy) CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); /* * Add the externally cached session to the internal cache as * well if and only if we are supposed to. */ if (! (s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE)) /* * The following should not return 1, otherwise, things are * very strange */ SSL_CTX_add_session(s->session_ctx, ret); } } if (ret == NULL) goto err; /* Now ret is non-NULL and we own one of its reference counts. */ if (ret->sid_ctx_length != s->sid_ctx_length || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) { /* * We have the session requested by the client, but we don't want to * use it in this context. */ goto err; /* treat like cache miss */ } if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) { /* * We can't be sure if this session is being used out of context, * which is especially important for SSL_VERIFY_PEER. The application * should have used SSL[_CTX]_set_session_id_context. For this error * case, we generate an error instead of treating the event like a * cache miss (otherwise it would be easy for applications to * effectively disable the session cache by accident without anyone * noticing). */ SSLerr(SSL_F_SSL_GET_PREV_SESSION, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED); fatal = 1; goto err; } if (ret->cipher == NULL) { unsigned char buf[5], *p; unsigned long l; p = buf; l = ret->cipher_id; l2n(l, p); if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR) ret->cipher = ssl_get_cipher_by_char(s, &(buf[2])); else ret->cipher = ssl_get_cipher_by_char(s, &(buf[1])); if (ret->cipher == NULL) goto err; } if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */ s->session_ctx->stats.sess_timeout++; if (try_session_cache) { /* session was from the cache, so remove it */ SSL_CTX_remove_session(s->session_ctx, ret); } goto err; } s->session_ctx->stats.sess_hit++; if (s->session != NULL) SSL_SESSION_free(s->session); s->session = ret; s->verify_result = s->session->verify_result; return 1; err: if (ret != NULL) { SSL_SESSION_free(ret); #ifndef OPENSSL_NO_TLSEXT if (!try_session_cache) { /* * The session was from a ticket, so we should issue a ticket for * the new session */ s->tlsext_ticket_expected = 1; } #endif } if (fatal) return -1; else return 0; }
165,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _handle_carbons(xmpp_stanza_t *const stanza) { xmpp_stanza_t *carbons = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CARBONS); if (!carbons) { return FALSE; } const char *name = xmpp_stanza_get_name(carbons); if (!name) { log_error("Unable to retrieve stanza name for Carbon"); return TRUE; } if (g_strcmp0(name, "private") == 0) { log_info("Carbon received with private element."); return FALSE; } if ((g_strcmp0(name, "received") != 0) && (g_strcmp0(name, "sent") != 0)) { log_warning("Carbon received with unrecognised stanza name: %s", name); return TRUE; } xmpp_stanza_t *forwarded = xmpp_stanza_get_child_by_ns(carbons, STANZA_NS_FORWARD); if (!forwarded) { log_warning("Carbon received with no forwarded element"); return TRUE; } xmpp_stanza_t *message = xmpp_stanza_get_child_by_name(forwarded, STANZA_NAME_MESSAGE); if (!message) { log_warning("Carbon received with no message element"); return TRUE; } char *message_txt = xmpp_message_get_body(message); if (!message_txt) { log_warning("Carbon received with no message."); return TRUE; } const gchar *to = xmpp_stanza_get_to(message); const gchar *from = xmpp_stanza_get_from(message); if (!to) to = from; Jid *jid_from = jid_create(from); Jid *jid_to = jid_create(to); Jid *my_jid = jid_create(connection_get_fulljid()); char *enc_message = NULL; xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(message, STANZA_NS_ENCRYPTED); if (x) { enc_message = xmpp_stanza_get_text(x); } if (g_strcmp0(my_jid->barejid, jid_to->barejid) == 0) { sv_ev_incoming_carbon(jid_from->barejid, jid_from->resourcepart, message_txt, enc_message); } else { sv_ev_outgoing_carbon(jid_to->barejid, message_txt, enc_message); } xmpp_ctx_t *ctx = connection_get_ctx(); xmpp_free(ctx, message_txt); xmpp_free(ctx, enc_message); jid_destroy(jid_from); jid_destroy(jid_to); jid_destroy(my_jid); return TRUE; } Commit Message: Add carbons from check CWE ID: CWE-346
_handle_carbons(xmpp_stanza_t *const stanza) { xmpp_stanza_t *carbons = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CARBONS); if (!carbons) { return FALSE; } const char *name = xmpp_stanza_get_name(carbons); if (!name) { log_error("Unable to retrieve stanza name for Carbon"); return TRUE; } if (g_strcmp0(name, "private") == 0) { log_info("Carbon received with private element."); return FALSE; } if ((g_strcmp0(name, "received") != 0) && (g_strcmp0(name, "sent") != 0)) { log_warning("Carbon received with unrecognised stanza name: %s", name); return TRUE; } xmpp_stanza_t *forwarded = xmpp_stanza_get_child_by_ns(carbons, STANZA_NS_FORWARD); if (!forwarded) { log_warning("Carbon received with no forwarded element"); return TRUE; } xmpp_stanza_t *message = xmpp_stanza_get_child_by_name(forwarded, STANZA_NAME_MESSAGE); if (!message) { log_warning("Carbon received with no message element"); return TRUE; } char *message_txt = xmpp_message_get_body(message); if (!message_txt) { log_warning("Carbon received with no message."); return TRUE; } Jid *my_jid = jid_create(connection_get_fulljid()); const char *const stanza_from = xmpp_stanza_get_from(stanza); Jid *msg_jid = jid_create(stanza_from); if (g_strcmp0(my_jid->barejid, msg_jid->barejid) != 0) { log_warning("Invalid carbon received, from: %s", stanza_from); return TRUE; } const gchar *to = xmpp_stanza_get_to(message); const gchar *from = xmpp_stanza_get_from(message); if (!to) to = from; Jid *jid_from = jid_create(from); Jid *jid_to = jid_create(to); char *enc_message = NULL; xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(message, STANZA_NS_ENCRYPTED); if (x) { enc_message = xmpp_stanza_get_text(x); } if (g_strcmp0(my_jid->barejid, jid_to->barejid) == 0) { sv_ev_incoming_carbon(jid_from->barejid, jid_from->resourcepart, message_txt, enc_message); } else { sv_ev_outgoing_carbon(jid_to->barejid, message_txt, enc_message); } xmpp_ctx_t *ctx = connection_get_ctx(); xmpp_free(ctx, message_txt); xmpp_free(ctx, enc_message); jid_destroy(jid_from); jid_destroy(jid_to); jid_destroy(my_jid); return TRUE; }
168,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { if (!parse_args(argc, argv)) { usage(argv[0]); } if (bond && discoverable) { fprintf(stderr, "Can only select either bond or discoverable, not both\n"); usage(argv[0]); } if (sco_listen && sco_connect) { fprintf(stderr, "Can only select either sco_listen or sco_connect, not both\n"); usage(argv[0]); } if (!bond && !discover && !discoverable && !up && !get_name && !set_name && !sco_listen && !sco_connect) { fprintf(stderr, "Must specify one command\n"); usage(argv[0]); } if (signal(SIGINT, sig_handler) == SIG_ERR) { fprintf(stderr, "Will be unable to catch signals\n"); } fprintf(stdout, "Bringing up bluetooth adapter\n"); if (!hal_open(callbacks_get_adapter_struct())) { fprintf(stderr, "Unable to open Bluetooth HAL.\n"); return 1; } if (discover) { CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); fprintf(stdout, "Starting to start discovery\n"); CALL_AND_WAIT(bt_interface->start_discovery(), discovery_state_changed); fprintf(stdout, "Started discovery for %d seconds\n", timeout_in_sec); sleep(timeout_in_sec); fprintf(stdout, "Starting to cancel discovery\n"); CALL_AND_WAIT(bt_interface->cancel_discovery(), discovery_state_changed); fprintf(stdout, "Cancelled discovery after %d seconds\n", timeout_in_sec); } if (discoverable) { CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); bt_property_t *property = property_new_scan_mode(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); int rc = bt_interface->set_adapter_property(property); fprintf(stdout, "Set rc:%d device as discoverable for %d seconds\n", rc, timeout_in_sec); sleep(timeout_in_sec); property_free(property); } if (bond) { if (bdaddr_is_empty(&bt_remote_bdaddr)) { fprintf(stderr, "Must specify a remote device address [ --bdaddr=xx:yy:zz:aa:bb:cc ]\n"); exit(1); } CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); int rc = bt_interface->create_bond(&bt_remote_bdaddr, 0 /* UNKNOWN; Currently not documented :( */); fprintf(stdout, "Started bonding:%d for %d seconds\n", rc, timeout_in_sec); sleep(timeout_in_sec); } if (up) { CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); fprintf(stdout, "Waiting for %d seconds\n", timeout_in_sec); sleep(timeout_in_sec); } if (get_name) { CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); int error; CALL_AND_WAIT(error = bt_interface->get_adapter_property(BT_PROPERTY_BDNAME), adapter_properties); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to get adapter property\n"); exit(1); } bt_property_t *property = adapter_get_property(BT_PROPERTY_BDNAME); const bt_bdname_t *name = property_as_name(property); if (name) printf("Queried bluetooth device name:%s\n", name->name); else printf("No name\n"); } if (set_name) { CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); bt_property_t *property = property_new_name(bd_name); printf("Setting bluetooth device name to:%s\n", bd_name); int error; CALL_AND_WAIT(error = bt_interface->set_adapter_property(property), adapter_properties); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to set adapter property\n"); exit(1); } CALL_AND_WAIT(error = bt_interface->get_adapter_property(BT_PROPERTY_BDNAME), adapter_properties); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to get adapter property\n"); exit(1); } property_free(property); sleep(timeout_in_sec); } if (sco_listen) { CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); bt_property_t *property = property_new_scan_mode(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); CALL_AND_WAIT(bt_interface->set_adapter_property(property), adapter_properties); property_free(property); const btsock_interface_t *sock = bt_interface->get_profile_interface(BT_PROFILE_SOCKETS_ID); int rfcomm_fd = INVALID_FD; int error = sock->listen(BTSOCK_RFCOMM, "meow", (const uint8_t *)&HFP_AG_UUID, 0, &rfcomm_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to listen for incoming RFCOMM socket: %d\n", error); exit(1); } int sock_fd = INVALID_FD; error = sock->listen(BTSOCK_SCO, NULL, NULL, 5, &sock_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to listen for incoming SCO sockets: %d\n", error); exit(1); } fprintf(stdout, "Waiting for incoming SCO connections...\n"); sleep(timeout_in_sec); } if (sco_connect) { if (bdaddr_is_empty(&bt_remote_bdaddr)) { fprintf(stderr, "Must specify a remote device address [ --bdaddr=xx:yy:zz:aa:bb:cc ]\n"); exit(1); } CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); const btsock_interface_t *sock = bt_interface->get_profile_interface(BT_PROFILE_SOCKETS_ID); int rfcomm_fd = INVALID_FD; int error = sock->connect(&bt_remote_bdaddr, BTSOCK_RFCOMM, (const uint8_t *)&HFP_AG_UUID, 0, &rfcomm_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to connect to RFCOMM socket: %d.\n", error); exit(1); } WAIT(acl_state_changed); fprintf(stdout, "Establishing SCO connection...\n"); int sock_fd = INVALID_FD; error = sock->connect(&bt_remote_bdaddr, BTSOCK_SCO, NULL, 5, &sock_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to connect to SCO socket: %d.\n", error); exit(1); } sleep(timeout_in_sec); } CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed); fprintf(stdout, "BT adapter is down\n"); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
int main(int argc, char **argv) { if (!parse_args(argc, argv)) { usage(argv[0]); } if (bond && discoverable) { fprintf(stderr, "Can only select either bond or discoverable, not both\n"); usage(argv[0]); } if (sco_listen && sco_connect) { fprintf(stderr, "Can only select either sco_listen or sco_connect, not both\n"); usage(argv[0]); } if (!bond && !discover && !discoverable && !up && !get_name && !set_name && !sco_listen && !sco_connect) { fprintf(stderr, "Must specify one command\n"); usage(argv[0]); } if (signal(SIGINT, sig_handler) == SIG_ERR) { fprintf(stderr, "Will be unable to catch signals\n"); } fprintf(stdout, "Bringing up bluetooth adapter\n"); if (!hal_open(callbacks_get_adapter_struct())) { fprintf(stderr, "Unable to open Bluetooth HAL.\n"); return 1; } if (discover) { CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); fprintf(stdout, "Starting to start discovery\n"); CALL_AND_WAIT(bt_interface->start_discovery(), discovery_state_changed); fprintf(stdout, "Started discovery for %d seconds\n", timeout_in_sec); sleep(timeout_in_sec); fprintf(stdout, "Starting to cancel discovery\n"); CALL_AND_WAIT(bt_interface->cancel_discovery(), discovery_state_changed); fprintf(stdout, "Cancelled discovery after %d seconds\n", timeout_in_sec); } if (discoverable) { CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); bt_property_t *property = property_new_scan_mode(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); int rc = bt_interface->set_adapter_property(property); fprintf(stdout, "Set rc:%d device as discoverable for %d seconds\n", rc, timeout_in_sec); sleep(timeout_in_sec); property_free(property); } if (bond) { if (bdaddr_is_empty(&bt_remote_bdaddr)) { fprintf(stderr, "Must specify a remote device address [ --bdaddr=xx:yy:zz:aa:bb:cc ]\n"); exit(1); } CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); int rc = bt_interface->create_bond(&bt_remote_bdaddr, 0 /* UNKNOWN; Currently not documented :( */); fprintf(stdout, "Started bonding:%d for %d seconds\n", rc, timeout_in_sec); sleep(timeout_in_sec); } if (up) { CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); fprintf(stdout, "Waiting for %d seconds\n", timeout_in_sec); sleep(timeout_in_sec); } if (get_name) { CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); int error; CALL_AND_WAIT(error = bt_interface->get_adapter_property(BT_PROPERTY_BDNAME), adapter_properties); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to get adapter property\n"); exit(1); } bt_property_t *property = adapter_get_property(BT_PROPERTY_BDNAME); const bt_bdname_t *name = property_as_name(property); if (name) printf("Queried bluetooth device name:%s\n", name->name); else printf("No name\n"); } if (set_name) { CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); bt_property_t *property = property_new_name(bd_name); printf("Setting bluetooth device name to:%s\n", bd_name); int error; CALL_AND_WAIT(error = bt_interface->set_adapter_property(property), adapter_properties); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to set adapter property\n"); exit(1); } CALL_AND_WAIT(error = bt_interface->get_adapter_property(BT_PROPERTY_BDNAME), adapter_properties); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to get adapter property\n"); exit(1); } property_free(property); sleep(timeout_in_sec); } if (sco_listen) { CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); bt_property_t *property = property_new_scan_mode(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); CALL_AND_WAIT(bt_interface->set_adapter_property(property), adapter_properties); property_free(property); const btsock_interface_t *sock = bt_interface->get_profile_interface(BT_PROFILE_SOCKETS_ID); int rfcomm_fd = INVALID_FD; int error = sock->listen(BTSOCK_RFCOMM, "meow", (const uint8_t *)&HFP_AG_UUID, 0, &rfcomm_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to listen for incoming RFCOMM socket: %d\n", error); exit(1); } int sock_fd = INVALID_FD; error = sock->listen(BTSOCK_SCO, NULL, NULL, 5, &sock_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to listen for incoming SCO sockets: %d\n", error); exit(1); } fprintf(stdout, "Waiting for incoming SCO connections...\n"); sleep(timeout_in_sec); } if (sco_connect) { if (bdaddr_is_empty(&bt_remote_bdaddr)) { fprintf(stderr, "Must specify a remote device address [ --bdaddr=xx:yy:zz:aa:bb:cc ]\n"); exit(1); } CALL_AND_WAIT(bt_interface->enable(false), adapter_state_changed); fprintf(stdout, "BT adapter is up\n"); const btsock_interface_t *sock = bt_interface->get_profile_interface(BT_PROFILE_SOCKETS_ID); int rfcomm_fd = INVALID_FD; int error = sock->connect(&bt_remote_bdaddr, BTSOCK_RFCOMM, (const uint8_t *)&HFP_AG_UUID, 0, &rfcomm_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to connect to RFCOMM socket: %d.\n", error); exit(1); } WAIT(acl_state_changed); fprintf(stdout, "Establishing SCO connection...\n"); int sock_fd = INVALID_FD; error = sock->connect(&bt_remote_bdaddr, BTSOCK_SCO, NULL, 5, &sock_fd, 0); if (error != BT_STATUS_SUCCESS) { fprintf(stderr, "Unable to connect to SCO socket: %d.\n", error); exit(1); } sleep(timeout_in_sec); } CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed); fprintf(stdout, "BT adapter is down\n"); }
173,558
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_set_sec_context_option( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value) { OM_uint32 ret; ret = gss_set_sec_context_option(minor_status, context_handle, desired_object, value); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_set_sec_context_option( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)*context_handle; /* There are no SPNEGO-specific OIDs for this function, and we cannot * construct an empty SPNEGO context with it. */ if (sc == NULL || sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_UNAVAILABLE); ret = gss_set_sec_context_option(minor_status, &sc->ctx_handle, desired_object, value); return (ret); }
166,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_ce_exception, 0, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; size_t fname_len, alias_len = 0; int arch_len, entry_len, is_data; zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; zend_long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data); if (is_data) { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } ZVAL_STRINGL(&arg1, fname, fname_len); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); zval_ptr_dtor(&arg1); if (!phar_data->is_persistent) { phar_obj->archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_ce_exception, 0, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; size_t fname_len, alias_len = 0; int arch_len, entry_len, is_data; zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; zend_long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data); if (is_data) { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } ZVAL_STRINGL(&arg1, fname, fname_len); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); zval_ptr_dtor(&arg1); if (!phar_data->is_persistent) { phar_obj->archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ }
165,060
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 * CAPSTONE_API cs_winkernel_malloc(size_t size) { NT_ASSERT(size); #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; } Commit Message: provide a validity check to prevent against Integer overflow conditions (#870) * provide a validity check to prevent against Integer overflow conditions * fix some style issues. CWE ID: CWE-190
void * CAPSTONE_API cs_winkernel_malloc(size_t size) { NT_ASSERT(size); #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory size_t number_of_bytes = 0; CS_WINKERNEL_MEMBLOCK *block = NULL; // A specially crafted size value can trigger the overflow. // If the sum in a value that overflows or underflows the capacity of the type, // the function returns NULL. if (!NT_SUCCESS(RtlSizeTAdd(size, sizeof(CS_WINKERNEL_MEMBLOCK), &number_of_bytes))) { return NULL; } block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, number_of_bytes, CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; }
168,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ion_free(struct ion_client *client, struct ion_handle *handle) { bool valid_handle; BUG_ON(client != handle->client); mutex_lock(&client->lock); valid_handle = ion_handle_validate(client, handle); if (!valid_handle) { WARN(1, "%s: invalid handle passed to free.\n", __func__); mutex_unlock(&client->lock); return; } mutex_unlock(&client->lock); ion_handle_put(handle); } Commit Message: staging/android/ion : fix a race condition in the ion driver There is a use-after-free problem in the ion driver. This is caused by a race condition in the ion_ioctl() function. A handle has ref count of 1 and two tasks on different cpus calls ION_IOC_FREE simultaneously. cpu 0 cpu 1 ------------------------------------------------------- ion_handle_get_by_id() (ref == 2) ion_handle_get_by_id() (ref == 3) ion_free() (ref == 2) ion_handle_put() (ref == 1) ion_free() (ref == 0 so ion_handle_destroy() is called and the handle is freed.) ion_handle_put() is called and it decreases the slub's next free pointer The problem is detected as an unaligned access in the spin lock functions since it uses load exclusive instruction. In some cases it corrupts the slub's free pointer which causes a mis-aligned access to the next free pointer.(kmalloc returns a pointer like ffffc0745b4580aa). And it causes lots of other hard-to-debug problems. This symptom is caused since the first member in the ion_handle structure is the reference count and the ion driver decrements the reference after it has been freed. To fix this problem client->lock mutex is extended to protect all the codes that uses the handle. Signed-off-by: Eun Taik Lee <[email protected]> Reviewed-by: Laura Abbott <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-416
void ion_free(struct ion_client *client, struct ion_handle *handle) static void ion_free_nolock(struct ion_client *client, struct ion_handle *handle) { bool valid_handle; BUG_ON(client != handle->client); valid_handle = ion_handle_validate(client, handle); if (!valid_handle) { WARN(1, "%s: invalid handle passed to free.\n", __func__); return; } ion_handle_put_nolock(handle); } void ion_free(struct ion_client *client, struct ion_handle *handle) { BUG_ON(client != handle->client); mutex_lock(&client->lock); ion_free_nolock(client, handle); mutex_unlock(&client->lock); }
166,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Con_Dump_f (void) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if (Cmd_Argc() != 2) { Com_Printf ("usage: condump <filename>\n"); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); f = FS_FOpenFileWrite( filename ); if (!f) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); for (l = con.current - con.totallines + 1 ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for (x=0 ; x<con.linewidth ; x++) if ((line[x] & 0xff) != ' ') break; if (x != con.linewidth) break; } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for(i=0; i<con.linewidth; i++) buffer[i] = line[i] & 0xff; for (x=con.linewidth-1 ; x>=0 ; x--) { if (buffer[x] == ' ') buffer[x] = 0; else break; } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write(buffer, strlen(buffer), f); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); } Commit Message: Merge some file writing extension checks from OpenJK. Thanks Ensiform. https://github.com/JACoders/OpenJK/commit/05928a57f9e4aae15a3bd0 https://github.com/JACoders/OpenJK/commit/ef124fd0fc48af164581176 CWE ID: CWE-269
void Con_Dump_f (void) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if (Cmd_Argc() != 2) { Com_Printf ("usage: condump <filename>\n"); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); if (!COM_CompareExtension(filename, ".txt")) { Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n"); return; } f = FS_FOpenFileWrite( filename ); if (!f) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); for (l = con.current - con.totallines + 1 ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for (x=0 ; x<con.linewidth ; x++) if ((line[x] & 0xff) != ' ') break; if (x != con.linewidth) break; } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for(i=0; i<con.linewidth; i++) buffer[i] = line[i] & 0xff; for (x=con.linewidth-1 ; x>=0 ; x--) { if (buffer[x] == ' ') buffer[x] = 0; else break; } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write(buffer, strlen(buffer), f); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); }
170,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); struct ipcm_cookie ipc; struct rtable *rt = NULL; struct flowi4 fl4; int free = 0; __be32 daddr; __be32 saddr; u8 tos; int err; struct ip_options_data opt_copy; struct raw_frag_vec rfv; err = -EMSGSIZE; if (len > 0xFFFF) goto out; /* * Check the flags. */ err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */ goto out; /* compatibility */ /* * Get and verify the address. */ if (msg->msg_namelen) { DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name); err = -EINVAL; if (msg->msg_namelen < sizeof(*usin)) goto out; if (usin->sin_family != AF_INET) { pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n", __func__, current->comm); err = -EAFNOSUPPORT; if (usin->sin_family) goto out; } daddr = usin->sin_addr.s_addr; /* ANK: I did not forget to get protocol from port field. * I just do not know, who uses this weirdness. * IP_HDRINCL is much more convenient. */ } else { err = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; } ipc.sockc.tsflags = sk->sk_tsflags; ipc.addr = inet->inet_saddr; ipc.opt = NULL; ipc.tx_flags = 0; ipc.ttl = 0; ipc.tos = -1; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(sk, msg, &ipc, false); if (unlikely(err)) { kfree(ipc.opt); goto out; } if (ipc.opt) free = 1; } saddr = ipc.addr; ipc.addr = daddr; if (!ipc.opt) { struct ip_options_rcu *inet_opt; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt) { memcpy(&opt_copy, inet_opt, sizeof(*inet_opt) + inet_opt->opt.optlen); ipc.opt = &opt_copy.opt; } rcu_read_unlock(); } if (ipc.opt) { err = -EINVAL; /* Linux does not mangle headers on raw sockets, * so that IP options + IP_HDRINCL is non-sense. */ if (inet->hdrincl) goto done; if (ipc.opt->opt.srr) { if (!daddr) goto done; daddr = ipc.opt->opt.faddr; } } tos = get_rtconn_flags(&ipc, sk); if (msg->msg_flags & MSG_DONTROUTE) tos |= RTO_ONLINK; if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; } else if (!ipc.oif) ipc.oif = inet->uc_index; flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk) | (inet->hdrincl ? FLOWI_FLAG_KNOWN_NH : 0), daddr, saddr, 0, 0, sk->sk_uid); if (!inet->hdrincl) { rfv.msg = msg; rfv.hlen = 0; err = raw_probe_proto_opt(&rfv, &fl4); if (err) goto done; } security_sk_classify_flow(sk, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto done; } err = -EACCES; if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST)) goto done; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: if (inet->hdrincl) err = raw_send_hdrinc(sk, &fl4, msg, len, &rt, msg->msg_flags, &ipc.sockc); else { sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags); if (!ipc.addr) ipc.addr = fl4.daddr; lock_sock(sk); err = ip_append_data(sk, &fl4, raw_getfrag, &rfv, len, 0, &ipc, &rt, msg->msg_flags); if (err) ip_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) { err = ip_push_pending_frames(sk, &fl4); if (err == -ENOBUFS && !inet->recverr) err = 0; } release_sock(sk); } done: if (free) kfree(ipc.opt); ip_rt_put(rt); out: if (err < 0) return err; return len; do_confirm: if (msg->msg_flags & MSG_PROBE) dst_confirm_neigh(&rt->dst, &fl4.daddr); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } Commit Message: net: ipv4: fix for a race condition in raw_sendmsg inet->hdrincl is racy, and could lead to uninitialized stack pointer usage, so its value should be read only once. Fixes: c008ba5bdc9f ("ipv4: Avoid reading user iov twice after raw_probe_proto_opt") Signed-off-by: Mohamed Ghannam <[email protected]> Reviewed-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); struct ipcm_cookie ipc; struct rtable *rt = NULL; struct flowi4 fl4; int free = 0; __be32 daddr; __be32 saddr; u8 tos; int err; struct ip_options_data opt_copy; struct raw_frag_vec rfv; int hdrincl; err = -EMSGSIZE; if (len > 0xFFFF) goto out; /* hdrincl should be READ_ONCE(inet->hdrincl) * but READ_ONCE() doesn't work with bit fields */ hdrincl = inet->hdrincl; /* * Check the flags. */ err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */ goto out; /* compatibility */ /* * Get and verify the address. */ if (msg->msg_namelen) { DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name); err = -EINVAL; if (msg->msg_namelen < sizeof(*usin)) goto out; if (usin->sin_family != AF_INET) { pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n", __func__, current->comm); err = -EAFNOSUPPORT; if (usin->sin_family) goto out; } daddr = usin->sin_addr.s_addr; /* ANK: I did not forget to get protocol from port field. * I just do not know, who uses this weirdness. * IP_HDRINCL is much more convenient. */ } else { err = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; } ipc.sockc.tsflags = sk->sk_tsflags; ipc.addr = inet->inet_saddr; ipc.opt = NULL; ipc.tx_flags = 0; ipc.ttl = 0; ipc.tos = -1; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(sk, msg, &ipc, false); if (unlikely(err)) { kfree(ipc.opt); goto out; } if (ipc.opt) free = 1; } saddr = ipc.addr; ipc.addr = daddr; if (!ipc.opt) { struct ip_options_rcu *inet_opt; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt) { memcpy(&opt_copy, inet_opt, sizeof(*inet_opt) + inet_opt->opt.optlen); ipc.opt = &opt_copy.opt; } rcu_read_unlock(); } if (ipc.opt) { err = -EINVAL; /* Linux does not mangle headers on raw sockets, * so that IP options + IP_HDRINCL is non-sense. */ if (hdrincl) goto done; if (ipc.opt->opt.srr) { if (!daddr) goto done; daddr = ipc.opt->opt.faddr; } } tos = get_rtconn_flags(&ipc, sk); if (msg->msg_flags & MSG_DONTROUTE) tos |= RTO_ONLINK; if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; } else if (!ipc.oif) ipc.oif = inet->uc_index; flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk) | (hdrincl ? FLOWI_FLAG_KNOWN_NH : 0), daddr, saddr, 0, 0, sk->sk_uid); if (!hdrincl) { rfv.msg = msg; rfv.hlen = 0; err = raw_probe_proto_opt(&rfv, &fl4); if (err) goto done; } security_sk_classify_flow(sk, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto done; } err = -EACCES; if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST)) goto done; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: if (hdrincl) err = raw_send_hdrinc(sk, &fl4, msg, len, &rt, msg->msg_flags, &ipc.sockc); else { sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags); if (!ipc.addr) ipc.addr = fl4.daddr; lock_sock(sk); err = ip_append_data(sk, &fl4, raw_getfrag, &rfv, len, 0, &ipc, &rt, msg->msg_flags); if (err) ip_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) { err = ip_push_pending_frames(sk, &fl4); if (err == -ENOBUFS && !inet->recverr) err = 0; } release_sock(sk); } done: if (free) kfree(ipc.opt); ip_rt_put(rt); out: if (err < 0) return err; return len; do_confirm: if (msg->msg_flags & MSG_PROBE) dst_confirm_neigh(&rt->dst, &fl4.daddr); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; }
167,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void set_banner(struct openconnect_info *vpninfo) { char *banner, *q; const char *p; if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) { unsetenv("CISCO_BANNER"); return; } p = vpninfo->banner; q = banner; while (*p) { if (*p == '%' && isxdigit((int)(unsigned char)p[1]) && isxdigit((int)(unsigned char)p[2])) { *(q++) = unhex(p + 1); p += 3; } else *(q++) = *(p++); } *q = 0; setenv("CISCO_BANNER", banner, 1); free(banner); } Commit Message: CWE ID: CWE-119
static void set_banner(struct openconnect_info *vpninfo) { char *banner, *q; const char *p; if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)+1))) { unsetenv("CISCO_BANNER"); return; } p = vpninfo->banner; q = banner; while (*p) { if (*p == '%' && isxdigit((int)(unsigned char)p[1]) && isxdigit((int)(unsigned char)p[2])) { *(q++) = unhex(p + 1); p += 3; } else *(q++) = *(p++); } *q = 0; setenv("CISCO_BANNER", banner, 1); free(banner); }
164,960
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs4_opendata *opendata; opendata = nfs4_opendata_alloc(&ctx->path, state->owner, 0, NULL); if (opendata == NULL) return ERR_PTR(-ENOMEM); opendata->state = state; atomic_inc(&state->count); return opendata; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs4_opendata *opendata; opendata = nfs4_opendata_alloc(&ctx->path, state->owner, 0, 0, NULL); if (opendata == NULL) return ERR_PTR(-ENOMEM); opendata->state = state; atomic_inc(&state->count); return opendata; }
165,697
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SocketStreamDispatcherHost::OnSSLCertificateError( net::SocketStream* socket, const net::SSLInfo& ssl_info, bool fatal) { int socket_id = SocketStreamHost::SocketIdFromSocketStream(socket); DVLOG(1) << "SocketStreamDispatcherHost::OnSSLCertificateError socket_id=" << socket_id; if (socket_id == content::kNoSocketId) { LOG(ERROR) << "NoSocketId in OnSSLCertificateError"; return; } SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id); DCHECK(socket_stream_host); content::GlobalRequestID request_id(-1, socket_id); SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(), request_id, ResourceType::SUB_RESOURCE, socket->url(), render_process_id_, socket_stream_host->render_view_id(), ssl_info, fatal); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void SocketStreamDispatcherHost::OnSSLCertificateError( net::SocketStream* socket, const net::SSLInfo& ssl_info, bool fatal) { int socket_id = SocketStreamHost::SocketIdFromSocketStream(socket); DVLOG(1) << "SocketStreamDispatcherHost::OnSSLCertificateError socket_id=" << socket_id; if (socket_id == content::kNoSocketId) { LOG(ERROR) << "NoSocketId in OnSSLCertificateError"; return; } SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id); DCHECK(socket_stream_host); content::GlobalRequestID request_id(-1, socket_id); SSLManager::OnSSLCertificateError( AsWeakPtr(), request_id, ResourceType::SUB_RESOURCE, socket->url(), render_process_id_, socket_stream_host->render_view_id(), ssl_info, fatal); }
170,992
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sched_read_attr(struct sched_attr __user *uattr, struct sched_attr *attr, unsigned int usize) { int ret; if (!access_ok(VERIFY_WRITE, uattr, usize)) return -EFAULT; /* * If we're handed a smaller struct than we know of, * ensure all the unknown bits are 0 - i.e. old * user-space does not get uncomplete information. */ if (usize < sizeof(*attr)) { unsigned char *addr; unsigned char *end; addr = (void *)attr + usize; end = (void *)attr + sizeof(*attr); for (; addr < end; addr++) { if (*addr) goto err_size; } attr->size = usize; } ret = copy_to_user(uattr, attr, usize); if (ret) return -EFAULT; out: return ret; err_size: ret = -E2BIG; goto out; } Commit Message: sched: Fix information leak in sys_sched_getattr() We're copying the on-stack structure to userspace, but forgot to give the right number of bytes to copy. This allows the calling process to obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent kernel memory). This fix copies only as much as we actually have on the stack (attr->size defaults to the size of the struct) and leaves the rest of the userspace-provided buffer untouched. Found using kmemcheck + trinity. Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI") Cc: Dario Faggioli <[email protected]> Cc: Juri Lelli <[email protected]> Cc: Ingo Molnar <[email protected]> Signed-off-by: Vegard Nossum <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Thomas Gleixner <[email protected]> CWE ID: CWE-200
static int sched_read_attr(struct sched_attr __user *uattr, struct sched_attr *attr, unsigned int usize) { int ret; if (!access_ok(VERIFY_WRITE, uattr, usize)) return -EFAULT; /* * If we're handed a smaller struct than we know of, * ensure all the unknown bits are 0 - i.e. old * user-space does not get uncomplete information. */ if (usize < sizeof(*attr)) { unsigned char *addr; unsigned char *end; addr = (void *)attr + usize; end = (void *)attr + sizeof(*attr); for (; addr < end; addr++) { if (*addr) goto err_size; } attr->size = usize; } ret = copy_to_user(uattr, attr, attr->size); if (ret) return -EFAULT; out: return ret; err_size: ret = -E2BIG; goto out; }
167,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: string DecodeFile(const string& filename, int num_threads) { libvpx_test::WebMVideoSource video(filename); video.Init(); vpx_codec_dec_cfg_t cfg = {0}; cfg.threads = num_threads; libvpx_test::VP9Decoder decoder(cfg, 0); libvpx_test::MD5 md5; for (video.Begin(); video.cxdata(); video.Next()) { const vpx_codec_err_t res = decoder.DecodeFrame(video.cxdata(), video.frame_size()); if (res != VPX_CODEC_OK) { EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError(); break; } libvpx_test::DxDataIterator dec_iter = decoder.GetDxData(); const vpx_image_t *img = NULL; while ((img = dec_iter.Next())) { md5.Add(img); } } return string(md5.Get()); } 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
string DecodeFile(const string& filename, int num_threads) { libvpx_test::WebMVideoSource video(filename); video.Init(); vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t(); cfg.threads = num_threads; libvpx_test::VP9Decoder decoder(cfg, 0); libvpx_test::MD5 md5; for (video.Begin(); video.cxdata(); video.Next()) { const vpx_codec_err_t res = decoder.DecodeFrame(video.cxdata(), video.frame_size()); if (res != VPX_CODEC_OK) { EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError(); break; } libvpx_test::DxDataIterator dec_iter = decoder.GetDxData(); const vpx_image_t *img = NULL; while ((img = dec_iter.Next())) { md5.Add(img); } } return string(md5.Get()); }
174,598
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } else { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_FALSE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } Commit Message: CWE ID: CWE-502
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; ent.type = ST_BOOLEAN; SET_STACK_VARNAME; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } else { ZVAL_FALSE(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); }
164,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *sock_poll_thread(void *arg) { struct pollfd pfds[MAX_POLL]; memset(pfds, 0, sizeof(pfds)); int h = (intptr_t)arg; for(;;) { prepare_poll_fds(h, pfds); int ret = poll(pfds, ts[h].poll_count, -1); if(ret == -1) { APPL_TRACE_ERROR("poll ret -1, exit the thread, errno:%d, err:%s", errno, strerror(errno)); break; } if(ret != 0) { int need_process_data_fd = TRUE; if(pfds[0].revents) //cmd fd always is the first one { asrt(pfds[0].fd == ts[h].cmd_fdr); if(!process_cmd_sock(h)) { APPL_TRACE_DEBUG("h:%d, process_cmd_sock return false, exit...", h); break; } if(ret == 1) need_process_data_fd = FALSE; else ret--; //exclude the cmd fd } if(need_process_data_fd) process_data_sock(h, pfds, ret); } else {APPL_TRACE_DEBUG("no data, select ret: %d", ret)}; } ts[h].thread_id = -1; APPL_TRACE_DEBUG("socket poll thread exiting, h:%d", h); return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void *sock_poll_thread(void *arg) { struct pollfd pfds[MAX_POLL]; memset(pfds, 0, sizeof(pfds)); int h = (intptr_t)arg; for(;;) { prepare_poll_fds(h, pfds); int ret = TEMP_FAILURE_RETRY(poll(pfds, ts[h].poll_count, -1)); if(ret == -1) { APPL_TRACE_ERROR("poll ret -1, exit the thread, errno:%d, err:%s", errno, strerror(errno)); break; } if(ret != 0) { int need_process_data_fd = TRUE; if(pfds[0].revents) //cmd fd always is the first one { asrt(pfds[0].fd == ts[h].cmd_fdr); if(!process_cmd_sock(h)) { APPL_TRACE_DEBUG("h:%d, process_cmd_sock return false, exit...", h); break; } if(ret == 1) need_process_data_fd = FALSE; else ret--; //exclude the cmd fd } if(need_process_data_fd) process_data_sock(h, pfds, ret); } else {APPL_TRACE_DEBUG("no data, select ret: %d", ret)}; } ts[h].thread_id = -1; APPL_TRACE_DEBUG("socket poll thread exiting, h:%d", h); return 0; }
173,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile( JNIEnv* env, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jstring>& java_start_url, const JavaParamRef<jstring>& java_scope, const JavaParamRef<jstring>& java_name, const JavaParamRef<jstring>& java_short_name, const JavaParamRef<jstring>& java_primary_icon_url, const JavaParamRef<jobject>& java_primary_icon_bitmap, const JavaParamRef<jstring>& java_badge_icon_url, const JavaParamRef<jobject>& java_badge_icon_bitmap, const JavaParamRef<jobjectArray>& java_icon_urls, const JavaParamRef<jobjectArray>& java_icon_hashes, jint java_display_mode, jint java_orientation, jlong java_theme_color, jlong java_background_color, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, jboolean java_is_manifest_stale, jint java_update_reason, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url))); info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope)); info.name = ConvertJavaStringToUTF16(env, java_name); info.short_name = ConvertJavaStringToUTF16(env, java_short_name); info.user_title = info.short_name; info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); info.theme_color = (int64_t)java_theme_color; info.background_color = (int64_t)java_background_color; info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url = GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url)); info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url)); base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls, &info.icon_urls); std::vector<std::string> icon_hashes; base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes, &icon_hashes); std::map<std::string, std::string> icon_url_to_murmur2_hash; for (size_t i = 0; i < info.icon_urls.size(); ++i) icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i]; gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap); SkBitmap primary_icon = gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock); primary_icon.setImmutable(); SkBitmap badge_icon; if (!java_badge_icon_bitmap.is_null()) { gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap); gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock); badge_icon.setImmutable(); } std::string webapk_package; ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); WebApkUpdateReason update_reason = static_cast<WebApkUpdateReason>(java_update_reason); WebApkInstaller::StoreUpdateRequestToFile( base::FilePath(update_request_path), info, primary_icon, badge_icon, webapk_package, std::to_string(java_webapk_version), icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason, base::BindOnce(&base::android::RunBooleanCallbackAndroid, ScopedJavaGlobalRef<jobject>(java_callback))); } Commit Message: [Android WebAPK] Send share target information in WebAPK updates This CL plumbs through share target information for WebAPK updates. Chromium detects Web Manifest updates (including Web Manifest share target updates) and requests an update. Currently, depending on whether the Web Manifest is for an intranet site, the updated WebAPK would either: - no longer be able handle share intents (even if the Web Manifest share target information was not deleted) - be created with the same share intent handlers as the current WebAPK (regardless of whether the Web Manifest share target information has changed). This CL plumbs through the share target information from WebApkUpdateDataFetcher#onDataAvailable() to WebApkUpdateManager::StoreWebApkUpdateRequestToFile() BUG=912945 Change-Id: Ie416570533abc848eeb23de8c197b44f2a1fd028 Reviewed-on: https://chromium-review.googlesource.com/c/1369709 Commit-Queue: Peter Kotwicz <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Cr-Commit-Position: refs/heads/master@{#616429} CWE ID: CWE-200
static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile( JNIEnv* env, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jstring>& java_start_url, const JavaParamRef<jstring>& java_scope, const JavaParamRef<jstring>& java_name, const JavaParamRef<jstring>& java_short_name, const JavaParamRef<jstring>& java_primary_icon_url, const JavaParamRef<jobject>& java_primary_icon_bitmap, const JavaParamRef<jstring>& java_badge_icon_url, const JavaParamRef<jobject>& java_badge_icon_bitmap, const JavaParamRef<jobjectArray>& java_icon_urls, const JavaParamRef<jobjectArray>& java_icon_hashes, jint java_display_mode, jint java_orientation, jlong java_theme_color, jlong java_background_color, const JavaParamRef<jstring>& java_share_target_action, const JavaParamRef<jstring>& java_share_target_param_title, const JavaParamRef<jstring>& java_share_target_param_text, const JavaParamRef<jstring>& java_share_target_param_url, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, jboolean java_is_manifest_stale, jint java_update_reason, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url))); info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope)); info.name = ConvertJavaStringToUTF16(env, java_name); info.short_name = ConvertJavaStringToUTF16(env, java_short_name); info.user_title = info.short_name; info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); info.theme_color = (int64_t)java_theme_color; info.background_color = (int64_t)java_background_color; info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url = GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url)); info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url)); GURL share_target_action = GURL(ConvertJavaStringToUTF8(env, java_share_target_action)); if (!share_target_action.is_empty()) { info.share_target = ShareTarget(); info.share_target->action = share_target_action; info.share_target->params.title = ConvertJavaStringToUTF16(java_share_target_param_title); info.share_target->params.text = ConvertJavaStringToUTF16(java_share_target_param_text); info.share_target->params.url = ConvertJavaStringToUTF16(java_share_target_param_url); } base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls, &info.icon_urls); std::vector<std::string> icon_hashes; base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes, &icon_hashes); std::map<std::string, std::string> icon_url_to_murmur2_hash; for (size_t i = 0; i < info.icon_urls.size(); ++i) icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i]; gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap); SkBitmap primary_icon = gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock); primary_icon.setImmutable(); SkBitmap badge_icon; if (!java_badge_icon_bitmap.is_null()) { gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap); gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock); badge_icon.setImmutable(); } std::string webapk_package; ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); WebApkUpdateReason update_reason = static_cast<WebApkUpdateReason>(java_update_reason); WebApkInstaller::StoreUpdateRequestToFile( base::FilePath(update_request_path), info, primary_icon, badge_icon, webapk_package, std::to_string(java_webapk_version), icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason, base::BindOnce(&base::android::RunBooleanCallbackAndroid, ScopedJavaGlobalRef<jobject>(java_callback))); }
172,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SyncManager::ReceivedExperiment(browser_sync::Experiments* experiments) const { ReadTransaction trans(FROM_HERE, GetUserShare()); ReadNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { DVLOG(1) << "Couldn't find Nigori node."; return false; } bool found_experiment = false; if (node.GetNigoriSpecifics().sync_tabs()) { experiments->sync_tabs = true; found_experiment = true; } if (node.GetNigoriSpecifics().sync_tab_favicons()) { experiments->sync_tab_favicons = true; found_experiment = true; } return found_experiment; } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
bool SyncManager::ReceivedExperiment(browser_sync::Experiments* experiments) const { ReadTransaction trans(FROM_HERE, GetUserShare()); ReadNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { DVLOG(1) << "Couldn't find Nigori node."; return false; } bool found_experiment = false; if (node.GetNigoriSpecifics().sync_tab_favicons()) { experiments->sync_tab_favicons = true; found_experiment = true; } return found_experiment; }
170,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cine_read_header(AVFormatContext *avctx) { AVIOContext *pb = avctx->pb; AVStream *st; unsigned int version, compression, offImageHeader, offSetup, offImageOffsets, biBitCount, length, CFA; int vflip; char *description; uint64_t i; st = avformat_new_stream(avctx, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; st->codecpar->codec_tag = 0; /* CINEFILEHEADER structure */ avio_skip(pb, 4); // Type, Headersize compression = avio_rl16(pb); version = avio_rl16(pb); if (version != 1) { avpriv_request_sample(avctx, "unknown version %i", version); return AVERROR_INVALIDDATA; } avio_skip(pb, 12); // FirstMovieImage, TotalImageCount, FirstImageNumber st->duration = avio_rl32(pb); offImageHeader = avio_rl32(pb); offSetup = avio_rl32(pb); offImageOffsets = avio_rl32(pb); avio_skip(pb, 8); // TriggerTime /* BITMAPINFOHEADER structure */ avio_seek(pb, offImageHeader, SEEK_SET); avio_skip(pb, 4); //biSize st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); if (avio_rl16(pb) != 1) // biPlanes return AVERROR_INVALIDDATA; biBitCount = avio_rl16(pb); if (biBitCount != 8 && biBitCount != 16 && biBitCount != 24 && biBitCount != 48) { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } switch (avio_rl32(pb)) { case BMP_RGB: vflip = 0; break; case 0x100: /* BI_PACKED */ st->codecpar->codec_tag = MKTAG('B', 'I', 'T', 0); vflip = 1; break; default: avpriv_request_sample(avctx, "unknown bitmap compression"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); // biSizeImage /* parse SETUP structure */ avio_seek(pb, offSetup, SEEK_SET); avio_skip(pb, 140); // FrameRatae16 .. descriptionOld if (avio_rl16(pb) != 0x5453) return AVERROR_INVALIDDATA; length = avio_rl16(pb); if (length < 0x163C) { avpriv_request_sample(avctx, "short SETUP header"); return AVERROR_INVALIDDATA; } avio_skip(pb, 616); // Binning .. bFlipH if (!avio_rl32(pb) ^ vflip) { st->codecpar->extradata = av_strdup("BottomUp"); st->codecpar->extradata_size = 9; } avio_skip(pb, 4); // Grid avpriv_set_pts_info(st, 64, 1, avio_rl32(pb)); avio_skip(pb, 20); // Shutter .. bEnableColor set_metadata_int(&st->metadata, "camera_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "firmware_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "software_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "recording_timezone", avio_rl32(pb), 0); CFA = avio_rl32(pb); set_metadata_int(&st->metadata, "brightness", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "contrast", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "gamma", avio_rl32(pb), 1); avio_skip(pb, 12 + 16); // Reserved1 .. AutoExpRect set_metadata_float(&st->metadata, "wbgain[0].r", av_int2float(avio_rl32(pb)), 1); set_metadata_float(&st->metadata, "wbgain[0].b", av_int2float(avio_rl32(pb)), 1); avio_skip(pb, 36); // WBGain[1].. WBView st->codecpar->bits_per_coded_sample = avio_rl32(pb); if (compression == CC_RGB) { if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_GRAY8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_GRAY16LE; } else if (biBitCount == 24) { st->codecpar->format = AV_PIX_FMT_BGR24; } else if (biBitCount == 48) { st->codecpar->format = AV_PIX_FMT_BGR48LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } } else if (compression == CC_UNINT) { switch (CFA & 0xFFFFFF) { case CFA_BAYER: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; case CFA_BAYERFLIP: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; default: avpriv_request_sample(avctx, "unsupported Color Field Array (CFA) %i", CFA & 0xFFFFFF); return AVERROR_INVALIDDATA; } } else { //CC_LEAD avpriv_request_sample(avctx, "unsupported compression %i", compression); return AVERROR_INVALIDDATA; } avio_skip(pb, 668); // Conv8Min ... Sensor set_metadata_int(&st->metadata, "shutter_ns", avio_rl32(pb), 0); avio_skip(pb, 24); // EDRShutterNs ... ImHeightAcq #define DESCRIPTION_SIZE 4096 description = av_malloc(DESCRIPTION_SIZE + 1); if (!description) return AVERROR(ENOMEM); i = avio_get_str(pb, DESCRIPTION_SIZE, description, DESCRIPTION_SIZE + 1); if (i < DESCRIPTION_SIZE) avio_skip(pb, DESCRIPTION_SIZE - i); if (description[0]) av_dict_set(&st->metadata, "description", description, AV_DICT_DONT_STRDUP_VAL); else av_free(description); avio_skip(pb, 1176); // RisingEdge ... cmUser set_metadata_int(&st->metadata, "enable_crop", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_left", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_top", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_right", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_bottom", avio_rl32(pb), 1); /* parse image offsets */ avio_seek(pb, offImageOffsets, SEEK_SET); for (i = 0; i < st->duration; i++) av_add_index_entry(st, avio_rl64(pb), i, 0, 0, AVINDEX_KEYFRAME); return 0; } Commit Message: avformat/cinedec: Fix DoS due to lack of eof check Fixes: loop.cine Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int cine_read_header(AVFormatContext *avctx) { AVIOContext *pb = avctx->pb; AVStream *st; unsigned int version, compression, offImageHeader, offSetup, offImageOffsets, biBitCount, length, CFA; int vflip; char *description; uint64_t i; st = avformat_new_stream(avctx, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; st->codecpar->codec_tag = 0; /* CINEFILEHEADER structure */ avio_skip(pb, 4); // Type, Headersize compression = avio_rl16(pb); version = avio_rl16(pb); if (version != 1) { avpriv_request_sample(avctx, "unknown version %i", version); return AVERROR_INVALIDDATA; } avio_skip(pb, 12); // FirstMovieImage, TotalImageCount, FirstImageNumber st->duration = avio_rl32(pb); offImageHeader = avio_rl32(pb); offSetup = avio_rl32(pb); offImageOffsets = avio_rl32(pb); avio_skip(pb, 8); // TriggerTime /* BITMAPINFOHEADER structure */ avio_seek(pb, offImageHeader, SEEK_SET); avio_skip(pb, 4); //biSize st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); if (avio_rl16(pb) != 1) // biPlanes return AVERROR_INVALIDDATA; biBitCount = avio_rl16(pb); if (biBitCount != 8 && biBitCount != 16 && biBitCount != 24 && biBitCount != 48) { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } switch (avio_rl32(pb)) { case BMP_RGB: vflip = 0; break; case 0x100: /* BI_PACKED */ st->codecpar->codec_tag = MKTAG('B', 'I', 'T', 0); vflip = 1; break; default: avpriv_request_sample(avctx, "unknown bitmap compression"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); // biSizeImage /* parse SETUP structure */ avio_seek(pb, offSetup, SEEK_SET); avio_skip(pb, 140); // FrameRatae16 .. descriptionOld if (avio_rl16(pb) != 0x5453) return AVERROR_INVALIDDATA; length = avio_rl16(pb); if (length < 0x163C) { avpriv_request_sample(avctx, "short SETUP header"); return AVERROR_INVALIDDATA; } avio_skip(pb, 616); // Binning .. bFlipH if (!avio_rl32(pb) ^ vflip) { st->codecpar->extradata = av_strdup("BottomUp"); st->codecpar->extradata_size = 9; } avio_skip(pb, 4); // Grid avpriv_set_pts_info(st, 64, 1, avio_rl32(pb)); avio_skip(pb, 20); // Shutter .. bEnableColor set_metadata_int(&st->metadata, "camera_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "firmware_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "software_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "recording_timezone", avio_rl32(pb), 0); CFA = avio_rl32(pb); set_metadata_int(&st->metadata, "brightness", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "contrast", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "gamma", avio_rl32(pb), 1); avio_skip(pb, 12 + 16); // Reserved1 .. AutoExpRect set_metadata_float(&st->metadata, "wbgain[0].r", av_int2float(avio_rl32(pb)), 1); set_metadata_float(&st->metadata, "wbgain[0].b", av_int2float(avio_rl32(pb)), 1); avio_skip(pb, 36); // WBGain[1].. WBView st->codecpar->bits_per_coded_sample = avio_rl32(pb); if (compression == CC_RGB) { if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_GRAY8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_GRAY16LE; } else if (biBitCount == 24) { st->codecpar->format = AV_PIX_FMT_BGR24; } else if (biBitCount == 48) { st->codecpar->format = AV_PIX_FMT_BGR48LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } } else if (compression == CC_UNINT) { switch (CFA & 0xFFFFFF) { case CFA_BAYER: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; case CFA_BAYERFLIP: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; default: avpriv_request_sample(avctx, "unsupported Color Field Array (CFA) %i", CFA & 0xFFFFFF); return AVERROR_INVALIDDATA; } } else { //CC_LEAD avpriv_request_sample(avctx, "unsupported compression %i", compression); return AVERROR_INVALIDDATA; } avio_skip(pb, 668); // Conv8Min ... Sensor set_metadata_int(&st->metadata, "shutter_ns", avio_rl32(pb), 0); avio_skip(pb, 24); // EDRShutterNs ... ImHeightAcq #define DESCRIPTION_SIZE 4096 description = av_malloc(DESCRIPTION_SIZE + 1); if (!description) return AVERROR(ENOMEM); i = avio_get_str(pb, DESCRIPTION_SIZE, description, DESCRIPTION_SIZE + 1); if (i < DESCRIPTION_SIZE) avio_skip(pb, DESCRIPTION_SIZE - i); if (description[0]) av_dict_set(&st->metadata, "description", description, AV_DICT_DONT_STRDUP_VAL); else av_free(description); avio_skip(pb, 1176); // RisingEdge ... cmUser set_metadata_int(&st->metadata, "enable_crop", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_left", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_top", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_right", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_bottom", avio_rl32(pb), 1); /* parse image offsets */ avio_seek(pb, offImageOffsets, SEEK_SET); for (i = 0; i < st->duration; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; av_add_index_entry(st, avio_rl64(pb), i, 0, 0, AVINDEX_KEYFRAME); } return 0; }
167,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copyMultiCh24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i] >> 8; } } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMultiCh24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) static void copyMultiCh24(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i] >> 8; } } }
174,019
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) { struct lib_t *libs; int i; if (!bin->nlibs) return NULL; if (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t)))) return NULL; for (i = 0; i < bin->nlibs; i++) { strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH); libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0'; libs[i].last = 0; } libs[i].last = 1; return libs; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416
struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) { struct lib_t *libs; int i; if (!bin->nlibs) { return NULL; } if (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t)))) { return NULL; } for (i = 0; i < bin->nlibs; i++) { strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH); libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0'; libs[i].last = 0; } libs[i].last = 1; return libs; }
168,234
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 k90_show_macro_mode(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct usb_interface *usbif = to_usb_interface(dev->parent); struct usb_device *usbdev = interface_to_usbdev(usbif); const char *macro_mode; char data[8]; ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), K90_REQUEST_GET_MODE, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, data, 2, USB_CTRL_SET_TIMEOUT); if (ret < 0) { dev_warn(dev, "Failed to get K90 initial mode (error %d).\n", ret); return -EIO; } switch (data[0]) { case K90_MACRO_MODE_HW: macro_mode = "HW"; break; case K90_MACRO_MODE_SW: macro_mode = "SW"; break; default: dev_warn(dev, "K90 in unknown mode: %02hhx.\n", data[0]); return -EIO; } return snprintf(buf, PAGE_SIZE, "%s\n", macro_mode); } Commit Message: HID: corsair: fix DMA buffers on stack Not all platforms support DMA to the stack, and specifically since v4.9 this is no longer supported on x86 with VMAP_STACK either. Note that the macro-mode buffer was larger than necessary. Fixes: 6f78193ee9ea ("HID: corsair: Add Corsair Vengeance K90 driver") Cc: stable <[email protected]> Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static ssize_t k90_show_macro_mode(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct usb_interface *usbif = to_usb_interface(dev->parent); struct usb_device *usbdev = interface_to_usbdev(usbif); const char *macro_mode; char *data; data = kmalloc(2, GFP_KERNEL); if (!data) return -ENOMEM; ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), K90_REQUEST_GET_MODE, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, data, 2, USB_CTRL_SET_TIMEOUT); if (ret < 0) { dev_warn(dev, "Failed to get K90 initial mode (error %d).\n", ret); ret = -EIO; goto out; } switch (data[0]) { case K90_MACRO_MODE_HW: macro_mode = "HW"; break; case K90_MACRO_MODE_SW: macro_mode = "SW"; break; default: dev_warn(dev, "K90 in unknown mode: %02hhx.\n", data[0]); ret = -EIO; goto out; } ret = snprintf(buf, PAGE_SIZE, "%s\n", macro_mode); out: kfree(data); return ret; }
168,395
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeMockRenderThread::OnDidPrintPage( const PrintHostMsg_DidPrintPage_Params& params) { if (printer_.get()) printer_->PrintPage(params); } 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 ChromeMockRenderThread::OnDidPrintPage( const PrintHostMsg_DidPrintPage_Params& params) { printer_->PrintPage(params); }
170,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { mpeg4_decode_profile_level(s, gb); if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (s->avctx->level > 0 && s->avctx->level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } Commit Message: avcodec/mpeg4videodec: Check read profile before setting it Fixes: null pointer dereference Fixes: ffmpeg_crash_7.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { int profile, level; mpeg4_decode_profile_level(s, gb, &profile, &level); if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (level > 0 && level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } else if (s->studio_profile) { avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n"); return AVERROR_PATCHWELCOME; } s->avctx->profile = profile; s->avctx->level = level; } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO); if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); }
169,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: void RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor(ui::Compositor*) { if (current_surface_ || !host_->is_hidden()) return; current_surface_in_use_by_compositor_ = false; AdjustSurfaceProtection(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [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 RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor(ui::Compositor*) {
171,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); final_p = fl6_update_dst(fl6, np->opt, &final); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); rcu_read_lock(); final_p = fl6_update_dst(fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; }
167,333
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vapic_enter(struct kvm_vcpu *vcpu) { struct kvm_lapic *apic = vcpu->arch.apic; struct page *page; if (!apic || !apic->vapic_addr) return 0; page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT); if (is_error_page(page)) return -EFAULT; vcpu->arch.apic->vapic_page = page; return 0; } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20
static int vapic_enter(struct kvm_vcpu *vcpu)
165,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::AcceleratedSurfaceNew( int32 width_in_pixel, int32 height_in_pixel, uint64 surface_handle) { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); scoped_refptr<ui::Texture> surface(factory->CreateTransportClient( gfx::Size(width_in_pixel, height_in_pixel), device_scale_factor_, surface_handle)); if (!surface) { LOG(ERROR) << "Failed to create ImageTransport texture"; return; } image_transport_clients_[surface_handle] = surface; } 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 RenderWidgetHostViewAura::AcceleratedSurfaceNew( int32 width_in_pixel, int32 height_in_pixel, uint64 surface_handle, const std::string& mailbox_name) { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); scoped_refptr<ui::Texture> surface(factory->CreateTransportClient( gfx::Size(width_in_pixel, height_in_pixel), device_scale_factor_, mailbox_name)); if (!surface) { LOG(ERROR) << "Failed to create ImageTransport texture"; return; } image_transport_clients_[surface_handle] = surface; }
171,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options, struct rusage32 __user *, ur) { struct rusage r; long ret, err; mm_segment_t old_fs; if (!ur) return sys_wait4(pid, ustatus, options, NULL); old_fs = get_fs(); set_fs (KERNEL_DS); ret = sys_wait4(pid, ustatus, options, (struct rusage __user *) &r); set_fs (old_fs); if (!access_ok(VERIFY_WRITE, ur, sizeof(*ur))) return -EFAULT; err = 0; err |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec); err |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec); err |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec); err |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec); err |= __put_user(r.ru_maxrss, &ur->ru_maxrss); err |= __put_user(r.ru_ixrss, &ur->ru_ixrss); err |= __put_user(r.ru_idrss, &ur->ru_idrss); err |= __put_user(r.ru_isrss, &ur->ru_isrss); err |= __put_user(r.ru_minflt, &ur->ru_minflt); err |= __put_user(r.ru_majflt, &ur->ru_majflt); err |= __put_user(r.ru_nswap, &ur->ru_nswap); err |= __put_user(r.ru_inblock, &ur->ru_inblock); err |= __put_user(r.ru_oublock, &ur->ru_oublock); err |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd); err |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv); err |= __put_user(r.ru_nsignals, &ur->ru_nsignals); err |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw); err |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw); return err ? err : ret; } Commit Message: alpha: fix several security issues Fix several security issues in Alpha-specific syscalls. Untested, but mostly trivial. 1. Signedness issue in osf_getdomainname allows copying out-of-bounds kernel memory to userland. 2. Signedness issue in osf_sysinfo allows copying large amounts of kernel memory to userland. 3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy size, allowing copying large amounts of kernel memory to userland. 4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows privilege escalation via writing return value of sys_wait4 to kernel memory. Signed-off-by: Dan Rosenberg <[email protected]> Cc: Richard Henderson <[email protected]> Cc: Ivan Kokshaysky <[email protected]> Cc: Matt Turner <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options, struct rusage32 __user *, ur) { struct rusage r; long ret, err; unsigned int status = 0; mm_segment_t old_fs; if (!ur) return sys_wait4(pid, ustatus, options, NULL); old_fs = get_fs(); set_fs (KERNEL_DS); ret = sys_wait4(pid, (unsigned int __user *) &status, options, (struct rusage __user *) &r); set_fs (old_fs); if (!access_ok(VERIFY_WRITE, ur, sizeof(*ur))) return -EFAULT; err = 0; err |= put_user(status, ustatus); err |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec); err |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec); err |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec); err |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec); err |= __put_user(r.ru_maxrss, &ur->ru_maxrss); err |= __put_user(r.ru_ixrss, &ur->ru_ixrss); err |= __put_user(r.ru_idrss, &ur->ru_idrss); err |= __put_user(r.ru_isrss, &ur->ru_isrss); err |= __put_user(r.ru_minflt, &ur->ru_minflt); err |= __put_user(r.ru_majflt, &ur->ru_majflt); err |= __put_user(r.ru_nswap, &ur->ru_nswap); err |= __put_user(r.ru_inblock, &ur->ru_inblock); err |= __put_user(r.ru_oublock, &ur->ru_oublock); err |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd); err |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv); err |= __put_user(r.ru_nsignals, &ur->ru_nsignals); err |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw); err |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw); return err ? err : ret; }
165,869
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: testing::AssertionResult ScriptAllowedExclusivelyOnTab( const Extension* extension, const std::set<GURL>& allowed_urls, int tab_id) { std::vector<std::string> errors; for (const GURL& url : urls_) { bool allowed = IsAllowedScript(extension, url, tab_id); if (allowed && !allowed_urls.count(url)) errors.push_back("Script unexpectedly disallowed on " + url.spec()); else if (!allowed && allowed_urls.count(url)) errors.push_back("Script unexpectedly allowed on " + url.spec()); } if (!errors.empty()) return testing::AssertionFailure() << base::JoinString(errors, "\n"); return testing::AssertionSuccess(); } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20
testing::AssertionResult ScriptAllowedExclusivelyOnTab( const Extension* extension, const std::set<GURL>& allowed_urls, int tab_id) { std::vector<std::string> errors; for (const GURL& url : urls_) { AccessType access = GetExtensionAccess(extension, url, tab_id); AccessType expected_access = allowed_urls.count(url) ? ALLOWED_SCRIPT_ONLY : DISALLOWED; if (access != expected_access) { errors.push_back( base::StringPrintf("Error for url '%s': expected %d, found %d", url.spec().c_str(), expected_access, access)); } } if (!errors.empty()) return testing::AssertionFailure() << base::JoinString(errors, "\n"); return testing::AssertionSuccess(); }
173,233
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!arp_checkentry(&e->arp)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-264
static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!arp_checkentry(&e->arp)) return -EINVAL; err = xt_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
167,216
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PepperMediaDeviceManager* PepperMediaDeviceManager::GetForRenderFrame( RenderFrame* render_frame) { PepperMediaDeviceManager* handler = PepperMediaDeviceManager::Get(render_frame); if (!handler) handler = new PepperMediaDeviceManager(render_frame); return handler; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
PepperMediaDeviceManager* PepperMediaDeviceManager::GetForRenderFrame( base::WeakPtr<PepperMediaDeviceManager> PepperMediaDeviceManager::GetForRenderFrame( RenderFrame* render_frame) { PepperMediaDeviceManager* handler = PepperMediaDeviceManager::Get(render_frame); if (!handler) handler = new PepperMediaDeviceManager(render_frame); return handler->AsWeakPtr(); }
171,608
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaStreamDispatcherHost::MediaStreamDispatcherHost( int render_process_id, int render_frame_id, MediaStreamManager* media_stream_manager) : render_process_id_(render_process_id), render_frame_id_(render_frame_id), media_stream_manager_(media_stream_manager), salt_and_origin_callback_( base::BindRepeating(&GetMediaDeviceSaltAndOrigin)), weak_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); bindings_.set_connection_error_handler( base::Bind(&MediaStreamDispatcherHost::CancelAllRequests, weak_factory_.GetWeakPtr())); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
MediaStreamDispatcherHost::MediaStreamDispatcherHost( int render_process_id, int render_frame_id, MediaStreamManager* media_stream_manager) : render_process_id_(render_process_id), render_frame_id_(render_frame_id), requester_id_(next_requester_id_++), media_stream_manager_(media_stream_manager), salt_and_origin_callback_( base::BindRepeating(&GetMediaDeviceSaltAndOrigin)), weak_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
173,096
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fsnotify_group *inotify_new_group(struct user_struct *user, unsigned int max_events) { struct fsnotify_group *group; group = fsnotify_alloc_group(&inotify_fsnotify_ops); if (IS_ERR(group)) return group; group->max_events = max_events; spin_lock_init(&group->inotify_data.idr_lock); idr_init(&group->inotify_data.idr); group->inotify_data.last_wd = 0; group->inotify_data.user = user; group->inotify_data.fa = NULL; return group; } Commit Message: inotify: fix double free/corruption of stuct user On an error path in inotify_init1 a normal user can trigger a double free of struct user. This is a regression introduced by a2ae4cc9a16e ("inotify: stop kernel memory leak on file creation failure"). We fix this by making sure that if a group exists the user reference is dropped when the group is cleaned up. We should not explictly drop the reference on error and also drop the reference when the group is cleaned up. The new lifetime rules are that an inotify group lives from inotify_new_group to the last fsnotify_put_group. Since the struct user and inotify_devs are directly tied to this lifetime they are only changed/updated in those two locations. We get rid of all special casing of struct user or user->inotify_devs. Signed-off-by: Eric Paris <[email protected]> Cc: [email protected] (2.6.37 and up) Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static struct fsnotify_group *inotify_new_group(struct user_struct *user, unsigned int max_events) static struct fsnotify_group *inotify_new_group(unsigned int max_events) { struct fsnotify_group *group; group = fsnotify_alloc_group(&inotify_fsnotify_ops); if (IS_ERR(group)) return group; group->max_events = max_events; spin_lock_init(&group->inotify_data.idr_lock); idr_init(&group->inotify_data.idr); group->inotify_data.last_wd = 0; group->inotify_data.fa = NULL; group->inotify_data.user = get_current_user(); if (atomic_inc_return(&group->inotify_data.user->inotify_devs) > inotify_max_user_instances) { fsnotify_put_group(group); return ERR_PTR(-EMFILE); } return group; }
165,888
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; }
173,839
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb) { struct xfrm_algo *algo; struct nlattr *nla; nla = nla_reserve(skb, XFRMA_ALG_AUTH, sizeof(*algo) + (auth->alg_key_len + 7) / 8); if (!nla) return -EMSGSIZE; algo = nla_data(nla); strcpy(algo->alg_name, auth->alg_name); memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8); algo->alg_key_len = auth->alg_key_len; return 0; } Commit Message: xfrm_user: fix info leak in copy_to_user_auth() copy_to_user_auth() fails to initialize the remainder of alg_name and therefore discloses up to 54 bytes of heap memory via netlink to userland. Use strncpy() instead of strcpy() to fill the trailing bytes of alg_name with null bytes. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb) { struct xfrm_algo *algo; struct nlattr *nla; nla = nla_reserve(skb, XFRMA_ALG_AUTH, sizeof(*algo) + (auth->alg_key_len + 7) / 8); if (!nla) return -EMSGSIZE; algo = nla_data(nla); strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name)); memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8); algo->alg_key_len = auth->alg_key_len; return 0; }
166,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics( const page_load_metrics::PageLoadExtraInfo& info, base::TimeTicks app_background_time) { ukm::builders::PageLoad builder(info.source_id); base::Optional<base::TimeDelta> foreground_duration = page_load_metrics::GetInitialForegroundDuration(info, app_background_time); if (foreground_duration) { builder.SetPageTiming_ForegroundDuration( foreground_duration.value().InMilliseconds()); } metrics::SystemProfileProto::Network::EffectiveConnectionType proto_effective_connection_type = metrics::ConvertEffectiveConnectionType(effective_connection_type_); if (proto_effective_connection_type != metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { builder.SetNet_EffectiveConnectionType2_OnNavigationStart( static_cast<int64_t>(proto_effective_connection_type)); } if (http_response_code_) { builder.SetNet_HttpResponseCode( static_cast<int64_t>(http_response_code_.value())); } if (http_rtt_estimate_) { builder.SetNet_HttpRttEstimate_OnNavigationStart( static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds())); } if (transport_rtt_estimate_) { builder.SetNet_TransportRttEstimate_OnNavigationStart( static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds())); } if (downstream_kbps_estimate_) { builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart( static_cast<int64_t>(downstream_kbps_estimate_.value())); } builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_)); builder.SetNavigation_PageEndReason( static_cast<int64_t>(info.page_end_reason)); if (info.did_commit && was_cached_) { builder.SetWasCached(1); } builder.Record(ukm::UkmRecorder::Get()); } Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation. Also refactor UkmPageLoadMetricsObserver to use this new boolean to report the user initiated metric in RecordPageLoadExtraInfoMetrics, so that it works correctly in the case when the page load failed. Bug: 925104 Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff Reviewed-on: https://chromium-review.googlesource.com/c/1450460 Commit-Queue: Annie Sullivan <[email protected]> Reviewed-by: Bryan McQuade <[email protected]> Cr-Commit-Position: refs/heads/master@{#630870} CWE ID: CWE-79
void UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics( const page_load_metrics::PageLoadExtraInfo& info, base::TimeTicks app_background_time) { ukm::builders::PageLoad builder(info.source_id); base::Optional<base::TimeDelta> foreground_duration = page_load_metrics::GetInitialForegroundDuration(info, app_background_time); if (foreground_duration) { builder.SetPageTiming_ForegroundDuration( foreground_duration.value().InMilliseconds()); } bool is_user_initiated_navigation = // All browser initiated page loads are user-initiated. info.user_initiated_info.browser_initiated || // Renderer-initiated navigations are user-initiated if there is an // associated input event. info.user_initiated_info.user_input_event; builder.SetExperimental_Navigation_UserInitiated( is_user_initiated_navigation); metrics::SystemProfileProto::Network::EffectiveConnectionType proto_effective_connection_type = metrics::ConvertEffectiveConnectionType(effective_connection_type_); if (proto_effective_connection_type != metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { builder.SetNet_EffectiveConnectionType2_OnNavigationStart( static_cast<int64_t>(proto_effective_connection_type)); } if (http_response_code_) { builder.SetNet_HttpResponseCode( static_cast<int64_t>(http_response_code_.value())); } if (http_rtt_estimate_) { builder.SetNet_HttpRttEstimate_OnNavigationStart( static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds())); } if (transport_rtt_estimate_) { builder.SetNet_TransportRttEstimate_OnNavigationStart( static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds())); } if (downstream_kbps_estimate_) { builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart( static_cast<int64_t>(downstream_kbps_estimate_.value())); } builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_)); builder.SetNavigation_PageEndReason( static_cast<int64_t>(info.page_end_reason)); if (info.did_commit && was_cached_) { builder.SetWasCached(1); } builder.Record(ukm::UkmRecorder::Get()); }
172,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: auth_read_binary(struct sc_card *card, unsigned int offset, unsigned char *buf, size_t count, unsigned long flags) { int rv; struct sc_pkcs15_bignum bn[2]; unsigned char *out = NULL; bn[0].data = NULL; bn[1].data = NULL; LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX", offset, count, flags); sc_log(card->ctx,"last selected : magic %X; ef %X", auth_current_ef->magic, auth_current_ef->ef_structure); if (offset & ~0x7FFF) LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset"); if (auth_current_ef->magic==SC_FILE_MAGIC && auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) { int jj; unsigned char resp[256]; size_t resp_len, out_len; struct sc_pkcs15_pubkey_rsa key; resp_len = sizeof(resp); rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC, 2, resp, resp_len); LOG_TEST_RET(card->ctx, rv, "read component failed"); for (jj=0; jj<rv && *(resp+jj)==0; jj++) ; bn[0].data = calloc(1, rv - jj); if (!bn[0].data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } bn[0].len = rv - jj; memcpy(bn[0].data, resp + jj, rv - jj); rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC, 1, resp, resp_len); LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component"); bn[1].data = calloc(1, rv); if (!bn[1].data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } bn[1].len = rv; memcpy(bn[1].data, resp, rv); key.exponent = bn[0]; key.modulus = bn[1]; if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) { rv = SC_ERROR_INVALID_ASN1_OBJECT; LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key"); } else { rv = out_len - offset > count ? count : out_len - offset; memcpy(buf, out + offset, rv); sc_log_hex(card->ctx, "write_publickey", buf, rv); } } else { rv = iso_ops->read_binary(card, offset, buf, count, 0); } err: free(bn[0].data); free(bn[1].data); free(out); LOG_FUNC_RETURN(card->ctx, rv); } 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
auth_read_binary(struct sc_card *card, unsigned int offset, unsigned char *buf, size_t count, unsigned long flags) { int rv; struct sc_pkcs15_bignum bn[2]; unsigned char *out = NULL; bn[0].data = NULL; bn[1].data = NULL; LOG_FUNC_CALLED(card->ctx); if (!auth_current_ef) LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid auth_current_ef"); sc_log(card->ctx, "offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX", offset, count, flags); sc_log(card->ctx,"last selected : magic %X; ef %X", auth_current_ef->magic, auth_current_ef->ef_structure); if (offset & ~0x7FFF) LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset"); if (auth_current_ef->magic==SC_FILE_MAGIC && auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) { int jj; unsigned char resp[256]; size_t resp_len, out_len; struct sc_pkcs15_pubkey_rsa key; resp_len = sizeof(resp); rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC, 2, resp, resp_len); LOG_TEST_RET(card->ctx, rv, "read component failed"); for (jj=0; jj<rv && *(resp+jj)==0; jj++) ; bn[0].data = calloc(1, rv - jj); if (!bn[0].data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } bn[0].len = rv - jj; memcpy(bn[0].data, resp + jj, rv - jj); rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC, 1, resp, resp_len); LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component"); bn[1].data = calloc(1, rv); if (!bn[1].data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } bn[1].len = rv; memcpy(bn[1].data, resp, rv); key.exponent = bn[0]; key.modulus = bn[1]; if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) { rv = SC_ERROR_INVALID_ASN1_OBJECT; LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key"); } else { rv = out_len - offset > count ? count : out_len - offset; memcpy(buf, out + offset, rv); sc_log_hex(card->ctx, "write_publickey", buf, rv); } } else { rv = iso_ops->read_binary(card, offset, buf, count, 0); } err: free(bn[0].data); free(bn[1].data); free(out); LOG_FUNC_RETURN(card->ctx, rv); }
169,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<FakeMediaStreamUIProxy> CreateMockUI(bool expect_started) { std::unique_ptr<MockMediaStreamUIProxy> fake_ui = std::make_unique<MockMediaStreamUIProxy>(); if (expect_started) EXPECT_CALL(*fake_ui, MockOnStarted(_)); return fake_ui; } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
std::unique_ptr<FakeMediaStreamUIProxy> CreateMockUI(bool expect_started) { std::unique_ptr<MockMediaStreamUIProxy> fake_ui = std::make_unique<MockMediaStreamUIProxy>(); testing::Mock::AllowLeak(fake_ui.get()); if (expect_started) EXPECT_CALL(*fake_ui, MockOnStarted(_)); return fake_ui; }
173,099
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: explicit LogoDelegateImpl( std::unique_ptr<image_fetcher::ImageDecoder> image_decoder) : image_decoder_(std::move(image_decoder)) {} Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
explicit LogoDelegateImpl(
171,954
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf) { fz_stream *file = doc->file; int64_t ofs; int len; char *s; size_t n; pdf_token tok; int64_t i; int c; int xref_len = pdf_xref_size_from_old_trailer(ctx, doc, buf); pdf_xref_entry *table; int carried; fz_skip_space(ctx, doc->file); if (fz_skip_string(ctx, doc->file, "xref")) fz_throw(ctx, FZ_ERROR_GENERIC, "cannot find xref marker"); fz_skip_space(ctx, doc->file); while (1) { c = fz_peek_byte(ctx, file); if (!(c >= '0' && c <= '9')) break; fz_read_line(ctx, file, buf->scratch, buf->size); s = buf->scratch; ofs = fz_atoi64(fz_strsep(&s, " ")); len = fz_atoi(fz_strsep(&s, " ")); /* broken pdfs where the section is not on a separate line */ if (s && *s != '\0') { fz_warn(ctx, "broken xref section. proceeding anyway."); fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR); } if (ofs < 0) fz_throw(ctx, FZ_ERROR_GENERIC, "out of range object num in xref: %d", (int)ofs); if (ofs > INT64_MAX - len) fz_throw(ctx, FZ_ERROR_GENERIC, "xref section object numbers too big"); /* broken pdfs where size in trailer undershoots entries in xref sections */ if (ofs + len > xref_len) { } table = pdf_xref_find_subsection(ctx, doc, ofs, len); /* Xref entries SHOULD be 20 bytes long, but we see 19 byte * ones more frequently than we'd like (e.g. PCLm drivers). * Cope with this by 'carrying' data forward. */ carried = 0; for (i = ofs; i < ofs + len; i++) { pdf_xref_entry *entry = &table[i-ofs]; n = fz_read(ctx, file, (unsigned char *) buf->scratch + carried, 20-carried); if (n != 20-carried) fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected EOF in xref table"); n += carried; if (!entry->type) { s = buf->scratch; /* broken pdfs where line start with white space */ while (*s != '\0' && iswhite(*s)) s++; entry->ofs = fz_atoi64(s); entry->gen = fz_atoi(s + 11); entry->num = (int)i; entry->type = s[17]; if (s[17] != 'f' && s[17] != 'n' && s[17] != 'o') fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected xref type: 0x%x (%d %d R)", s[17], entry->num, entry->gen); /* If the last byte of our buffer isn't an EOL (or space), carry one byte forward */ carried = s[19] > 32; if (carried) s[0] = s[19]; } } if (carried) fz_unread_byte(ctx, file); } tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_TRAILER) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer marker"); tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_OPEN_DICT) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer dictionary"); return pdf_parse_dict(ctx, doc, file, buf); } Commit Message: CWE ID: CWE-119
pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf) { fz_stream *file = doc->file; int64_t ofs; int len; char *s; size_t n; pdf_token tok; int64_t i; int c; int xref_len = pdf_xref_size_from_old_trailer(ctx, doc, buf); pdf_xref_entry *table; int carried; fz_skip_space(ctx, doc->file); if (fz_skip_string(ctx, doc->file, "xref")) fz_throw(ctx, FZ_ERROR_GENERIC, "cannot find xref marker"); fz_skip_space(ctx, doc->file); while (1) { c = fz_peek_byte(ctx, file); if (!(c >= '0' && c <= '9')) break; fz_read_line(ctx, file, buf->scratch, buf->size); s = buf->scratch; ofs = fz_atoi64(fz_strsep(&s, " ")); len = fz_atoi(fz_strsep(&s, " ")); /* broken pdfs where the section is not on a separate line */ if (s && *s != '\0') { fz_warn(ctx, "broken xref section. proceeding anyway."); fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR); } if (ofs < 0 || ofs > PDF_MAX_OBJECT_NUMBER || len < 0 || len > PDF_MAX_OBJECT_NUMBER || ofs + len - 1 > PDF_MAX_OBJECT_NUMBER) { fz_throw(ctx, FZ_ERROR_GENERIC, "xref subsection object numbers are out of range"); } /* broken pdfs where size in trailer undershoots entries in xref sections */ if (ofs + len > xref_len) { } table = pdf_xref_find_subsection(ctx, doc, ofs, len); /* Xref entries SHOULD be 20 bytes long, but we see 19 byte * ones more frequently than we'd like (e.g. PCLm drivers). * Cope with this by 'carrying' data forward. */ carried = 0; for (i = ofs; i < ofs + len; i++) { pdf_xref_entry *entry = &table[i-ofs]; n = fz_read(ctx, file, (unsigned char *) buf->scratch + carried, 20-carried); if (n != 20-carried) fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected EOF in xref table"); n += carried; if (!entry->type) { s = buf->scratch; /* broken pdfs where line start with white space */ while (*s != '\0' && iswhite(*s)) s++; entry->ofs = fz_atoi64(s); entry->gen = fz_atoi(s + 11); entry->num = (int)i; entry->type = s[17]; if (s[17] != 'f' && s[17] != 'n' && s[17] != 'o') fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected xref type: 0x%x (%d %d R)", s[17], entry->num, entry->gen); /* If the last byte of our buffer isn't an EOL (or space), carry one byte forward */ carried = s[19] > 32; if (carried) s[0] = s[19]; } } if (carried) fz_unread_byte(ctx, file); } tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_TRAILER) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer marker"); tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_OPEN_DICT) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer dictionary"); return pdf_parse_dict(ctx, doc, file, buf); }
165,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t ESDS::parseESDescriptor(size_t offset, size_t size) { if (size < 3) { return ERROR_MALFORMED; } offset += 2; // skip ES_ID size -= 2; unsigned streamDependenceFlag = mData[offset] & 0x80; unsigned URL_Flag = mData[offset] & 0x40; unsigned OCRstreamFlag = mData[offset] & 0x20; ++offset; --size; if (streamDependenceFlag) { offset += 2; size -= 2; } if (URL_Flag) { if (offset >= size) { return ERROR_MALFORMED; } unsigned URLlength = mData[offset]; offset += URLlength + 1; size -= URLlength + 1; } if (OCRstreamFlag) { offset += 2; size -= 2; if ((offset >= size || mData[offset] != kTag_DecoderConfigDescriptor) && offset - 2 < size && mData[offset - 2] == kTag_DecoderConfigDescriptor) { offset -= 2; size += 2; ALOGW("Found malformed 'esds' atom, ignoring missing OCR_ES_Id."); } } if (offset >= size) { return ERROR_MALFORMED; } uint8_t tag; size_t sub_offset, sub_size; status_t err = skipDescriptorHeader( offset, size, &tag, &sub_offset, &sub_size); if (err != OK) { return err; } if (tag != kTag_DecoderConfigDescriptor) { return ERROR_MALFORMED; } err = parseDecoderConfigDescriptor(sub_offset, sub_size); return err; } Commit Message: Fix integer underflow in ESDS processing Several arithmetic operations within parseESDescriptor could underflow, leading to an out-of-bounds read operation. Ensure that subtractions from 'size' do not cause it to wrap around. Bug: 20139950 (cherry picked from commit 07c0f59d6c48874982d2b5c713487612e5af465a) Change-Id: I377d21051e07ca654ea1f7037120429d3f71924a CWE ID: CWE-189
status_t ESDS::parseESDescriptor(size_t offset, size_t size) { if (size < 3) { return ERROR_MALFORMED; } offset += 2; // skip ES_ID size -= 2; unsigned streamDependenceFlag = mData[offset] & 0x80; unsigned URL_Flag = mData[offset] & 0x40; unsigned OCRstreamFlag = mData[offset] & 0x20; ++offset; --size; if (streamDependenceFlag) { if (size < 2) return ERROR_MALFORMED; offset += 2; size -= 2; } if (URL_Flag) { if (offset >= size) { return ERROR_MALFORMED; } unsigned URLlength = mData[offset]; if (URLlength >= size) return ERROR_MALFORMED; offset += URLlength + 1; size -= URLlength + 1; } if (OCRstreamFlag) { if (size < 2) return ERROR_MALFORMED; offset += 2; size -= 2; if ((offset >= size || mData[offset] != kTag_DecoderConfigDescriptor) && offset - 2 < size && mData[offset - 2] == kTag_DecoderConfigDescriptor) { offset -= 2; size += 2; ALOGW("Found malformed 'esds' atom, ignoring missing OCR_ES_Id."); } } if (offset >= size) { return ERROR_MALFORMED; } uint8_t tag; size_t sub_offset, sub_size; status_t err = skipDescriptorHeader( offset, size, &tag, &sub_offset, &sub_size); if (err != OK) { return err; } if (tag != kTag_DecoderConfigDescriptor) { return ERROR_MALFORMED; } err = parseDecoderConfigDescriptor(sub_offset, sub_size); return err; }
173,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 void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inR1outI2_tail(pcrc, r); if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); passert(GLOBALS_ARE_RESET()); } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20
static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inR1outI2_tail(pcrc, r); if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); }
166,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 key_update(key_ref_t key_ref, const void *payload, size_t plen) { struct key_preparsed_payload prep; struct key *key = key_ref_to_ptr(key_ref); int ret; key_check(key); /* the key must be writable */ ret = key_permission(key_ref, KEY_NEED_WRITE); if (ret < 0) return ret; /* attempt to update it if supported */ if (!key->type->update) return -EOPNOTSUPP; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = key->type->def_datalen; prep.expiry = TIME_T_MAX; if (key->type->preparse) { ret = key->type->preparse(&prep); if (ret < 0) goto error; } down_write(&key->sem); ret = key->type->update(key, &prep); if (ret == 0) /* updating a negative key instantiates it */ clear_bit(KEY_FLAG_NEGATIVE, &key->flags); up_write(&key->sem); error: if (key->type->preparse) key->type->free_preparse(&prep); return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
int key_update(key_ref_t key_ref, const void *payload, size_t plen) { struct key_preparsed_payload prep; struct key *key = key_ref_to_ptr(key_ref); int ret; key_check(key); /* the key must be writable */ ret = key_permission(key_ref, KEY_NEED_WRITE); if (ret < 0) return ret; /* attempt to update it if supported */ if (!key->type->update) return -EOPNOTSUPP; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = key->type->def_datalen; prep.expiry = TIME_T_MAX; if (key->type->preparse) { ret = key->type->preparse(&prep); if (ret < 0) goto error; } down_write(&key->sem); ret = key->type->update(key, &prep); if (ret == 0) /* Updating a negative key positively instantiates it */ mark_key_instantiated(key, 0); up_write(&key->sem); error: if (key->type->preparse) key->type->free_preparse(&prep); return ret; }
167,699
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h, const cdf_stream_t *sst, const uint64_t clsid[2]) { cdf_summary_info_header_t si; cdf_property_info_t *info; size_t count; int m; if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1) return -1; if (NOTMIME(ms)) { const char *str; if (file_printf(ms, "Composite Document File V2 Document") == -1) return -1; if (file_printf(ms, ", %s Endian", si.si_byte_order == 0xfffe ? "Little" : "Big") == -1) return -2; switch (si.si_os) { case 2: if (file_printf(ms, ", Os: Windows, Version %d.%d", si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; case 1: if (file_printf(ms, ", Os: MacOS, Version %d.%d", (uint32_t)si.si_os_version >> 8, si.si_os_version & 0xff) == -1) return -2; break; default: if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os, si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; } str = cdf_clsid_to_mime(clsid, clsid2desc); if (str) if (file_printf(ms, ", %s", str) == -1) return -2; } m = cdf_file_property_info(ms, info, count, clsid); free(info); return m == -1 ? -2 : m; } Commit Message: Apply patches from file-CVE-2012-1571.patch From Francisco Alonso Espejo: file < 5.18/git version can be made to crash when checking some corrupt CDF files (Using an invalid cdf_read_short_sector size) The problem I found here, is that in most situations (if h_short_sec_size_p2 > 8) because the blocksize is 512 and normal values are 06 which means reading 64 bytes.As long as the check for the block size copy is not checked properly (there's an assert that makes wrong/invalid assumptions) CWE ID: CWE-119
cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h, const cdf_stream_t *sst, const cdf_directory_t *root_storage) { cdf_summary_info_header_t si; cdf_property_info_t *info; size_t count; int m; if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1) return -1; if (NOTMIME(ms)) { const char *str; if (file_printf(ms, "Composite Document File V2 Document") == -1) return -1; if (file_printf(ms, ", %s Endian", si.si_byte_order == 0xfffe ? "Little" : "Big") == -1) return -2; switch (si.si_os) { case 2: if (file_printf(ms, ", Os: Windows, Version %d.%d", si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; case 1: if (file_printf(ms, ", Os: MacOS, Version %d.%d", (uint32_t)si.si_os_version >> 8, si.si_os_version & 0xff) == -1) return -2; break; default: if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os, si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; } if (root_storage) { str = cdf_clsid_to_mime(root_storage->d_storage_uuid, clsid2desc); if (str) if (file_printf(ms, ", %s", str) == -1) return -2; } } m = cdf_file_property_info(ms, info, count, root_storage); free(info); return m == -1 ? -2 : m; }
166,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Edition::ShallowCopy(Edition& rhs) const { rhs.m_atoms = m_atoms; rhs.m_atoms_size = m_atoms_size; rhs.m_atoms_count = m_atoms_count; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Edition::ShallowCopy(Edition& rhs) const rhs.m_displays = m_displays; rhs.m_displays_size = m_displays_size; rhs.m_displays_count = m_displays_count; }
174,441
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int picolcd_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *raw_data, int size) { struct picolcd_data *data = hid_get_drvdata(hdev); unsigned long flags; int ret = 0; if (!data) return 1; if (report->id == REPORT_KEY_STATE) { if (data->input_keys) ret = picolcd_raw_keypad(data, report, raw_data+1, size-1); } else if (report->id == REPORT_IR_DATA) { ret = picolcd_raw_cir(data, report, raw_data+1, size-1); } else { spin_lock_irqsave(&data->lock, flags); /* * We let the caller of picolcd_send_and_wait() check if the * report we got is one of the expected ones or not. */ if (data->pending) { memcpy(data->pending->raw_data, raw_data+1, size-1); data->pending->raw_size = size-1; data->pending->in_report = report; complete(&data->pending->ready); } spin_unlock_irqrestore(&data->lock, flags); } picolcd_debug_raw_event(data, hdev, report, raw_data, size); return 1; } Commit Message: HID: picolcd: sanity check report size in raw_event() callback The report passed to us from transport driver could potentially be arbitrarily large, therefore we better sanity-check it so that raw_data that we hold in picolcd_pending structure are always kept within proper bounds. Cc: [email protected] Reported-by: Steven Vittitoe <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static int picolcd_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *raw_data, int size) { struct picolcd_data *data = hid_get_drvdata(hdev); unsigned long flags; int ret = 0; if (!data) return 1; if (size > 64) { hid_warn(hdev, "invalid size value (%d) for picolcd raw event\n", size); return 0; } if (report->id == REPORT_KEY_STATE) { if (data->input_keys) ret = picolcd_raw_keypad(data, report, raw_data+1, size-1); } else if (report->id == REPORT_IR_DATA) { ret = picolcd_raw_cir(data, report, raw_data+1, size-1); } else { spin_lock_irqsave(&data->lock, flags); /* * We let the caller of picolcd_send_and_wait() check if the * report we got is one of the expected ones or not. */ if (data->pending) { memcpy(data->pending->raw_data, raw_data+1, size-1); data->pending->raw_size = size-1; data->pending->in_report = report; complete(&data->pending->ready); } spin_unlock_irqrestore(&data->lock, flags); } picolcd_debug_raw_event(data, hdev, report, raw_data, size); return 1; }
166,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionSettingsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { RegisterTitle(localized_strings, "extensionSettings", IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE); localized_strings->SetString("extensionSettingsVisitWebsite", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VISIT_WEBSITE)); localized_strings->SetString("extensionSettingsDeveloperMode", l10n_util::GetStringUTF16(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings->SetString("extensionSettingsNoExtensions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings->SetString("extensionSettingsSuggestGallery", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsGetMoreExtensions", l10n_util::GetStringFUTF16(IDS_GET_MORE_EXTENSIONS, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsExtensionId", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ID)); localized_strings->SetString("extensionSettingsExtensionPath", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PATH)); localized_strings->SetString("extensionSettingsInspectViews", l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings->SetString("viewIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VIEW_INCOGNITO)); localized_strings->SetString("extensionSettingsEnable", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE)); localized_strings->SetString("extensionSettingsEnabled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLED)); localized_strings->SetString("extensionSettingsRemove", l10n_util::GetStringUTF16(IDS_EXTENSIONS_REMOVE)); localized_strings->SetString("extensionSettingsEnableIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE_INCOGNITO)); localized_strings->SetString("extensionSettingsAllowFileAccess", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ALLOW_FILE_ACCESS)); localized_strings->SetString("extensionSettingsIncognitoWarning", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_INCOGNITO_WARNING, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))); localized_strings->SetString("extensionSettingsReload", l10n_util::GetStringUTF16(IDS_EXTENSIONS_RELOAD)); localized_strings->SetString("extensionSettingsOptions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS)); localized_strings->SetString("extensionSettingsPolicyControlled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_POLICY_CONTROLLED)); localized_strings->SetString("extensionSettingsShowButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_BUTTON)); localized_strings->SetString("extensionSettingsLoadUnpackedButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings->SetString("extensionSettingsPackButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings->SetString("extensionSettingsUpdateButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings->SetString("extensionSettingsCrashMessage", l10n_util::GetStringUTF16(IDS_EXTENSIONS_CRASHED_EXTENSION)); localized_strings->SetString("extensionSettingsInDevelopment", l10n_util::GetStringUTF16(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings->SetString("extensionSettingsWarningsTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WARNINGS_TITLE)); localized_strings->SetString("extensionSettingsShowDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS)); localized_strings->SetString("extensionSettingsHideDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS)); } 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
void ExtensionSettingsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { RegisterTitle(localized_strings, "extensionSettings", IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE); localized_strings->SetString("extensionSettingsVisitWebsite", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VISIT_WEBSITE)); localized_strings->SetString("extensionSettingsDeveloperMode", l10n_util::GetStringUTF16(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings->SetString("extensionSettingsNoExtensions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings->SetString("extensionSettingsSuggestGallery", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsGetMoreExtensions", l10n_util::GetStringFUTF16(IDS_GET_MORE_EXTENSIONS, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsExtensionId", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ID)); localized_strings->SetString("extensionSettingsExtensionPath", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PATH)); localized_strings->SetString("extensionSettingsInspectViews", l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings->SetString("viewIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VIEW_INCOGNITO)); localized_strings->SetString("extensionSettingsEnable", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE)); localized_strings->SetString("extensionSettingsEnabled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLED)); localized_strings->SetString("extensionSettingsRemove", l10n_util::GetStringUTF16(IDS_EXTENSIONS_REMOVE)); localized_strings->SetString("extensionSettingsEnableIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE_INCOGNITO)); localized_strings->SetString("extensionSettingsAllowFileAccess", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ALLOW_FILE_ACCESS)); localized_strings->SetString("extensionSettingsIncognitoWarning", l10n_util::GetStringUTF16(IDS_EXTENSIONS_INCOGNITO_WARNING)); localized_strings->SetString("extensionSettingsReload", l10n_util::GetStringUTF16(IDS_EXTENSIONS_RELOAD)); localized_strings->SetString("extensionSettingsOptions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS)); localized_strings->SetString("extensionSettingsPolicyControlled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_POLICY_CONTROLLED)); localized_strings->SetString("extensionSettingsShowButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_BUTTON)); localized_strings->SetString("extensionSettingsLoadUnpackedButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings->SetString("extensionSettingsPackButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings->SetString("extensionSettingsUpdateButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings->SetString("extensionSettingsCrashMessage", l10n_util::GetStringUTF16(IDS_EXTENSIONS_CRASHED_EXTENSION)); localized_strings->SetString("extensionSettingsInDevelopment", l10n_util::GetStringUTF16(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings->SetString("extensionSettingsWarningsTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WARNINGS_TITLE)); localized_strings->SetString("extensionSettingsShowDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS)); localized_strings->SetString("extensionSettingsHideDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS)); }
170,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: CatalogueRescan (FontPathElementPtr fpe) { CataloguePtr cat = fpe->private; char link[MAXFONTFILENAMELEN]; char dest[MAXFONTFILENAMELEN]; char *attrib; FontPathElementPtr subfpe; struct stat statbuf; const char *path; DIR *dir; struct dirent *entry; int len; int pathlen; path = fpe->name + strlen(CataloguePrefix); if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode)) return BadFontPath; if (statbuf.st_mtime <= cat->mtime) return Successful; dir = opendir(path); if (dir == NULL) { xfree(cat); return BadFontPath; } CatalogueUnrefFPEs (fpe); while (entry = readdir(dir), entry != NULL) { snprintf(link, sizeof link, "%s/%s", path, entry->d_name); len = readlink(link, dest, sizeof dest); if (len < 0) continue; dest[len] = '\0'; if (dest[0] != '/') { pathlen = strlen(path); memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1); memcpy(dest, path, pathlen); memcpy(dest + pathlen, "/", 1); len += pathlen + 1; } attrib = strchr(link, ':'); if (attrib && len + strlen(attrib) < sizeof dest) { memcpy(dest + len, attrib, strlen(attrib)); len += strlen(attrib); } subfpe = xalloc(sizeof *subfpe); if (subfpe == NULL) continue; /* The fonts returned by OpenFont will point back to the * subfpe they come from. So set the type of the subfpe to * what the catalogue fpe was assigned, so calls to CloseFont * (which uses font->fpe->type) goes to CatalogueCloseFont. */ subfpe->type = fpe->type; subfpe->name_length = len; subfpe->name = xalloc (len + 1); if (subfpe == NULL) { xfree(subfpe); continue; } memcpy(subfpe->name, dest, len); subfpe->name[len] = '\0'; /* The X server will manipulate the subfpe ref counts * associated with the font in OpenFont and CloseFont, so we * have to make sure it's valid. */ subfpe->refcount = 1; if (FontFileInitFPE (subfpe) != Successful) { xfree(subfpe->name); xfree(subfpe); continue; } if (CatalogueAddFPE(cat, subfpe) != Successful) { FontFileFreeFPE (subfpe); xfree(subfpe); continue; } } closedir(dir); qsort(cat->fpeList, cat->fpeCount, sizeof cat->fpeList[0], ComparePriority); cat->mtime = statbuf.st_mtime; return Successful; } Commit Message: CWE ID: CWE-119
CatalogueRescan (FontPathElementPtr fpe) { CataloguePtr cat = fpe->private; char link[MAXFONTFILENAMELEN]; char dest[MAXFONTFILENAMELEN]; char *attrib; FontPathElementPtr subfpe; struct stat statbuf; const char *path; DIR *dir; struct dirent *entry; int len; int pathlen; path = fpe->name + strlen(CataloguePrefix); if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode)) return BadFontPath; if (statbuf.st_mtime <= cat->mtime) return Successful; dir = opendir(path); if (dir == NULL) { xfree(cat); return BadFontPath; } CatalogueUnrefFPEs (fpe); while (entry = readdir(dir), entry != NULL) { snprintf(link, sizeof link, "%s/%s", path, entry->d_name); len = readlink(link, dest, sizeof dest - 1); if (len < 0) continue; dest[len] = '\0'; if (dest[0] != '/') { pathlen = strlen(path); memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1); memcpy(dest, path, pathlen); memcpy(dest + pathlen, "/", 1); len += pathlen + 1; } attrib = strchr(link, ':'); if (attrib && len + strlen(attrib) < sizeof dest) { memcpy(dest + len, attrib, strlen(attrib)); len += strlen(attrib); } subfpe = xalloc(sizeof *subfpe); if (subfpe == NULL) continue; /* The fonts returned by OpenFont will point back to the * subfpe they come from. So set the type of the subfpe to * what the catalogue fpe was assigned, so calls to CloseFont * (which uses font->fpe->type) goes to CatalogueCloseFont. */ subfpe->type = fpe->type; subfpe->name_length = len; subfpe->name = xalloc (len + 1); if (subfpe == NULL) { xfree(subfpe); continue; } memcpy(subfpe->name, dest, len); subfpe->name[len] = '\0'; /* The X server will manipulate the subfpe ref counts * associated with the font in OpenFont and CloseFont, so we * have to make sure it's valid. */ subfpe->refcount = 1; if (FontFileInitFPE (subfpe) != Successful) { xfree(subfpe->name); xfree(subfpe); continue; } if (CatalogueAddFPE(cat, subfpe) != Successful) { FontFileFreeFPE (subfpe); xfree(subfpe); continue; } } closedir(dir); qsort(cat->fpeList, cat->fpeCount, sizeof cat->fpeList[0], ComparePriority); cat->mtime = statbuf.st_mtime; return Successful; }
165,425
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_vmon(struct kvm_vcpu *vcpu) { int ret; gpa_t vmptr; struct page *page; struct vcpu_vmx *vmx = to_vmx(vcpu); const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX; /* * The Intel VMX Instruction Reference lists a bunch of bits that are * prerequisite to running VMXON, most notably cr4.VMXE must be set to * 1 (see vmx_set_cr4() for when we allow the guest to set this). * Otherwise, we should fail with #UD. But most faulting conditions * have already been checked by hardware, prior to the VM-exit for * VMXON. We do test guest cr4.VMXE because processor CR4 always has * that bit set to 1 in non-root mode. */ if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (vmx->nested.vmxon) { nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION); return kvm_skip_emulated_instruction(vcpu); } if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES) != VMXON_NEEDED_FEATURES) { kvm_inject_gp(vcpu, 0); return 1; } if (nested_vmx_get_vmptr(vcpu, &vmptr)) return 1; /* * SDM 3: 24.11.5 * The first 4 bytes of VMXON region contain the supported * VMCS revision identifier * * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case; * which replaces physical address width with 32 */ if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } page = kvm_vcpu_gpa_to_page(vcpu, vmptr); if (is_error_page(page)) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } if (*(u32 *)kmap(page) != VMCS12_REVISION) { kunmap(page); kvm_release_page_clean(page); nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } kunmap(page); kvm_release_page_clean(page); vmx->nested.vmxon_ptr = vmptr; ret = enter_vmx_operation(vcpu); if (ret) return ret; nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); } Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions VMX instructions executed inside a L1 VM will always trigger a VM exit even when executed with cpl 3. This means we must perform the privilege check in software. Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks") Cc: [email protected] Signed-off-by: Felix Wilhelm <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID:
static int handle_vmon(struct kvm_vcpu *vcpu) { int ret; gpa_t vmptr; struct page *page; struct vcpu_vmx *vmx = to_vmx(vcpu); const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX; /* * The Intel VMX Instruction Reference lists a bunch of bits that are * prerequisite to running VMXON, most notably cr4.VMXE must be set to * 1 (see vmx_set_cr4() for when we allow the guest to set this). * Otherwise, we should fail with #UD. But most faulting conditions * have already been checked by hardware, prior to the VM-exit for * VMXON. We do test guest cr4.VMXE because processor CR4 always has * that bit set to 1 in non-root mode. */ if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } /* CPL=0 must be checked manually. */ if (vmx_get_cpl(vcpu)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (vmx->nested.vmxon) { nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION); return kvm_skip_emulated_instruction(vcpu); } if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES) != VMXON_NEEDED_FEATURES) { kvm_inject_gp(vcpu, 0); return 1; } if (nested_vmx_get_vmptr(vcpu, &vmptr)) return 1; /* * SDM 3: 24.11.5 * The first 4 bytes of VMXON region contain the supported * VMCS revision identifier * * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case; * which replaces physical address width with 32 */ if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } page = kvm_vcpu_gpa_to_page(vcpu, vmptr); if (is_error_page(page)) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } if (*(u32 *)kmap(page) != VMCS12_REVISION) { kunmap(page); kvm_release_page_clean(page); nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } kunmap(page); kvm_release_page_clean(page); vmx->nested.vmxon_ptr = vmptr; ret = enter_vmx_operation(vcpu); if (ret) return ret; nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); }
169,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 newque(struct ipc_namespace *ns, struct ipc_params *params) { struct msg_queue *msq; int id, retval; key_t key = params->key; int msgflg = params->flg; msq = ipc_rcu_alloc(sizeof(*msq)); if (!msq) return -ENOMEM; msq->q_perm.mode = msgflg & S_IRWXUGO; msq->q_perm.key = key; msq->q_perm.security = NULL; retval = security_msg_queue_alloc(msq); if (retval) { ipc_rcu_putref(msq, ipc_rcu_free); return retval; } /* ipc_addid() locks msq upon success. */ id = ipc_addid(&msg_ids(ns), &msq->q_perm, ns->msg_ctlmni); if (id < 0) { ipc_rcu_putref(msq, msg_rcu_free); return id; } msq->q_stime = msq->q_rtime = 0; msq->q_ctime = get_seconds(); msq->q_cbytes = msq->q_qnum = 0; msq->q_qbytes = ns->msg_ctlmnb; msq->q_lspid = msq->q_lrpid = 0; INIT_LIST_HEAD(&msq->q_messages); INIT_LIST_HEAD(&msq->q_receivers); INIT_LIST_HEAD(&msq->q_senders); ipc_unlock_object(&msq->q_perm); rcu_read_unlock(); return msq->q_perm.id; } Commit Message: Initialize msg/shm IPC objects before doing ipc_addid() As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before having initialized the IPC object state. Yes, we initialize the IPC object in a locked state, but with all the lockless RCU lookup work, that IPC object lock no longer means that the state cannot be seen. We already did this for the IPC semaphore code (see commit e8577d1f0329: "ipc/sem.c: fully initialize sem_array before making it visible") but we clearly forgot about msg and shm. Reported-by: Dmitry Vyukov <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static int newque(struct ipc_namespace *ns, struct ipc_params *params) { struct msg_queue *msq; int id, retval; key_t key = params->key; int msgflg = params->flg; msq = ipc_rcu_alloc(sizeof(*msq)); if (!msq) return -ENOMEM; msq->q_perm.mode = msgflg & S_IRWXUGO; msq->q_perm.key = key; msq->q_perm.security = NULL; retval = security_msg_queue_alloc(msq); if (retval) { ipc_rcu_putref(msq, ipc_rcu_free); return retval; } msq->q_stime = msq->q_rtime = 0; msq->q_ctime = get_seconds(); msq->q_cbytes = msq->q_qnum = 0; msq->q_qbytes = ns->msg_ctlmnb; msq->q_lspid = msq->q_lrpid = 0; INIT_LIST_HEAD(&msq->q_messages); INIT_LIST_HEAD(&msq->q_receivers); INIT_LIST_HEAD(&msq->q_senders); /* ipc_addid() locks msq upon success. */ id = ipc_addid(&msg_ids(ns), &msq->q_perm, ns->msg_ctlmni); if (id < 0) { ipc_rcu_putref(msq, msg_rcu_free); return id; } ipc_unlock_object(&msq->q_perm); rcu_read_unlock(); return msq->q_perm.id; }
166,578
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BufferMeta(const sp<GraphicBuffer> &graphicBuffer) : mGraphicBuffer(graphicBuffer), mIsBackup(false) { } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
BufferMeta(const sp<GraphicBuffer> &graphicBuffer) BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mIsBackup(false), mPortIndex(portIndex) { }
173,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rsRetVal createSocket(instanceConf_t* info, void** sock) { int rv; sublist* sub; *sock = zsocket_new(s_context, info->type); if (!sock) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zsocket_new failed: %s, for type %d", zmq_strerror(errno),info->type); /* DK: invalid params seems right here */ return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: socket of type %d created successfully\n", info->type) /* Set options *before* the connect/bind. */ if (info->identity) zsocket_set_identity(*sock, info->identity); if (info->sndBuf > -1) zsocket_set_sndbuf(*sock, info->sndBuf); if (info->rcvBuf > -1) zsocket_set_rcvbuf(*sock, info->rcvBuf); if (info->linger > -1) zsocket_set_linger(*sock, info->linger); if (info->backlog > -1) zsocket_set_backlog(*sock, info->backlog); if (info->sndTimeout > -1) zsocket_set_sndtimeo(*sock, info->sndTimeout); if (info->rcvTimeout > -1) zsocket_set_rcvtimeo(*sock, info->rcvTimeout); if (info->maxMsgSize > -1) zsocket_set_maxmsgsize(*sock, info->maxMsgSize); if (info->rate > -1) zsocket_set_rate(*sock, info->rate); if (info->recoveryIVL > -1) zsocket_set_recovery_ivl(*sock, info->recoveryIVL); if (info->multicastHops > -1) zsocket_set_multicast_hops(*sock, info->multicastHops); if (info->reconnectIVL > -1) zsocket_set_reconnect_ivl(*sock, info->reconnectIVL); if (info->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(*sock, info->reconnectIVLMax); if (info->ipv4Only > -1) zsocket_set_ipv4only(*sock, info->ipv4Only); if (info->affinity > -1) zsocket_set_affinity(*sock, info->affinity); if (info->sndHWM > -1 ) zsocket_set_sndhwm(*sock, info->sndHWM); if (info->rcvHWM > -1 ) zsocket_set_rcvhwm(*sock, info->rcvHWM); /* Set subscriptions.*/ if (info->type == ZMQ_SUB) { for(sub = info->subscriptions; sub!=NULL; sub=sub->next) { zsocket_set_subscribe(*sock, sub->subscribe); } } /* Do the bind/connect... */ if (info->action==ACTION_CONNECT) { rv = zsocket_connect(*sock, info->description); if (rv == -1) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zmq_connect using %s failed: %s", info->description, zmq_strerror(errno)); return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: connect for %s successful\n",info->description); } else { rv = zsocket_bind(*sock, info->description); if (rv == -1) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zmq_bind using %s failed: %s", info->description, zmq_strerror(errno)); return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: bind for %s successful\n",info->description); } return RS_RET_OK; } Commit Message: Merge pull request #1565 from Whissi/fix-format-security-issue-in-zmq-modules Fix format security issue in zmq3 modules CWE ID: CWE-134
static rsRetVal createSocket(instanceConf_t* info, void** sock) { int rv; sublist* sub; *sock = zsocket_new(s_context, info->type); if (!sock) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zsocket_new failed: %s, for type %d", zmq_strerror(errno),info->type); /* DK: invalid params seems right here */ return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: socket of type %d created successfully\n", info->type) /* Set options *before* the connect/bind. */ if (info->identity) zsocket_set_identity(*sock, info->identity); if (info->sndBuf > -1) zsocket_set_sndbuf(*sock, info->sndBuf); if (info->rcvBuf > -1) zsocket_set_rcvbuf(*sock, info->rcvBuf); if (info->linger > -1) zsocket_set_linger(*sock, info->linger); if (info->backlog > -1) zsocket_set_backlog(*sock, info->backlog); if (info->sndTimeout > -1) zsocket_set_sndtimeo(*sock, info->sndTimeout); if (info->rcvTimeout > -1) zsocket_set_rcvtimeo(*sock, info->rcvTimeout); if (info->maxMsgSize > -1) zsocket_set_maxmsgsize(*sock, info->maxMsgSize); if (info->rate > -1) zsocket_set_rate(*sock, info->rate); if (info->recoveryIVL > -1) zsocket_set_recovery_ivl(*sock, info->recoveryIVL); if (info->multicastHops > -1) zsocket_set_multicast_hops(*sock, info->multicastHops); if (info->reconnectIVL > -1) zsocket_set_reconnect_ivl(*sock, info->reconnectIVL); if (info->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(*sock, info->reconnectIVLMax); if (info->ipv4Only > -1) zsocket_set_ipv4only(*sock, info->ipv4Only); if (info->affinity > -1) zsocket_set_affinity(*sock, info->affinity); if (info->sndHWM > -1 ) zsocket_set_sndhwm(*sock, info->sndHWM); if (info->rcvHWM > -1 ) zsocket_set_rcvhwm(*sock, info->rcvHWM); /* Set subscriptions.*/ if (info->type == ZMQ_SUB) { for(sub = info->subscriptions; sub!=NULL; sub=sub->next) { zsocket_set_subscribe(*sock, sub->subscribe); } } /* Do the bind/connect... */ if (info->action==ACTION_CONNECT) { rv = zsocket_connect(*sock, "%s", info->description); if (rv == -1) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zmq_connect using %s failed: %s", info->description, zmq_strerror(errno)); return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: connect for %s successful\n",info->description); } else { rv = zsocket_bind(*sock, "%s", info->description); if (rv == -1) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zmq_bind using %s failed: %s", info->description, zmq_strerror(errno)); return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: bind for %s successful\n",info->description); } return RS_RET_OK; }
167,983
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) { if (ComputeVisibleSelectionInDOMTree().IsNone()) return; SetSelection( SelectionInDOMTree::Builder( GetGranularityStrategy()->UpdateExtent(contents_point, frame_)) .SetIsHandleVisible(true) .Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetDoNotClearStrategy(true) .SetSetSelectionBy(SetSelectionBy::kUser) .Build()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) { if (ComputeVisibleSelectionInDOMTree().IsNone()) return; SetSelection( SelectionInDOMTree::Builder( GetGranularityStrategy()->UpdateExtent(contents_point, frame_)) .Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetDoNotClearStrategy(true) .SetSetSelectionBy(SetSelectionBy::kUser) .SetShouldShowHandle(true) .Build()); }
171,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long madvise_remove(struct vm_area_struct *vma, struct vm_area_struct **prev, unsigned long start, unsigned long end) { loff_t offset; int error; *prev = NULL; /* tell sys_madvise we drop mmap_sem */ if (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB)) return -EINVAL; if (!vma->vm_file || !vma->vm_file->f_mapping || !vma->vm_file->f_mapping->host) { return -EINVAL; } if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE)) return -EACCES; offset = (loff_t)(start - vma->vm_start) + ((loff_t)vma->vm_pgoff << PAGE_SHIFT); /* filesystem's fallocate may need to take i_mutex */ up_read(&current->mm->mmap_sem); error = do_fallocate(vma->vm_file, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, end - start); down_read(&current->mm->mmap_sem); return error; } Commit Message: mm: Hold a file reference in madvise_remove Otherwise the code races with munmap (causing a use-after-free of the vma) or with close (causing a use-after-free of the struct file). The bug was introduced by commit 90ed52ebe481 ("[PATCH] holepunch: fix mmap_sem i_mutex deadlock") Cc: Hugh Dickins <[email protected]> Cc: Miklos Szeredi <[email protected]> Cc: Badari Pulavarty <[email protected]> Cc: Nick Piggin <[email protected]> Cc: [email protected] Signed-off-by: Andy Lutomirski <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static long madvise_remove(struct vm_area_struct *vma, struct vm_area_struct **prev, unsigned long start, unsigned long end) { loff_t offset; int error; struct file *f; *prev = NULL; /* tell sys_madvise we drop mmap_sem */ if (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB)) return -EINVAL; f = vma->vm_file; if (!f || !f->f_mapping || !f->f_mapping->host) { return -EINVAL; } if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE)) return -EACCES; offset = (loff_t)(start - vma->vm_start) + ((loff_t)vma->vm_pgoff << PAGE_SHIFT); /* * Filesystem's fallocate may need to take i_mutex. We need to * explicitly grab a reference because the vma (and hence the * vma's reference to the file) can go away as soon as we drop * mmap_sem. */ get_file(f); up_read(&current->mm->mmap_sem); error = do_fallocate(f, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, end - start); fput(f); down_read(&current->mm->mmap_sem); return error; }
165,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr, bool *set_rtrn) { bool ok = false; const char *ident; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) { log_err(ctx, "Found constant of type %s where boolean was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *set_rtrn = expr->boolean.set; return true; case EXPR_IDENT: ident = xkb_atom_text(ctx, expr->ident.ident); if (ident) { if (istreq(ident, "true") || istreq(ident, "yes") || istreq(ident, "on")) { *set_rtrn = true; return true; } else if (istreq(ident, "false") || istreq(ident, "no") || istreq(ident, "off")) { *set_rtrn = false; return true; } } log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident); return false; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_INVERT: case EXPR_NOT: ok = ExprResolveBoolean(ctx, expr, set_rtrn); if (ok) *set_rtrn = !*set_rtrn; return ok; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: case EXPR_ASSIGN: case EXPR_NEGATE: case EXPR_UNARY_PLUS: log_err(ctx, "%s of boolean values not permitted\n", expr_op_type_to_string(expr->expr.op)); break; default: log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n", expr->expr.op); break; } return false; } Commit Message: xkbcomp: fix stack overflow when evaluating boolean negation The expression evaluator would go into an infinite recursion when evaluating something like this as a boolean: `!True`. Instead of recursing to just `True` and negating, it recursed to `!True` itself again. Bug inherited from xkbcomp. Caught with the afl fuzzer. Signed-off-by: Ran Benita <[email protected]> CWE ID: CWE-400
ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr, bool *set_rtrn) { bool ok = false; const char *ident; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) { log_err(ctx, "Found constant of type %s where boolean was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *set_rtrn = expr->boolean.set; return true; case EXPR_IDENT: ident = xkb_atom_text(ctx, expr->ident.ident); if (ident) { if (istreq(ident, "true") || istreq(ident, "yes") || istreq(ident, "on")) { *set_rtrn = true; return true; } else if (istreq(ident, "false") || istreq(ident, "no") || istreq(ident, "off")) { *set_rtrn = false; return true; } } log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident); return false; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_INVERT: case EXPR_NOT: ok = ExprResolveBoolean(ctx, expr->unary.child, set_rtrn); if (ok) *set_rtrn = !*set_rtrn; return ok; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: case EXPR_ASSIGN: case EXPR_NEGATE: case EXPR_UNARY_PLUS: log_err(ctx, "%s of boolean values not permitted\n", expr_op_type_to_string(expr->expr.op)); break; default: log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n", expr->expr.op); break; } return false; }
169,096