instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FrameworkListener::init(const char *socketName UNUSED, bool withSeq) { mCommands = new FrameworkCommandCollection(); errorRate = 0; mCommandCount = 0; mWithSeq = withSeq; } Commit Message: Fix vold vulnerability in FrameworkListener Modify FrameworkListener to ignore commands that exceed the maximum buffer length and send an error message. Bug: 29831647 Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950 Signed-off-by: Connor O'Brien <[email protected]> (cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a) (cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e) CWE ID: CWE-264
void FrameworkListener::init(const char *socketName UNUSED, bool withSeq) { mCommands = new FrameworkCommandCollection(); errorRate = 0; mCommandCount = 0; mWithSeq = withSeq; mSkipToNextNullByte = false; }
173,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ShellWindowFrameView::ButtonPressed(views::Button* sender, const views::Event& event) { if (sender == close_button_) frame_->Close(); } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 [email protected] Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
void ShellWindowFrameView::ButtonPressed(views::Button* sender, const views::Event& event) { DCHECK(!is_frameless_); if (sender == close_button_) frame_->Close(); }
170,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = (const char *)sst->sst_tab; const char *e = ((const char *)p) + tail; (void)&line; if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len)); errno = EFTYPE; return -1; } Commit Message: Use the proper sector size when checking stream offsets (Francisco Alonso and Jan Kaluza at RedHat) CWE ID: CWE-189
cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = (const char *)sst->sst_tab; const char *e = ((const char *)p) + tail; size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); (void)&line; if (e >= b && (size_t)(e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; }
166,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: AccessibilityButtonState AXObject::checkboxOrRadioValue() const { const AtomicString& checkedAttribute = getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked); if (equalIgnoringCase(checkedAttribute, "true")) return ButtonStateOn; if (equalIgnoringCase(checkedAttribute, "mixed")) { AccessibilityRole role = ariaRoleAttribute(); if (role == CheckBoxRole || role == MenuItemCheckBoxRole) return ButtonStateMixed; } return ButtonStateOff; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
AccessibilityButtonState AXObject::checkboxOrRadioValue() const { const AtomicString& checkedAttribute = getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked); if (equalIgnoringASCIICase(checkedAttribute, "true")) return ButtonStateOn; if (equalIgnoringASCIICase(checkedAttribute, "mixed")) { AccessibilityRole role = ariaRoleAttribute(); if (role == CheckBoxRole || role == MenuItemCheckBoxRole) return ButtonStateMixed; } return ButtonStateOff; }
171,924
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cib_tls_close(cib_t * cib) { cib_remote_opaque_t *private = cib->variant_opaque; shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */ shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */ close(private->command.socket); close(private->callback.socket); #ifdef HAVE_GNUTLS_GNUTLS_H if (private->command.encrypted) { gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->command.session)); gnutls_free(private->command.session); gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->callback.session)); gnutls_free(private->callback.session); gnutls_anon_free_client_credentials(anon_cred_c); gnutls_global_deinit(); } #endif return 0; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_tls_close(cib_t * cib) { cib_remote_opaque_t *private = cib->variant_opaque; #ifdef HAVE_GNUTLS_GNUTLS_H if (private->command.encrypted) { if (private->command.session) { gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->command.session)); gnutls_free(private->command.session); } if (private->callback.session) { gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->callback.session)); gnutls_free(private->callback.session); } private->command.session = NULL; private->callback.session = NULL; if (remote_gnutls_credentials_init) { gnutls_anon_free_client_credentials(anon_cred_c); gnutls_global_deinit(); remote_gnutls_credentials_init = FALSE; } } #endif if (private->command.socket) { shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */ close(private->command.socket); } if (private->callback.socket) { shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */ close(private->callback.socket); } private->command.socket = 0; private->callback.socket = 0; free(private->command.recv_buf); free(private->callback.recv_buf); private->command.recv_buf = NULL; private->callback.recv_buf = NULL; return 0; }
166,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents); TabAttachedImpl(new_contents->web_contents()); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents->web_contents()); TabAttachedImpl(new_contents->web_contents()); }
171,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }
170,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static PHP_FUNCTION(gzopen) { char *filename; char *mode; int filename_len, mode_len; int flags = REPORT_ERRORS; php_stream *stream; long use_include_path = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) { return; } if (use_include_path) { flags |= USE_PATH; } stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC); if (!stream) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); } Commit Message: CWE ID: CWE-254
static PHP_FUNCTION(gzopen) { char *filename; char *mode; int filename_len, mode_len; int flags = REPORT_ERRORS; php_stream *stream; long use_include_path = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) { return; } if (use_include_path) { flags |= USE_PATH; } stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC); if (!stream) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); }
165,319
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BrowserContext* SharedWorkerDevToolsAgentHost::GetBrowserContext() { RenderProcessHost* rph = GetProcess(); return rph ? rph->GetBrowserContext() : nullptr; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
BrowserContext* SharedWorkerDevToolsAgentHost::GetBrowserContext() { if (!worker_host_) return nullptr; RenderProcessHost* rph = RenderProcessHost::FromID(worker_host_->process_id()); return rph ? rph->GetBrowserContext() : nullptr; }
172,788
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) { ut32 i = 0; while (buf + i < max && buf[i] != eoc) { i += 1; } if (buf[i] != eoc) { return 0; } if (offset) { *offset += i + 1; } return i + 1; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125
static size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) { ut32 i = 0; while (buf + i < max && buf[i] != eoc) { i++; } if (buf[i] != eoc) { return 0; } if (offset) { *offset += i + 1; } return i + 1; }
168,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: get_next_file(FILE *VFile, char *ptr) { char *ret; ret = fgets(ptr, PATH_MAX, VFile); if (!ret) return NULL; if (ptr[strlen(ptr) - 1] == '\n') ptr[strlen(ptr) - 1] = '\0'; return ret; } Commit Message: (for 4.9.3) CVE-2018-14879/fix -V to fail invalid input safely get_next_file() did not check the return value of strlen() and underflowed an array index if the line read by fgets() from the file started with \0. This caused an out-of-bounds read and could cause a write. Add the missing check. This vulnerability was discovered by Brian Carpenter & Geeknik Labs. CWE ID: CWE-120
get_next_file(FILE *VFile, char *ptr) { char *ret; size_t len; ret = fgets(ptr, PATH_MAX, VFile); if (!ret) return NULL; len = strlen (ptr); if (len > 0 && ptr[len - 1] == '\n') ptr[len - 1] = '\0'; return ret; }
169,835
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int a2dp_command(struct a2dp_stream_common *common, char cmd) { char ack; DEBUG("A2DP COMMAND %s", dump_a2dp_ctrl_event(cmd)); /* send command */ if (send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL) == -1) { ERROR("cmd failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } /* wait for ack byte */ if (a2dp_ctrl_receive(common, &ack, 1) < 0) return -1; DEBUG("A2DP COMMAND %s DONE STATUS %d", dump_a2dp_ctrl_event(cmd), ack); if (ack == A2DP_CTRL_ACK_INCALL_FAILURE) return ack; if (ack != A2DP_CTRL_ACK_SUCCESS) return -1; return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int a2dp_command(struct a2dp_stream_common *common, char cmd) { char ack; DEBUG("A2DP COMMAND %s", dump_a2dp_ctrl_event(cmd)); /* send command */ if (TEMP_FAILURE_RETRY(send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL)) == -1) { ERROR("cmd failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } /* wait for ack byte */ if (a2dp_ctrl_receive(common, &ack, 1) < 0) return -1; DEBUG("A2DP COMMAND %s DONE STATUS %d", dump_a2dp_ctrl_event(cmd), ack); if (ack == A2DP_CTRL_ACK_INCALL_FAILURE) return ack; if (ack != A2DP_CTRL_ACK_SUCCESS) return -1; return 0; }
173,422
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } 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
nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; if (!xdr_argsize_check(rqstp, p)) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }
168,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int mpeg4video_probe(AVProbeData *probe_packet) { uint32_t temp_buffer = -1; int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0; int i; for (i = 0; i < probe_packet->buf_size; i++) { temp_buffer = (temp_buffer << 8) + probe_packet->buf[i]; if ((temp_buffer & 0xffffff00) != 0x100) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer < 0x120) VO++; else if (temp_buffer < 0x130) VOL++; else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++; } if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0) return AVPROBE_SCORE_EXTENSION; return 0; } Commit Message: m4vdec: Check for non-startcode 00 00 00 sequences in probe This makes the m4v detection less trigger-happy. Bug-Id: 949 Signed-off-by: Diego Biurrun <[email protected]> CWE ID: CWE-476
static int mpeg4video_probe(AVProbeData *probe_packet) { uint32_t temp_buffer = -1; int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0; int i; for (i = 0; i < probe_packet->buf_size; i++) { temp_buffer = (temp_buffer << 8) + probe_packet->buf[i]; if (temp_buffer & 0xfffffe00) continue; if (temp_buffer < 2) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer >= 0x100 && temp_buffer < 0x120) VO++; else if (temp_buffer >= 0x120 && temp_buffer < 0x130) VOL++; else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++; } if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0) return AVPROBE_SCORE_EXTENSION; return 0; }
168,768
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; for (i = 1; i <= SYSTEM_ID_LEN; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } Commit Message: CVE-2017-13035/Properly handle IS-IS IDs shorter than a system ID (MAC address). Some of them are variable-length, with a field giving the total length, and therefore they can be shorter than 6 octets. If one is, don't run past the end. 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
isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; int sysid_len; sysid_len = SYSTEM_ID_LEN; if (sysid_len > id_len) sysid_len = id_len; for (i = 1; i <= sysid_len; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); }
167,848
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) { static PNG_CONST char short_months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (png_ptr == NULL) return (NULL); if (png_ptr->time_buffer == NULL) { png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* png_sizeof(char))); } #ifdef _WIN32_WCE { wchar_t time_buf[29]; wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"), ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29, NULL, NULL); } #else #ifdef USE_FAR_KEYWORD { char near_time_buf[29]; png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); png_memcpy(png_ptr->time_buffer, near_time_buf, 29*png_sizeof(char)); } #else png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); #endif #endif /* _WIN32_WCE */ return ((png_charp)png_ptr->time_buffer); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) { static PNG_CONST char short_months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (png_ptr == NULL) return (NULL); if (png_ptr->time_buffer == NULL) { png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* png_sizeof(char))); } #ifdef _WIN32_WCE { wchar_t time_buf[29]; wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"), ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29, NULL, NULL); } #else #ifdef USE_FAR_KEYWORD { char near_time_buf[29]; png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); png_memcpy(png_ptr->time_buffer, near_time_buf, 29*png_sizeof(char)); } #else png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); #endif #endif /* _WIN32_WCE */ return ((png_charp)png_ptr->time_buffer); }
172,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: mkvparser::IMkvReader::~IMkvReader() { //// Disable MSVC warnings that suggest making code non-portable. } 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
mkvparser::IMkvReader::~IMkvReader() #ifdef _MSC_VER //// Disable MSVC warnings that suggest making code non-portable. #pragma warning(disable : 4996) #endif mkvparser::IMkvReader::~IMkvReader() {} void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) { major = 1; minor = 0; build = 0; revision = 28; }
174,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); }
165,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PrintPreviewMessageHandler::PrintPreviewMessageHandler( WebContents* web_contents) : content::WebContentsObserver(web_contents) { DCHECK(web_contents); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
PrintPreviewMessageHandler::PrintPreviewMessageHandler( WebContents* web_contents) : content::WebContentsObserver(web_contents), weak_ptr_factory_(this) { DCHECK(web_contents); }
171,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; } Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created. This could happen if there are IDB objects that survive the call to didStopWorkerRunLoop. BUG=121734 TEST= Review URL: http://codereview.chromium.org/9999035 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get() == HAS_BEEN_DELETED) { NOTREACHED() << "Re-instantiating TLS IndexedDBDispatcher."; g_idb_dispatcher_tls.Pointer()->Set(NULL); } if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; }
171,039
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int xt_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct xt_standard_target) != next_offset) return -EINVAL; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-264
int xt_check_entry_offsets(const void *base, const char *elems, unsigned int target_offset, unsigned int next_offset) { long size_of_base_struct = elems - (const char *)base; const struct xt_entry_target *t; const char *e = base; /* target start is within the ip/ip6/arpt_entry struct */ if (target_offset < size_of_base_struct) return -EINVAL; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct xt_standard_target) != next_offset) return -EINVAL; return 0; }
167,221
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Block::IsInvisible() const { return bool(int(m_flags & 0x08) != 0); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Block::IsInvisible() const const Block::Frame& Block::GetFrame(int idx) const { assert(idx >= 0); assert(idx < m_frame_count); const Frame& f = m_frames[idx]; assert(f.pos > 0); assert(f.len > 0); return f; }
174,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer overflow on generation of PixarLog / LUV compressed files, with ColorMap, TransferFunction attached and nasty plays with bitspersample. The fix for LUV has not been tested, but suffers from the same kind of issue of PixarLog. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604 CWE ID: CWE-125
PixarLogClose(TIFF* tif) { PixarLogState* sp = (PixarLogState*) tif->tif_data; TIFFDirectory *td = &tif->tif_dir; assert(sp != 0); /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ if (sp->state&PLSTATE_INIT) { /* We test the state to avoid an issue such as in * http://bugzilla.maptools.org/show_bug.cgi?id=2604 * What appends in that case is that the bitspersample is 1 and * a TransferFunction is set. The size of the TransferFunction * depends on 1<<bitspersample. So if we increase it, an access * out of the buffer will happen at directory flushing. * Another option would be to clear those targs. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } }
168,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int snmp_version(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { if (*(unsigned char *)data > 1) return -ENOTSUPP; return 1; } Commit Message: netfilter: nf_nat_snmp_basic: add missing length checks in ASN.1 cbs The generic ASN.1 decoder infrastructure doesn't guarantee that callbacks will get as much data as they expect; callbacks have to check the `datalen` parameter before looking at `data`. Make sure that snmp_version() and snmp_helper() don't read/write beyond the end of the packet data. (Also move the assignment to `pdata` down below the check to make it clear that it isn't necessarily a pointer we can use before the `datalen` check.) Fixes: cc2d58634e0f ("netfilter: nf_nat_snmp_basic: use asn1 decoder library") Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-129
int snmp_version(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { if (datalen != 1) return -EINVAL; if (*(unsigned char *)data > 1) return -ENOTSUPP; return 1; }
169,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc) { struct ib_cqe *cqe = wc->wr_cqe; struct svc_rdma_op_ctxt *ctxt; svc_rdma_send_wc_common_put(cq, wc, "write"); ctxt = container_of(cqe, struct svc_rdma_op_ctxt, cqe); svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 0); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
void svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc)
168,184
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MockPrinter::UpdateSettings(int cookie, PrintMsg_PrintPages_Params* params, const std::vector<int>& pages) { EXPECT_EQ(document_cookie_, cookie); params->Reset(); params->pages = pages; SetPrintParams(&(params->params)); printer_status_ = PRINTER_PRINTING; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MockPrinter::UpdateSettings(int cookie, PrintMsg_PrintPages_Params* params, const std::vector<int>& pages) { if (document_cookie_ == -1) { document_cookie_ = CreateDocumentCookie(); } params->Reset(); params->pages = pages; SetPrintParams(&(params->params)); printer_status_ = PRINTER_PRINTING; }
170,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GaiaOAuthClient::Core::OnUserInfoFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { std::string email; if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kEmailValue, &email); } } if (email.empty()) { delegate_->OnNetworkError(response_code); } else { delegate_->OnRefreshTokenResponse( email, access_token_, expires_in_seconds_); } } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::OnUserInfoFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); url_fetcher_type_ = URL_FETCHER_NONE; std::string email; if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kEmailValue, &email); } } if (email.empty()) { delegate_->OnNetworkError(response_code); } else { delegate_->OnRefreshTokenResponse( email, access_token_, expires_in_seconds_); } }
170,808
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_DH DH *dh_clnt = NULL; const BIGNUM *pub_key; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); dh_clnt = EVP_PKEY_get0_DH(ckey); if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); EVP_PKEY_free(ckey); return 0; } /* send off the data */ DH_get0_key(dh_clnt, &pub_key, NULL); *len = BN_num_bytes(pub_key); s2n(*len, *p); BN_bn2bin(pub_key, *p); *len += 2; EVP_PKEY_free(ckey); return 1; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif } Commit Message: Fix missing NULL checks in CKE processing Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-476
static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_DH DH *dh_clnt = NULL; const BIGNUM *pub_key; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); if (ckey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); return 0; } dh_clnt = EVP_PKEY_get0_DH(ckey); if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); EVP_PKEY_free(ckey); return 0; } /* send off the data */ DH_get0_key(dh_clnt, &pub_key, NULL); *len = BN_num_bytes(pub_key); s2n(*len, *p); BN_bn2bin(pub_key, *p); *len += 2; EVP_PKEY_free(ckey); return 1; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif }
168,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx) { u32 exit_intr_info; if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)) return; vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO); exit_intr_info = vmx->exit_intr_info; /* Handle machine checks before interrupts are enabled */ if (is_machine_check(exit_intr_info)) kvm_machine_check(); /* We need to handle NMIs before interrupts are enabled */ if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR && (exit_intr_info & INTR_INFO_VALID_MASK)) { kvm_before_handle_nmi(&vmx->vcpu); asm("int $2"); kvm_after_handle_nmi(&vmx->vcpu); } } Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF) When L2 exits to L0 due to "exception or NMI", software exceptions (#BP and #OF) for which L1 has requested an intercept should be handled by L1 rather than L0. Previously, only hardware exceptions were forwarded to L1. Signed-off-by: Jim Mattson <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-388
static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx) { u32 exit_intr_info; if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)) return; vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO); exit_intr_info = vmx->exit_intr_info; /* Handle machine checks before interrupts are enabled */ if (is_machine_check(exit_intr_info)) kvm_machine_check(); /* We need to handle NMIs before interrupts are enabled */ if (is_nmi(exit_intr_info)) { kvm_before_handle_nmi(&vmx->vcpu); asm("int $2"); kvm_after_handle_nmi(&vmx->vcpu); } }
166,857
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void swizzleImageData(unsigned char* srcAddr, size_t height, size_t bytesPerRow, bool flipY) { if (flipY) { for (size_t i = 0; i < height / 2; i++) { size_t topRowStartPosition = i * bytesPerRow; size_t bottomRowStartPosition = (height - 1 - i) * bytesPerRow; if (kN32_SkColorType == kBGRA_8888_SkColorType) { // needs to swizzle for (size_t j = 0; j < bytesPerRow; j += 4) { std::swap(srcAddr[topRowStartPosition + j], srcAddr[bottomRowStartPosition + j + 2]); std::swap(srcAddr[topRowStartPosition + j + 1], srcAddr[bottomRowStartPosition + j + 1]); std::swap(srcAddr[topRowStartPosition + j + 2], srcAddr[bottomRowStartPosition + j]); std::swap(srcAddr[topRowStartPosition + j + 3], srcAddr[bottomRowStartPosition + j + 3]); } } else { std::swap_ranges(srcAddr + topRowStartPosition, srcAddr + topRowStartPosition + bytesPerRow, srcAddr + bottomRowStartPosition); } } } else { if (kN32_SkColorType == kBGRA_8888_SkColorType) // needs to swizzle for (size_t i = 0; i < height * bytesPerRow; i += 4) std::swap(srcAddr[i], srcAddr[i + 2]); } } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} CWE ID: CWE-787
static void swizzleImageData(unsigned char* srcAddr, unsigned height, unsigned bytesPerRow, bool flipY) { if (flipY) { for (unsigned i = 0; i < height / 2; i++) { unsigned topRowStartPosition = i * bytesPerRow; unsigned bottomRowStartPosition = (height - 1 - i) * bytesPerRow; if (kN32_SkColorType == kBGRA_8888_SkColorType) { // needs to swizzle for (unsigned j = 0; j < bytesPerRow; j += 4) { std::swap(srcAddr[topRowStartPosition + j], srcAddr[bottomRowStartPosition + j + 2]); std::swap(srcAddr[topRowStartPosition + j + 1], srcAddr[bottomRowStartPosition + j + 1]); std::swap(srcAddr[topRowStartPosition + j + 2], srcAddr[bottomRowStartPosition + j]); std::swap(srcAddr[topRowStartPosition + j + 3], srcAddr[bottomRowStartPosition + j + 3]); } } else { std::swap_ranges(srcAddr + topRowStartPosition, srcAddr + topRowStartPosition + bytesPerRow, srcAddr + bottomRowStartPosition); } } } else { if (kN32_SkColorType == kBGRA_8888_SkColorType) // needs to swizzle for (unsigned i = 0; i < height * bytesPerRow; i += 4) std::swap(srcAddr[i], srcAddr[i + 2]); } }
172,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChromeDownloadDelegate::RequestHTTPGetDownload( const std::string& url, const std::string& user_agent, const std::string& content_disposition, const std::string& mime_type, const std::string& cookie, const std::string& referer, const base::string16& file_name, int64_t content_length, bool has_user_gesture, bool must_download) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jurl = ConvertUTF8ToJavaString(env, url); ScopedJavaLocalRef<jstring> juser_agent = ConvertUTF8ToJavaString(env, user_agent); ScopedJavaLocalRef<jstring> jcontent_disposition = ConvertUTF8ToJavaString(env, content_disposition); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); ScopedJavaLocalRef<jstring> jcookie = ConvertUTF8ToJavaString(env, cookie); ScopedJavaLocalRef<jstring> jreferer = ConvertUTF8ToJavaString(env, referer); ScopedJavaLocalRef<jstring> jfilename = base::android::ConvertUTF16ToJavaString(env, file_name); Java_ChromeDownloadDelegate_requestHttpGetDownload( env, java_ref_, jurl, juser_agent, jcontent_disposition, jmime_type, jcookie, jreferer, has_user_gesture, jfilename, content_length, must_download); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void ChromeDownloadDelegate::RequestHTTPGetDownload(
171,880
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } copy_file_as_user(src, dest, getuid(), getgid(), 0644); fs_logger2("clone", dest); return 1; // file copied } return 0; } Commit Message: security fix CWE ID: CWE-269
static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; // create an empty file as root, and change ownership to user FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } copy_file_as_user(src, dest, getuid(), getgid(), 0644); fs_logger2("clone", dest); return 1; // file copied } return 0; }
168,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo( int child_id, int render_view_route_id, int render_frame_route_id, PreviewsState previews_state, bool download, ResourceContext* context) { return new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id), render_view_route_id, -1, // frame_tree_node_id ChildProcessHost::kInvalidUniqueID, // plugin_child_id MakeRequestID(), render_frame_route_id, false, // is_main_frame {}, // fetch_window_id RESOURCE_TYPE_SUB_RESOURCE, ui::PAGE_TRANSITION_LINK, download, // is_download false, // is_stream download, // allow_download false, // has_user_gesture false, // enable_load_timing false, // enable_upload_progress false, // do_not_prompt_for_login false, // keepalive network::mojom::ReferrerPolicy::kDefault, false, // is_prerendering context, false, // report_raw_headers false, // report_security_info true, // is_async previews_state, // previews_state nullptr, // body false); // initiated_in_secure_context } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo( int child_id, int render_view_route_id, int render_frame_route_id, int frame_tree_node_id, PreviewsState previews_state, bool download, ResourceContext* context) { return new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id), render_view_route_id, frame_tree_node_id, ChildProcessHost::kInvalidUniqueID, // plugin_child_id MakeRequestID(), render_frame_route_id, false, // is_main_frame {}, // fetch_window_id RESOURCE_TYPE_SUB_RESOURCE, ui::PAGE_TRANSITION_LINK, download, // is_download false, // is_stream download, // allow_download false, // has_user_gesture false, // enable_load_timing false, // enable_upload_progress false, // do_not_prompt_for_login false, // keepalive network::mojom::ReferrerPolicy::kDefault, false, // is_prerendering context, false, // report_raw_headers false, // report_security_info true, // is_async previews_state, // previews_state nullptr, // body false); // initiated_in_secure_context }
173,026
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) { if (paintingDisabled()) return; m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle()))); m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, angleSpan); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) { if (paintingDisabled()) return; m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle()))); m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, startAngle + angleSpan); }
170,427
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg) IPC_MESSAGE_HANDLER(GpuChannelMsg_Initialize, OnInitialize) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer, OnCreateOffscreenCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer, OnDestroyCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur, OnWillGpuSwitchOccur) IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled) << msg.type(); return handled; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer, OnCreateOffscreenCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer, OnDestroyCommandBuffer) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur, OnWillGpuSwitchOccur) IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled) << msg.type(); return handled; }
170,933
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ServiceWorkerHandler::ServiceWorkerHandler() : DevToolsDomainHandler(ServiceWorker::Metainfo::domainName), enabled_(false), process_(nullptr), weak_factory_(this) {} Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
ServiceWorkerHandler::ServiceWorkerHandler() : DevToolsDomainHandler(ServiceWorker::Metainfo::domainName), enabled_(false), browser_context_(nullptr), storage_partition_(nullptr), weak_factory_(this) {}
172,768
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int __init ipgre_init(void) { int err; printk(KERN_INFO "GRE over IPv4 tunneling driver\n"); if (inet_add_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) { printk(KERN_INFO "ipgre init: can't add protocol\n"); return -EAGAIN; } err = register_pernet_device(&ipgre_net_ops); if (err < 0) goto gen_device_failed; err = rtnl_link_register(&ipgre_link_ops); if (err < 0) goto rtnl_link_failed; err = rtnl_link_register(&ipgre_tap_ops); if (err < 0) goto tap_ops_failed; out: return err; tap_ops_failed: rtnl_link_unregister(&ipgre_link_ops); rtnl_link_failed: unregister_pernet_device(&ipgre_net_ops); gen_device_failed: inet_del_protocol(&ipgre_protocol, IPPROTO_GRE); goto out; } Commit Message: gre: fix netns vs proto registration ordering GRE protocol receive hook can be called right after protocol addition is done. If netns stuff is not yet initialized, we're going to oops in net_generic(). This is remotely oopsable if ip_gre is compiled as module and packet comes at unfortunate moment of module loading. Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int __init ipgre_init(void) { int err; printk(KERN_INFO "GRE over IPv4 tunneling driver\n"); err = register_pernet_device(&ipgre_net_ops); if (err < 0) return err; err = inet_add_protocol(&ipgre_protocol, IPPROTO_GRE); if (err < 0) { printk(KERN_INFO "ipgre init: can't add protocol\n"); goto add_proto_failed; } err = rtnl_link_register(&ipgre_link_ops); if (err < 0) goto rtnl_link_failed; err = rtnl_link_register(&ipgre_tap_ops); if (err < 0) goto tap_ops_failed; out: return err; tap_ops_failed: rtnl_link_unregister(&ipgre_link_ops); rtnl_link_failed: inet_del_protocol(&ipgre_protocol, IPPROTO_GRE); add_proto_failed: unregister_pernet_device(&ipgre_net_ops); goto out; }
165,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PluginChannel::~PluginChannel() { if (renderer_handle_) base::CloseProcessHandle(renderer_handle_); MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
PluginChannel::~PluginChannel() { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); }
170,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) { SetState(STATE_NORMAL); ui::MouseEvent synthetic_event( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); NotifyClick(synthetic_event); return true; } Commit Message: Custom buttons should only handle accelerators when focused. BUG=541415 Review URL: https://codereview.chromium.org/1437523005 Cr-Commit-Position: refs/heads/master@{#360130} CWE ID: CWE-254
bool CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) { // Should only handle accelerators when active. However, only top level // widgets can be active, so for child widgets check if they are focused // instead. if ((IsChildWidget() && !FocusInChildWidget()) || (!IsChildWidget() && !GetWidget()->IsActive())) { return false; } SetState(STATE_NORMAL); ui::MouseEvent synthetic_event( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); NotifyClick(synthetic_event); return true; }
172,236
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata) { struct nfs4_state *state = opendata->state; struct nfs_inode *nfsi = NFS_I(state->inode); struct nfs_delegation *delegation; int open_mode = opendata->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL); nfs4_stateid stateid; int ret = -EAGAIN; for (;;) { if (can_open_cached(state, open_mode)) { spin_lock(&state->owner->so_lock); if (can_open_cached(state, open_mode)) { update_open_stateflags(state, open_mode); spin_unlock(&state->owner->so_lock); goto out_return_state; } spin_unlock(&state->owner->so_lock); } rcu_read_lock(); delegation = rcu_dereference(nfsi->delegation); if (delegation == NULL || !can_open_delegated(delegation, open_mode)) { rcu_read_unlock(); break; } /* Save the delegation */ memcpy(stateid.data, delegation->stateid.data, sizeof(stateid.data)); rcu_read_unlock(); ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode); if (ret != 0) goto out; ret = -EAGAIN; /* Try to update the stateid using the delegation */ if (update_open_stateid(state, NULL, &stateid, open_mode)) goto out_return_state; } out: return ERR_PTR(ret); out_return_state: atomic_inc(&state->count); return state; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata) { struct nfs4_state *state = opendata->state; struct nfs_inode *nfsi = NFS_I(state->inode); struct nfs_delegation *delegation; int open_mode = opendata->o_arg.open_flags & O_EXCL; fmode_t fmode = opendata->o_arg.fmode; nfs4_stateid stateid; int ret = -EAGAIN; for (;;) { if (can_open_cached(state, fmode, open_mode)) { spin_lock(&state->owner->so_lock); if (can_open_cached(state, fmode, open_mode)) { update_open_stateflags(state, fmode); spin_unlock(&state->owner->so_lock); goto out_return_state; } spin_unlock(&state->owner->so_lock); } rcu_read_lock(); delegation = rcu_dereference(nfsi->delegation); if (delegation == NULL || !can_open_delegated(delegation, fmode)) { rcu_read_unlock(); break; } /* Save the delegation */ memcpy(stateid.data, delegation->stateid.data, sizeof(stateid.data)); rcu_read_unlock(); ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode); if (ret != 0) goto out; ret = -EAGAIN; /* Try to update the stateid using the delegation */ if (update_open_stateid(state, NULL, &stateid, fmode)) goto out_return_state; } out: return ERR_PTR(ret); out_return_state: atomic_inc(&state->count); return state; }
165,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int irssi_ssl_handshake(GIOChannel *handle) { GIOSSLChannel *chan = (GIOSSLChannel *)handle; int ret, err; X509 *cert; const char *errstr; ret = SSL_connect(chan->ssl); if (ret <= 0) { err = SSL_get_error(chan->ssl, ret); switch (err) { case SSL_ERROR_WANT_READ: return 1; case SSL_ERROR_WANT_WRITE: return 3; case SSL_ERROR_ZERO_RETURN: g_warning("SSL handshake failed: %s", "server closed connection"); return -1; case SSL_ERROR_SYSCALL: errstr = ERR_reason_error_string(ERR_get_error()); if (errstr == NULL && ret == -1) errstr = strerror(errno); g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "server closed connection unexpectedly"); return -1; default: errstr = ERR_reason_error_string(ERR_get_error()); g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "unknown SSL error"); return -1; } } cert = SSL_get_peer_certificate(chan->ssl); if (cert == NULL) { g_warning("SSL server supplied no certificate"); return -1; } ret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, cert); X509_free(cert); return ret ? 0 : -1; } Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564 CWE ID: CWE-20
int irssi_ssl_handshake(GIOChannel *handle) { GIOSSLChannel *chan = (GIOSSLChannel *)handle; int ret, err; X509 *cert; const char *errstr; ret = SSL_connect(chan->ssl); if (ret <= 0) { err = SSL_get_error(chan->ssl, ret); switch (err) { case SSL_ERROR_WANT_READ: return 1; case SSL_ERROR_WANT_WRITE: return 3; case SSL_ERROR_ZERO_RETURN: g_warning("SSL handshake failed: %s", "server closed connection"); return -1; case SSL_ERROR_SYSCALL: errstr = ERR_reason_error_string(ERR_get_error()); if (errstr == NULL && ret == -1) errstr = strerror(errno); g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "server closed connection unexpectedly"); return -1; default: errstr = ERR_reason_error_string(ERR_get_error()); g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "unknown SSL error"); return -1; } } cert = SSL_get_peer_certificate(chan->ssl); if (cert == NULL) { g_warning("SSL server supplied no certificate"); return -1; } ret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, chan->hostname, cert); X509_free(cert); return ret ? 0 : -1; }
165,517
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void update_logging() { bool should_log = module_started && (logging_enabled_via_api || stack_config->get_btsnoop_turned_on()); if (should_log == is_logging) return; is_logging = should_log; if (should_log) { btsnoop_net_open(); const char *log_path = stack_config->get_btsnoop_log_path(); if (stack_config->get_btsnoop_should_save_last()) { char last_log_path[PATH_MAX]; snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp()); if (!rename(log_path, last_log_path) && errno != ENOENT) LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno)); } logfile_fd = open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); if (logfile_fd == INVALID_FD) { LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno)); is_logging = false; return; } write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16); } else { if (logfile_fd != INVALID_FD) close(logfile_fd); logfile_fd = INVALID_FD; btsnoop_net_close(); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void update_logging() { bool should_log = module_started && (logging_enabled_via_api || stack_config->get_btsnoop_turned_on()); if (should_log == is_logging) return; is_logging = should_log; if (should_log) { btsnoop_net_open(); const char *log_path = stack_config->get_btsnoop_log_path(); if (stack_config->get_btsnoop_should_save_last()) { char last_log_path[PATH_MAX]; snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp()); if (!rename(log_path, last_log_path) && errno != ENOENT) LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno)); } logfile_fd = TEMP_FAILURE_RETRY(open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)); if (logfile_fd == INVALID_FD) { LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno)); is_logging = false; return; } TEMP_FAILURE_RETRY(write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16)); } else { if (logfile_fd != INVALID_FD) close(logfile_fd); logfile_fd = INVALID_FD; btsnoop_net_close(); } }
173,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() { if (!ContextGL()) return; ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_); } 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
void WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() { void WebGLRenderingContextBase:: DrawingBufferClientRestorePixelPackParameters() { if (!ContextGL()) return; ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_); }
172,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: wb_id(netdissect_options *ndo, const struct pkt_id *id, u_int len) { int i; const char *cp; const struct id_off *io; char c; int nid; ND_PRINT((ndo, " wb-id:")); if (len < sizeof(*id) || !ND_TTEST(*id)) return (-1); len -= sizeof(*id); ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ", EXTRACT_32BITS(&id->pi_ps.slot), ipaddr_string(ndo, &id->pi_ps.page.p_sid), EXTRACT_32BITS(&id->pi_ps.page.p_uid), EXTRACT_32BITS(&id->pi_mslot), ipaddr_string(ndo, &id->pi_mpage.p_sid), EXTRACT_32BITS(&id->pi_mpage.p_uid))); nid = EXTRACT_16BITS(&id->pi_ps.nid); len -= sizeof(*io) * nid; io = (struct id_off *)(id + 1); cp = (char *)(io + nid); if (!ND_TTEST2(cp, len)) { ND_PRINT((ndo, "\"")); fn_print(ndo, (u_char *)cp, (u_char *)cp + len); ND_PRINT((ndo, "\"")); } c = '<'; for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } if (i >= nid) { ND_PRINT((ndo, ">")); return (0); } return (-1); } Commit Message: whiteboard: fixup a few reversed tests (GH #446) This is a follow-up to commit 3a3ec26. CWE ID: CWE-20
wb_id(netdissect_options *ndo, const struct pkt_id *id, u_int len) { int i; const char *cp; const struct id_off *io; char c; int nid; ND_PRINT((ndo, " wb-id:")); if (len < sizeof(*id) || !ND_TTEST(*id)) return (-1); len -= sizeof(*id); ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ", EXTRACT_32BITS(&id->pi_ps.slot), ipaddr_string(ndo, &id->pi_ps.page.p_sid), EXTRACT_32BITS(&id->pi_ps.page.p_uid), EXTRACT_32BITS(&id->pi_mslot), ipaddr_string(ndo, &id->pi_mpage.p_sid), EXTRACT_32BITS(&id->pi_mpage.p_uid))); nid = EXTRACT_16BITS(&id->pi_ps.nid); len -= sizeof(*io) * nid; io = (struct id_off *)(id + 1); cp = (char *)(io + nid); if (ND_TTEST2(cp, len)) { ND_PRINT((ndo, "\"")); fn_print(ndo, (u_char *)cp, (u_char *)cp + len); ND_PRINT((ndo, "\"")); } c = '<'; for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } if (i >= nid) { ND_PRINT((ndo, ">")); return (0); } return (-1); }
168,892
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DrawingBuffer::RestoreAllState() { client_->DrawingBufferClientRestoreScissorTest(); client_->DrawingBufferClientRestoreMaskAndClearValues(); client_->DrawingBufferClientRestorePixelPackAlignment(); client_->DrawingBufferClientRestoreTexture2DBinding(); client_->DrawingBufferClientRestoreRenderbufferBinding(); client_->DrawingBufferClientRestoreFramebufferBinding(); client_->DrawingBufferClientRestorePixelUnpackBufferBinding(); } 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
void DrawingBuffer::RestoreAllState() { client_->DrawingBufferClientRestoreScissorTest(); client_->DrawingBufferClientRestoreMaskAndClearValues(); client_->DrawingBufferClientRestorePixelPackParameters(); client_->DrawingBufferClientRestoreTexture2DBinding(); client_->DrawingBufferClientRestoreRenderbufferBinding(); client_->DrawingBufferClientRestoreFramebufferBinding(); client_->DrawingBufferClientRestorePixelUnpackBufferBinding(); client_->DrawingBufferClientRestorePixelPackBufferBinding(); }
172,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_skcipher_setkey(private, key, keylen); } Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: [email protected] Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> CWE ID: CWE-476
static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen) { struct skcipher_tfm *tfm = private; int err; err = crypto_skcipher_setkey(tfm->skcipher, key, keylen); tfm->has_key = !err; return err; }
167,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: lookup_bytestring(netdissect_options *ndo, register const u_char *bs, const unsigned int nlen) { struct enamemem *tp; register u_int i, j, k; if (nlen >= 6) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = (bs[4] << 8) | bs[5]; } else if (nlen >= 4) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = 0; } else i = j = k = 0; tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->e_nxt) if (tp->e_addr0 == i && tp->e_addr1 == j && tp->e_addr2 == k && memcmp((const char *)bs, (const char *)(tp->e_bs), nlen) == 0) return tp; else tp = tp->e_nxt; tp->e_addr0 = i; tp->e_addr1 = j; tp->e_addr2 = k; tp->e_bs = (u_char *) calloc(1, nlen + 1); if (tp->e_bs == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); memcpy(tp->e_bs, bs, nlen); tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp)); if (tp->e_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); return tp; } Commit Message: CVE-2017-12894/In lookup_bytestring(), take the length of the byte string into account. Otherwise, if, in our search of the hash table, we come across a byte string that's shorter than the string we're looking for, we'll search past the end of the string in the hash table. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
lookup_bytestring(netdissect_options *ndo, register const u_char *bs, const unsigned int nlen) { struct bsnamemem *tp; register u_int i, j, k; if (nlen >= 6) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = (bs[4] << 8) | bs[5]; } else if (nlen >= 4) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = 0; } else i = j = k = 0; tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->bs_nxt) if (nlen == tp->bs_nbytes && tp->bs_addr0 == i && tp->bs_addr1 == j && tp->bs_addr2 == k && memcmp((const char *)bs, (const char *)(tp->bs_bytes), nlen) == 0) return tp; else tp = tp->bs_nxt; tp->bs_addr0 = i; tp->bs_addr1 = j; tp->bs_addr2 = k; tp->bs_bytes = (u_char *) calloc(1, nlen + 1); if (tp->bs_bytes == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); memcpy(tp->bs_bytes, bs, nlen); tp->bs_nbytes = nlen; tp->bs_nxt = (struct bsnamemem *)calloc(1, sizeof(*tp)); if (tp->bs_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); return tp; }
167,960
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DocumentLoader::CommitNavigation(const AtomicString& mime_type, const KURL& overriding_url) { if (state_ != kProvisional) return; if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) { SetHistoryItemStateForCommit( GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_, HistoryNavigationType::kDifferentDocument); } DCHECK_EQ(state_, kProvisional); GetFrameLoader().CommitProvisionalLoad(); if (!frame_) return; const AtomicString& encoding = GetResponse().TextEncodingName(); Document* owner_document = nullptr; if (Document::ShouldInheritSecurityOriginFromOwner(Url())) { Frame* owner_frame = frame_->Tree().Parent(); if (!owner_frame) owner_frame = frame_->Loader().Opener(); if (owner_frame && owner_frame->IsLocalFrame()) owner_document = ToLocalFrame(owner_frame)->GetDocument(); } DCHECK(frame_->GetPage()); ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing; if (!Document::ThreadedParsingEnabledForTesting()) parsing_policy = kForceSynchronousParsing; InstallNewDocument(Url(), owner_document, frame_->ShouldReuseDefaultView(Url()) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew, mime_type, encoding, InstallNewDocumentReason::kNavigation, parsing_policy, overriding_url); parser_->SetDocumentWasLoadedAsPartOfNavigation(); if (request_.WasDiscarded()) frame_->GetDocument()->SetWasDiscarded(true); frame_->GetDocument()->MaybeHandleHttpRefresh( response_.HttpHeaderField(HTTPNames::Refresh), Document::kHttpRefreshFromHeader); } 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
void DocumentLoader::CommitNavigation(const AtomicString& mime_type, const KURL& overriding_url) { if (state_ != kProvisional) return; if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) { SetHistoryItemStateForCommit( GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_, HistoryNavigationType::kDifferentDocument); } DCHECK_EQ(state_, kProvisional); GetFrameLoader().CommitProvisionalLoad(); if (!frame_) return; const AtomicString& encoding = GetResponse().TextEncodingName(); Document* owner_document = nullptr; if (Document::ShouldInheritSecurityOriginFromOwner(Url())) { Frame* owner_frame = frame_->Tree().Parent(); if (!owner_frame) owner_frame = frame_->Loader().Opener(); if (owner_frame && owner_frame->IsLocalFrame()) owner_document = ToLocalFrame(owner_frame)->GetDocument(); } DCHECK(frame_->GetPage()); ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing; if (!Document::ThreadedParsingEnabledForTesting()) parsing_policy = kForceSynchronousParsing; InstallNewDocument( Url(), owner_document, frame_->ShouldReuseDefaultView(Url(), GetContentSecurityPolicy()) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew, mime_type, encoding, InstallNewDocumentReason::kNavigation, parsing_policy, overriding_url); parser_->SetDocumentWasLoadedAsPartOfNavigation(); if (request_.WasDiscarded()) frame_->GetDocument()->SetWasDiscarded(true); frame_->GetDocument()->MaybeHandleHttpRefresh( response_.HttpHeaderField(HTTPNames::Refresh), Document::kHttpRefreshFromHeader); }
173,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DWORD WtsSessionProcessDelegate::GetExitCode() { if (!core_) return CONTROL_C_EXIT; return core_->GetExitCode(); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
DWORD WtsSessionProcessDelegate::GetExitCode() { DWORD WtsSessionProcessDelegate::GetProcessId() const { if (core_) return 0; return core_->GetProcessId(); } bool WtsSessionProcessDelegate::IsPermanentError(int failure_count) const { if (core_) return false; return core_->IsPermanentError(failure_count); }
171,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; size_t newsize; switch(option) { case PHP_STREAM_OPTION_TRUNCATE_API: switch (value) { case PHP_STREAM_TRUNCATE_SUPPORTED: return PHP_STREAM_OPTION_RETURN_OK; case PHP_STREAM_TRUNCATE_SET_SIZE: if (ms->mode & TEMP_STREAM_READONLY) { return PHP_STREAM_OPTION_RETURN_ERR; } newsize = *(size_t*)ptrparam; if (newsize <= ms->fsize) { if (newsize < ms->fpos) { ms->fpos = newsize; } } else { ms->data = erealloc(ms->data, newsize); memset(ms->data+ms->fsize, 0, newsize - ms->fsize); ms->fsize = newsize; } ms->fsize = newsize; return PHP_STREAM_OPTION_RETURN_OK; } default: return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */ Commit Message: CWE ID: CWE-20
static int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; size_t newsize; switch(option) { case PHP_STREAM_OPTION_TRUNCATE_API: switch (value) { case PHP_STREAM_TRUNCATE_SUPPORTED: return PHP_STREAM_OPTION_RETURN_OK; case PHP_STREAM_TRUNCATE_SET_SIZE: if (ms->mode & TEMP_STREAM_READONLY) { return PHP_STREAM_OPTION_RETURN_ERR; } newsize = *(size_t*)ptrparam; if (newsize <= ms->fsize) { if (newsize < ms->fpos) { ms->fpos = newsize; } } else { ms->data = erealloc(ms->data, newsize); memset(ms->data+ms->fsize, 0, newsize - ms->fsize); ms->fsize = newsize; } ms->fsize = newsize; return PHP_STREAM_OPTION_RETURN_OK; } default: return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */
165,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static unsigned int seedsize(struct crypto_alg *alg) { struct rng_alg *ralg = container_of(alg, struct rng_alg, base); return alg->cra_rng.rng_make_random ? alg->cra_rng.seedsize : ralg->seedsize; } 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
static unsigned int seedsize(struct crypto_alg *alg) { struct rng_alg *ralg = container_of(alg, struct rng_alg, base); return ralg->seedsize; }
167,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ExtensionBrowserTest::OpenWindow(content::WebContents* contents, const GURL& url, bool newtab_process_should_equal_opener, content::WebContents** newtab_result) { content::WebContentsAddedObserver tab_added_observer; ASSERT_TRUE(content::ExecuteScript(contents, "window.open('" + url.spec() + "');")); content::WebContents* newtab = tab_added_observer.GetWebContents(); ASSERT_TRUE(newtab); WaitForLoadStop(newtab); EXPECT_EQ(url, newtab->GetLastCommittedURL()); if (newtab_process_should_equal_opener) { EXPECT_EQ(contents->GetMainFrame()->GetSiteInstance(), newtab->GetMainFrame()->GetSiteInstance()); } else { EXPECT_NE(contents->GetMainFrame()->GetSiteInstance(), newtab->GetMainFrame()->GetSiteInstance()); } if (newtab_result) *newtab_result = newtab; } Commit Message: [Extensions] Update navigations across hypothetical extension extents Update code to treat navigations across hypothetical extension extents (e.g. for nonexistent extensions) the same as we do for navigations crossing installed extension extents. Bug: 598265 Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b Reviewed-on: https://chromium-review.googlesource.com/617180 Commit-Queue: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#495779} CWE ID:
void ExtensionBrowserTest::OpenWindow(content::WebContents* contents, const GURL& url, bool newtab_process_should_equal_opener, bool should_succeed, content::WebContents** newtab_result) { content::WebContentsAddedObserver tab_added_observer; ASSERT_TRUE(content::ExecuteScript(contents, "window.open('" + url.spec() + "');")); content::WebContents* newtab = tab_added_observer.GetWebContents(); ASSERT_TRUE(newtab); WaitForLoadStop(newtab); if (should_succeed) { EXPECT_EQ(url, newtab->GetLastCommittedURL()); EXPECT_EQ(content::PAGE_TYPE_NORMAL, newtab->GetController().GetLastCommittedEntry()->GetPageType()); } else { // "Failure" comes in two forms: redirecting to about:blank or showing an // error page. At least one should be true. EXPECT_TRUE( newtab->GetLastCommittedURL() == GURL(url::kAboutBlankURL) || newtab->GetController().GetLastCommittedEntry()->GetPageType() == content::PAGE_TYPE_ERROR); } if (newtab_process_should_equal_opener) { EXPECT_EQ(contents->GetMainFrame()->GetSiteInstance(), newtab->GetMainFrame()->GetSiteInstance()); } else { EXPECT_NE(contents->GetMainFrame()->GetSiteInstance(), newtab->GetMainFrame()->GetSiteInstance()); } if (newtab_result) *newtab_result = newtab; }
172,958
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebContentsImpl::DidFailProvisionalLoadWithError( RenderViewHost* render_view_host, const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", is_main_frame: " << params.is_main_frame << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << params.frame_id; GURL validated_url(params.url); RenderProcessHost* render_process_host = render_view_host->GetProcess(); RenderViewHost::FilterURL(render_process_host, false, &validated_url); if (net::ERR_ABORTED == params.error_code) { if (ShowingInterstitialPage()) { LOG(WARNING) << "Discarding message during interstitial."; return; } render_manager_.RendererAbortedProvisionalLoad(render_view_host); } FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidFailProvisionalLoad(params.frame_id, params.is_main_frame, validated_url, params.error_code, params.error_description, render_view_host)); } Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof. BUG=280512 BUG=278899 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23978003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void WebContentsImpl::DidFailProvisionalLoadWithError( RenderViewHost* render_view_host, const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", is_main_frame: " << params.is_main_frame << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << params.frame_id; GURL validated_url(params.url); RenderProcessHost* render_process_host = render_view_host->GetProcess(); RenderViewHost::FilterURL(render_process_host, false, &validated_url); if (net::ERR_ABORTED == params.error_code) { if (ShowingInterstitialPage()) { LOG(WARNING) << "Discarding message during interstitial."; return; } render_manager_.RendererAbortedProvisionalLoad(render_view_host); } // Do not usually clear the pending entry if one exists, so that the user's // typed URL is not lost when a navigation fails or is aborted. However, in // cases that we don't show the pending entry (e.g., renderer-initiated // navigations in an existing tab), we don't keep it around. That prevents // spoofs on in-page navigations that don't go through // DidStartProvisionalLoadForFrame. // In general, we allow the view to clear the pending entry and typed URL if // the user requests (e.g., hitting Escape with focus in the address bar). // Note: don't touch the transient entry, since an interstitial may exist. if (controller_.GetPendingEntry() != controller_.GetVisibleEntry()) controller_.DiscardPendingEntry(); FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidFailProvisionalLoad(params.frame_id, params.is_main_frame, validated_url, params.error_code, params.error_description, render_view_host)); }
171,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_is_block_algorithm_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_is_block_algorithm_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,096
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: NetworkLibrary* CrosLibrary::GetNetworkLibrary() { return network_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
170,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static uint32_t fdctrl_read_data(FDCtrl *fdctrl) { FDrive *cur_drv; uint32_t retval = 0; int pos; cur_drv = get_cur_drv(fdctrl); fdctrl->dsr &= ~FD_DSR_PWRDOWN; if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) { FLOPPY_DPRINTF("error: controller not ready for reading\n"); return 0; } pos = fdctrl->data_pos; if (fdctrl->msr & FD_MSR_NONDMA) { pos %= FD_SECTOR_LEN; if (pos == 0) { if (fdctrl->data_pos != 0) if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) { FLOPPY_DPRINTF("error seeking to next sector %d\n", fd_sector(cur_drv)); return 0; } if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { FLOPPY_DPRINTF("error getting sector %d\n", fd_sector(cur_drv)); /* Sure, image size is too small... */ memset(fdctrl->fifo, 0, FD_SECTOR_LEN); } } } retval = fdctrl->fifo[pos]; if (++fdctrl->data_pos == fdctrl->data_len) { fdctrl->data_pos = 0; /* Switch from transfer mode to status mode * then from status mode to command mode */ if (fdctrl->msr & FD_MSR_NONDMA) { fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00); } else { fdctrl_reset_fifo(fdctrl); fdctrl_reset_irq(fdctrl); } } FLOPPY_DPRINTF("data register: 0x%02x\n", retval); return retval; } Commit Message: CWE ID: CWE-119
static uint32_t fdctrl_read_data(FDCtrl *fdctrl) { FDrive *cur_drv; uint32_t retval = 0; uint32_t pos; cur_drv = get_cur_drv(fdctrl); fdctrl->dsr &= ~FD_DSR_PWRDOWN; if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) { FLOPPY_DPRINTF("error: controller not ready for reading\n"); return 0; } pos = fdctrl->data_pos; pos %= FD_SECTOR_LEN; if (fdctrl->msr & FD_MSR_NONDMA) { if (pos == 0) { if (fdctrl->data_pos != 0) if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) { FLOPPY_DPRINTF("error seeking to next sector %d\n", fd_sector(cur_drv)); return 0; } if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { FLOPPY_DPRINTF("error getting sector %d\n", fd_sector(cur_drv)); /* Sure, image size is too small... */ memset(fdctrl->fifo, 0, FD_SECTOR_LEN); } } } retval = fdctrl->fifo[pos]; if (++fdctrl->data_pos == fdctrl->data_len) { fdctrl->data_pos = 0; /* Switch from transfer mode to status mode * then from status mode to command mode */ if (fdctrl->msr & FD_MSR_NONDMA) { fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00); } else { fdctrl_reset_fifo(fdctrl); fdctrl_reset_irq(fdctrl); } } FLOPPY_DPRINTF("data register: 0x%02x\n", retval); return retval; }
164,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int gdAlphaBlend (int dst, int src) { int src_alpha = gdTrueColorGetAlpha(src); int dst_alpha, alpha, red, green, blue; int src_weight, dst_weight, tot_weight; /* -------------------------------------------------------------------- */ /* Simple cases we want to handle fast. */ /* -------------------------------------------------------------------- */ if( src_alpha == gdAlphaOpaque ) return src; dst_alpha = gdTrueColorGetAlpha(dst); if( src_alpha == gdAlphaTransparent ) return dst; if( dst_alpha == gdAlphaTransparent ) return src; /* -------------------------------------------------------------------- */ /* What will the source and destination alphas be? Note that */ /* the destination weighting is substantially reduced as the */ /* overlay becomes quite opaque. */ /* -------------------------------------------------------------------- */ src_weight = gdAlphaTransparent - src_alpha; dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax; tot_weight = src_weight + dst_weight; /* -------------------------------------------------------------------- */ /* What red, green and blue result values will we use? */ /* -------------------------------------------------------------------- */ alpha = src_alpha * dst_alpha / gdAlphaMax; red = (gdTrueColorGetRed(src) * src_weight + gdTrueColorGetRed(dst) * dst_weight) / tot_weight; green = (gdTrueColorGetGreen(src) * src_weight + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight; blue = (gdTrueColorGetBlue(src) * src_weight + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight; /* -------------------------------------------------------------------- */ /* Return merged result. */ /* -------------------------------------------------------------------- */ return ((alpha << 24) + (red << 16) + (green << 8) + blue); } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
int gdAlphaBlend (int dst, int src) { int src_alpha = gdTrueColorGetAlpha(src); int dst_alpha, alpha, red, green, blue; int src_weight, dst_weight, tot_weight; /* -------------------------------------------------------------------- */ /* Simple cases we want to handle fast. */ /* -------------------------------------------------------------------- */ if( src_alpha == gdAlphaOpaque ) return src; dst_alpha = gdTrueColorGetAlpha(dst); if( src_alpha == gdAlphaTransparent ) return dst; if( dst_alpha == gdAlphaTransparent ) return src; /* -------------------------------------------------------------------- */ /* What will the source and destination alphas be? Note that */ /* the destination weighting is substantially reduced as the */ /* overlay becomes quite opaque. */ /* -------------------------------------------------------------------- */ src_weight = gdAlphaTransparent - src_alpha; dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax; tot_weight = src_weight + dst_weight; /* -------------------------------------------------------------------- */ /* What red, green and blue result values will we use? */ /* -------------------------------------------------------------------- */ alpha = src_alpha * dst_alpha / gdAlphaMax; red = (gdTrueColorGetRed(src) * src_weight + gdTrueColorGetRed(dst) * dst_weight) / tot_weight; green = (gdTrueColorGetGreen(src) * src_weight + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight; blue = (gdTrueColorGetBlue(src) * src_weight + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight; /* -------------------------------------------------------------------- */ /* Return merged result. */ /* -------------------------------------------------------------------- */ return ((alpha << 24) + (red << 16) + (green << 8) + blue); }
167,124
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int uinput_create(char *name) { struct uinput_dev dev; int fd, x = 0; for(x=0; x < MAX_UINPUT_PATHS; x++) { fd = open(uinput_dev_path[x], O_RDWR); if (fd < 0) continue; break; } if (x == MAX_UINPUT_PATHS) { BTIF_TRACE_ERROR("%s ERROR: uinput device open failed", __FUNCTION__); return -1; } memset(&dev, 0, sizeof(dev)); if (name) strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE-1); dev.id.bustype = BUS_BLUETOOTH; dev.id.vendor = 0x0000; dev.id.product = 0x0000; dev.id.version = 0x0000; if (write(fd, &dev, sizeof(dev)) < 0) { BTIF_TRACE_ERROR("%s Unable to write device information", __FUNCTION__); close(fd); return -1; } ioctl(fd, UI_SET_EVBIT, EV_KEY); ioctl(fd, UI_SET_EVBIT, EV_REL); ioctl(fd, UI_SET_EVBIT, EV_SYN); for (x = 0; key_map[x].name != NULL; x++) ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id); if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) { BTIF_TRACE_ERROR("%s Unable to create uinput device", __FUNCTION__); close(fd); return -1; } return fd; } 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
int uinput_create(char *name) { struct uinput_dev dev; int fd, x = 0; for(x=0; x < MAX_UINPUT_PATHS; x++) { fd = TEMP_FAILURE_RETRY(open(uinput_dev_path[x], O_RDWR)); if (fd < 0) continue; break; } if (x == MAX_UINPUT_PATHS) { BTIF_TRACE_ERROR("%s ERROR: uinput device open failed", __FUNCTION__); return -1; } memset(&dev, 0, sizeof(dev)); if (name) strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE-1); dev.id.bustype = BUS_BLUETOOTH; dev.id.vendor = 0x0000; dev.id.product = 0x0000; dev.id.version = 0x0000; if (TEMP_FAILURE_RETRY(write(fd, &dev, sizeof(dev))) < 0) { BTIF_TRACE_ERROR("%s Unable to write device information", __FUNCTION__); close(fd); return -1; } TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_KEY)); TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_REL)); TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_SYN)); for (x = 0; key_map[x].name != NULL; x++) TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id)); if (TEMP_FAILURE_RETRY(ioctl(fd, UI_DEV_CREATE, NULL)) < 0) { BTIF_TRACE_ERROR("%s Unable to create uinput device", __FUNCTION__); close(fd); return -1; } return fd; }
173,452
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GpuProcessHost::OnProcessLaunched() { base::ProcessHandle child_handle = in_process_ ? base::GetCurrentProcessHandle() : process_->GetData().handle; #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), child_handle, base::GetCurrentProcessHandle(), &gpu_process_, PROCESS_DUP_HANDLE, FALSE, 0); #else gpu_process_ = child_handle; #endif UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHost::OnProcessLaunched() { UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); }
170,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode) { struct nfs_inode *nfsi = NFS_I(inode); struct nfs_open_context *pos, *ctx = NULL; spin_lock(&inode->i_lock); list_for_each_entry(pos, &nfsi->open_files, list) { if (cred != NULL && pos->cred != cred) continue; if ((pos->mode & mode) == mode) { ctx = get_nfs_open_context(pos); break; } } spin_unlock(&inode->i_lock); return ctx; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode) struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, fmode_t mode) { struct nfs_inode *nfsi = NFS_I(inode); struct nfs_open_context *pos, *ctx = NULL; spin_lock(&inode->i_lock); list_for_each_entry(pos, &nfsi->open_files, list) { if (cred != NULL && pos->cred != cred) continue; if ((pos->mode & mode) == mode) { ctx = get_nfs_open_context(pos); break; } } spin_unlock(&inode->i_lock); return ctx; }
165,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync( content::CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kUnconnected || gpu_channel_->state() == GpuChannelHost::kConnected) return GetGpuChannel(); gpu_channel_ = NULL; } int client_id = 0; IPC::ChannelHandle channel_handle; base::ProcessHandle renderer_process_for_gpu; content::GPUInfo gpu_info; if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch, &client_id, &channel_handle, &renderer_process_for_gpu, &gpu_info)) || channel_handle.name.empty() || #if defined(OS_POSIX) channel_handle.socket.fd == -1 || #endif renderer_process_for_gpu == base::kNullProcessHandle) { gpu_channel_ = NULL; return NULL; } gpu_channel_ = new GpuChannelHost(this, 0, client_id); gpu_channel_->set_gpu_info(gpu_info); content::GetContentClient()->SetGpuInfo(gpu_info); gpu_channel_->Connect(channel_handle, renderer_process_for_gpu); return GetGpuChannel(); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync( content::CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kUnconnected || gpu_channel_->state() == GpuChannelHost::kConnected) return GetGpuChannel(); gpu_channel_ = NULL; } int client_id = 0; IPC::ChannelHandle channel_handle; content::GPUInfo gpu_info; if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch, &client_id, &channel_handle, &gpu_info)) || #if defined(OS_POSIX) channel_handle.socket.fd == -1 || #endif channel_handle.name.empty()) { gpu_channel_ = NULL; return NULL; } gpu_channel_ = new GpuChannelHost(this, 0, client_id); gpu_channel_->set_gpu_info(gpu_info); content::GetContentClient()->SetGpuInfo(gpu_info); gpu_channel_->Connect(channel_handle); return GetGpuChannel(); }
170,954
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) { _cleanup_close_ int fd; int r; assert(path); if (parents) mkdir_parents(path, 0755); fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644); if (fd < 0) return -errno; if (mode > 0) { r = fchmod(fd, mode); if (r < 0) return -errno; } if (uid != UID_INVALID || gid != GID_INVALID) { r = fchown(fd, uid, gid); if (r < 0) return -errno; } if (stamp != USEC_INFINITY) { struct timespec ts[2]; timespec_store(&ts[0], stamp); ts[1] = ts[0]; r = futimens(fd, ts); } else r = futimens(fd, NULL); if (r < 0) return -errno; return 0; } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264
int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) { _cleanup_close_ int fd; int r; assert(path); if (parents) mkdir_parents(path, 0755); fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644); if (fd < 0) return -errno; if (mode != MODE_INVALID) { r = fchmod(fd, mode); if (r < 0) return -errno; } if (uid != UID_INVALID || gid != GID_INVALID) { r = fchown(fd, uid, gid); if (r < 0) return -errno; } if (stamp != USEC_INFINITY) { struct timespec ts[2]; timespec_store(&ts[0], stamp); ts[1] = ts[0]; r = futimens(fd, ts); } else r = futimens(fd, NULL); if (r < 0) return -errno; return 0; }
170,105
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; unsigned char* cp = (unsigned char*) cp0; assert((cc%stride)==0); if (cc > stride) { /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; cc -= 3; cp += 3; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cc -= 3; cp += 3; } } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; cc -= 4; cp += 4; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cp[3] = (unsigned char) ((ca += cp[3]) & 0xff); cc -= 4; cp += 4; } } else { cc -= stride; do { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + *cp) & 0xff); cp++) cc -= stride; } while (cc>0); } } } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; unsigned char* cp = (unsigned char*) cp0; if((cc%stride)!=0) { TIFFErrorExt(tif->tif_clientdata, "horAcc8", "%s", "(cc%stride)!=0"); return 0; } if (cc > stride) { /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; cc -= 3; cp += 3; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cc -= 3; cp += 3; } } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; cc -= 4; cp += 4; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cp[3] = (unsigned char) ((ca += cp[3]) & 0xff); cc -= 4; cp += 4; } } else { cc -= stride; do { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + *cp) & 0xff); cp++) cc -= stride; } while (cc>0); } } return 1; }
166,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { uint32_t end = readU16(data, kEndCountOffset + 2 * i); uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i)); if (end < start) { return false; } uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (uint32_t j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (uint32_t j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { continue; } uint32_t glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; } Commit Message: Add error logging on invalid cmap - DO NOT MERGE This patch logs instances of fonts with invalid cmap tables. Bug: 25645298 Bug: 26413177 Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e CWE ID: CWE-20
static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { uint32_t end = readU16(data, kEndCountOffset + 2 * i); uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i)); if (end < start) { android_errorWriteLog(0x534e4554, "26413177"); return false; } uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (uint32_t j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (uint32_t j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { continue; } uint32_t glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; }
173,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: gfx::Size CardUnmaskPromptViews::GetPreferredSize() const { const int kWidth = 375; return gfx::Size(kWidth, GetHeightForWidth(kWidth)); } Commit Message: Clear out some minor TODOs. BUG=none Review URL: https://codereview.chromium.org/1047063002 Cr-Commit-Position: refs/heads/master@{#322959} CWE ID: CWE-20
gfx::Size CardUnmaskPromptViews::GetPreferredSize() const { // Must hardcode a width so the label knows where to wrap. const int kWidth = 375; return gfx::Size(kWidth, GetHeightForWidth(kWidth)); }
171,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: IPC::PlatformFileForTransit ProxyChannelDelegate::ShareHandleWithRemote( base::PlatformFile handle, const IPC::SyncChannel& channel, bool should_close_source) { return content::BrokerGetFileHandleForProcess(handle, channel.peer_pid(), should_close_source); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
IPC::PlatformFileForTransit ProxyChannelDelegate::ShareHandleWithRemote(
170,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GaiaOAuthClient::Core::OnAuthTokenFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); if (!status.is_success()) { delegate_->OnNetworkError(response_code); return; } if (response_code == net::HTTP_BAD_REQUEST) { LOG(ERROR) << "Gaia response: response code=net::HTTP_BAD_REQUEST."; delegate_->OnOAuthError(); return; } if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kAccessTokenValue, &access_token_); response_dict->GetInteger(kExpiresInValue, &expires_in_seconds_); } VLOG(1) << "Gaia response: acess_token='" << access_token_ << "', expires in " << expires_in_seconds_ << " second(s)"; } else { LOG(ERROR) << "Gaia response: response code=" << response_code; } if (access_token_.empty()) { delegate_->OnNetworkError(response_code); } else { FetchUserInfoAndInvokeCallback(); } } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::OnAuthTokenFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); if (!status.is_success()) { delegate_->OnNetworkError(response_code); return; } if (response_code == net::HTTP_BAD_REQUEST) { LOG(ERROR) << "Gaia response: response code=net::HTTP_BAD_REQUEST."; delegate_->OnOAuthError(); return; } if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); std::string access_token; response_dict->GetString(kAccessTokenValue, &access_token); if (access_token.find("\r\n") != std::string::npos) { LOG(ERROR) << "Gaia response: access token include CRLF"; delegate_->OnOAuthError(); return; } access_token_ = access_token; response_dict->GetInteger(kExpiresInValue, &expires_in_seconds_); } VLOG(1) << "Gaia response: acess_token='" << access_token_ << "', expires in " << expires_in_seconds_ << " second(s)"; } else { LOG(ERROR) << "Gaia response: response code=" << response_code; } if (access_token_.empty()) { delegate_->OnNetworkError(response_code); } else { FetchUserInfoAndInvokeCallback(); } }
170,807
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number, QuicFecGroupNumber fec_group) { header_.packet_sequence_number = number; header_.flags = PACKET_FLAGS_NONE; header_.fec_group = fec_group; QuicFrames frames; QuicFrame frame(&frame1_); frames.push_back(frame); QuicPacket* packet; framer_.ConstructFragementDataPacket(header_, frames, &packet); return packet; } Commit Message: Fix uninitialized access in QuicConnectionHelperTest BUG=159928 Review URL: https://chromiumcodereview.appspot.com/11360153 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@166708 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number, QuicFecGroupNumber fec_group) { header_.guid = guid_; header_.packet_sequence_number = number; header_.transmission_time = 0; header_.retransmission_count = 0; header_.flags = PACKET_FLAGS_NONE; header_.fec_group = fec_group; QuicFrames frames; QuicFrame frame(&frame1_); frames.push_back(frame); QuicPacket* packet; framer_.ConstructFragementDataPacket(header_, frames, &packet); return packet; }
171,410
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PrintMsg_Print_Params::PrintMsg_Print_Params() : page_size(), content_size(), printable_area(), margin_top(0), margin_left(0), dpi(0), min_shrink(0), max_shrink(0), desired_dpi(0), document_cookie(0), selection_only(false), supports_alpha_blend(false), preview_ui_addr(), preview_request_id(0), is_first_request(false), print_scaling_option(WebKit::WebPrintScalingOptionSourceSize), print_to_pdf(false), display_header_footer(false), date(), title(), url() { } 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
PrintMsg_Print_Params::PrintMsg_Print_Params() : page_size(), content_size(), printable_area(), margin_top(0), margin_left(0), dpi(0), min_shrink(0), max_shrink(0), desired_dpi(0), document_cookie(0), selection_only(false), supports_alpha_blend(false), preview_ui_id(-1), preview_request_id(0), is_first_request(false), print_scaling_option(WebKit::WebPrintScalingOptionSourceSize), print_to_pdf(false), display_header_footer(false), date(), title(), url() { }
170,845
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int ret; int copylen; ret = -EOPNOTSUPP; if (m->msg_flags&MSG_OOB) goto read_error; skb = skb_recv_datagram(sk, flags, 0 , &ret); if (!skb) goto read_error; copylen = skb->len; if (len < copylen) { m->msg_flags |= MSG_TRUNC; copylen = len; } ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen); if (ret) goto out_free; ret = (flags & MSG_TRUNC) ? skb->len : copylen; out_free: skb_free_datagram(sk, skb); caif_check_flow_release(sk); return ret; read_error: return ret; } Commit Message: caif: Fix missing msg_namelen update in caif_seqpkt_recvmsg() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about caif_seqpkt_recvmsg() not filling the msg_name in case it was set. Cc: Sjur Braendeland <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int ret; int copylen; ret = -EOPNOTSUPP; if (m->msg_flags&MSG_OOB) goto read_error; m->msg_namelen = 0; skb = skb_recv_datagram(sk, flags, 0 , &ret); if (!skb) goto read_error; copylen = skb->len; if (len < copylen) { m->msg_flags |= MSG_TRUNC; copylen = len; } ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen); if (ret) goto out_free; ret = (flags & MSG_TRUNC) ? skb->len : copylen; out_free: skb_free_datagram(sk, skb); caif_check_flow_release(sk); return ret; read_error: return ret; }
166,040
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FileBrowserHandlerCustomBindings::GetExternalFileEntry( const v8::FunctionCallbackInfo<v8::Value>& args) { //// TODO(zelidrag): Make this magic work on other platforms when file browser //// matures enough on ChromeOS. #if defined(OS_CHROMEOS) CHECK(args.Length() == 1); CHECK(args[0]->IsObject()); v8::Local<v8::Object> file_def = args[0]->ToObject(); std::string file_system_name( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemName")))); GURL file_system_root( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemRoot")))); std::string file_full_path( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileFullPath")))); bool is_directory = file_def->Get(v8::String::NewFromUtf8( args.GetIsolate(), "fileIsDirectory"))->ToBoolean()->Value(); blink::WebDOMFileSystem::EntryType entry_type = is_directory ? blink::WebDOMFileSystem::EntryTypeDirectory : blink::WebDOMFileSystem::EntryTypeFile; blink::WebLocalFrame* webframe = blink::WebLocalFrame::frameForContext(context()->v8_context()); args.GetReturnValue().Set( blink::WebDOMFileSystem::create( webframe, blink::WebFileSystemTypeExternal, blink::WebString::fromUTF8(file_system_name), file_system_root) .createV8Entry(blink::WebString::fromUTF8(file_full_path), entry_type, args.Holder(), args.GetIsolate())); #endif } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
void FileBrowserHandlerCustomBindings::GetExternalFileEntry( const v8::FunctionCallbackInfo<v8::Value>& args, ScriptContext* context) { //// TODO(zelidrag): Make this magic work on other platforms when file browser //// matures enough on ChromeOS. #if defined(OS_CHROMEOS) CHECK(args.Length() == 1); CHECK(args[0]->IsObject()); v8::Local<v8::Object> file_def = args[0]->ToObject(); std::string file_system_name( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemName")))); GURL file_system_root( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileSystemRoot")))); std::string file_full_path( *v8::String::Utf8Value(file_def->Get( v8::String::NewFromUtf8(args.GetIsolate(), "fileFullPath")))); bool is_directory = file_def->Get(v8::String::NewFromUtf8( args.GetIsolate(), "fileIsDirectory"))->ToBoolean()->Value(); blink::WebDOMFileSystem::EntryType entry_type = is_directory ? blink::WebDOMFileSystem::EntryTypeDirectory : blink::WebDOMFileSystem::EntryTypeFile; blink::WebLocalFrame* webframe = blink::WebLocalFrame::frameForContext(context->v8_context()); args.GetReturnValue().Set( blink::WebDOMFileSystem::create( webframe, blink::WebFileSystemTypeExternal, blink::WebString::fromUTF8(file_system_name), file_system_root) .createV8Entry(blink::WebString::fromUTF8(file_full_path), entry_type, args.Holder(), args.GetIsolate())); #endif }
173,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void smp_proc_master_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; tBTM_LE_PENC_KEYS le_key; SMP_TRACE_DEBUG("%s", __func__); smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true); STREAM_TO_UINT16(le_key.ediv, p); STREAM_TO_ARRAY(le_key.rand, p, BT_OCTET8_LEN); /* store the encryption keys from peer device */ memcpy(le_key.ltk, p_cb->ltk, BT_OCTET16_LEN); le_key.sec_level = p_cb->sec_level; le_key.key_size = p_cb->loc_enc_size; if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, (tBTM_LE_KEY_VALUE*)&le_key, true); smp_key_distribution(p_cb, NULL); } Commit Message: Add packet length check in smp_proc_master_id Bug: 111937027 Test: manual Change-Id: I1144c9879e84fa79d68ad9d5fece4f58e2a3b075 (cherry picked from commit c8294662d07a98e9b8b1cab1ab681ec0805ce4e8) CWE ID: CWE-200
void smp_proc_master_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; tBTM_LE_PENC_KEYS le_key; SMP_TRACE_DEBUG("%s", __func__); if (p_cb->rcvd_cmd_len < 11) { // 1(Code) + 2(EDIV) + 8(Rand) android_errorWriteLog(0x534e4554, "111937027"); SMP_TRACE_ERROR("%s: Invalid command length: %d, should be at least 11", __func__, p_cb->rcvd_cmd_len); return; } smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true); STREAM_TO_UINT16(le_key.ediv, p); STREAM_TO_ARRAY(le_key.rand, p, BT_OCTET8_LEN); /* store the encryption keys from peer device */ memcpy(le_key.ltk, p_cb->ltk, BT_OCTET16_LEN); le_key.sec_level = p_cb->sec_level; le_key.key_size = p_cb->loc_enc_size; if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, (tBTM_LE_KEY_VALUE*)&le_key, true); smp_key_distribution(p_cb, NULL); }
174,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } }
167,125
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } Commit Message: xfrm_user: fix info leak in copy_to_user_state() The memory reserved to dump the xfrm state includes the padding bytes of struct xfrm_usersa_info added by the compiler for alignment (7 for amd64, 3 for i386). Add an explicit memset(0) before filling the buffer to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memset(p, 0, sizeof(*p)); memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; }
166,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void rds_inc_info_copy(struct rds_incoming *inc, struct rds_info_iterator *iter, __be32 saddr, __be32 daddr, int flip) { struct rds_info_message minfo; minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence); minfo.len = be32_to_cpu(inc->i_hdr.h_len); if (flip) { minfo.laddr = daddr; minfo.faddr = saddr; minfo.lport = inc->i_hdr.h_dport; minfo.fport = inc->i_hdr.h_sport; } else { minfo.laddr = saddr; minfo.faddr = daddr; minfo.lport = inc->i_hdr.h_sport; minfo.fport = inc->i_hdr.h_dport; } rds_info_copy(iter, &minfo, sizeof(minfo)); } Commit Message: rds: fix an infoleak in rds_inc_info_copy The last field "flags" of object "minfo" is not initialized. Copying this object out may leak kernel stack data. Assign 0 to it to avoid leak. Signed-off-by: Kangjie Lu <[email protected]> Acked-by: Santosh Shilimkar <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
void rds_inc_info_copy(struct rds_incoming *inc, struct rds_info_iterator *iter, __be32 saddr, __be32 daddr, int flip) { struct rds_info_message minfo; minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence); minfo.len = be32_to_cpu(inc->i_hdr.h_len); if (flip) { minfo.laddr = daddr; minfo.faddr = saddr; minfo.lport = inc->i_hdr.h_dport; minfo.fport = inc->i_hdr.h_sport; } else { minfo.laddr = saddr; minfo.faddr = daddr; minfo.lport = inc->i_hdr.h_sport; minfo.fport = inc->i_hdr.h_dport; } minfo.flags = 0; rds_info_copy(iter, &minfo, sizeof(minfo)); }
167,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void set_own_dir(const char *argv0) { size_t l = strlen(argv0); while(l && argv0[l - 1] != '/') l--; if(l == 0) memcpy(own_dir, ".", 2); else { memcpy(own_dir, argv0, l - 1); own_dir[l] = 0; } } Commit Message: fix for CVE-2015-3887 closes #60 CWE ID: CWE-426
static void set_own_dir(const char *argv0) { size_t l = strlen(argv0); while(l && argv0[l - 1] != '/') l--; if(l == 0) #ifdef SUPER_SECURE memcpy(own_dir, "/dev/null/", 2); #else memcpy(own_dir, ".", 2); #endif else { memcpy(own_dir, argv0, l - 1); own_dir[l] = 0; } }
168,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DownloadManagerImpl::CreateNewDownloadItemToStart( std::unique_ptr<download::DownloadCreateInfo> info, const download::DownloadUrlParameters::OnStartedCallback& on_started, download::InProgressDownloadManager::StartDownloadItemCallback callback, uint32_t id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); download::DownloadItemImpl* download = CreateActiveItem(id, *info); std::move(callback).Run(std::move(info), download, should_persist_new_download_); for (auto& observer : observers_) observer.OnDownloadCreated(this, download); OnNewDownloadCreated(download); OnDownloadStarted(download, on_started); } Commit Message: Early return if a download Id is already used when creating a download This is protect against download Id overflow and use-after-free issue. BUG=958533 Change-Id: I2c183493cb09106686df9822b3987bfb95bcf720 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591485 Reviewed-by: Xing Liu <[email protected]> Commit-Queue: Min Qin <[email protected]> Cr-Commit-Position: refs/heads/master@{#656910} CWE ID: CWE-416
void DownloadManagerImpl::CreateNewDownloadItemToStart( std::unique_ptr<download::DownloadCreateInfo> info, const download::DownloadUrlParameters::OnStartedCallback& on_started, download::InProgressDownloadManager::StartDownloadItemCallback callback, uint32_t id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); download::DownloadItemImpl* download = CreateActiveItem(id, *info); std::move(callback).Run(std::move(info), download, should_persist_new_download_); if (download) { // For new downloads, we notify here, rather than earlier, so that // the download_file is bound to download and all the usual // setters (e.g. Cancel) work. for (auto& observer : observers_) observer.OnDownloadCreated(this, download); OnNewDownloadCreated(download); } OnDownloadStarted(download, on_started); }
172,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { struct ieee_types_header *rate_ie; int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable); const u8 *var_pos = params->beacon.head + var_offset; int len = params->beacon.head_len - var_offset; u8 rate_len = 0; rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len); if (rate_ie) { memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len); rate_len = rate_ie->len; } rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES, params->beacon.tail, params->beacon.tail_len); if (rate_ie) memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len); return; } Commit Message: mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and mwifiex_set_wmm_params() call memcpy() without checking the destination size.Since the source is given from user-space, this may trigger a heap buffer overflow. Fix them by putting the length check before performing memcpy(). This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816. Signed-off-by: Wen Huang <[email protected]> Acked-by: Ganapathi Bhat <[email protected]> Signed-off-by: Kalle Valo <[email protected]> CWE ID: CWE-120
mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { struct ieee_types_header *rate_ie; int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable); const u8 *var_pos = params->beacon.head + var_offset; int len = params->beacon.head_len - var_offset; u8 rate_len = 0; rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len); if (rate_ie) { if (rate_ie->len > MWIFIEX_SUPPORTED_RATES) return; memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len); rate_len = rate_ie->len; } rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES, params->beacon.tail, params->beacon.tail_len); if (rate_ie) { if (rate_ie->len > MWIFIEX_SUPPORTED_RATES - rate_len) return; memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len); } return; }
169,576
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed( const GURL& method_manifest_url, const std::vector<GURL>& default_applications, const std::vector<url::Origin>& supported_origins, bool all_origins_supported) { number_of_payment_method_manifest_to_parse_--; if (web_contents() == nullptr) return; content::PermissionManager* permission_manager = web_contents()->GetBrowserContext()->GetPermissionManager(); if (permission_manager == nullptr) return; for (const auto& url : default_applications) { if (downloaded_web_app_manifests_.find(url) != downloaded_web_app_manifests_.end()) { continue; } if (permission_manager->GetPermissionStatus( content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(), url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) { continue; } number_of_web_app_manifest_to_download_++; downloaded_web_app_manifests_.insert(url); downloader_->DownloadWebAppManifest( url, base::BindOnce( &InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded, weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url)); } FinishCrawlingPaymentAppsIfReady(); } Commit Message: [Payments] Restrict just-in-time payment handler to payment method domain and its subdomains Bug: 853937 Change-Id: I148b3d96950a9d90fa362e580e9593caa6b92a36 Reviewed-on: https://chromium-review.googlesource.com/1132116 Reviewed-by: Mathieu Perreault <[email protected]> Commit-Queue: Ganggui Tang <[email protected]> Cr-Commit-Position: refs/heads/master@{#573911} CWE ID:
void InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed( const GURL& method_manifest_url, const std::vector<GURL>& default_applications, const std::vector<url::Origin>& supported_origins, bool all_origins_supported) { number_of_payment_method_manifest_to_parse_--; if (web_contents() == nullptr) return; content::PermissionManager* permission_manager = web_contents()->GetBrowserContext()->GetPermissionManager(); if (permission_manager == nullptr) return; for (const auto& url : default_applications) { if (downloaded_web_app_manifests_.find(url) != downloaded_web_app_manifests_.end()) { continue; } if (!net::registry_controlled_domains::SameDomainOrHost( method_manifest_url, url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { WarnIfPossible("Installable payment app from " + url.spec() + " is not allowed for the method " + method_manifest_url.spec()); continue; } if (permission_manager->GetPermissionStatus( content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(), url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) { continue; } number_of_web_app_manifest_to_download_++; downloaded_web_app_manifests_.insert(url); downloader_->DownloadWebAppManifest( url, base::BindOnce( &InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded, weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url)); } FinishCrawlingPaymentAppsIfReady(); }
172,652
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: raptor_libxml_resolveEntity(void* user_data, const xmlChar *publicId, const xmlChar *systemId) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_resolveEntity(sax2->xc, publicId, systemId); } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_libxml_resolveEntity(void* user_data, const xmlChar *publicId, const xmlChar *systemId) { raptor_sax2* sax2 = (raptor_sax2*)user_data; xmlParserCtxtPtr ctxt = sax2->xc; const unsigned char *uri_string = NULL; xmlParserInputPtr entity_input; int load_entity = 0; if(ctxt->input) uri_string = RAPTOR_GOOD_CAST(const unsigned char *, ctxt->input->filename); if(!uri_string) uri_string = RAPTOR_GOOD_CAST(const unsigned char *, ctxt->directory); load_entity = RAPTOR_OPTIONS_GET_NUMERIC(sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES); if(load_entity) load_entity = raptor_sax2_check_load_uri_string(sax2, uri_string); if(load_entity) { entity_input = xmlLoadExternalEntity(RAPTOR_GOOD_CAST(const char*, uri_string), RAPTOR_GOOD_CAST(const char*, publicId), ctxt); } else { RAPTOR_DEBUG4("Not loading entity URI %s by policy for publicId '%s' systemId '%s'\n", uri_string, publicId, systemId); } return entity_input; }
165,659
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr); close(sk); return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; TEMP_FAILURE_RETRY(ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr)); close(sk); return 0; }
173,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val - 1); } Commit Message: CWE ID: CWE-20
void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); }
165,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AcceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas, const cc::PaintFlags& flags, const FloatRect& dst_rect, const FloatRect& src_rect, RespectImageOrientationEnum, ImageClampingMode image_clamping_mode, ImageDecodingMode decode_mode) { auto paint_image = PaintImageForCurrentFrame(); if (!paint_image) return; auto paint_image_decoding_mode = ToPaintImageDecodingMode(decode_mode); if (paint_image.decoding_mode() != paint_image_decoding_mode) { paint_image = PaintImageBuilder::WithCopy(std::move(paint_image)) .set_decoding_mode(paint_image_decoding_mode) .TakePaintImage(); } StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, image_clamping_mode, paint_image); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas, const cc::PaintFlags& flags, const FloatRect& dst_rect, const FloatRect& src_rect, RespectImageOrientationEnum, ImageClampingMode image_clamping_mode, ImageDecodingMode decode_mode) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); auto paint_image = PaintImageForCurrentFrame(); if (!paint_image) return; auto paint_image_decoding_mode = ToPaintImageDecodingMode(decode_mode); if (paint_image.decoding_mode() != paint_image_decoding_mode) { paint_image = PaintImageBuilder::WithCopy(std::move(paint_image)) .set_decoding_mode(paint_image_decoding_mode) .TakePaintImage(); } StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, image_clamping_mode, paint_image); }
172,594
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { gdImagePtr pim = 0, tim = im; int interlace, BitsPerPixel; interlace = im->interlace; if (im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if (!pim) { return; } tim = pim; } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFEncode( out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel, tim->red, tim->green, tim->blue, tim); if (pim) { /* Destroy palette based temporary image. */ gdImageDestroy( pim); } } Commit Message: Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here. CWE ID: CWE-415
void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { _gdImageGifCtx(im, out); } /* returns 0 on success, 1 on failure */ static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { gdImagePtr pim = 0, tim = im; int interlace, BitsPerPixel; interlace = im->interlace; if (im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if (!pim) { return 1; } tim = pim; } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFEncode( out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel, tim->red, tim->green, tim->blue, tim); if (pim) { /* Destroy palette based temporary image. */ gdImageDestroy( pim); } return 0; }
169,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void NetworkHandler::ClearBrowserCache( std::unique_ptr<ClearBrowserCacheCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } content::BrowsingDataRemover* remover = content::BrowserContext::GetBrowsingDataRemover( process_->GetBrowserContext()); remover->RemoveAndReply( base::Time(), base::Time::Max(), content::BrowsingDataRemover::DATA_TYPE_CACHE, content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, new DevtoolsClearCacheObserver(remover, std::move(callback))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::ClearBrowserCache( std::unique_ptr<ClearBrowserCacheCallback> callback) { if (!browser_context_) { callback->sendFailure(Response::InternalError()); return; } content::BrowsingDataRemover* remover = content::BrowserContext::GetBrowsingDataRemover(browser_context_); remover->RemoveAndReply( base::Time(), base::Time::Max(), content::BrowsingDataRemover::DATA_TYPE_CACHE, content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, new DevtoolsClearCacheObserver(remover, std::move(callback))); }
172,752
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: CMD_FUNC(m_authenticate) { aClient *agent_p = NULL; /* Failing to use CAP REQ for sasl is a protocol violation. */ if (!SASL_SERVER || !MyConnect(sptr) || BadPtr(parv[1]) || !CHECKPROTO(sptr, PROTO_SASL)) return 0; if (sptr->local->sasl_complete) { sendto_one(sptr, err_str(ERR_SASLALREADY), me.name, BadPtr(sptr->name) ? "*" : sptr->name); return 0; } if (strlen(parv[1]) > 400) { sendto_one(sptr, err_str(ERR_SASLTOOLONG), me.name, BadPtr(sptr->name) ? "*" : sptr->name); return 0; } if (*sptr->local->sasl_agent) agent_p = find_client(sptr->local->sasl_agent, NULL); if (agent_p == NULL) { char *addr = BadPtr(sptr->ip) ? "0" : sptr->ip; char *certfp = moddata_client_get(sptr, "certfp"); sendto_server(NULL, 0, 0, ":%s SASL %s %s H %s %s", me.name, SASL_SERVER, encode_puid(sptr), addr, addr); if (certfp) sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s %s", me.name, SASL_SERVER, encode_puid(sptr), parv[1], certfp); else sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s", me.name, SASL_SERVER, encode_puid(sptr), parv[1]); } else sendto_server(NULL, 0, 0, ":%s SASL %s %s C %s", me.name, AGENT_SID(agent_p), encode_puid(sptr), parv[1]); sptr->local->sasl_out++; return 0; } Commit Message: Fix AUTHENTICATE bug CWE ID: CWE-287
CMD_FUNC(m_authenticate) { aClient *agent_p = NULL; /* Failing to use CAP REQ for sasl is a protocol violation. */ if (!SASL_SERVER || !MyConnect(sptr) || BadPtr(parv[1]) || !CHECKPROTO(sptr, PROTO_SASL)) return 0; if (sptr->local->sasl_complete) { sendto_one(sptr, err_str(ERR_SASLALREADY), me.name, BadPtr(sptr->name) ? "*" : sptr->name); return 0; } if ((parv[1][0] == ':') || strchr(parv[1], ' ')) { sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name, "*", "AUTHENTICATE", "Invalid parameter"); return 0; } if (strlen(parv[1]) > 400) { sendto_one(sptr, err_str(ERR_SASLTOOLONG), me.name, BadPtr(sptr->name) ? "*" : sptr->name); return 0; } if (*sptr->local->sasl_agent) agent_p = find_client(sptr->local->sasl_agent, NULL); if (agent_p == NULL) { char *addr = BadPtr(sptr->ip) ? "0" : sptr->ip; char *certfp = moddata_client_get(sptr, "certfp"); sendto_server(NULL, 0, 0, ":%s SASL %s %s H %s %s", me.name, SASL_SERVER, encode_puid(sptr), addr, addr); if (certfp) sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s %s", me.name, SASL_SERVER, encode_puid(sptr), parv[1], certfp); else sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s", me.name, SASL_SERVER, encode_puid(sptr), parv[1]); } else sendto_server(NULL, 0, 0, ":%s SASL %s %s C %s", me.name, AGENT_SID(agent_p), encode_puid(sptr), parv[1]); sptr->local->sasl_out++; return 0; }
168,814
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) { if (HasTextBeingDragged()) return ui::DragDropTypes::DRAG_NONE; if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) { GURL url; base::string16 title; if (data.GetURLAndTitle( ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) { base::string16 text( StripJavascriptSchemas(base::UTF8ToUTF16(url.spec()))); if (model()->CanPasteAndGo(text)) { model()->PasteAndGo(text); return ui::DragDropTypes::DRAG_COPY; } } } else if (data.HasString()) { base::string16 text; if (data.GetString(&text)) { base::string16 collapsed_text(base::CollapseWhitespace(text, true)); if (model()->CanPasteAndGo(collapsed_text)) model()->PasteAndGo(collapsed_text); return ui::DragDropTypes::DRAG_COPY; } } return ui::DragDropTypes::DRAG_NONE; } Commit Message: Strip JavaScript schemas on Linux text drop When dropping text onto the Omnibox, any leading JavaScript schemes should be stripped to avoid a "self-XSS" attack. This stripping already occurs in all cases except when plaintext is dropped on Linux. This CL corrects that oversight. Bug: 768910 Change-Id: I43af24ace4a13cf61d15a32eb9382dcdd498a062 Reviewed-on: https://chromium-review.googlesource.com/685638 Reviewed-by: Justin Donnelly <[email protected]> Commit-Queue: Eric Lawrence <[email protected]> Cr-Commit-Position: refs/heads/master@{#504695} CWE ID: CWE-79
int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) { if (HasTextBeingDragged()) return ui::DragDropTypes::DRAG_NONE; if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) { GURL url; base::string16 title; if (data.GetURLAndTitle( ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) { base::string16 text( StripJavascriptSchemas(base::UTF8ToUTF16(url.spec()))); if (model()->CanPasteAndGo(text)) { model()->PasteAndGo(text); return ui::DragDropTypes::DRAG_COPY; } } } else if (data.HasString()) { base::string16 text; if (data.GetString(&text)) { base::string16 collapsed_text( StripJavascriptSchemas(base::CollapseWhitespace(text, true))); if (model()->CanPasteAndGo(collapsed_text)) model()->PasteAndGo(collapsed_text); return ui::DragDropTypes::DRAG_COPY; } } return ui::DragDropTypes::DRAG_NONE; }
172,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: XineramaXvShmPutImage(ClientPtr client) { REQUEST(xvShmPutImageReq); PanoramiXRes *draw, *gc, *port; Bool send_event = stuff->send_event; Bool isRoot; int result, i, x, y; REQUEST_SIZE_MATCH(xvShmPutImageReq); result = dixLookupResourceByClass((void **) &draw, stuff->drawable, XRC_DRAWABLE, client, DixWriteAccess); if (result != Success) result = dixLookupResourceByType((void **) &gc, stuff->gc, XRT_GC, client, DixReadAccess); if (result != Success) return result; result = dixLookupResourceByType((void **) &port, stuff->port, XvXRTPort, client, DixReadAccess); if (result != Success) return result; isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; x = stuff->drw_x; y = stuff->drw_y; FOR_NSCREENS_BACKWARD(i) { if (port->info[i].id) { stuff->drawable = draw->info[i].id; stuff->port = port->info[i].id; stuff->gc = gc->info[i].id; stuff->drw_x = x; stuff->drw_y = y; if (isRoot) { stuff->drw_x -= screenInfo.screens[i]->x; stuff->drw_y -= screenInfo.screens[i]->y; } stuff->send_event = (send_event && !i) ? 1 : 0; result = ProcXvShmPutImage(client); } } return result; } Commit Message: CWE ID: CWE-20
XineramaXvShmPutImage(ClientPtr client) { REQUEST(xvShmPutImageReq); PanoramiXRes *draw, *gc, *port; Bool send_event; Bool isRoot; int result, i, x, y; REQUEST_SIZE_MATCH(xvShmPutImageReq); send_event = stuff->send_event; result = dixLookupResourceByClass((void **) &draw, stuff->drawable, XRC_DRAWABLE, client, DixWriteAccess); if (result != Success) result = dixLookupResourceByType((void **) &gc, stuff->gc, XRT_GC, client, DixReadAccess); if (result != Success) return result; result = dixLookupResourceByType((void **) &port, stuff->port, XvXRTPort, client, DixReadAccess); if (result != Success) return result; isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; x = stuff->drw_x; y = stuff->drw_y; FOR_NSCREENS_BACKWARD(i) { if (port->info[i].id) { stuff->drawable = draw->info[i].id; stuff->port = port->info[i].id; stuff->gc = gc->info[i].id; stuff->drw_x = x; stuff->drw_y = y; if (isRoot) { stuff->drw_x -= screenInfo.screens[i]->x; stuff->drw_y -= screenInfo.screens[i]->y; } stuff->send_event = (send_event && !i) ? 1 : 0; result = ProcXvShmPutImage(client); } } return result; }
165,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: png_get_mmx_bitdepth_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ return (png_ptr? 0: 0); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_mmx_bitdepth_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ PNG_UNUSED(png_ptr) return 0L; }
172,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); }
169,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_ERRORTYPE SoftGSM::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1) { return OMX_ErrorUndefined; } if (pcmParams->nSamplingRate != 8000) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.gsm", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftGSM::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1) { return OMX_ErrorUndefined; } if (pcmParams->nSamplingRate != 8000) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.gsm", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_METHOD(snmp, __construct) { php_snmp_object *snmp_object; zval *object = getThis(); char *a1, *a2; int a1_len, a2_len; long timeout = SNMP_DEFAULT_TIMEOUT; long retries = SNMP_DEFAULT_RETRIES; long version = SNMP_DEFAULT_VERSION; int argc = ZEND_NUM_ARGS(); zend_error_handling error_handling; snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); switch(version) { case SNMP_VERSION_1: case SNMP_VERSION_2c: case SNMP_VERSION_3: break; default: zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC); return; } /* handle re-open of snmp session */ if (snmp_object->session) { netsnmp_session_free(&(snmp_object->session)); } if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) { return; } snmp_object->max_oids = 0; snmp_object->valueretrieval = SNMP_G(valueretrieval); snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); snmp_object->oid_increasing_check = TRUE; snmp_object->exceptions_enabled = 0; } Commit Message: CWE ID: CWE-416
PHP_METHOD(snmp, __construct) { php_snmp_object *snmp_object; zval *object = getThis(); char *a1, *a2; int a1_len, a2_len; long timeout = SNMP_DEFAULT_TIMEOUT; long retries = SNMP_DEFAULT_RETRIES; long version = SNMP_DEFAULT_VERSION; int argc = ZEND_NUM_ARGS(); zend_error_handling error_handling; snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); switch(version) { case SNMP_VERSION_1: case SNMP_VERSION_2c: case SNMP_VERSION_3: break; default: zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC); return; } /* handle re-open of snmp session */ if (snmp_object->session) { netsnmp_session_free(&(snmp_object->session)); } if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) { return; } snmp_object->max_oids = 0; snmp_object->valueretrieval = SNMP_G(valueretrieval); snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); snmp_object->oid_increasing_check = TRUE; snmp_object->exceptions_enabled = 0; }
164,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebsiteSettings::OnUIClosing() { if (show_info_bar_) WebsiteSettingsInfoBarDelegate::Create(infobar_service_); SSLCertificateDecisionsDidRevoke user_decision = did_revoke_user_ssl_decisions_ ? USER_CERT_DECISIONS_REVOKED : USER_CERT_DECISIONS_NOT_REVOKED; UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.did_user_revoke_decisions", user_decision, END_OF_SSL_CERTIFICATE_DECISIONS_DID_REVOKE_ENUM); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
void WebsiteSettings::OnUIClosing() { if (show_info_bar_ && web_contents_) { InfoBarService* infobar_service = InfoBarService::FromWebContents(web_contents_); if (infobar_service) WebsiteSettingsInfoBarDelegate::Create(infobar_service); } SSLCertificateDecisionsDidRevoke user_decision = did_revoke_user_ssl_decisions_ ? USER_CERT_DECISIONS_REVOKED : USER_CERT_DECISIONS_NOT_REVOKED; UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.did_user_revoke_decisions", user_decision, END_OF_SSL_CERTIFICATE_DECISIONS_DID_REVOKE_ENUM); }
171,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static ssize_t exitcode_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { char *end, buf[sizeof("nnnnn\0")]; int tmp; if (copy_from_user(buf, buffer, count)) return -EFAULT; tmp = simple_strtol(buf, &end, 0); if ((*end != '\0') && !isspace(*end)) return -EINVAL; uml_exitcode = tmp; return count; } Commit Message: uml: check length in exitcode_proc_write() We don't cap the size of buffer from the user so we could write past the end of the array here. Only root can write to this file. Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119
static ssize_t exitcode_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { char *end, buf[sizeof("nnnnn\0")]; size_t size; int tmp; size = min(count, sizeof(buf)); if (copy_from_user(buf, buffer, size)) return -EFAULT; tmp = simple_strtol(buf, &end, 0); if ((*end != '\0') && !isspace(*end)) return -EINVAL; uml_exitcode = tmp; return count; }
165,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PepperDeviceEnumerationHostHelper::PepperDeviceEnumerationHostHelper( ppapi::host::ResourceHost* resource_host, Delegate* delegate, PP_DeviceType_Dev device_type, const GURL& document_url) : resource_host_(resource_host), delegate_(delegate), device_type_(device_type), document_url_(document_url) {} Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
PepperDeviceEnumerationHostHelper::PepperDeviceEnumerationHostHelper( ppapi::host::ResourceHost* resource_host, base::WeakPtr<Delegate> delegate, PP_DeviceType_Dev device_type, const GURL& document_url) : resource_host_(resource_host), delegate_(delegate), device_type_(device_type), document_url_(document_url) {}
171,604
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Context::Scope contextScope(context); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> console = v8::Object::New(isolate); createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback); createBoundFunctionProperty(context, console, "error", V8Console::errorCallback); createBoundFunctionProperty(context, console, "info", V8Console::infoCallback); createBoundFunctionProperty(context, console, "log", V8Console::logCallback); createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback); createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback); createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback); createBoundFunctionProperty(context, console, "table", V8Console::tableCallback); createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback); createBoundFunctionProperty(context, console, "group", V8Console::groupCallback); createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback); createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback); createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback); createBoundFunctionProperty(context, console, "count", V8Console::countCallback); createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback); createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback); createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback); createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback); createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback); createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback); createBoundFunctionProperty(context, console, "time", V8Console::timeCallback); createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback); createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback); bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false); DCHECK(success); if (hasMemoryAttribute) console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT); console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return console; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Context::Scope contextScope(context); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> console = v8::Object::New(isolate); bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false); DCHECK(success); createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback); createBoundFunctionProperty(context, console, "error", V8Console::errorCallback); createBoundFunctionProperty(context, console, "info", V8Console::infoCallback); createBoundFunctionProperty(context, console, "log", V8Console::logCallback); createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback); createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback); createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback); createBoundFunctionProperty(context, console, "table", V8Console::tableCallback); createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback); createBoundFunctionProperty(context, console, "group", V8Console::groupCallback); createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback); createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback); createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback); createBoundFunctionProperty(context, console, "count", V8Console::countCallback); createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback); createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback); createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback); createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback); createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback); createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback); createBoundFunctionProperty(context, console, "time", V8Console::timeCallback); createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback); createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback); if (hasMemoryAttribute) console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT); console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return console; }
172,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: CreateFileHelper(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type) : m_result(result) , m_name(name) , m_url(url) , m_type(type) { } 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
CreateFileHelper(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type) CreateFileHelper(CreateFileResult* result, const String& name, const KURL& url, FileSystemType type) : m_result(result) , m_name(name) , m_url(url) , m_type(type) { }
171,412
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(INFO); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); LOGFN(INFO) << "exit_code=" << exit_code; if (*exit_code == kUiecAbort) { LOGFN(ERROR) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#646278} CWE ID: CWE-284
HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(INFO); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); LOGFN(INFO) << "exit_code=" << *exit_code; if (*exit_code == kUiecAbort) { LOGFN(ERROR) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; }
172,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState) { ASSERT(eventTarget.toDOMWindow()); if (!canvas) { exceptionState.throwTypeError("The canvas element provided is invalid."); return ScriptPromise(); } if (!canvas->originClean()) { exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data."); return ScriptPromise(); } if (!sw || !sh) { exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width")); return ScriptPromise(); } return fulfillImageBitmap(eventTarget.executionContext(), ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh))); } Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas BUG=354356 Review URL: https://codereview.chromium.org/211313003 git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState) { ASSERT(eventTarget.toDOMWindow()); if (!canvas) { exceptionState.throwTypeError("The canvas element provided is invalid."); return ScriptPromise(); } if (!canvas->originClean()) { exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data."); return ScriptPromise(); } if (!sw || !sh) { exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width")); return ScriptPromise(); } return fulfillImageBitmap(eventTarget.executionContext(), canvas->buffer() ? ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)) : nullptr); }
171,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) { if (!strncmp(line, "export ", 7)) continue; val = strchr(line, '='); if (!val) { printf("invalid configuration line\n"); break; } *val++ = '\0'; if (!strcmp(line, "JSON_INDENT")) conf.indent = atoi(val); if (!strcmp(line, "JSON_COMPACT")) conf.compact = atoi(val); if (!strcmp(line, "JSON_ENSURE_ASCII")) conf.ensure_ascii = atoi(val); if (!strcmp(line, "JSON_PRESERVE_ORDER")) conf.preserve_order = atoi(val); if (!strcmp(line, "JSON_SORT_KEYS")) conf.sort_keys = atoi(val); if (!strcmp(line, "STRIP")) conf.strip = atoi(val); } free(buffer); } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) { if (!strncmp(line, "export ", 7)) continue; val = strchr(line, '='); if (!val) { printf("invalid configuration line\n"); break; } *val++ = '\0'; if (!strcmp(line, "JSON_INDENT")) conf.indent = atoi(val); if (!strcmp(line, "JSON_COMPACT")) conf.compact = atoi(val); if (!strcmp(line, "JSON_ENSURE_ASCII")) conf.ensure_ascii = atoi(val); if (!strcmp(line, "JSON_PRESERVE_ORDER")) conf.preserve_order = atoi(val); if (!strcmp(line, "JSON_SORT_KEYS")) conf.sort_keys = atoi(val); if (!strcmp(line, "STRIP")) conf.strip = atoi(val); if (!strcmp(line, "HASHSEED")) { conf.have_hashseed = 1; conf.hashseed = atoi(val); } else { conf.have_hashseed = 0; } } free(buffer); }
166,536