prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, int xoff, int yoff, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); int diff = r - src[w * y + x]; se += diff; sse += diff * diff; } } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: R_API void U(copy_type_info_to_stack_frame_list)(RList * type_list, RList * sf_list) { RListIter *iter, *iter_tmp; RBinJavaVerificationObj *ver_obj, *new_ver_obj; if (type_list == NULL) { return; } if (sf_list == NULL) { return; } r_list_foreach_safe (type_list, iter, iter_tmp, ver_obj) { new_ver_obj = (RBinJavaVerificationObj *) malloc (sizeof (RBinJavaVerificationObj)); if (new_ver_obj && ver_obj) { memcpy (new_ver_obj, ver_obj, sizeof (RBinJavaVerificationObj)); if (!r_list_append (sf_list, (void *) new_ver_obj)) { R_FREE (new_ver_obj); } } else { R_FREE (new_ver_obj); } } } Commit Message: Fix #10498 - Crash in fuzzed java file CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() { return RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled(); } Commit Message: Remove SpeechSynthesis runtime flag (status=stable) BUG=402536 Review URL: https://codereview.chromium.org/482273005 git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-94 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n, CH_UNIX, &c_size); src += c_size; c = toupper_m(c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: int sc_asn1_decode_bit_string_ni(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen) { return decode_bit_string(inbuf, inlen, outbuf, outlen, 0); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void vrend_set_framebuffer_state(struct vrend_context *ctx, uint32_t nr_cbufs, uint32_t surf_handle[8], uint32_t zsurf_handle) { struct vrend_surface *surf, *zsurf; int i; int old_num; GLenum status; GLint new_height = -1; bool new_ibf = false; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id); if (zsurf_handle) { zsurf = vrend_object_lookup(ctx->sub->object_hash, zsurf_handle, VIRGL_OBJECT_SURFACE); if (!zsurf) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, zsurf_handle); return; } } else zsurf = NULL; if (ctx->sub->zsurf != zsurf) { vrend_surface_reference(&ctx->sub->zsurf, zsurf); vrend_hw_set_zsurf_texture(ctx); } old_num = ctx->sub->nr_cbufs; ctx->sub->nr_cbufs = nr_cbufs; ctx->sub->old_nr_cbufs = old_num; for (i = 0; i < nr_cbufs; i++) { if (surf_handle[i] != 0) { surf = vrend_object_lookup(ctx->sub->object_hash, surf_handle[i], VIRGL_OBJECT_SURFACE); if (!surf) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, surf_handle[i]); return; } } else surf = NULL; if (ctx->sub->surf[i] != surf) { vrend_surface_reference(&ctx->sub->surf[i], surf); vrend_hw_set_color_surface(ctx, i); } } if (old_num > ctx->sub->nr_cbufs) { for (i = ctx->sub->nr_cbufs; i < old_num; i++) { vrend_surface_reference(&ctx->sub->surf[i], NULL); vrend_hw_set_color_surface(ctx, i); } } /* find a buffer to set fb_height from */ if (ctx->sub->nr_cbufs == 0 && !ctx->sub->zsurf) { new_height = 0; new_ibf = false; } else if (ctx->sub->nr_cbufs == 0) { new_height = u_minify(ctx->sub->zsurf->texture->base.height0, ctx->sub->zsurf->val0); new_ibf = ctx->sub->zsurf->texture->y_0_top ? true : false; } else { surf = NULL; for (i = 0; i < ctx->sub->nr_cbufs; i++) { if (ctx->sub->surf[i]) { surf = ctx->sub->surf[i]; break; } } if (surf == NULL) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, i); return; } new_height = u_minify(surf->texture->base.height0, surf->val0); new_ibf = surf->texture->y_0_top ? true : false; } if (new_height != -1) { if (ctx->sub->fb_height != new_height || ctx->sub->inverted_fbo_content != new_ibf) { ctx->sub->fb_height = new_height; ctx->sub->inverted_fbo_content = new_ibf; ctx->sub->scissor_state_dirty = (1 << 0); ctx->sub->viewport_state_dirty = (1 << 0); } } vrend_hw_emit_framebuffer_state(ctx); if (ctx->sub->nr_cbufs > 0 || ctx->sub->zsurf) { status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) fprintf(stderr,"failed to complete framebuffer 0x%x %s\n", status, ctx->debug_name); } ctx->sub->shader_dirty = true; } Commit Message: CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int 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 Target: 1 Example 2: Code: png_get_image_width(png_structp png_ptr, png_infop info_ptr) { if (png_ptr != NULL && info_ptr != NULL) return info_ptr->width; return (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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: pdf_set_shade(fz_context *ctx, pdf_run_processor *pr, int what, fz_shade *shade) { pdf_gstate *gs; pdf_material *mat; gs = pdf_flush_text(ctx, pr); mat = what == PDF_FILL ? &gs->fill : &gs->stroke; fz_drop_shade(ctx, mat->shade); mat->kind = PDF_MAT_SHADE; mat->shade = fz_keep_shade(ctx, shade); mat->gstate_num = pr->gparent; } Commit Message: CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: intuit_diff_type (bool need_header, mode_t *p_file_type) { file_offset this_line = 0; file_offset first_command_line = -1; char first_ed_command_letter = 0; lin fcl_line = 0; /* Pacify 'gcc -W'. */ bool this_is_a_command = false; bool stars_this_line = false; bool extended_headers = false; enum nametype i; struct stat st[3]; int stat_errno[3]; int version_controlled[3]; enum diff retval; mode_t file_type; size_t indent = 0; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { free (p_name[i]); p_name[i] = 0; } for (i = 0; i < ARRAY_SIZE (invalid_names); i++) invalid_names[i] = NULL; for (i = OLD; i <= NEW; i++) if (p_timestr[i]) { free(p_timestr[i]); p_timestr[i] = 0; } for (i = OLD; i <= NEW; i++) if (p_sha1[i]) { free (p_sha1[i]); p_sha1[i] = 0; } p_git_diff = false; for (i = OLD; i <= NEW; i++) { p_mode[i] = 0; p_copy[i] = false; p_rename[i] = false; } /* Ed and normal format patches don't have filename headers. */ if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF) need_header = false; version_controlled[OLD] = -1; version_controlled[NEW] = -1; version_controlled[INDEX] = -1; p_rfc934_nesting = 0; p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1; p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0; Fseek (pfp, p_base, SEEK_SET); p_input_line = p_bline - 1; for (;;) { char *s; char *t; file_offset previous_line = this_line; bool last_line_was_command = this_is_a_command; bool stars_last_line = stars_this_line; size_t indent_last_line = indent; char ed_command_letter; bool strip_trailing_cr; size_t chars_read; indent = 0; this_line = file_tell (pfp); chars_read = pget_line (0, 0, false, false); if (chars_read == (size_t) -1) xalloc_die (); if (! chars_read) { if (first_ed_command_letter) { /* nothing but deletes!? */ p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } else { p_start = this_line; p_sline = p_input_line; if (extended_headers) { /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } return NO_DIFF; } } strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r'; for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) { if (*s == '\t') indent = (indent + 8) & ~7; else indent++; } if (ISDIGIT (*s)) { for (t = s + 1; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; if (*t == 'd' || *t == 'c' || *t == 'a') { for (t++; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; for (; *t == ' ' || *t == '\t'; t++) /* do nothing */ ; if (*t == '\r') t++; this_is_a_command = (*t == '\n'); } } if (! need_header && first_command_line < 0 && ((ed_command_letter = get_ed_command_letter (s)) || this_is_a_command)) { first_command_line = this_line; first_ed_command_letter = ed_command_letter; fcl_line = p_input_line; p_indent = indent; /* assume this for now */ p_strip_trailing_cr = strip_trailing_cr; } if (!stars_last_line && strnEQ(s, "*** ", 4)) { fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; } else if (strnEQ(s, "+++ ", 4)) { /* Swap with NEW below. */ fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Index:", 6)) { fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Prereq:", 7)) { for (t = s + 7; ISSPACE ((unsigned char) *t); t++) /* do nothing */ ; revision = t; for (t = revision; *t; t++) if (ISSPACE ((unsigned char) *t)) { char const *u; for (u = t + 1; ISSPACE ((unsigned char) *u); u++) /* do nothing */ ; if (*u) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("Prereq: with multiple words at line %s of patch\n", format_linenum (numbuf, this_line)); } break; } if (t == revision) revision = 0; else { char oldc = *t; *t = '\0'; revision = xstrdup (revision); *t = oldc; } } else if (strnEQ (s, "diff --git ", 11)) { char const *u; if (extended_headers) { p_start = this_line; p_sline = p_input_line; /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u)) && ISSPACE ((unsigned char) *u) && (p_name[NEW] = parse_name (u, strippath, &u)) && (u = skip_spaces (u), ! *u))) for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } p_git_diff = true; need_header = false; } else if (p_git_diff && strnEQ (s, "index ", 6)) { char const *u, *v; if ((u = skip_hex_digits (s + 6)) && u[0] == '.' && u[1] == '.' && (v = skip_hex_digits (u + 2)) && (! *v || ISSPACE ((unsigned char) *v))) { get_sha1(&p_sha1[OLD], s + 6, u); get_sha1(&p_sha1[NEW], u + 2, v); p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]); p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]); if (*(v = skip_spaces (v))) p_mode[OLD] = p_mode[NEW] = fetchmode (v); extended_headers = true; } } else if (p_git_diff && strnEQ (s, "old mode ", 9)) { p_mode[OLD] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "new mode ", 9)) { p_mode[NEW] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "deleted file mode ", 18)) { p_mode[OLD] = fetchmode (s + 18); p_says_nonexistent[NEW] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "new file mode ", 14)) { p_mode[NEW] = fetchmode (s + 14); p_says_nonexistent[OLD] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename from ", 12)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename to ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy from ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy to ", 8)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "GIT binary patch", 16)) { p_start = this_line; p_sline = p_input_line; retval = GIT_BINARY_DIFF; goto scan_exit; } else { for (t = s; t[0] == '-' && t[1] == ' '; t += 2) /* do nothing */ ; if (strnEQ(t, "--- ", 4)) { struct timespec timestamp; timestamp.tv_sec = -1; fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW], &timestamp); need_header = false; if (timestamp.tv_sec != -1) { p_timestamp[NEW] = timestamp; p_rfc934_nesting = (t - s) >> 1; } p_strip_trailing_cr = strip_trailing_cr; } } if (need_header) continue; if ((diff_type == NO_DIFF || diff_type == ED_DIFF) && first_command_line >= 0 && strEQ(s, ".\n") ) { p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) { /* 'p_name', 'p_timestr', and 'p_timestamp' are backwards; swap them. */ struct timespec ti = p_timestamp[OLD]; p_timestamp[OLD] = p_timestamp[NEW]; p_timestamp[NEW] = ti; t = p_name[OLD]; p_name[OLD] = p_name[NEW]; p_name[NEW] = t; t = p_timestr[OLD]; p_timestr[OLD] = p_timestr[NEW]; p_timestr[NEW] = t; s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; while (*s != ' ' && *s != '\n') s++; while (*s == ' ') s++; if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2])) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; p_indent = indent; p_start = this_line; p_sline = p_input_line; retval = UNI_DIFF; if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for unified diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } stars_this_line = strnEQ(s, "********", 8); if ((diff_type == NO_DIFF || diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) && stars_last_line && indent_last_line == indent && strnEQ (s, "*** ", 4)) { s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; /* if this is a new context diff the character just before */ /* the newline is a '*'. */ while (*s != '\n') s++; p_indent = indent; p_strip_trailing_cr = strip_trailing_cr; p_start = previous_line; p_sline = p_input_line - 1; retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF); { /* Scan the first hunk to see whether the file contents appear to have been deleted. */ file_offset saved_p_base = p_base; lin saved_p_bline = p_bline; Fseek (pfp, previous_line, SEEK_SET); p_input_line -= 2; if (another_hunk (retval, false) && ! p_repl_lines && p_newfirst == 1) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; next_intuit_at (saved_p_base, saved_p_bline); } if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for context diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) && last_line_was_command && (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) { p_start = previous_line; p_sline = p_input_line - 1; p_indent = indent; retval = NORMAL_DIFF; goto scan_exit; } } scan_exit: /* The old, new, or old and new file types may be defined. When both file types are defined, make sure they are the same, or else assume we do not know the file type. */ file_type = p_mode[OLD] & S_IFMT; if (file_type) { mode_t new_file_type = p_mode[NEW] & S_IFMT; if (new_file_type && file_type != new_file_type) file_type = 0; } else { file_type = p_mode[NEW] & S_IFMT; if (! file_type) file_type = S_IFREG; } *p_file_type = file_type; /* To intuit 'inname', the name of the file to patch, use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599 (with some modifications if posixly_correct is zero): - Take the old and new names from the context header if present, and take the index name from the 'Index:' line if present and if either the old and new names are both absent or posixly_correct is nonzero. Consider the file names to be in the order (old, new, index). - If some named files exist, use the first one if posixly_correct is nonzero, the best one otherwise. - If patch_get is nonzero, and no named files exist, but an RCS or SCCS master file exists, use the first named file with an RCS or SCCS master. - If no named files exist, no RCS or SCCS master was found, some names are given, posixly_correct is zero, and the patch appears to create a file, then use the best name requiring the creation of the fewest directories. - Otherwise, report failure by setting 'inname' to 0; this causes our invoker to ask the user for a file name. */ i = NONE; if (!inname) { enum nametype i0 = NONE; if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX]) { free (p_name[INDEX]); p_name[INDEX] = 0; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) { if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0) { /* It's the same name as before; reuse stat results. */ stat_errno[i] = stat_errno[i0]; if (! stat_errno[i]) st[i] = st[i0]; } else { stat_errno[i] = stat_file (p_name[i], &st[i]); if (! stat_errno[i]) { if (lookup_file_id (&st[i]) == DELETE_LATER) stat_errno[i] = ENOENT; else if (posixly_correct && name_is_valid (p_name[i])) break; } } i0 = i; } if (! posixly_correct) { /* The best of all existing files. */ i = best_name (p_name, stat_errno); if (i == NONE && patch_get) { enum nametype nope = NONE; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { char const *cs; char *getbuf; char *diffbuf; bool readonly = (outfile && strcmp (outfile, p_name[i]) != 0); if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0) { cs = (version_controller (p_name[i], readonly, (struct stat *) 0, &getbuf, &diffbuf)); version_controlled[i] = !! cs; if (cs) { if (version_get (p_name[i], cs, false, readonly, getbuf, &st[i])) stat_errno[i] = 0; else version_controlled[i] = 0; free (getbuf); free (diffbuf); if (! stat_errno[i]) break; } } nope = i; } } if (i0 != NONE && (i == NONE || (st[i].st_mode & S_IFMT) == file_type) && maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE, i == NONE || st[i].st_size == 0) && i == NONE) i = i0; if (i == NONE && p_says_nonexistent[reverse]) { int newdirs[3]; int newdirs_min = INT_MAX; int distance_from_minimum[3]; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { newdirs[i] = (prefix_components (p_name[i], false) - prefix_components (p_name[i], true)); if (newdirs[i] < newdirs_min) newdirs_min = newdirs[i]; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) distance_from_minimum[i] = newdirs[i] - newdirs_min; /* The best of the filenames which create the fewest directories. */ i = best_name (p_name, distance_from_minimum); } } } if ((pch_rename () || pch_copy ()) && ! inname && ! ((i == OLD || i == NEW) && p_name[! reverse] && name_is_valid (p_name[! reverse]))) { say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy"); } if (i == NONE) { if (inname) { inerrno = stat_file (inname, &instat); if (inerrno || (instat.st_mode & S_IFMT) == file_type) maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0); } else inerrno = -1; } else { inname = xstrdup (p_name[i]); inerrno = stat_errno[i]; invc = version_controlled[i]; instat = st[i]; } return retval; } Commit Message: CWE ID: CWE-476 Target: 1 Example 2: Code: WebGLShaderPrecisionFormat* WebGLRenderingContextBase::getShaderPrecisionFormat( GLenum shader_type, GLenum precision_type) { if (isContextLost()) return nullptr; if (!ValidateShaderType("getShaderPrecisionFormat", shader_type)) { return nullptr; } switch (precision_type) { case GL_LOW_FLOAT: case GL_MEDIUM_FLOAT: case GL_HIGH_FLOAT: case GL_LOW_INT: case GL_MEDIUM_INT: case GL_HIGH_INT: break; default: SynthesizeGLError(GL_INVALID_ENUM, "getShaderPrecisionFormat", "invalid precision type"); return nullptr; } GLint range[2] = {0, 0}; GLint precision = 0; ContextGL()->GetShaderPrecisionFormat(shader_type, precision_type, range, &precision); return WebGLShaderPrecisionFormat::Create(range[0], range[1], precision); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: enum paravirt_lazy_mode paravirt_get_lazy_mode(void) { if (in_interrupt()) return PARAVIRT_LAZY_NONE; return this_cpu_read(paravirt_lazy_mode); } Commit Message: x86/paravirt: Fix spectre-v2 mitigations for paravirt guests Nadav reported that on guests we're failing to rewrite the indirect calls to CALLEE_SAVE paravirt functions. In particular the pv_queued_spin_unlock() call is left unpatched and that is all over the place. This obviously wrecks Spectre-v2 mitigation (for paravirt guests) which relies on not actually having indirect calls around. The reason is an incorrect clobber test in paravirt_patch_call(); this function rewrites an indirect call with a direct call to the _SAME_ function, there is no possible way the clobbers can be different because of this. Therefore remove this clobber check. Also put WARNs on the other patch failure case (not enough room for the instruction) which I've not seen trigger in my (limited) testing. Three live kernel image disassemblies for lock_sock_nested (as a small function that illustrates the problem nicely). PRE is the current situation for guests, POST is with this patch applied and NATIVE is with or without the patch for !guests. PRE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq *0xffffffff822299e8 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. POST: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq 0xffffffff810a0c20 <__raw_callee_save___pv_queued_spin_unlock> 0xffffffff817be9a5 <+53>: xchg %ax,%ax 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063aa0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. NATIVE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: movb $0x0,(%rdi) 0xffffffff817be9a3 <+51>: nopl 0x0(%rax) 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. Fixes: 63f70270ccd9 ("[PATCH] i386: PARAVIRT: add common patching machinery") Fixes: 3010a0663fd9 ("x86/paravirt, objtool: Annotate indirect calls") Reported-by: Nadav Amit <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Juergen Gross <[email protected]> Cc: Konrad Rzeszutek Wilk <[email protected]> Cc: Boris Ostrovsky <[email protected]> Cc: David Woodhouse <[email protected]> Cc: [email protected] CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long long Segment::CreateInstance(IMkvReader* pReader, long long pos, Segment*& pSegment) { assert(pReader); assert(pos >= 0); pSegment = NULL; long long total, available; const long status = pReader->Length(&total, &available); if (status < 0) // error return status; if (available < 0) return -1; if ((total >= 0) && (available > total)) return -1; for (;;) { if ((total >= 0) && (pos >= total)) return E_FILE_FORMAT_INVALID; long len; long long result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return id; pos += len; // consume ID result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return size; pos += len; // consume length of size of element const long long unknown_size = (1LL << (7 * len)) - 1; if (id == 0x08538067) { // Segment ID if (size == unknown_size) size = -1; else if (total < 0) size = -1; else if ((pos + size) > total) size = -1; pSegment = new (std::nothrow) Segment(pReader, idpos, pos, size); if (pSegment == 0) return -1; // generic error return 0; // success } if (size == unknown_size) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + size) > total)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; pos += size; // consume payload } } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20 Target: 1 Example 2: Code: bool CanRequestURLFromRenderer(int render_process_id, GURL url) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL( render_process_id, url)) { DVLOG(1) << "Denied unauthorized download request for " << url.possibly_invalid_spec(); return false; } return true; } Commit Message: Downloads : Fixed an issue of opening incorrect download file When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download. Bug: 793620 Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8 Reviewed-on: https://chromium-review.googlesource.com/826477 Reviewed-by: David Trainor <[email protected]> Reviewed-by: Xing Liu <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Commit-Queue: Shakti Sahu <[email protected]> Cr-Commit-Position: refs/heads/master@{#525810} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m1[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m2[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */ { time_t timestamp = 0; php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; assert(ms != NULL); memset(ssb, 0, sizeof(php_stream_statbuf)); /* read-only across the board */ ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666; ssb->sb.st_size = ms->fsize; ssb->sb.st_mode |= S_IFREG; /* regular file */ #ifdef NETWARE ssb->sb.st_mtime.tv_sec = timestamp; ssb->sb.st_atime.tv_sec = timestamp; ssb->sb.st_ctime.tv_sec = timestamp; #else ssb->sb.st_mtime = timestamp; ssb->sb.st_atime = timestamp; ssb->sb.st_ctime = timestamp; #endif ssb->sb.st_nlink = 1; ssb->sb.st_rdev = -1; /* this is only for APC, so use /dev/null device - no chance of conflict there! */ ssb->sb.st_dev = 0xC; /* generate unique inode number for alias/filename, so no phars will conflict */ ssb->sb.st_ino = 0; #ifndef PHP_WIN32 ssb->sb.st_blksize = -1; #endif #if !defined(PHP_WIN32) && !defined(__BEOS__) ssb->sb.st_blocks = -1; #endif return 0; } /* }}} */ Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: int _sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1, u8 **ptr, size_t *size, int depth) { return asn1_encode(ctx, asn1, ptr, size, depth); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int flush_completed_IO(struct inode *inode) { ext4_io_end_t *io; int ret = 0; int ret2 = 0; if (list_empty(&EXT4_I(inode)->i_completed_io_list)) return ret; dump_completed_IO(inode); while (!list_empty(&EXT4_I(inode)->i_completed_io_list)){ io = list_entry(EXT4_I(inode)->i_completed_io_list.next, ext4_io_end_t, list); /* * Calling ext4_end_io_nolock() to convert completed * IO to written. * * When ext4_sync_file() is called, run_queue() may already * about to flush the work corresponding to this io structure. * It will be upset if it founds the io structure related * to the work-to-be schedule is freed. * * Thus we need to keep the io structure still valid here after * convertion finished. The io structure has a flag to * avoid double converting from both fsync and background work * queue work. */ ret = ext4_end_io_nolock(io); if (ret < 0) ret2 = ret; else list_del_init(&io->list); } return (ret2 < 0) ? ret2 : 0; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void set_task_blockstep(struct task_struct *task, bool on) { unsigned long debugctl; /* * Ensure irq/preemption can't change debugctl in between. * Note also that both TIF_BLOCKSTEP and debugctl should * be changed atomically wrt preemption. * FIXME: this means that set/clear TIF_BLOCKSTEP is simply * wrong if task != current, SIGKILL can wakeup the stopped * tracee and set/clear can play with the running task, this * can confuse the next __switch_to_xtra(). */ local_irq_disable(); debugctl = get_debugctlmsr(); if (on) { debugctl |= DEBUGCTLMSR_BTF; set_tsk_thread_flag(task, TIF_BLOCKSTEP); } else { debugctl &= ~DEBUGCTLMSR_BTF; clear_tsk_thread_flag(task, TIF_BLOCKSTEP); } if (task == current) update_debugctlmsr(debugctl); local_irq_enable(); } Commit Message: ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL putreg() assumes that the tracee is not running and pt_regs_access() can safely play with its stack. However a killed tracee can return from ptrace_stop() to the low-level asm code and do RESTORE_REST, this means that debugger can actually read/modify the kernel stack until the tracee does SAVE_REST again. set_task_blockstep() can race with SIGKILL too and in some sense this race is even worse, the very fact the tracee can be woken up breaks the logic. As Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace() call, this ensures that nobody can ever wakeup the tracee while the debugger looks at it. Not only this fixes the mentioned problems, we can do some cleanups/simplifications in arch_ptrace() paths. Probably ptrace_unfreeze_traced() needs more callers, for example it makes sense to make the tracee killable for oom-killer before access_process_vm(). While at it, add the comment into may_ptrace_stop() to explain why ptrace_stop() still can't rely on SIGKILL and signal_pending_state(). Reported-by: Salman Qazi <[email protected]> Reported-by: Suleiman Souhlal <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Oleg Nesterov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus, u16 portchange) { int status = -ENODEV; int i; unsigned unit_load; struct usb_device *hdev = hub->hdev; struct usb_hcd *hcd = bus_to_hcd(hdev->bus); struct usb_port *port_dev = hub->ports[port1 - 1]; struct usb_device *udev = port_dev->child; static int unreliable_port = -1; /* Disconnect any existing devices under this port */ if (udev) { if (hcd->usb_phy && !hdev->parent) usb_phy_notify_disconnect(hcd->usb_phy, udev->speed); usb_disconnect(&port_dev->child); } /* We can forget about a "removed" device when there's a physical * disconnect or the connect status changes. */ if (!(portstatus & USB_PORT_STAT_CONNECTION) || (portchange & USB_PORT_STAT_C_CONNECTION)) clear_bit(port1, hub->removed_bits); if (portchange & (USB_PORT_STAT_C_CONNECTION | USB_PORT_STAT_C_ENABLE)) { status = hub_port_debounce_be_stable(hub, port1); if (status < 0) { if (status != -ENODEV && port1 != unreliable_port && printk_ratelimit()) dev_err(&port_dev->dev, "connect-debounce failed\n"); portstatus &= ~USB_PORT_STAT_CONNECTION; unreliable_port = port1; } else { portstatus = status; } } /* Return now if debouncing failed or nothing is connected or * the device was "removed". */ if (!(portstatus & USB_PORT_STAT_CONNECTION) || test_bit(port1, hub->removed_bits)) { /* * maybe switch power back on (e.g. root hub was reset) * but only if the port isn't owned by someone else. */ if (hub_is_port_power_switchable(hub) && !port_is_power_on(hub, portstatus) && !port_dev->port_owner) set_port_feature(hdev, port1, USB_PORT_FEAT_POWER); if (portstatus & USB_PORT_STAT_ENABLE) goto done; return; } if (hub_is_superspeed(hub->hdev)) unit_load = 150; else unit_load = 100; status = 0; for (i = 0; i < SET_CONFIG_TRIES; i++) { /* reallocate for each attempt, since references * to the previous one can escape in various ways */ udev = usb_alloc_dev(hdev, hdev->bus, port1); if (!udev) { dev_err(&port_dev->dev, "couldn't allocate usb_device\n"); goto done; } usb_set_device_state(udev, USB_STATE_POWERED); udev->bus_mA = hub->mA_per_port; udev->level = hdev->level + 1; udev->wusb = hub_is_wusb(hub); /* Devices connected to SuperSpeed hubs are USB 3.0 or later */ if (hub_is_superspeed(hub->hdev)) udev->speed = USB_SPEED_SUPER; else udev->speed = USB_SPEED_UNKNOWN; choose_devnum(udev); if (udev->devnum <= 0) { status = -ENOTCONN; /* Don't retry */ goto loop; } /* reset (non-USB 3.0 devices) and get descriptor */ usb_lock_port(port_dev); status = hub_port_init(hub, udev, port1, i); usb_unlock_port(port_dev); if (status < 0) goto loop; if (udev->quirks & USB_QUIRK_DELAY_INIT) msleep(2000); /* consecutive bus-powered hubs aren't reliable; they can * violate the voltage drop budget. if the new child has * a "powered" LED, users should notice we didn't enable it * (without reading syslog), even without per-port LEDs * on the parent. */ if (udev->descriptor.bDeviceClass == USB_CLASS_HUB && udev->bus_mA <= unit_load) { u16 devstat; status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0, &devstat); if (status) { dev_dbg(&udev->dev, "get status %d ?\n", status); goto loop_disable; } if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) { dev_err(&udev->dev, "can't connect bus-powered hub " "to this port\n"); if (hub->has_indicators) { hub->indicator[port1-1] = INDICATOR_AMBER_BLINK; queue_delayed_work( system_power_efficient_wq, &hub->leds, 0); } status = -ENOTCONN; /* Don't retry */ goto loop_disable; } } /* check for devices running slower than they could */ if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200 && udev->speed == USB_SPEED_FULL && highspeed_hubs != 0) check_highspeed(hub, udev, port1); /* Store the parent's children[] pointer. At this point * udev becomes globally accessible, although presumably * no one will look at it until hdev is unlocked. */ status = 0; mutex_lock(&usb_port_peer_mutex); /* We mustn't add new devices if the parent hub has * been disconnected; we would race with the * recursively_mark_NOTATTACHED() routine. */ spin_lock_irq(&device_state_lock); if (hdev->state == USB_STATE_NOTATTACHED) status = -ENOTCONN; else port_dev->child = udev; spin_unlock_irq(&device_state_lock); mutex_unlock(&usb_port_peer_mutex); /* Run it through the hoops (find a driver, etc) */ if (!status) { status = usb_new_device(udev); if (status) { mutex_lock(&usb_port_peer_mutex); spin_lock_irq(&device_state_lock); port_dev->child = NULL; spin_unlock_irq(&device_state_lock); mutex_unlock(&usb_port_peer_mutex); } else { if (hcd->usb_phy && !hdev->parent) usb_phy_notify_connect(hcd->usb_phy, udev->speed); } } if (status) goto loop_disable; status = hub_power_remaining(hub); if (status) dev_dbg(hub->intfdev, "%dmA power budget left\n", status); return; loop_disable: hub_port_disable(hub, port1, 1); loop: usb_ep0_reinit(udev); release_devnum(udev); hub_free_dev(udev); usb_put_dev(udev); if ((status == -ENOTCONN) || (status == -ENOTSUPP)) break; /* When halfway through our retry count, power-cycle the port */ if (i == (SET_CONFIG_TRIES / 2) - 1) { dev_info(&port_dev->dev, "attempt power cycle\n"); usb_hub_set_port_power(hdev, hub, port1, false); msleep(2 * hub_power_on_good_delay(hub)); usb_hub_set_port_power(hdev, hub, port1, true); msleep(hub_power_on_good_delay(hub)); } } if (hub->hdev->parent || !hcd->driver->port_handed_over || !(hcd->driver->port_handed_over)(hcd, port1)) { if (status != -ENOTCONN && status != -ENODEV) dev_err(&port_dev->dev, "unable to enumerate USB device\n"); } done: hub_port_disable(hub, port1, 1); if (hcd->driver->relinquish_port && !hub->hdev->parent) { if (status != -ENOTCONN && status != -ENODEV) hcd->driver->relinquish_port(hcd, port1); } } Commit Message: USB: check usb_get_extra_descriptor for proper size When reading an extra descriptor, we need to properly check the minimum and maximum size allowed, to prevent from invalid data being sent by a device. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Co-developed-by: Linus Torvalds <[email protected]> Signed-off-by: Hui Peng <[email protected]> Signed-off-by: Mathias Payer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static PassRefPtr<CSSValue> valueForReflection(const StyleReflection* reflection, const RenderStyle* style) { if (!reflection) return cssValuePool().createIdentifierValue(CSSValueNone); RefPtr<CSSPrimitiveValue> offset; if (reflection->offset().isPercent()) offset = cssValuePool().createValue(reflection->offset().percent(), CSSPrimitiveValue::CSS_PERCENTAGE); else offset = zoomAdjustedPixelValue(reflection->offset().value(), style); return CSSReflectValue::create(reflection->direction(), offset.release(), valueForNinePieceImage(reflection->mask())); } Commit Message: Rename isPositioned to isOutOfFlowPositioned for clarity https://bugs.webkit.org/show_bug.cgi?id=89836 Reviewed by Antti Koivisto. RenderObject and RenderStyle had an isPositioned() method that was confusing, because it excluded relative positioning. Rename to isOutOfFlowPositioned(), which makes it clearer that it only applies to absolute and fixed positioning. Simple rename; no behavior change. Source/WebCore: * css/CSSComputedStyleDeclaration.cpp: (WebCore::getPositionOffsetValue): * css/StyleResolver.cpp: (WebCore::StyleResolver::collectMatchingRulesForList): * dom/Text.cpp: (WebCore::Text::rendererIsNeeded): * editing/DeleteButtonController.cpp: (WebCore::isDeletableElement): * editing/TextIterator.cpp: (WebCore::shouldEmitNewlinesBeforeAndAfterNode): * rendering/AutoTableLayout.cpp: (WebCore::shouldScaleColumns): * rendering/InlineFlowBox.cpp: (WebCore::InlineFlowBox::addToLine): (WebCore::InlineFlowBox::placeBoxesInInlineDirection): (WebCore::InlineFlowBox::requiresIdeographicBaseline): (WebCore::InlineFlowBox::adjustMaxAscentAndDescent): (WebCore::InlineFlowBox::computeLogicalBoxHeights): (WebCore::InlineFlowBox::placeBoxesInBlockDirection): (WebCore::InlineFlowBox::flipLinesInBlockDirection): (WebCore::InlineFlowBox::computeOverflow): (WebCore::InlineFlowBox::computeOverAnnotationAdjustment): (WebCore::InlineFlowBox::computeUnderAnnotationAdjustment): * rendering/InlineIterator.h: (WebCore::isIteratorTarget): * rendering/LayoutState.cpp: (WebCore::LayoutState::LayoutState): * rendering/RenderBlock.cpp: (WebCore::RenderBlock::MarginInfo::MarginInfo): (WebCore::RenderBlock::styleWillChange): (WebCore::RenderBlock::styleDidChange): (WebCore::RenderBlock::addChildToContinuation): (WebCore::RenderBlock::addChildToAnonymousColumnBlocks): (WebCore::RenderBlock::containingColumnsBlock): (WebCore::RenderBlock::columnsBlockForSpanningElement): (WebCore::RenderBlock::addChildIgnoringAnonymousColumnBlocks): (WebCore::getInlineRun): (WebCore::RenderBlock::isSelfCollapsingBlock): (WebCore::RenderBlock::layoutBlock): (WebCore::RenderBlock::addOverflowFromBlockChildren): (WebCore::RenderBlock::expandsToEncloseOverhangingFloats): (WebCore::RenderBlock::handlePositionedChild): (WebCore::RenderBlock::moveRunInUnderSiblingBlockIfNeeded): (WebCore::RenderBlock::collapseMargins): (WebCore::RenderBlock::clearFloatsIfNeeded): (WebCore::RenderBlock::simplifiedNormalFlowLayout): (WebCore::RenderBlock::isSelectionRoot): (WebCore::RenderBlock::blockSelectionGaps): (WebCore::RenderBlock::clearFloats): (WebCore::RenderBlock::markAllDescendantsWithFloatsForLayout): (WebCore::RenderBlock::markSiblingsWithFloatsForLayout): (WebCore::isChildHitTestCandidate): (WebCore::InlineMinMaxIterator::next): (WebCore::RenderBlock::computeBlockPreferredLogicalWidths): (WebCore::RenderBlock::firstLineBoxBaseline): (WebCore::RenderBlock::lastLineBoxBaseline): (WebCore::RenderBlock::updateFirstLetter): (WebCore::shouldCheckLines): (WebCore::getHeightForLineCount): (WebCore::RenderBlock::adjustForBorderFit): (WebCore::inNormalFlow): (WebCore::RenderBlock::adjustLinePositionForPagination): (WebCore::RenderBlock::adjustBlockChildForPagination): (WebCore::RenderBlock::renderName): * rendering/RenderBlock.h: (WebCore::RenderBlock::shouldSkipCreatingRunsForObject): * rendering/RenderBlockLineLayout.cpp: (WebCore::RenderBlock::setMarginsForRubyRun): (WebCore::RenderBlock::computeInlineDirectionPositionsForLine): (WebCore::RenderBlock::computeBlockDirectionPositionsForLine): (WebCore::RenderBlock::layoutInlineChildren): (WebCore::requiresLineBox): (WebCore::RenderBlock::LineBreaker::skipTrailingWhitespace): (WebCore::RenderBlock::LineBreaker::skipLeadingWhitespace): (WebCore::RenderBlock::LineBreaker::nextLineBreak): * rendering/RenderBox.cpp: (WebCore::RenderBox::removeFloatingOrPositionedChildFromBlockLists): (WebCore::RenderBox::styleWillChange): (WebCore::RenderBox::styleDidChange): (WebCore::RenderBox::updateBoxModelInfoFromStyle): (WebCore::RenderBox::offsetFromContainer): (WebCore::RenderBox::positionLineBox): (WebCore::RenderBox::computeRectForRepaint): (WebCore::RenderBox::computeLogicalWidthInRegion): (WebCore::RenderBox::renderBoxRegionInfo): (WebCore::RenderBox::computeLogicalHeight): (WebCore::RenderBox::computePercentageLogicalHeight): (WebCore::RenderBox::computeReplacedLogicalWidthUsing): (WebCore::RenderBox::computeReplacedLogicalHeightUsing): (WebCore::RenderBox::availableLogicalHeightUsing): (WebCore::percentageLogicalHeightIsResolvable): * rendering/RenderBox.h: (WebCore::RenderBox::stretchesToViewport): (WebCore::RenderBox::isDeprecatedFlexItem): * rendering/RenderBoxModelObject.cpp: (WebCore::RenderBoxModelObject::adjustedPositionRelativeToOffsetParent): (WebCore::RenderBoxModelObject::mapAbsoluteToLocalPoint): * rendering/RenderBoxModelObject.h: (WebCore::RenderBoxModelObject::requiresLayer): * rendering/RenderDeprecatedFlexibleBox.cpp: (WebCore::childDoesNotAffectWidthOrFlexing): (WebCore::RenderDeprecatedFlexibleBox::layoutBlock): (WebCore::RenderDeprecatedFlexibleBox::layoutHorizontalBox): (WebCore::RenderDeprecatedFlexibleBox::layoutVerticalBox): (WebCore::RenderDeprecatedFlexibleBox::renderName): * rendering/RenderFieldset.cpp: (WebCore::RenderFieldset::findLegend): * rendering/RenderFlexibleBox.cpp: (WebCore::RenderFlexibleBox::computePreferredLogicalWidths): (WebCore::RenderFlexibleBox::autoMarginOffsetInMainAxis): (WebCore::RenderFlexibleBox::availableAlignmentSpaceForChild): (WebCore::RenderFlexibleBox::computeMainAxisPreferredSizes): (WebCore::RenderFlexibleBox::computeNextFlexLine): (WebCore::RenderFlexibleBox::resolveFlexibleLengths): (WebCore::RenderFlexibleBox::prepareChildForPositionedLayout): (WebCore::RenderFlexibleBox::layoutAndPlaceChildren): (WebCore::RenderFlexibleBox::layoutColumnReverse): (WebCore::RenderFlexibleBox::adjustAlignmentForChild): (WebCore::RenderFlexibleBox::flipForRightToLeftColumn): * rendering/RenderGrid.cpp: (WebCore::RenderGrid::renderName): * rendering/RenderImage.cpp: (WebCore::RenderImage::computeIntrinsicRatioInformation): * rendering/RenderInline.cpp: (WebCore::RenderInline::addChildIgnoringContinuation): (WebCore::RenderInline::addChildToContinuation): (WebCore::RenderInline::generateCulledLineBoxRects): (WebCore): (WebCore::RenderInline::culledInlineFirstLineBox): (WebCore::RenderInline::culledInlineLastLineBox): (WebCore::RenderInline::culledInlineVisualOverflowBoundingBox): (WebCore::RenderInline::computeRectForRepaint): (WebCore::RenderInline::dirtyLineBoxes): * rendering/RenderLayer.cpp: (WebCore::checkContainingBlockChainForPagination): (WebCore::RenderLayer::updateLayerPosition): (WebCore::isPositionedContainer): (WebCore::RenderLayer::calculateClipRects): (WebCore::RenderLayer::shouldBeNormalFlowOnly): * rendering/RenderLayerCompositor.cpp: (WebCore::RenderLayerCompositor::requiresCompositingForPosition): * rendering/RenderLineBoxList.cpp: (WebCore::RenderLineBoxList::dirtyLinesFromChangedChild): * rendering/RenderListItem.cpp: (WebCore::getParentOfFirstLineBox): * rendering/RenderMultiColumnBlock.cpp: (WebCore::RenderMultiColumnBlock::renderName): * rendering/RenderObject.cpp: (WebCore::RenderObject::markContainingBlocksForLayout): (WebCore::RenderObject::setPreferredLogicalWidthsDirty): (WebCore::RenderObject::invalidateContainerPreferredLogicalWidths): (WebCore::RenderObject::styleWillChange): (WebCore::RenderObject::offsetParent): * rendering/RenderObject.h: (WebCore::RenderObject::isOutOfFlowPositioned): (WebCore::RenderObject::isInFlowPositioned): (WebCore::RenderObject::hasClip): (WebCore::RenderObject::isFloatingOrOutOfFlowPositioned): * rendering/RenderObjectChildList.cpp: (WebCore::RenderObjectChildList::removeChildNode): * rendering/RenderReplaced.cpp: (WebCore::hasAutoHeightOrContainingBlockWithAutoHeight): * rendering/RenderRubyRun.cpp: (WebCore::RenderRubyRun::rubyText): * rendering/RenderTable.cpp: (WebCore::RenderTable::addChild): (WebCore::RenderTable::computeLogicalWidth): (WebCore::RenderTable::layout): * rendering/style/RenderStyle.h: Source/WebKit/blackberry: * Api/WebPage.cpp: (BlackBerry::WebKit::isPositionedContainer): (BlackBerry::WebKit::isNonRenderViewFixedPositionedContainer): (BlackBerry::WebKit::isFixedPositionedContainer): Source/WebKit2: * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::updateOffsetFromViewportForSelf): git-svn-id: svn://svn.chromium.org/blink/trunk@121123 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SYSCALL_DEFINE5(perf_event_open, struct perf_event_attr __user *, attr_uptr, pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) { struct perf_event *group_leader = NULL, *output_event = NULL; struct perf_event *event, *sibling; struct perf_event_attr attr; struct perf_event_context *ctx, *uninitialized_var(gctx); struct file *event_file = NULL; struct fd group = {NULL, 0}; struct task_struct *task = NULL; struct pmu *pmu; int event_fd; int move_group = 0; int err; int f_flags = O_RDWR; int cgroup_fd = -1; /* for future expandability... */ if (flags & ~PERF_FLAG_ALL) return -EINVAL; err = perf_copy_attr(attr_uptr, &attr); if (err) return err; if (!attr.exclude_kernel) { if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr.freq) { if (attr.sample_freq > sysctl_perf_event_sample_rate) return -EINVAL; } else { if (attr.sample_period & (1ULL << 63)) return -EINVAL; } if (!attr.sample_max_stack) attr.sample_max_stack = sysctl_perf_event_max_stack; /* * In cgroup mode, the pid argument is used to pass the fd * opened to the cgroup directory in cgroupfs. The cpu argument * designates the cpu on which to monitor threads from that * cgroup. */ if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) return -EINVAL; if (flags & PERF_FLAG_FD_CLOEXEC) f_flags |= O_CLOEXEC; event_fd = get_unused_fd_flags(f_flags); if (event_fd < 0) return event_fd; if (group_fd != -1) { err = perf_fget_light(group_fd, &group); if (err) goto err_fd; group_leader = group.file->private_data; if (flags & PERF_FLAG_FD_OUTPUT) output_event = group_leader; if (flags & PERF_FLAG_FD_NO_GROUP) group_leader = NULL; } if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { task = find_lively_task_by_vpid(pid); if (IS_ERR(task)) { err = PTR_ERR(task); goto err_group_fd; } } if (task && group_leader && group_leader->attr.inherit != attr.inherit) { err = -EINVAL; goto err_task; } get_online_cpus(); if (task) { err = mutex_lock_interruptible(&task->signal->cred_guard_mutex); if (err) goto err_cpus; /* * Reuse ptrace permission checks for now. * * We must hold cred_guard_mutex across this and any potential * perf_install_in_context() call for this new event to * serialize against exec() altering our credentials (and the * perf_event_exit_task() that could imply). */ err = -EACCES; if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) goto err_cred; } if (flags & PERF_FLAG_PID_CGROUP) cgroup_fd = pid; event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL, NULL, cgroup_fd); if (IS_ERR(event)) { err = PTR_ERR(event); goto err_cred; } if (is_sampling_event(event)) { if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { err = -EOPNOTSUPP; goto err_alloc; } } /* * Special case software events and allow them to be part of * any hardware group. */ pmu = event->pmu; if (attr.use_clockid) { err = perf_event_set_clock(event, attr.clockid); if (err) goto err_alloc; } if (pmu->task_ctx_nr == perf_sw_context) event->event_caps |= PERF_EV_CAP_SOFTWARE; if (group_leader && (is_software_event(event) != is_software_event(group_leader))) { if (is_software_event(event)) { /* * If event and group_leader are not both a software * event, and event is, then group leader is not. * * Allow the addition of software events to !software * groups, this is safe because software events never * fail to schedule. */ pmu = group_leader->pmu; } else if (is_software_event(group_leader) && (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { /* * In case the group is a pure software group, and we * try to add a hardware event, move the whole group to * the hardware context. */ move_group = 1; } } /* * Get the target context (task or percpu): */ ctx = find_get_context(pmu, task, event); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_alloc; } if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) { err = -EBUSY; goto err_context; } /* * Look up the group leader (we will attach this event to it): */ if (group_leader) { err = -EINVAL; /* * Do not allow a recursive hierarchy (this new sibling * becoming part of another group-sibling): */ if (group_leader->group_leader != group_leader) goto err_context; /* All events in a group should have the same clock */ if (group_leader->clock != event->clock) goto err_context; /* * Do not allow to attach to a group in a different * task or CPU context: */ if (move_group) { /* * Make sure we're both on the same task, or both * per-cpu events. */ if (group_leader->ctx->task != ctx->task) goto err_context; /* * Make sure we're both events for the same CPU; * grouping events for different CPUs is broken; since * you can never concurrently schedule them anyhow. */ if (group_leader->cpu != event->cpu) goto err_context; } else { if (group_leader->ctx != ctx) goto err_context; } /* * Only a group leader can be exclusive or pinned */ if (attr.exclusive || attr.pinned) goto err_context; } if (output_event) { err = perf_event_set_output(event, output_event); if (err) goto err_context; } event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); if (IS_ERR(event_file)) { err = PTR_ERR(event_file); event_file = NULL; goto err_context; } if (move_group) { gctx = group_leader->ctx; mutex_lock_double(&gctx->mutex, &ctx->mutex); if (gctx->task == TASK_TOMBSTONE) { err = -ESRCH; goto err_locked; } } else { mutex_lock(&ctx->mutex); } if (ctx->task == TASK_TOMBSTONE) { err = -ESRCH; goto err_locked; } if (!perf_event_validate_size(event)) { err = -E2BIG; goto err_locked; } /* * Must be under the same ctx::mutex as perf_install_in_context(), * because we need to serialize with concurrent event creation. */ if (!exclusive_event_installable(event, ctx)) { /* exclusive and group stuff are assumed mutually exclusive */ WARN_ON_ONCE(move_group); err = -EBUSY; goto err_locked; } WARN_ON_ONCE(ctx->parent_ctx); /* * This is the point on no return; we cannot fail hereafter. This is * where we start modifying current state. */ if (move_group) { /* * See perf_event_ctx_lock() for comments on the details * of swizzling perf_event::ctx. */ perf_remove_from_context(group_leader, 0); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_remove_from_context(sibling, 0); put_ctx(gctx); } /* * Wait for everybody to stop referencing the events through * the old lists, before installing it on new lists. */ synchronize_rcu(); /* * Install the group siblings before the group leader. * * Because a group leader will try and install the entire group * (through the sibling list, which is still in-tact), we can * end up with siblings installed in the wrong context. * * By installing siblings first we NO-OP because they're not * reachable through the group lists. */ list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_event__state_init(sibling); perf_install_in_context(ctx, sibling, sibling->cpu); get_ctx(ctx); } /* * Removing from the context ends up with disabled * event. What we want here is event in the initial * startup state, ready to be add into new context. */ perf_event__state_init(group_leader); perf_install_in_context(ctx, group_leader, group_leader->cpu); get_ctx(ctx); /* * Now that all events are installed in @ctx, nothing * references @gctx anymore, so drop the last reference we have * on it. */ put_ctx(gctx); } /* * Precalculate sample_data sizes; do while holding ctx::mutex such * that we're serialized against further additions and before * perf_install_in_context() which is the point the event is active and * can use these values. */ perf_event__header_size(event); perf_event__id_header_size(event); event->owner = current; perf_install_in_context(ctx, event, event->cpu); perf_unpin_context(ctx); if (move_group) mutex_unlock(&gctx->mutex); mutex_unlock(&ctx->mutex); if (task) { mutex_unlock(&task->signal->cred_guard_mutex); put_task_struct(task); } put_online_cpus(); mutex_lock(&current->perf_event_mutex); list_add_tail(&event->owner_entry, &current->perf_event_list); mutex_unlock(&current->perf_event_mutex); /* * Drop the reference on the group_event after placing the * new event on the sibling_list. This ensures destruction * of the group leader will find the pointer to itself in * perf_group_detach(). */ fdput(group); fd_install(event_fd, event_file); return event_fd; err_locked: if (move_group) mutex_unlock(&gctx->mutex); mutex_unlock(&ctx->mutex); /* err_file: */ fput(event_file); err_context: perf_unpin_context(ctx); put_ctx(ctx); err_alloc: /* * If event_file is set, the fput() above will have called ->release() * and that will take care of freeing the event. */ if (!event_file) free_event(event); err_cred: if (task) mutex_unlock(&task->signal->cred_guard_mutex); err_cpus: put_online_cpus(); err_task: if (task) put_task_struct(task); err_group_fd: fdput(group); err_fd: put_unused_fd(event_fd); return err; } Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race Di Shen reported a race between two concurrent sys_perf_event_open() calls where both try and move the same pre-existing software group into a hardware context. The problem is exactly that described in commit: f63a8daa5812 ("perf: Fix event->ctx locking") ... where, while we wait for a ctx->mutex acquisition, the event->ctx relation can have changed under us. That very same commit failed to recognise sys_perf_event_context() as an external access vector to the events and thereby didn't apply the established locking rules correctly. So while one sys_perf_event_open() call is stuck waiting on mutex_lock_double(), the other (which owns said locks) moves the group about. So by the time the former sys_perf_event_open() acquires the locks, the context we've acquired is stale (and possibly dead). Apply the established locking rules as per perf_event_ctx_lock_nested() to the mutex_lock_double() for the 'move_group' case. This obviously means we need to validate state after we acquire the locks. Reported-by: Di Shen (Keen Lab) Tested-by: John Dias <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Alexander Shishkin <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Kees Cook <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Min Chong <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Fixes: f63a8daa5812 ("perf: Fix event->ctx locking") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static int putint(jas_stream_t *out, int sgnd, int prec, long val) { int n; int c; bool s; ulong tmp; assert((!sgnd && prec >= 1) || (sgnd && prec >= 2)); if (sgnd) { val = encode_twos_comp(val, prec); } assert(val >= 0); val &= (1 << prec) - 1; n = (prec + 7) / 8; while (--n >= 0) { c = (val >> (n * 8)) & 0xff; if (jas_stream_putc(out, c) != c) return -1; } return 0; } Commit Message: The component domains must be the same for the ICT/RCT in the JPC codec. This was previously enforced with an assertion. Now, it is handled in a more graceful manner. CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void inc_nr_running(struct rq *rq) { rq->nr_running++; } Commit Message: Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <[email protected]> Reported-by: Bjoern B. Brandenburg <[email protected]> Tested-by: Yong Zhang <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: [email protected] LKML-Reference: <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void xfrm6_tunnel_spi_fini(void) { kmem_cache_destroy(xfrm6_tunnel_spi_kmem); } Commit Message: tunnels: fix netns vs proto registration ordering Same stuff as in ip_gre patch: receive hook can be called before netns setup is done, oopsing in net_generic(). Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static struct trusted_key_payload *trusted_payload_alloc(struct key *key) { struct trusted_key_payload *p = NULL; int ret; ret = key_payload_reserve(key, sizeof *p); if (ret < 0) return p; p = kzalloc(sizeof *p, GFP_KERNEL); if (p) p->migratable = 1; /* migratable by default */ return p; } Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key If a user key gets negatively instantiated, an error code is cached in the payload area. A negatively instantiated key may be then be positively instantiated by updating it with valid data. However, the ->update key type method must be aware that the error code may be there. The following may be used to trigger the bug in the user key type: keyctl request2 user user "" @u keyctl add user user "a" @u which manifests itself as: BUG: unable to handle kernel paging request at 00000000ffffff8a IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 PGD 7cc30067 PUD 0 Oops: 0002 [#1] SMP Modules linked in: CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000 RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246 RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001 RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82 RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000 R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82 R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700 FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0 Stack: ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82 ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5 ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620 Call Trace: [<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136 [<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129 [< inline >] __key_update security/keys/key.c:730 [<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908 [< inline >] SYSC_add_key security/keys/keyctl.c:125 [<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60 [<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185 Note the error code (-ENOKEY) in EDX. A similar bug can be tripped by: keyctl request2 trusted user "" @u keyctl add trusted user "a" @u This should also affect encrypted keys - but that has to be correctly parameterised or it will fail with EINVAL before getting to the bit that will crashes. Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David Howells <[email protected]> Acked-by: Mimi Zohar <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: kvp_get_ip_info(int family, char *if_name, int op, void *out_buffer, int length) { struct ifaddrs *ifap; struct ifaddrs *curp; int offset = 0; int sn_offset = 0; int error = 0; char *buffer; struct hv_kvp_ipaddr_value *ip_buffer; char cidr_mask[5]; /* /xyz */ int weight; int i; unsigned int *w; char *sn_str; struct sockaddr_in6 *addr6; if (op == KVP_OP_ENUMERATE) { buffer = out_buffer; } else { ip_buffer = out_buffer; buffer = (char *)ip_buffer->ip_addr; ip_buffer->addr_family = 0; } /* * On entry into this function, the buffer is capable of holding the * maximum key value. */ if (getifaddrs(&ifap)) { strcpy(buffer, "getifaddrs failed\n"); return HV_E_FAIL; } curp = ifap; while (curp != NULL) { if (curp->ifa_addr == NULL) { curp = curp->ifa_next; continue; } if ((if_name != NULL) && (strncmp(curp->ifa_name, if_name, strlen(if_name)))) { /* * We want info about a specific interface; * just continue. */ curp = curp->ifa_next; continue; } /* * We only support two address families: AF_INET and AF_INET6. * If a family value of 0 is specified, we collect both * supported address families; if not we gather info on * the specified address family. */ if ((((family != 0) && (curp->ifa_addr->sa_family != family))) || (curp->ifa_flags & IFF_LOOPBACK)) { curp = curp->ifa_next; continue; } if ((curp->ifa_addr->sa_family != AF_INET) && (curp->ifa_addr->sa_family != AF_INET6)) { curp = curp->ifa_next; continue; } if (op == KVP_OP_GET_IP_INFO) { /* * Gather info other than the IP address. * IP address info will be gathered later. */ if (curp->ifa_addr->sa_family == AF_INET) { ip_buffer->addr_family |= ADDR_FAMILY_IPV4; /* * Get subnet info. */ error = kvp_process_ip_address( curp->ifa_netmask, AF_INET, (char *) ip_buffer->sub_net, length, &sn_offset); if (error) goto gather_ipaddr; } else { ip_buffer->addr_family |= ADDR_FAMILY_IPV6; /* * Get subnet info in CIDR format. */ weight = 0; sn_str = (char *)ip_buffer->sub_net; addr6 = (struct sockaddr_in6 *) curp->ifa_netmask; w = addr6->sin6_addr.s6_addr32; for (i = 0; i < 4; i++) weight += hweight32(&w[i]); sprintf(cidr_mask, "/%d", weight); if ((length - sn_offset) < (strlen(cidr_mask) + 1)) goto gather_ipaddr; if (sn_offset == 0) strcpy(sn_str, cidr_mask); else strcat(sn_str, cidr_mask); strcat((char *)ip_buffer->sub_net, ";"); sn_offset += strlen(sn_str) + 1; } /* * Collect other ip related configuration info. */ kvp_get_ipconfig_info(if_name, ip_buffer); } gather_ipaddr: error = kvp_process_ip_address(curp->ifa_addr, curp->ifa_addr->sa_family, buffer, length, &offset); if (error) goto getaddr_done; curp = curp->ifa_next; } getaddr_done: freeifaddrs(ifap); return error; } Commit Message: tools: hv: Netlink source address validation allows DoS The source code without this patch caused hypervkvpd to exit when it processed a spoofed Netlink packet which has been sent from an untrusted local user. Now Netlink messages with a non-zero nl_pid source address are ignored and a warning is printed into the syslog. Signed-off-by: Tomas Hozza <[email protected]> Acked-by: K. Y. Srinivasan <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: enum ImapAuthRes imap_auth_cram_md5(struct ImapData *idata, const char *method) { char ibuf[LONG_STRING * 2], obuf[LONG_STRING]; unsigned char hmac_response[MD5_DIGEST_LEN]; int len; int rc; if (!mutt_bit_isset(idata->capabilities, ACRAM_MD5)) return IMAP_AUTH_UNAVAIL; mutt_message(_("Authenticating (CRAM-MD5)...")); /* get auth info */ if (mutt_account_getlogin(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; imap_cmd_start(idata, "AUTHENTICATE CRAM-MD5"); /* From RFC2195: * The data encoded in the first ready response contains a presumptively * arbitrary string of random digits, a timestamp, and the fully-qualified * primary host name of the server. The syntax of the unencoded form must * correspond to that of an RFC822 'msg-id' [RFC822] as described in [POP3]. */ do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_RESPOND) { mutt_debug(1, "Invalid response from server: %s\n", ibuf); goto bail; } len = mutt_b64_decode(obuf, idata->buf + 2); if (len == -1) { mutt_debug(1, "Error decoding base64 response.\n"); goto bail; } obuf[len] = '\0'; mutt_debug(2, "CRAM challenge: %s\n", obuf); /* The client makes note of the data and then responds with a string * consisting of the user name, a space, and a 'digest'. The latter is * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the * key is a shared secret and the digested text is the timestamp (including * angle-brackets). * * Note: The user name shouldn't be quoted. Since the digest can't contain * spaces, there is no ambiguity. Some servers get this wrong, we'll work * around them when the bug report comes in. Until then, we'll remain * blissfully RFC-compliant. */ hmac_md5(idata->conn->account.pass, obuf, hmac_response); /* dubious optimisation I saw elsewhere: make the whole string in one call */ int off = snprintf(obuf, sizeof(obuf), "%s ", idata->conn->account.user); mutt_md5_toascii(hmac_response, obuf + off); mutt_debug(2, "CRAM response: %s\n", obuf); /* ibuf must be long enough to store the base64 encoding of obuf, * plus the additional debris */ mutt_b64_encode(ibuf, obuf, strlen(obuf), sizeof(ibuf) - 2); mutt_str_strcat(ibuf, sizeof(ibuf), "\r\n"); mutt_socket_send(idata->conn, ibuf); do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_OK) { mutt_debug(1, "Error receiving server response.\n"); goto bail; } if (imap_code(idata->buf)) return IMAP_AUTH_SUCCESS; bail: mutt_error(_("CRAM-MD5 authentication failed.")); return IMAP_AUTH_FAILURE; } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderViewHostImpl::OnTakeFocus(bool reverse) { RenderViewHostDelegateView* view = delegate_->GetDelegateView(); if (view) view->TakeFocus(reverse); } Commit Message: Filter more incoming URLs in the CreateWindow path. BUG=170532 Review URL: https://chromiumcodereview.appspot.com/12036002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void LocalDOMWindow::cancelIdleCallback(int id) { if (Document* document = this->document()) document->CancelIdleCallback(id); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FileSystemOperation::GetUsageAndQuotaThenRunTask( const GURL& origin, FileSystemType type, const base::Closure& task, const base::Closure& error_callback) { quota::QuotaManagerProxy* quota_manager_proxy = file_system_context()->quota_manager_proxy(); if (!quota_manager_proxy || !file_system_context()->GetQuotaUtil(type)) { operation_context_.set_allowed_bytes_growth(kint64max); task.Run(); return; } TaskParamsForDidGetQuota params; params.origin = origin; params.type = type; params.task = task; params.error_callback = error_callback; DCHECK(quota_manager_proxy); DCHECK(quota_manager_proxy->quota_manager()); quota_manager_proxy->quota_manager()->GetUsageAndQuota( origin, FileSystemTypeToQuotaStorageType(type), base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask, base::Unretained(this), params)); } Commit Message: Crash fix in fileapi::FileSystemOperation::DidGetUsageAndQuotaAndRunTask https://chromiumcodereview.appspot.com/10008047 introduced delete-with-inflight-tasks in Write sequence but I failed to convert this callback to use WeakPtr(). BUG=128178 TEST=manual test Review URL: https://chromiumcodereview.appspot.com/10408006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137635 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=2&t=28946 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ext4_file_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct inode *inode = file_inode(iocb->ki_filp); struct mutex *aio_mutex = NULL; struct blk_plug plug; int o_direct = file->f_flags & O_DIRECT; int overwrite = 0; size_t length = iov_iter_count(from); ssize_t ret; loff_t pos = iocb->ki_pos; /* * Unaligned direct AIO must be serialized; see comment above * In the case of O_APPEND, assume that we must always serialize */ if (o_direct && ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) && !is_sync_kiocb(iocb) && (file->f_flags & O_APPEND || ext4_unaligned_aio(inode, from, pos))) { aio_mutex = ext4_aio_mutex(inode); mutex_lock(aio_mutex); ext4_unwritten_wait(inode); } mutex_lock(&inode->i_mutex); if (file->f_flags & O_APPEND) iocb->ki_pos = pos = i_size_read(inode); /* * If we have encountered a bitmap-format file, the size limit * is smaller than s_maxbytes, which is for extent-mapped files. */ if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); if ((pos > sbi->s_bitmap_maxbytes) || (pos == sbi->s_bitmap_maxbytes && length > 0)) { mutex_unlock(&inode->i_mutex); ret = -EFBIG; goto errout; } if (pos + length > sbi->s_bitmap_maxbytes) iov_iter_truncate(from, sbi->s_bitmap_maxbytes - pos); } if (o_direct) { blk_start_plug(&plug); iocb->private = &overwrite; /* check whether we do a DIO overwrite or not */ if (ext4_should_dioread_nolock(inode) && !aio_mutex && !file->f_mapping->nrpages && pos + length <= i_size_read(inode)) { struct ext4_map_blocks map; unsigned int blkbits = inode->i_blkbits; int err, len; map.m_lblk = pos >> blkbits; map.m_len = (EXT4_BLOCK_ALIGN(pos + length, blkbits) >> blkbits) - map.m_lblk; len = map.m_len; err = ext4_map_blocks(NULL, inode, &map, 0); /* * 'err==len' means that all of blocks has * been preallocated no matter they are * initialized or not. For excluding * unwritten extents, we need to check * m_flags. There are two conditions that * indicate for initialized extents. 1) If we * hit extent cache, EXT4_MAP_MAPPED flag is * returned; 2) If we do a real lookup, * non-flags are returned. So we should check * these two conditions. */ if (err == len && (map.m_flags & EXT4_MAP_MAPPED)) overwrite = 1; } } ret = __generic_file_write_iter(iocb, from); mutex_unlock(&inode->i_mutex); if (ret > 0) { ssize_t err; err = generic_write_sync(file, iocb->ki_pos - ret, ret); if (err < 0) ret = err; } if (o_direct) blk_finish_plug(&plug); errout: if (aio_mutex) mutex_unlock(aio_mutex); return ret; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: name_len(netdissect_options *ndo, const unsigned char *s, const unsigned char *maxbuf) { const unsigned char *s0 = s; unsigned char c; if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); c = *s; if ((c & 0xC0) == 0xC0) return(2); while (*s) { if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); s += (*s) + 1; } return(PTR_DIFF(s, s0) + 1); trunc: return(-1); /* name goes past the end of the buffer */ } Commit Message: CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len(). After we advance the pointer by the length value in the buffer, make sure it points to something in the captured data. 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 Target: 1 Example 2: Code: v8::Extension* LoadTimesExtension::Get() { return new LoadTimesExtensionWrapper(); } Commit Message: Cache all chrome.loadTimes info before passing them to setters. The setters can invalidate the pointers frame, data_source and document_state. BUG=549251 Review URL: https://codereview.chromium.org/1422753007 Cr-Commit-Position: refs/heads/master@{#357201} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ConversionContext::Convert(const PaintChunkSubset& paint_chunks, const DisplayItemList& display_items) { for (const auto& chunk : paint_chunks) { const auto& chunk_state = chunk.properties; bool switched_to_chunk_state = false; for (const auto& item : display_items.ItemsInPaintChunk(chunk)) { DCHECK(item.IsDrawing()); auto record = static_cast<const DrawingDisplayItem&>(item).GetPaintRecord(); if ((!record || record->size() == 0) && chunk_state.Effect() == EffectPaintPropertyNode::Root()) { continue; } TranslateForLayerOffsetOnce(); if (!switched_to_chunk_state) { SwitchToChunkState(chunk); switched_to_chunk_state = true; } cc_list_.StartPaint(); if (record && record->size() != 0) cc_list_.push<cc::DrawRecordOp>(std::move(record)); cc_list_.EndPaintOfUnpaired( chunk_to_layer_mapper_.MapVisualRect(item.VisualRect())); } UpdateEffectBounds(chunk.bounds, chunk_state.Transform()); } } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text) { int i; int opts; Resub m; opts = 0; if (re->flags & JS_REGEXP_G) { if (re->last > strlen(text)) { re->last = 0; js_pushnull(J); return; } if (re->last > 0) { text += re->last; opts |= REG_NOTBOL; } } if (!js_regexec(re->prog, text, &m, opts)) { js_newarray(J); js_pushstring(J, text); js_setproperty(J, -2, "input"); js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp)); js_setproperty(J, -2, "index"); for (i = 0; i < m.nsub; ++i) { js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp); js_setindex(J, -2, i); } if (re->flags & JS_REGEXP_G) re->last = re->last + (m.sub[0].ep - text); return; } if (re->flags & JS_REGEXP_G) re->last = 0; js_pushnull(J); } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400 Target: 1 Example 2: Code: void OnUpdateViewportIntersectionPostOnIO( const gfx::Rect& viewport_intersection, const gfx::Rect& compositing_rect, bool occluded_or_obscured) { base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&UpdateViewportIntersectionMessageFilter:: OnUpdateViewportIntersectionOnUI, this, viewport_intersection, compositing_rect, occluded_or_obscured)); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AXTableCell::isRowHeaderCell() const { const AtomicString& scope = getAttribute(scopeAttr); return equalIgnoringCase(scope, "row") || equalIgnoringCase(scope, "rowgroup"); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadCMYKImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); SetImageColorspace(image,CMYKColorspace); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.cmyk[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); quantum_type=CMYKQuantum; if (LocaleCompare(image_info->magick,"CMYKA") == 0) { quantum_type=CMYKAQuantum; image->matte=MagickTrue; } if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; SetImageColorspace(image,CMYKColorspace); switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: CMYKCMYKCMYKCMYKCMYKCMYK... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelBlack(indexes+x,GetPixelBlack( canvas_indexes+image->extract_info.x+x)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } count=ReadBlob(image,length,pixels); } break; } case LineInterlace: { static QuantumType quantum_types[5] = { CyanQuantum, MagentaQuantum, YellowQuantum, BlackQuantum, OpacityQuantum }; /* Line interlacing: CCC...MMM...YYY...KKK...CCC...MMM...YYY...KKK... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,CyanQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } for (i=0; i < (image->matte != MagickFalse ? 5 : 4); i++) { quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case CyanQuantum: { SetPixelCyan(q,GetPixelCyan(p)); break; } case MagentaQuantum: { SetPixelMagenta(q,GetPixelMagenta(p)); break; } case YellowQuantum: { SetPixelYellow(q,GetPixelYellow(p)); break; } case BlackQuantum: { SetPixelIndex(indexes+x,GetPixelIndex( canvas_indexes+image->extract_info.x+x)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: CCCCCC...MMMMMM...YYYYYY...KKKKKK... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,CyanQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,CyanQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,MagentaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,YellowQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlackQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,GetPixelIndex( canvas_indexes+image->extract_info.x+x)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: CCCCCC..., MMMMMM..., YYYYYY..., KKKKKK... */ AppendImageFormat("C",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,CyanQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,CyanQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("M",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,MagentaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,MagentaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,YellowQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,YellowQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("K",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,BlackQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlackQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,GetPixelIndex( canvas_indexes+image->extract_info.x+x)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,YellowQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: change_identity (const struct passwd *pw) { if (setgid (pw->pw_gid)) err (EXIT_FAILURE, _("cannot set group id")); if (setuid (pw->pw_uid)) err (EXIT_FAILURE, _("cannot set user id")); } Commit Message: su: properly clear child PID Reported-by: Tobias Stöckmann <[email protected]> Signed-off-by: Karel Zak <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool ath_drain_all_txq(struct ath_softc *sc) { struct ath_hw *ah = sc->sc_ah; struct ath_common *common = ath9k_hw_common(sc->sc_ah); struct ath_txq *txq; int i; u32 npend = 0; if (test_bit(SC_OP_INVALID, &sc->sc_flags)) return true; ath9k_hw_abort_tx_dma(ah); /* Check if any queue remains active */ for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) { if (!ATH_TXQ_SETUP(sc, i)) continue; if (!sc->tx.txq[i].axq_depth) continue; if (ath9k_hw_numtxpending(ah, sc->tx.txq[i].axq_qnum)) npend |= BIT(i); } if (npend) ath_err(common, "Failed to stop TX DMA, queues=0x%03x!\n", npend); for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) { if (!ATH_TXQ_SETUP(sc, i)) continue; /* * The caller will resume queues with ieee80211_wake_queues. * Mark the queue as not stopped to prevent ath_tx_complete * from waking the queue too early. */ txq = &sc->tx.txq[i]; txq->stopped = false; ath_draintxq(sc, txq); } return !npend; } Commit Message: ath9k: protect tid->sched check We check tid->sched without a lock taken on ath_tx_aggr_sleep(). That is race condition which can result of doing list_del(&tid->list) twice (second time with poisoned list node) and cause crash like shown below: [424271.637220] BUG: unable to handle kernel paging request at 00100104 [424271.637328] IP: [<f90fc072>] ath_tx_aggr_sleep+0x62/0xe0 [ath9k] ... [424271.639953] Call Trace: [424271.639998] [<f90f6900>] ? ath9k_get_survey+0x110/0x110 [ath9k] [424271.640083] [<f90f6942>] ath9k_sta_notify+0x42/0x50 [ath9k] [424271.640177] [<f809cfef>] sta_ps_start+0x8f/0x1c0 [mac80211] [424271.640258] [<c10f730e>] ? free_compound_page+0x2e/0x40 [424271.640346] [<f809e915>] ieee80211_rx_handlers+0x9d5/0x2340 [mac80211] [424271.640437] [<c112f048>] ? kmem_cache_free+0x1d8/0x1f0 [424271.640510] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640578] [<c10fc23c>] ? put_page+0x2c/0x40 [424271.640640] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640706] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640787] [<f809dde3>] ? ieee80211_rx_handlers_result+0x73/0x1d0 [mac80211] [424271.640897] [<f80a07a0>] ieee80211_prepare_and_rx_handle+0x520/0xad0 [mac80211] [424271.641009] [<f809e22d>] ? ieee80211_rx_handlers+0x2ed/0x2340 [mac80211] [424271.641104] [<c13846ce>] ? ip_output+0x7e/0xd0 [424271.641182] [<f80a1057>] ieee80211_rx+0x307/0x7c0 [mac80211] [424271.641266] [<f90fa6ee>] ath_rx_tasklet+0x88e/0xf70 [ath9k] [424271.641358] [<f80a0f2c>] ? ieee80211_rx+0x1dc/0x7c0 [mac80211] [424271.641445] [<f90f82db>] ath9k_tasklet+0xcb/0x130 [ath9k] Bug report: https://bugzilla.kernel.org/show_bug.cgi?id=70551 Reported-and-tested-by: Max Sydorenko <[email protected]> Cc: [email protected] Signed-off-by: Stanislaw Gruszka <[email protected]> Signed-off-by: John W. Linville <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SetUpCacheMetadata() { metadata_.reset(new GDataCacheMetadataMap( NULL, base::SequencedWorkerPool::SequenceToken())); metadata_->Initialize(cache_paths_); } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: hfs_cat_compare_keys(HFS_INFO * hfs, const hfs_btree_key_cat * key1, const hfs_btree_key_cat * key2) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); uint32_t cnid1, cnid2; cnid1 = tsk_getu32(fs->endian, key1->parent_cnid); cnid2 = tsk_getu32(fs->endian, key2->parent_cnid); if (cnid1 < cnid2) return -1; if (cnid1 > cnid2) return 1; return hfs_unicode_compare(hfs, &key1->name, &key2->name); } Commit Message: Merge pull request #1374 from JordyZomer/develop Fix CVE-2018-19497. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ResourceMultiBufferDataProvider::SetDeferred(bool deferred) { if (active_loader_) active_loader_->SetDefersLoading(deferred); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; char line[TOSHIBA_LINE_LENGTH]; int num_items_scanned; int pkt_len, pktnum, hr, min, sec, csec; char channel[10], direction[10]; int i, hex_lines; guint8 *pd; /* Our file pointer should be on the line containing the * summary information for a packet. Read in that line and * extract the useful information */ if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Find text in line after "[No.". Limit the length of the * two strings since we have fixed buffers for channel[] and * direction[] */ num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s", &pktnum, &hr, &min, &sec, &csec, channel, direction); if (num_items_scanned != 7) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: record header isn't valid"); return FALSE; } /* Scan lines until we find the OFFSET line. In a "telnet" trace, * this will be the next line. But if you save your telnet session * to a file from within a Windows-based telnet client, it may * put in line breaks at 80 columns (or however big your "telnet" box * is). CRT (a Windows telnet app from VanDyke) does this. * Here we assume that 80 columns will be the minimum size, and that * the OFFSET line is not broken in the middle. It's the previous * line that is normally long and can thus be broken at column 80. */ do { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Check for "OFFSET 0001-0203" at beginning of line */ line[16] = '\0'; } while (strcmp(line, "OFFSET 0001-0203") != 0); num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len); if (num_items_scanned != 1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item"); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; phdr->ts.secs = hr * 3600 + min * 60 + sec; phdr->ts.nsecs = csec * 10000000; phdr->caplen = pkt_len; phdr->len = pkt_len; switch (channel[0]) { case 'B': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = (guint8) strtol(&channel[1], NULL, 10); break; case 'D': phdr->pkt_encap = WTAP_ENCAP_ISDN; pseudo_header->isdn.uton = (direction[0] == 'T'); pseudo_header->isdn.channel = 0; break; default: phdr->pkt_encap = WTAP_ENCAP_ETHERNET; /* XXX - is there an FCS in the frame? */ pseudo_header->eth.fcs_len = -1; break; } /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, TOSHIBA_MAX_PACKET_LEN); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (!parse_single_hex_dump_line(line, pd, i * 16)) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("toshiba: hex dump not valid"); return FALSE; } } return TRUE; } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Bug: 12394 Change-Id: Ifa023ce70f7a2697bf151009b035a6e6cf8d5d90 Reviewed-on: https://code.wireshark.org/review/15169 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: kdc_get_ticket_endtime(kdc_realm_t *kdc_active_realm, krb5_timestamp starttime, krb5_timestamp endtime, krb5_timestamp till, krb5_db_entry *client, krb5_db_entry *server, krb5_timestamp *out_endtime) { krb5_timestamp until; krb5_deltat life; if (till == 0) till = kdc_infinity; until = ts_min(till, endtime); /* Determine the requested lifetime, capped at the maximum valid time * interval. */ life = ts_delta(until, starttime); if (ts_after(until, starttime) && life < 0) life = INT32_MAX; if (client != NULL && client->max_life != 0) life = min(life, client->max_life); if (server->max_life != 0) life = min(life, server->max_life); if (kdc_active_realm->realm_maxlife != 0) life = min(life, kdc_active_realm->realm_maxlife); *out_endtime = ts_incr(starttime, life); } Commit Message: Ignore password attributes for S4U2Self requests For consistency with Windows KDCs, allow protocol transition to work even if the password has expired or needs changing. Also, when looking up an enterprise principal with an AS request, treat ERR_KEY_EXP as confirmation that the client is present in the realm. [[email protected]: added comment in kdc_process_s4u2self_req(); edited commit message] ticket: 8763 (new) tags: pullup target_version: 1.17 CWE ID: CWE-617 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void signal_handler(int signum) { size_t pos = 0; char msg[64]; pos = safecat(msg, sizeof msg, pos, "caught signal: "); switch (signum) { case SIGABRT: pos = safecat(msg, sizeof msg, pos, "abort"); break; case SIGFPE: pos = safecat(msg, sizeof msg, pos, "floating point exception"); break; case SIGILL: pos = safecat(msg, sizeof msg, pos, "illegal instruction"); break; case SIGINT: pos = safecat(msg, sizeof msg, pos, "interrupt"); break; case SIGSEGV: pos = safecat(msg, sizeof msg, pos, "invalid memory access"); break; case SIGTERM: pos = safecat(msg, sizeof msg, pos, "termination request"); break; default: pos = safecat(msg, sizeof msg, pos, "unknown "); pos = safecatn(msg, sizeof msg, pos, signum); break; } store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/); /* And finally throw an exception so we can keep going, unless this is * SIGTERM in which case stop now. */ if (signum != SIGTERM) { struct exception_context *the_exception_context = &pm.this.exception_context; Throw &pm.this; } else exit(1); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); { printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; goto err0; } globalParams = new GlobalParams(); ok = extractPages (argv[1], argv[2]); if (ok) { exitCode = 0; } delete globalParams; err0: return exitCode; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: void V8Window::openerAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info) { LocalDOMWindow* impl = toLocalDOMWindow(V8Window::toImpl(info.Holder())); ExceptionState exceptionState(ExceptionState::SetterContext, "opener", "Window", info.Holder(), info.GetIsolate()); if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), impl->frame(), exceptionState)) { exceptionState.throwIfNeeded(); return; } if (value->IsNull()) { ASSERT(impl->frame()); impl->frame()->loader().setOpener(0); } info.Holder()->Delete(v8AtomicString(info.GetIsolate(), "opener")); if (info.This()->IsObject()) v8::Handle<v8::Object>::Cast(info.This())->Set(v8AtomicString(info.GetIsolate(), "opener"), value); } Commit Message: Reload frame in V8Window::namedPropertyGetterCustom after js call [email protected] BUG=454954 Review URL: https://codereview.chromium.org/901053006 git-svn-id: svn://svn.chromium.org/blink/trunk@189574 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void jspInit() { jspSoftInit(); } Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437) CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: spnego_gss_verify_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t msg_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_verify_mic(minor_status, context_handle, msg_buffer, token_buffer, qop_state); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18 Target: 1 Example 2: Code: void HTMLMediaElement::textTrackModeChanged(TextTrack* track) { if (track->trackType() == TextTrack::TrackElement) track->setHasBeenConfigured(true); configureTextTrackDisplay(); DCHECK(textTracks()->contains(track)); textTracks()->scheduleChangeEvent(); } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: on_favicon_received(const char *page_url, Evas_Object *icon, void *event_info) { Browser_Window *app_data = (Browser_Window *)event_info; if (strcmp(page_url, ewk_view_url_get(app_data->webview))) return; /* Remove previous icon from URL bar */ Evas_Object *old_icon = elm_object_part_content_unset(app_data->url_bar, "icon"); if (old_icon) { evas_object_unref(old_icon); evas_object_del(old_icon); } /* Show new icon in URL bar */ if (icon) { /* Workaround for icon display bug: * http://trac.enlightenment.org/e/ticket/1616 */ evas_object_size_hint_min_set(icon, 48, 24); evas_object_image_filled_set(icon, EINA_FALSE); evas_object_image_fill_set(icon, 24, 0, 24, 24); elm_object_part_content_set(app_data->url_bar, "icon", icon); evas_object_ref(icon); } } Commit Message: [EFL][WK2] Add --window-size command line option to EFL MiniBrowser https://bugs.webkit.org/show_bug.cgi?id=100942 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-11-05 Reviewed by Kenneth Rohde Christiansen. Added window-size (-s) command line option to EFL MiniBrowser. * MiniBrowser/efl/main.c: (window_create): (parse_window_size): (elm_main): git-svn-id: svn://svn.chromium.org/blink/trunk@133450 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size) { int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems; int sg_tablesize = sfp->parentdp->sg_tablesize; int blk_size = buff_size, order; gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN; struct sg_device *sdp = sfp->parentdp; if (blk_size < 0) return -EFAULT; if (0 == blk_size) ++blk_size; /* don't know why */ /* round request up to next highest SG_SECTOR_SZ byte boundary */ blk_size = ALIGN(blk_size, SG_SECTOR_SZ); SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: buff_size=%d, blk_size=%d\n", buff_size, blk_size)); /* N.B. ret_sz carried into this block ... */ mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize); if (mx_sc_elems < 0) return mx_sc_elems; /* most likely -ENOMEM */ num = scatter_elem_sz; if (unlikely(num != scatter_elem_sz_prev)) { if (num < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = PAGE_SIZE; } else scatter_elem_sz_prev = num; } if (sdp->device->host->unchecked_isa_dma) gfp_mask |= GFP_DMA; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) gfp_mask |= __GFP_ZERO; order = get_order(num); retry: ret_sz = 1 << (PAGE_SHIFT + order); for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems; k++, rem_sz -= ret_sz) { num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz; schp->pages[k] = alloc_pages(gfp_mask, order); if (!schp->pages[k]) goto out; if (num == scatter_elem_sz_prev) { if (unlikely(ret_sz > scatter_elem_sz_prev)) { scatter_elem_sz = ret_sz; scatter_elem_sz_prev = ret_sz; } } SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n", k, num, ret_sz)); } /* end of for loop */ schp->page_order = order; schp->k_use_sg = k; SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n", k, rem_sz)); schp->bufflen = blk_size; if (rem_sz > 0) /* must have failed */ return -ENOMEM; return 0; out: for (i = 0; i < k; i++) __free_pages(schp->pages[i], order); if (--order >= 0) goto retry; return -ENOMEM; } Commit Message: scsi: sg: allocate with __GFP_ZERO in sg_build_indirect() This shall help avoid copying uninitialized memory to the userspace when calling ioctl(fd, SG_IO) with an empty command. Reported-by: [email protected] Cc: [email protected] Signed-off-by: Alexander Potapenko <[email protected]> Acked-by: Douglas Gilbert <[email protected]> Reviewed-by: Johannes Thumshirn <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Target: 1 Example 2: Code: void BackgroundLoaderOffliner::ResetLoader() { loader_.reset( new background_loader::BackgroundLoaderContents(browser_context_)); loader_->SetDelegate(this); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <[email protected]> Reviewed-by: Steven Holte <[email protected]> Commit-Queue: Peter Williamson <[email protected]> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) { unsigned short type, size, len; /* If resumed session or no custom extensions nothing to do */ if (s->hit || s->cert->srv_ext.meths_count == 0) return 1; if (data >= limit - 2) return 1; n2s(data, len); if (data > limit - len) return 1; while (data <= limit - 4) { n2s(data, type); n2s(data, size); if (data + size > limit) return 1; if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) return 0; data += size; } return 1; } Commit Message: CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool EditorClientBlackBerry::shouldChangeSelectedRange(Range* fromRange, Range* toRange, EAffinity affinity, bool stillSelecting) { if (m_webPagePrivate->m_dumpRenderTree) return m_webPagePrivate->m_dumpRenderTree->shouldChangeSelectedDOMRangeToDOMRangeAffinityStillSelecting(fromRange, toRange, static_cast<int>(affinity), stillSelecting); Frame* frame = m_webPagePrivate->focusedOrMainFrame(); if (frame && frame->document()) { if (frame->document()->focusedNode() && frame->document()->focusedNode()->hasTagName(HTMLNames::selectTag)) return false; if (m_webPagePrivate->m_inputHandler->isInputMode() && fromRange && toRange && (fromRange->startContainer() == toRange->startContainer())) m_webPagePrivate->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true); } return true; } Commit Message: [BlackBerry] Prevent text selection inside Colour and Date/Time input fields https://bugs.webkit.org/show_bug.cgi?id=111733 Reviewed by Rob Buis. PR 305194. Prevent selection for popup input fields as they are buttons. Informally Reviewed Gen Mak. * WebCoreSupport/EditorClientBlackBerry.cpp: (WebCore::EditorClientBlackBerry::shouldChangeSelectedRange): git-svn-id: svn://svn.chromium.org/blink/trunk@145121 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: MagickExport const char *GetMagickQuantumDepth(size_t *depth) { if (depth != (size_t *) NULL) *depth=(size_t) MAGICKCORE_QUANTUM_DEPTH; return(MagickQuantumDepth); } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long Track::GetNumber() const { return m_info.number; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PluginChannel::OnChannelConnected(int32 peer_pid) { base::ProcessHandle handle; if (!base::OpenProcessHandle(peer_pid, &handle)) { NOTREACHED(); } renderer_handle_ = handle; NPChannelBase::OnChannelConnected(peer_pid); } 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: Target: 1 Example 2: Code: buffer_percent_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_array *tr = filp->private_data; unsigned long val; int ret; ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; if (val > 100) return -EINVAL; if (!val) val = 1; tr->buffer_percent = val; (*ppos)++; return cnt; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GDataCache::CommitDirtyOnUIThread(const std::string& resource_id, const std::string& md5, const CacheOperationCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::PlatformFileError* error = new base::PlatformFileError(base::PLATFORM_FILE_OK); pool_->GetSequencedTaskRunner(sequence_token_)->PostTaskAndReply( FROM_HERE, base::Bind(&GDataCache::CommitDirty, base::Unretained(this), resource_id, md5, GDataCache::FILE_OPERATION_MOVE, error), base::Bind(&GDataCache::OnCommitDirty, ui_weak_ptr_, base::Owned(error), resource_id, md5, callback)); } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> itemCallback(const v8::Arguments& args) { INC_STATS("DOM.TestEventTarget.item"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestEventTarget* imp = V8TestEventTarget::toNative(args.Holder()); ExceptionCode ec = 0; { EXCEPTION_BLOCK(int, index, toUInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); if (UNLIKELY(index < 0)) { ec = INDEX_SIZE_ERR; goto fail; } return toV8(imp->item(index), args.GetIsolate()); } fail: V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: __acquires(ping_table.lock) { struct ping_iter_state *state = seq->private; state->bucket = 0; state->family = family; read_lock_bh(&ping_table.lock); return *pos ? ping_get_idx(seq, *pos-1) : SEQ_START_TOKEN; } Commit Message: ping: implement proper locking We got a report of yet another bug in ping http://www.openwall.com/lists/oss-security/2017/03/24/6 ->disconnect() is not called with socket lock held. Fix this by acquiring ping rwlock earlier. Thanks to Daniel, Alexander and Andrey for letting us know this problem. Fixes: c319b4d76b9e ("net: ipv4: add IPPROTO_ICMP socket kind") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Daniel Jiang <[email protected]> Reported-by: Solar Designer <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, xmlNodePtr node, const xmlChar *mode, const xmlChar *modeURI) { int i; xsltStepOpPtr step, sel = NULL; xsltStepStates states = {0, 0, NULL}; /* // may require backtrack */ if ((comp == NULL) || (node == NULL) || (ctxt == NULL)) { xsltTransformError(ctxt, NULL, node, "xsltTestCompMatch: null arg\n"); return(-1); } if (mode != NULL) { if (comp->mode == NULL) return(0); /* * both mode strings must be interned on the stylesheet dictionary */ if (comp->mode != mode) return(0); } else { if (comp->mode != NULL) return(0); } if (modeURI != NULL) { if (comp->modeURI == NULL) return(0); /* * both modeURI strings must be interned on the stylesheet dictionary */ if (comp->modeURI != modeURI) return(0); } else { if (comp->modeURI != NULL) return(0); } i = 0; restart: for (;i < comp->nbStep;i++) { step = &comp->steps[i]; if (step->op != XSLT_OP_PREDICATE) sel = step; switch (step->op) { case XSLT_OP_END: goto found; case XSLT_OP_ROOT: if ((node->type == XML_DOCUMENT_NODE) || #ifdef LIBXML_DOCB_ENABLED (node->type == XML_DOCB_DOCUMENT_NODE) || #endif (node->type == XML_HTML_DOCUMENT_NODE)) continue; if ((node->type == XML_ELEMENT_NODE) && (node->name[0] == ' ')) continue; goto rollback; case XSLT_OP_ELEM: if (node->type != XML_ELEMENT_NODE) goto rollback; if (step->value == NULL) continue; if (step->value[0] != node->name[0]) goto rollback; if (!xmlStrEqual(step->value, node->name)) goto rollback; /* Namespace test */ if (node->ns == NULL) { if (step->value2 != NULL) goto rollback; } else if (node->ns->href != NULL) { if (step->value2 == NULL) goto rollback; if (!xmlStrEqual(step->value2, node->ns->href)) goto rollback; } continue; case XSLT_OP_ATTR: if (node->type != XML_ATTRIBUTE_NODE) goto rollback; if (step->value != NULL) { if (step->value[0] != node->name[0]) goto rollback; if (!xmlStrEqual(step->value, node->name)) goto rollback; } /* Namespace test */ if (node->ns == NULL) { if (step->value2 != NULL) goto rollback; } else if (step->value2 != NULL) { if (!xmlStrEqual(step->value2, node->ns->href)) goto rollback; } continue; case XSLT_OP_PARENT: if ((node->type == XML_DOCUMENT_NODE) || (node->type == XML_HTML_DOCUMENT_NODE) || #ifdef LIBXML_DOCB_ENABLED (node->type == XML_DOCB_DOCUMENT_NODE) || #endif (node->type == XML_NAMESPACE_DECL)) goto rollback; node = node->parent; if (node == NULL) goto rollback; if (step->value == NULL) continue; if (step->value[0] != node->name[0]) goto rollback; if (!xmlStrEqual(step->value, node->name)) goto rollback; /* Namespace test */ if (node->ns == NULL) { if (step->value2 != NULL) goto rollback; } else if (node->ns->href != NULL) { if (step->value2 == NULL) goto rollback; if (!xmlStrEqual(step->value2, node->ns->href)) goto rollback; } continue; case XSLT_OP_ANCESTOR: /* TODO: implement coalescing of ANCESTOR/NODE ops */ if (step->value == NULL) { step = &comp->steps[i+1]; if (step->op == XSLT_OP_ROOT) goto found; /* added NS, ID and KEY as a result of bug 168208 */ if ((step->op != XSLT_OP_ELEM) && (step->op != XSLT_OP_ALL) && (step->op != XSLT_OP_NS) && (step->op != XSLT_OP_ID) && (step->op != XSLT_OP_KEY)) goto rollback; } if (node == NULL) goto rollback; if ((node->type == XML_DOCUMENT_NODE) || (node->type == XML_HTML_DOCUMENT_NODE) || #ifdef LIBXML_DOCB_ENABLED (node->type == XML_DOCB_DOCUMENT_NODE) || #endif (node->type == XML_NAMESPACE_DECL)) goto rollback; node = node->parent; if ((step->op != XSLT_OP_ELEM) && step->op != XSLT_OP_ALL) { xsltPatPushState(ctxt, &states, i, node); continue; } i++; if (step->value == NULL) { xsltPatPushState(ctxt, &states, i - 1, node); continue; } while (node != NULL) { if ((node->type == XML_ELEMENT_NODE) && (step->value[0] == node->name[0]) && (xmlStrEqual(step->value, node->name))) { /* Namespace test */ if (node->ns == NULL) { if (step->value2 == NULL) break; } else if (node->ns->href != NULL) { if ((step->value2 != NULL) && (xmlStrEqual(step->value2, node->ns->href))) break; } } node = node->parent; } if (node == NULL) goto rollback; xsltPatPushState(ctxt, &states, i - 1, node); continue; case XSLT_OP_ID: { /* TODO Handle IDs decently, must be done differently */ xmlAttrPtr id; if (node->type != XML_ELEMENT_NODE) goto rollback; id = xmlGetID(node->doc, step->value); if ((id == NULL) || (id->parent != node)) goto rollback; break; } case XSLT_OP_KEY: { xmlNodeSetPtr list; int indx; list = xsltGetKey(ctxt, step->value, step->value3, step->value2); if (list == NULL) goto rollback; for (indx = 0;indx < list->nodeNr;indx++) if (list->nodeTab[indx] == node) break; if (indx >= list->nodeNr) goto rollback; break; } case XSLT_OP_NS: if (node->type != XML_ELEMENT_NODE) goto rollback; if (node->ns == NULL) { if (step->value != NULL) goto rollback; } else if (node->ns->href != NULL) { if (step->value == NULL) goto rollback; if (!xmlStrEqual(step->value, node->ns->href)) goto rollback; } break; case XSLT_OP_ALL: if (node->type != XML_ELEMENT_NODE) goto rollback; break; case XSLT_OP_PREDICATE: { xmlNodePtr oldNode; xmlDocPtr doc; int oldCS, oldCP; int pos = 0, len = 0; int isRVT; /* * when there is cascading XSLT_OP_PREDICATE, then use a * direct computation approach. It's not done directly * at the beginning of the routine to filter out as much * as possible this costly computation. */ if (comp->direct) { if (states.states != NULL) { /* Free the rollback states */ xmlFree(states.states); } return(xsltTestCompMatchDirect(ctxt, comp, node, comp->nsList, comp->nsNr)); } doc = node->doc; if (XSLT_IS_RES_TREE_FRAG(doc)) isRVT = 1; else isRVT = 0; /* * Depending on the last selection, one may need to * recompute contextSize and proximityPosition. */ oldCS = ctxt->xpathCtxt->contextSize; oldCP = ctxt->xpathCtxt->proximityPosition; if ((sel != NULL) && (sel->op == XSLT_OP_ELEM) && (sel->value != NULL) && (node->type == XML_ELEMENT_NODE) && (node->parent != NULL)) { xmlNodePtr previous; int nocache = 0; previous = (xmlNodePtr) XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); if ((previous != NULL) && (previous->parent == node->parent)) { /* * just walk back to adjust the index */ int indx = 0; xmlNodePtr sibling = node; while (sibling != NULL) { if (sibling == previous) break; if ((sibling->type == XML_ELEMENT_NODE) && (previous->name != NULL) && (sibling->name != NULL) && (previous->name[0] == sibling->name[0]) && (xmlStrEqual(previous->name, sibling->name))) { if ((sel->value2 == NULL) || ((sibling->ns != NULL) && (xmlStrEqual(sel->value2, sibling->ns->href)))) indx++; } sibling = sibling->prev; } if (sibling == NULL) { /* hum going backward in document order ... */ indx = 0; sibling = node; while (sibling != NULL) { if (sibling == previous) break; if ((sibling->type == XML_ELEMENT_NODE) && (previous->name != NULL) && (sibling->name != NULL) && (previous->name[0] == sibling->name[0]) && (xmlStrEqual(previous->name, sibling->name))) { if ((sel->value2 == NULL) || ((sibling->ns != NULL) && (xmlStrEqual(sel->value2, sibling->ns->href)))) { indx--; } } sibling = sibling->next; } } if (sibling != NULL) { pos = XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) + indx; /* * If the node is in a Value Tree we need to * save len, but cannot cache the node! * (bugs 153137 and 158840) */ if (node->doc != NULL) { len = XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival); if (!isRVT) { XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; } } } else pos = 0; } else { /* * recompute the index */ xmlNodePtr parent = node->parent; xmlNodePtr siblings = NULL; if (parent) siblings = parent->children; while (siblings != NULL) { if (siblings->type == XML_ELEMENT_NODE) { if (siblings == node) { len++; pos = len; } else if ((node->name != NULL) && (siblings->name != NULL) && (node->name[0] == siblings->name[0]) && (xmlStrEqual(node->name, siblings->name))) { if ((sel->value2 == NULL) || ((siblings->ns != NULL) && (xmlStrEqual(sel->value2, siblings->ns->href)))) len++; } } siblings = siblings->next; } if ((parent == NULL) || (node->doc == NULL)) nocache = 1; else { while (parent->parent != NULL) parent = parent->parent; if (((parent->type != XML_DOCUMENT_NODE) && (parent->type != XML_HTML_DOCUMENT_NODE)) || (parent != (xmlNodePtr) node->doc)) nocache = 1; } } if (pos != 0) { ctxt->xpathCtxt->contextSize = len; ctxt->xpathCtxt->proximityPosition = pos; /* * If the node is in a Value Tree we cannot * cache it ! */ if ((!isRVT) && (node->doc != NULL) && (nocache == 0)) { XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = len; } } } else if ((sel != NULL) && (sel->op == XSLT_OP_ALL) && (node->type == XML_ELEMENT_NODE)) { xmlNodePtr previous; int nocache = 0; previous = (xmlNodePtr) XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); if ((previous != NULL) && (previous->parent == node->parent)) { /* * just walk back to adjust the index */ int indx = 0; xmlNodePtr sibling = node; while (sibling != NULL) { if (sibling == previous) break; if (sibling->type == XML_ELEMENT_NODE) indx++; sibling = sibling->prev; } if (sibling == NULL) { /* hum going backward in document order ... */ indx = 0; sibling = node; while (sibling != NULL) { if (sibling == previous) break; if (sibling->type == XML_ELEMENT_NODE) indx--; sibling = sibling->next; } } if (sibling != NULL) { pos = XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) + indx; /* * If the node is in a Value Tree we cannot * cache it ! */ if ((node->doc != NULL) && !isRVT) { len = XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival); XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; } } else pos = 0; } else { /* * recompute the index */ xmlNodePtr parent = node->parent; xmlNodePtr siblings = NULL; if (parent) siblings = parent->children; while (siblings != NULL) { if (siblings->type == XML_ELEMENT_NODE) { len++; if (siblings == node) { pos = len; } } siblings = siblings->next; } if ((parent == NULL) || (node->doc == NULL)) nocache = 1; else { while (parent->parent != NULL) parent = parent->parent; if (((parent->type != XML_DOCUMENT_NODE) && (parent->type != XML_HTML_DOCUMENT_NODE)) || (parent != (xmlNodePtr) node->doc)) nocache = 1; } } if (pos != 0) { ctxt->xpathCtxt->contextSize = len; ctxt->xpathCtxt->proximityPosition = pos; /* * If the node is in a Value Tree we cannot * cache it ! */ if ((node->doc != NULL) && (nocache == 0) && !isRVT) { XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = len; } } } oldNode = ctxt->node; ctxt->node = node; if (step->value == NULL) goto wrong_index; if (step->comp == NULL) goto wrong_index; if (!xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList, comp->nsNr)) goto wrong_index; if (pos != 0) { ctxt->xpathCtxt->contextSize = oldCS; ctxt->xpathCtxt->proximityPosition = oldCP; } ctxt->node = oldNode; break; wrong_index: if (pos != 0) { ctxt->xpathCtxt->contextSize = oldCS; ctxt->xpathCtxt->proximityPosition = oldCP; } ctxt->node = oldNode; goto rollback; } case XSLT_OP_PI: if (node->type != XML_PI_NODE) goto rollback; if (step->value != NULL) { if (!xmlStrEqual(step->value, node->name)) goto rollback; } break; case XSLT_OP_COMMENT: if (node->type != XML_COMMENT_NODE) goto rollback; break; case XSLT_OP_TEXT: if ((node->type != XML_TEXT_NODE) && (node->type != XML_CDATA_SECTION_NODE)) goto rollback; break; case XSLT_OP_NODE: switch (node->type) { case XML_ELEMENT_NODE: case XML_CDATA_SECTION_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: case XML_TEXT_NODE: break; default: goto rollback; } break; } } found: if (states.states != NULL) { /* Free the rollback states */ xmlFree(states.states); } return(1); rollback: /* got an error try to rollback */ if (states.states == NULL) return(0); if (states.nbstates <= 0) { xmlFree(states.states); return(0); } states.nbstates--; i = states.states[states.nbstates].step; node = states.states[states.nbstates].node; #if 0 fprintf(stderr, "Pop: %d, %s\n", i, node->name); #endif goto restart; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void xen_netbk_tx_submit(struct xen_netbk *netbk) { struct gnttab_copy *gop = netbk->tx_copy_ops; struct sk_buff *skb; while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) { struct xen_netif_tx_request *txp; struct xenvif *vif; u16 pending_idx; unsigned data_len; pending_idx = *((u16 *)skb->data); vif = netbk->pending_tx_info[pending_idx].vif; txp = &netbk->pending_tx_info[pending_idx].req; /* Check the remap error code. */ if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) { netdev_dbg(vif->dev, "netback grant failed.\n"); skb_shinfo(skb)->nr_frags = 0; kfree_skb(skb); continue; } data_len = skb->len; memcpy(skb->data, (void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset), data_len); if (data_len < txp->size) { /* Append the packet payload as a fragment. */ txp->offset += data_len; txp->size -= data_len; } else { /* Schedule a response immediately. */ xen_netbk_idx_release(netbk, pending_idx); } if (txp->flags & XEN_NETTXF_csum_blank) skb->ip_summed = CHECKSUM_PARTIAL; else if (txp->flags & XEN_NETTXF_data_validated) skb->ip_summed = CHECKSUM_UNNECESSARY; xen_netbk_fill_frags(netbk, skb); /* * If the initial fragment was < PKT_PROT_LEN then * pull through some bytes from the other fragments to * increase the linear region to PKT_PROT_LEN bytes. */ if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) { int target = min_t(int, skb->len, PKT_PROT_LEN); __pskb_pull_tail(skb, target - skb_headlen(skb)); } skb->dev = vif->dev; skb->protocol = eth_type_trans(skb, skb->dev); if (checksum_setup(vif, skb)) { netdev_dbg(vif->dev, "Can't setup checksum in net_tx_action\n"); kfree_skb(skb); continue; } vif->dev->stats.rx_bytes += skb->len; vif->dev->stats.rx_packets++; xenvif_receive_skb(vif, skb); } } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Ian Campbell <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static int rfcomm_tty_write_room(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; int room; BT_DBG("tty %p", tty); if (!dev || !dev->dlc) return 0; room = rfcomm_room(dev->dlc) - atomic_read(&dev->wmem_alloc); if (room < 0) room = 0; return room; } Commit Message: Bluetooth: RFCOMM - Fix info leak in ioctl(RFCOMMGETDEVLIST) The RFCOMM code fails to initialize the two padding bytes of struct rfcomm_dev_list_req inserted for alignment before copying it to userland. Additionally there are two padding bytes in each instance of struct rfcomm_dev_info. The ioctl() that for disclosures two bytes plus dev_num times two bytes uninitialized kernel heap memory. Allocate the memory using kzalloc() to fix this issue. Signed-off-by: Mathias Krause <[email protected]> Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void writeFileIndex(int blobIndex) { append(FileIndexTag); doWriteUint32(blobIndex); } Commit Message: Replace further questionable HashMap::add usages in bindings BUG=390928 [email protected] Review URL: https://codereview.chromium.org/411273002 git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int handle_vmon(struct kvm_vcpu *vcpu) { int ret; gpa_t vmptr; struct page *page; struct vcpu_vmx *vmx = to_vmx(vcpu); const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX; /* * The Intel VMX Instruction Reference lists a bunch of bits that are * prerequisite to running VMXON, most notably cr4.VMXE must be set to * 1 (see vmx_set_cr4() for when we allow the guest to set this). * Otherwise, we should fail with #UD. But most faulting conditions * have already been checked by hardware, prior to the VM-exit for * VMXON. We do test guest cr4.VMXE because processor CR4 always has * that bit set to 1 in non-root mode. */ if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (vmx->nested.vmxon) { nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION); return kvm_skip_emulated_instruction(vcpu); } if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES) != VMXON_NEEDED_FEATURES) { kvm_inject_gp(vcpu, 0); return 1; } if (nested_vmx_get_vmptr(vcpu, &vmptr)) return 1; /* * SDM 3: 24.11.5 * The first 4 bytes of VMXON region contain the supported * VMCS revision identifier * * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case; * which replaces physical address width with 32 */ if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } page = kvm_vcpu_gpa_to_page(vcpu, vmptr); if (is_error_page(page)) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } if (*(u32 *)kmap(page) != VMCS12_REVISION) { kunmap(page); kvm_release_page_clean(page); nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } kunmap(page); kvm_release_page_clean(page); vmx->nested.vmxon_ptr = vmptr; ret = enter_vmx_operation(vcpu); if (ret) return ret; nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); } Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions VMX instructions executed inside a L1 VM will always trigger a VM exit even when executed with cpl 3. This means we must perform the privilege check in software. Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks") Cc: [email protected] Signed-off-by: Felix Wilhelm <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: Target: 1 Example 2: Code: int32_t PPB_URLLoader_Impl::FinishStreamingToFile( scoped_refptr<TrackedCallback> callback) { int32_t rv = ValidateCallback(callback); if (rv != PP_OK) return rv; if (!response_info_ || !response_info_->body()) return PP_ERROR_FAILED; if (done_status_ != PP_OK_COMPLETIONPENDING) return done_status_; is_streaming_to_file_ = true; if (is_asynchronous_load_suspended_) SetDefersLoading(false); RegisterCallback(callback); return PP_OK_COMPLETIONPENDING; } Commit Message: Break path whereby AssociatedURLLoader::~AssociatedURLLoader() is re-entered on top of itself. BUG=159429 Review URL: https://chromiumcodereview.appspot.com/11359222 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168150 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: const char * util_acl_to_str(const sc_acl_entry_t *e) { static char line[80], buf[20]; unsigned int acl; if (e == NULL) return "N/A"; line[0] = 0; while (e != NULL) { acl = e->method; switch (acl) { case SC_AC_UNKNOWN: return "N/A"; case SC_AC_NEVER: return "NEVR"; case SC_AC_NONE: return "NONE"; case SC_AC_CHV: strcpy(buf, "CHV"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "%d", e->key_ref); break; case SC_AC_TERM: strcpy(buf, "TERM"); break; case SC_AC_PRO: strcpy(buf, "PROT"); break; case SC_AC_AUT: strcpy(buf, "AUTH"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 4, "%d", e->key_ref); break; case SC_AC_SEN: strcpy(buf, "Sec.Env. "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; case SC_AC_SCB: strcpy(buf, "Sec.ControlByte "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "Ox%X", e->key_ref); break; case SC_AC_IDA: strcpy(buf, "PKCS#15 AuthID "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; default: strcpy(buf, "????"); break; } strcat(line, buf); strcat(line, " "); e = e->next; } line[strlen(line)-1] = 0; /* get rid of trailing space */ return line; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void comps_rtree_unite(COMPS_RTree *rt1, COMPS_RTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; struct Pair { COMPS_HSList * subnodes; char * key; char added; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_RTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_RTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key + strlen(parent_pair->key), ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_RTreeData*)it->data)->key) +1)); memcpy(pair->key, ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_RTreeData*)it->data)->data != NULL) { comps_rtree_set(rt1, pair->key, rt2->data_cloner(((COMPS_RTreeData*)it->data)->data)); } if (((COMPS_RTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); } Commit Message: Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste. CWE ID: CWE-416 Target: 1 Example 2: Code: int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *a) { ASN1_OCTET_STRING *msg; TS_X509_ALGOR_print_bio(bio, a->hash_algo); BIO_printf(bio, "Message data:\n"); msg = a->hashed_msg; BIO_dump_indent(bio, (const char *)ASN1_STRING_data(msg), ASN1_STRING_length(msg), 4); return 1; } Commit Message: Fix OOB read in TS_OBJ_print_bio(). TS_OBJ_print_bio() misuses OBJ_txt2obj: it should print the result as a null terminated buffer. The length value returned is the total length the complete text reprsentation would need not the amount of data written. CVE-2016-2180 Thanks to Shi Lei for reporting this bug. Reviewed-by: Matt Caswell <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Element::hasFlagsSetDuringStylingOfChildren() const { if (!hasRareData()) return false; return rareDataChildrenAffectedByHover() || rareDataChildrenAffectedByActive() || rareDataChildrenAffectedByDrag() || rareDataChildrenAffectedByFirstChildRules() || rareDataChildrenAffectedByLastChildRules() || rareDataChildrenAffectedByDirectAdjacentRules() || rareDataChildrenAffectedByForwardPositionalRules() || rareDataChildrenAffectedByBackwardPositionalRules(); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); return 0; } JAS_DBGLOG(1, ( "BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n", hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off )); /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); return 0; } JAS_DBGLOG(1, ("BMP information: len %d; width %d; height %d; numplanes %d; " "depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; " "mincolors %d\n", info->len, info->width, info->height, info->numplanes, info->depth, info->enctype, info->siz, info->hres, info->vres, info->numcolors, info->mincolors)); /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); return 0; } if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { bmp_info_destroy(info); return 0; } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { bmp_info_destroy(info); return 0; } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { bmp_info_destroy(info); jas_image_destroy(image); return 0; } bmp_info_destroy(info); return image; } Commit Message: Fixed a problem with a null pointer dereference in the BMP decoder. CWE ID: CWE-476 Target: 1 Example 2: Code: static int sctp_v4_available(union sctp_addr *addr, struct sctp_sock *sp) { struct net *net = sock_net(&sp->inet.sk); int ret = inet_addr_type(net, addr->v4.sin_addr.s_addr); if (addr->v4.sin_addr.s_addr != htonl(INADDR_ANY) && ret != RTN_LOCAL && !sp->inet.freebind && !net->ipv4.sysctl_ip_nonlocal_bind) return 0; if (ipv6_only_sock(sctp_opt2sk(sp))) return 0; return 1; } Commit Message: sctp: fix race on protocol/netns initialization Consider sctp module is unloaded and is being requested because an user is creating a sctp socket. During initialization, sctp will add the new protocol type and then initialize pernet subsys: status = sctp_v4_protosw_init(); if (status) goto err_protosw_init; status = sctp_v6_protosw_init(); if (status) goto err_v6_protosw_init; status = register_pernet_subsys(&sctp_net_ops); The problem is that after those calls to sctp_v{4,6}_protosw_init(), it is possible for userspace to create SCTP sockets like if the module is already fully loaded. If that happens, one of the possible effects is that we will have readers for net->sctp.local_addr_list list earlier than expected and sctp_net_init() does not take precautions while dealing with that list, leading to a potential panic but not limited to that, as sctp_sock_init() will copy a bunch of blank/partially initialized values from net->sctp. The race happens like this: CPU 0 | CPU 1 socket() | __sock_create | socket() inet_create | __sock_create list_for_each_entry_rcu( | answer, &inetsw[sock->type], | list) { | inet_create /* no hits */ | if (unlikely(err)) { | ... | request_module() | /* socket creation is blocked | * the module is fully loaded | */ | sctp_init | sctp_v4_protosw_init | inet_register_protosw | list_add_rcu(&p->list, | last_perm); | | list_for_each_entry_rcu( | answer, &inetsw[sock->type], sctp_v6_protosw_init | list) { | /* hit, so assumes protocol | * is already loaded | */ | /* socket creation continues | * before netns is initialized | */ register_pernet_subsys | Simply inverting the initialization order between register_pernet_subsys() and sctp_v4_protosw_init() is not possible because register_pernet_subsys() will create a control sctp socket, so the protocol must be already visible by then. Deferring the socket creation to a work-queue is not good specially because we loose the ability to handle its errors. So, as suggested by Vlad, the fix is to split netns initialization in two moments: defaults and control socket, so that the defaults are already loaded by when we register the protocol, while control socket initialization is kept at the same moment it is today. Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace") Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline bool is_flush_request(struct request *rq, struct blk_flush_queue *fq, unsigned int tag) { return ((rq->cmd_flags & REQ_FLUSH_SEQ) && fq->flush_rq->tag == tag); } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int audit_log_single_execve_arg(struct audit_context *context, struct audit_buffer **ab, int arg_num, size_t *len_sent, const char __user *p, char *buf) { char arg_num_len_buf[12]; const char __user *tmp_p = p; /* how many digits are in arg_num? 5 is the length of ' a=""' */ size_t arg_num_len = snprintf(arg_num_len_buf, 12, "%d", arg_num) + 5; size_t len, len_left, to_send; size_t max_execve_audit_len = MAX_EXECVE_AUDIT_LEN; unsigned int i, has_cntl = 0, too_long = 0; int ret; /* strnlen_user includes the null we don't want to send */ len_left = len = strnlen_user(p, MAX_ARG_STRLEN) - 1; /* * We just created this mm, if we can't find the strings * we just copied into it something is _very_ wrong. Similar * for strings that are too long, we should not have created * any. */ if (WARN_ON_ONCE(len < 0 || len > MAX_ARG_STRLEN - 1)) { send_sig(SIGKILL, current, 0); return -1; } /* walk the whole argument looking for non-ascii chars */ do { if (len_left > MAX_EXECVE_AUDIT_LEN) to_send = MAX_EXECVE_AUDIT_LEN; else to_send = len_left; ret = copy_from_user(buf, tmp_p, to_send); /* * There is no reason for this copy to be short. We just * copied them here, and the mm hasn't been exposed to user- * space yet. */ if (ret) { WARN_ON(1); send_sig(SIGKILL, current, 0); return -1; } buf[to_send] = '\0'; has_cntl = audit_string_contains_control(buf, to_send); if (has_cntl) { /* * hex messages get logged as 2 bytes, so we can only * send half as much in each message */ max_execve_audit_len = MAX_EXECVE_AUDIT_LEN / 2; break; } len_left -= to_send; tmp_p += to_send; } while (len_left > 0); len_left = len; if (len > max_execve_audit_len) too_long = 1; /* rewalk the argument actually logging the message */ for (i = 0; len_left > 0; i++) { int room_left; if (len_left > max_execve_audit_len) to_send = max_execve_audit_len; else to_send = len_left; /* do we have space left to send this argument in this ab? */ room_left = MAX_EXECVE_AUDIT_LEN - arg_num_len - *len_sent; if (has_cntl) room_left -= (to_send * 2); else room_left -= to_send; if (room_left < 0) { *len_sent = 0; audit_log_end(*ab); *ab = audit_log_start(context, GFP_KERNEL, AUDIT_EXECVE); if (!*ab) return 0; } /* * first record needs to say how long the original string was * so we can be sure nothing was lost. */ if ((i == 0) && (too_long)) audit_log_format(*ab, " a%d_len=%zu", arg_num, has_cntl ? 2*len : len); /* * normally arguments are small enough to fit and we already * filled buf above when we checked for control characters * so don't bother with another copy_from_user */ if (len >= max_execve_audit_len) ret = copy_from_user(buf, p, to_send); else ret = 0; if (ret) { WARN_ON(1); send_sig(SIGKILL, current, 0); return -1; } buf[to_send] = '\0'; /* actually log it */ audit_log_format(*ab, " a%d", arg_num); if (too_long) audit_log_format(*ab, "[%d]", i); audit_log_format(*ab, "="); if (has_cntl) audit_log_n_hex(*ab, buf, to_send); else audit_log_string(*ab, buf); p += to_send; len_left -= to_send; *len_sent += arg_num_len; if (has_cntl) *len_sent += to_send * 2; else *len_sent += to_send; } /* include the null we didn't log */ return len + 1; } Commit Message: audit: fix a double fetch in audit_log_single_execve_arg() There is a double fetch problem in audit_log_single_execve_arg() where we first check the execve(2) argumnets for any "bad" characters which would require hex encoding and then re-fetch the arguments for logging in the audit record[1]. Of course this leaves a window of opportunity for an unsavory application to munge with the data. This patch reworks things by only fetching the argument data once[2] into a buffer where it is scanned and logged into the audit records(s). In addition to fixing the double fetch, this patch improves on the original code in a few other ways: better handling of large arguments which require encoding, stricter record length checking, and some performance improvements (completely unverified, but we got rid of some strlen() calls, that's got to be a good thing). As part of the development of this patch, I've also created a basic regression test for the audit-testsuite, the test can be tracked on GitHub at the following link: * https://github.com/linux-audit/audit-testsuite/issues/25 [1] If you pay careful attention, there is actually a triple fetch problem due to a strnlen_user() call at the top of the function. [2] This is a tiny white lie, we do make a call to strnlen_user() prior to fetching the argument data. I don't like it, but due to the way the audit record is structured we really have no choice unless we copy the entire argument at once (which would require a rather wasteful allocation). The good news is that with this patch the kernel no longer relies on this strnlen_user() value for anything beyond recording it in the log, we also update it with a trustworthy value whenever possible. Reported-by: Pengfei Wang <[email protected]> Cc: <[email protected]> Signed-off-by: Paul Moore <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: void nl80211_send_scan_done(struct cfg80211_registered_device *rdev, struct net_device *netdev) { struct sk_buff *msg; msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!msg) return; if (nl80211_send_scan_msg(msg, rdev, netdev, 0, 0, 0, NL80211_CMD_NEW_SCAN_RESULTS) < 0) { nlmsg_free(msg); return; } genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0, nl80211_scan_mcgrp.id, GFP_KERNEL); } Commit Message: nl80211: fix check for valid SSID size in scan operations In both trigger_scan and sched_scan operations, we were checking for the SSID length before assigning the value correctly. Since the memory was just kzalloc'ed, the check was always failing and SSID with over 32 characters were allowed to go through. This was causing a buffer overflow when copying the actual SSID to the proper place. This bug has been there since 2.6.29-rc4. Cc: [email protected] Signed-off-by: Luciano Coelho <[email protected]> Signed-off-by: John W. Linville <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer( PepperPluginInstanceImpl* plugin) { blink::WebURL main_frame_url; WebFrame* main_frame = render_view()->webview()->MainFrame(); if (main_frame->IsWebLocalFrame()) main_frame_url = main_frame->ToWebLocalFrame()->GetDocument().Url(); mojom::WidgetPtr widget_channel; mojom::WidgetRequest widget_channel_request = mojo::MakeRequest(&widget_channel); int32_t fullscreen_widget_routing_id = MSG_ROUTING_NONE; if (!RenderThreadImpl::current_render_message_filter() ->CreateFullscreenWidget(render_view()->GetRoutingID(), std::move(widget_channel), &fullscreen_widget_routing_id)) { return nullptr; } RenderWidget::ShowCallback show_callback = base::BindOnce(&RenderViewImpl::ShowCreatedFullscreenWidget, render_view()->GetWeakPtr()); RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create( fullscreen_widget_routing_id, std::move(show_callback), GetRenderWidget()->compositor_deps(), plugin, std::move(main_frame_url), GetRenderWidget()->GetWebScreenInfo(), std::move(widget_channel_request)); widget->Show(blink::kWebNavigationPolicyCurrentTab); return widget; } Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s) ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl. We need to reset external_popup_menu_ before calling it. Bug: 912211 Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc Reviewed-on: https://chromium-review.googlesource.com/c/1381325 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#618026} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool IsSiteMuted(const TabStripModel& tab_strip, const int index) { content::WebContents* web_contents = tab_strip.GetWebContentsAt(index); GURL url = web_contents->GetLastCommittedURL(); if (url.SchemeIs(content::kChromeUIScheme)) { return web_contents->IsAudioMuted() && GetTabAudioMutedReason(web_contents) == TabMutedReason::CONTENT_SETTING_CHROME; } Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); return settings->GetContentSetting(url, url, CONTENT_SETTINGS_TYPE_SOUND, std::string()) == CONTENT_SETTING_BLOCK; } Commit Message: Fix nullptr crash in IsSiteMuted This CL adds a nullptr check in IsSiteMuted to prevent a crash on Mac. Bug: 797647 Change-Id: Ic36f0fb39f2dbdf49d2bec9e548a4a6e339dc9a2 Reviewed-on: https://chromium-review.googlesource.com/848245 Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Yuri Wiitala <[email protected]> Commit-Queue: Tommy Steimel <[email protected]> Cr-Commit-Position: refs/heads/master@{#526825} CWE ID: Target: 1 Example 2: Code: void Document::ReportFeaturePolicyViolation( mojom::FeaturePolicyFeature feature, mojom::FeaturePolicyDisposition disposition, const String& message) const { if (!RuntimeEnabledFeatures::FeaturePolicyReportingEnabled()) return; LocalFrame* frame = GetFrame(); if (!frame) return; const String& feature_name = GetNameForFeature(feature); FeaturePolicyViolationReportBody* body = MakeGarbageCollected<FeaturePolicyViolationReportBody>( feature_name, "Feature policy violation", (disposition == mojom::FeaturePolicyDisposition::kReport ? "report" : "enforce"), SourceLocation::Capture()); Report* report = new Report("feature-policy-violation", Url().GetString(), body); ReportingContext::From(this)->QueueReport(report); bool is_null; int line_number = body->lineNumber(is_null); line_number = is_null ? 0 : line_number; int column_number = body->columnNumber(is_null); column_number = is_null ? 0 : column_number; frame->GetReportingService()->QueueFeaturePolicyViolationReport( Url(), feature_name, (disposition == mojom::FeaturePolicyDisposition::kReport ? "report" : "enforce"), "Feature policy violation", body->sourceFile(), line_number, column_number); if (disposition == mojom::FeaturePolicyDisposition::kEnforce) { frame->Console().AddMessage(ConsoleMessage::Create( kViolationMessageSource, kErrorMessageLevel, (message.IsEmpty() ? ("Feature policy violation: " + feature_name + " is not allowed in this document.") : message))); } } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void wakeup_pipe_readers(struct pipe_inode_info *pipe) { smp_mb(); if (waitqueue_active(&pipe->wait)) wake_up_interruptible(&pipe->wait); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static plist_t parse_bin_node(struct bplist_data *bplist, const char** object) { uint16_t type = 0; uint64_t size = 0; if (!object) return NULL; type = (**object) & BPLIST_MASK; size = (**object) & BPLIST_FILL; (*object)++; if (size == BPLIST_FILL) { switch (type) { case BPLIST_DATA: case BPLIST_STRING: case BPLIST_UNICODE: case BPLIST_ARRAY: case BPLIST_SET: case BPLIST_DICT: { uint16_t next_size = **object & BPLIST_FILL; if ((**object & BPLIST_MASK) != BPLIST_UINT) { PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT); return NULL; } (*object)++; next_size = 1 << next_size; if (*object + next_size > bplist->offset_table) { PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type); return NULL; } size = UINT_TO_HOST(*object, next_size); (*object) += next_size; break; } default: break; } } switch (type) { case BPLIST_NULL: switch (size) { case BPLIST_TRUE: { plist_data_t data = plist_new_plist_data(); data->type = PLIST_BOOLEAN; data->boolval = TRUE; data->length = 1; return node_create(NULL, data); } case BPLIST_FALSE: { plist_data_t data = plist_new_plist_data(); data->type = PLIST_BOOLEAN; data->boolval = FALSE; data->length = 1; return node_create(NULL, data); } case BPLIST_NULL: default: return NULL; } case BPLIST_UINT: if (*object + (uint64_t)(1 << size) > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__); return NULL; } return parse_uint_node(object, size); case BPLIST_REAL: if (*object + (uint64_t)(1 << size) > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__); return NULL; } return parse_real_node(object, size); case BPLIST_DATE: if (3 != size) { PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__); return NULL; } if (*object + (uint64_t)(1 << size) > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__); return NULL; } return parse_date_node(object, size); case BPLIST_DATA: if (*object + size > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__); return NULL; } return parse_data_node(object, size); case BPLIST_STRING: if (*object + size > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__); return NULL; } return parse_string_node(object, size); case BPLIST_UNICODE: if (size*2 < size) { PLIST_BIN_ERR("%s: Integer overflow when calculating BPLIST_UNICODE data size.\n", __func__); return NULL; } if (*object + size*2 > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__); return NULL; } return parse_unicode_node(object, size); case BPLIST_SET: case BPLIST_ARRAY: if (*object + size > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__); return NULL; } return parse_array_node(bplist, object, size); case BPLIST_UID: if (*object + size+1 > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__); return NULL; } return parse_uid_node(object, size); case BPLIST_DICT: if (*object + size > bplist->offset_table) { PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__); return NULL; } return parse_dict_node(bplist, object, size); default: PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type); return NULL; } return NULL; } Commit Message: bplist: Fix data range check for string/data/dict/array nodes Passing a size of 0xFFFFFFFFFFFFFFFF to parse_string_node() might result in a memcpy with a size of -1, leading to undefined behavior. This commit makes sure that the actual node data (which depends on the size) is in the range start_of_object..start_of_object+size. Credit to OSS-Fuzz CWE ID: CWE-787 Target: 1 Example 2: Code: bool CNB::MapDataToVirtioSGL(CTXDescriptor &Descriptor, ULONG Offset) const { for (ULONG i = 0; i < m_SGL->NumberOfElements; i++) { if (Offset < m_SGL->Elements[i].Length) { PHYSICAL_ADDRESS PA; PA.QuadPart = m_SGL->Elements[i].Address.QuadPart + Offset; if (!Descriptor.AddDataChunk(PA, m_SGL->Elements[i].Length - Offset)) { return false; } Offset = 0; } else { Offset -= m_SGL->Elements[i].Length; } } return true; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; } Commit Message: Security: Cross Protocol Scripting protection. This is an attempt at mitigating problems due to cross protocol scripting, an attack targeting services using line oriented protocols like Redis that can accept HTTP requests as valid protocol, by discarding the invalid parts and accepting the payloads sent, for example, via a POST request. For this to be effective, when we detect POST and Host: and terminate the connection asynchronously, the networking code was modified in order to never process further input. It was later verified that in a pipelined request containing a POST command, the successive commands are not executed. CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool FrameFetchContext::UpdateTimingInfoForIFrameNavigation( ResourceTimingInfo* info) { if (IsDetached()) return false; if (!GetFrame()->Owner()) return false; if (!GetFrame()->should_send_resource_timing_info_to_parent()) return false; if (MasterDocumentLoader()->LoadType() == WebFrameLoadType::kBackForward) return false; return true; } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Kunihiko Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200 Target: 1 Example 2: Code: WebFrameTest() : m_baseURL("http://www.test.com/") , m_chromeURL("chrome://") , m_webView(0) { } Commit Message: Call didAccessInitialDocument when javascript: URLs are used. BUG=265221 TEST=See bug for repro. Review URL: https://chromiumcodereview.appspot.com/22572004 git-svn-id: svn://svn.chromium.org/blink/trunk@155790 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void cachedAttributeAnyAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); TestObjectPythonV8Internal::cachedAttributeAnyAttributeAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|truncated]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125 Target: 1 Example 2: Code: void WebGLRenderingContextBase::MarkLayerComposited() { if (!isContextLost()) GetDrawingBuffer()->ResetBuffersToAutoClear(); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void cleanup_cgroups(char *path) { int i; char **slist = subsystems; if (cgm_supports_multiple_controllers) slist = subsystems_inone; for (i = 0; slist[i]; i++) cgm_remove_cgroup(slist[i], path); } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { unsigned char arg[128]; int ret = 0; unsigned int copylen; struct net *net = sock_net(sk); struct netns_ipvs *ipvs = net_ipvs(net); BUG_ON(!net); if (!capable(CAP_NET_ADMIN)) return -EPERM; if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX) return -EINVAL; if (*len < get_arglen[GET_CMDID(cmd)]) { pr_err("get_ctl: len %u < %u\n", *len, get_arglen[GET_CMDID(cmd)]); return -EINVAL; } copylen = get_arglen[GET_CMDID(cmd)]; if (copylen > 128) return -EINVAL; if (copy_from_user(arg, user, copylen) != 0) return -EFAULT; /* * Handle daemons first since it has its own locking */ if (cmd == IP_VS_SO_GET_DAEMON) { struct ip_vs_daemon_user d[2]; memset(&d, 0, sizeof(d)); if (mutex_lock_interruptible(&ipvs->sync_mutex)) return -ERESTARTSYS; if (ipvs->sync_state & IP_VS_STATE_MASTER) { d[0].state = IP_VS_STATE_MASTER; strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn, sizeof(d[0].mcast_ifn)); d[0].syncid = ipvs->master_syncid; } if (ipvs->sync_state & IP_VS_STATE_BACKUP) { d[1].state = IP_VS_STATE_BACKUP; strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn, sizeof(d[1].mcast_ifn)); d[1].syncid = ipvs->backup_syncid; } if (copy_to_user(user, &d, sizeof(d)) != 0) ret = -EFAULT; mutex_unlock(&ipvs->sync_mutex); return ret; } if (mutex_lock_interruptible(&__ip_vs_mutex)) return -ERESTARTSYS; switch (cmd) { case IP_VS_SO_GET_VERSION: { char buf[64]; sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)", NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size); if (copy_to_user(user, buf, strlen(buf)+1) != 0) { ret = -EFAULT; goto out; } *len = strlen(buf)+1; } break; case IP_VS_SO_GET_INFO: { struct ip_vs_getinfo info; info.version = IP_VS_VERSION_CODE; info.size = ip_vs_conn_tab_size; info.num_services = ipvs->num_services; if (copy_to_user(user, &info, sizeof(info)) != 0) ret = -EFAULT; } break; case IP_VS_SO_GET_SERVICES: { struct ip_vs_get_services *get; int size; get = (struct ip_vs_get_services *)arg; size = sizeof(*get) + sizeof(struct ip_vs_service_entry) * get->num_services; if (*len != size) { pr_err("length: %u != %u\n", *len, size); ret = -EINVAL; goto out; } ret = __ip_vs_get_service_entries(net, get, user); } break; case IP_VS_SO_GET_SERVICE: { struct ip_vs_service_entry *entry; struct ip_vs_service *svc; union nf_inet_addr addr; entry = (struct ip_vs_service_entry *)arg; addr.ip = entry->addr; if (entry->fwmark) svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark); else svc = __ip_vs_service_find(net, AF_INET, entry->protocol, &addr, entry->port); if (svc) { ip_vs_copy_service(entry, svc); if (copy_to_user(user, entry, sizeof(*entry)) != 0) ret = -EFAULT; } else ret = -ESRCH; } break; case IP_VS_SO_GET_DESTS: { struct ip_vs_get_dests *get; int size; get = (struct ip_vs_get_dests *)arg; size = sizeof(*get) + sizeof(struct ip_vs_dest_entry) * get->num_dests; if (*len != size) { pr_err("length: %u != %u\n", *len, size); ret = -EINVAL; goto out; } ret = __ip_vs_get_dest_entries(net, get, user); } break; case IP_VS_SO_GET_TIMEOUT: { struct ip_vs_timeout_user t; __ip_vs_get_timeouts(net, &t); if (copy_to_user(user, &t, sizeof(t)) != 0) ret = -EFAULT; } break; default: ret = -EINVAL; } out: mutex_unlock(&__ip_vs_mutex); return ret; } Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT) If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is not set, __ip_vs_get_timeouts() does not fully initialize the structure that gets copied to userland and that for leaks up to 12 bytes of kernel stack. Add an explicit memset(0) before passing the structure to __ip_vs_get_timeouts() to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Wensong Zhang <[email protected]> Cc: Simon Horman <[email protected]> Cc: Julian Anastasov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: bool AnyOtherBitsSet(GLbitfield bits, GLbitfield ref) { DCHECK_NE(0u, ref); GLbitfield mask = ~ref; return ((bits & mask) != 0); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: extract_job_on_completed (AutoarExtractor *extractor, gpointer user_data) { ExtractJob *extract_job = user_data; GFile *output_file; output_file = G_FILE (extract_job->output_files->data); nautilus_file_changes_queue_file_added (output_file); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip, impeg2d_video_decode_op_t *ps_op) { UWORD32 u4_bits_read; dec_state_t *ps_dec; ps_dec = (dec_state_t *)pv_dec; ps_op->s_ivd_video_decode_op_t.u4_error_code = 0; impeg2d_bit_stream_init(&(ps_dec->s_bit_stream),ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes); { { IMPEG2D_ERROR_CODES_T e_error; e_error = impeg2d_process_video_header(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; } if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0) ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE); return; } } ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size; ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size; ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME; ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS; u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; } ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0; /* MOD */ ps_dec->u2_header_done = 1; } } Commit Message: Fix in handling header decode errors If header decode was unsuccessful, do not try decoding a frame Also, initialize pic_wd, pic_ht for reinitialization when decoder is created with smaller dimensions Bug: 28886651 Bug: 35219737 Change-Id: I8c06d9052910e47fce2e6fe25ad318d4c83d2c50 (cherry picked from commit 2b9fa9ace2dbedfbac026fc9b6ab6cdac7f68c27) (cherry picked from commit c2395cd7cc0c286a66de674032dd2ed26500aef4) CWE ID: CWE-119 Target: 1 Example 2: Code: IntRect WebPagePrivate::mapFromTransformedViewportToTransformedContents(const IntRect& rect) const { return m_backingStoreClient->mapFromTransformedViewportToTransformedContents(rect); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::DidLoadAllScriptBlockingResources() { execute_scripts_waiting_for_resources_task_handle_ = TaskRunnerHelper::Get(TaskType::kNetworking, this) ->PostCancellableTask( BLINK_FROM_HERE, WTF::Bind(&Document::ExecuteScriptsWaitingForResources, WrapWeakPersistent(this))); if (IsHTMLDocument() && body()) { BeginLifecycleUpdatesIfRenderingReady(); } else if (!IsHTMLDocument() && documentElement()) { BeginLifecycleUpdatesIfRenderingReady(); } if (goto_anchor_needed_after_stylesheets_load_ && View()) View()->ProcessUrlFragment(url_); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int vt_reset_keyboard(int fd) { int kb; /* If we can't read the default, then default to unicode. It's 2017 after all. */ kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE; if (ioctl(fd, KDSKBMODE, kb) < 0) return -errno; return 0; } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255 Target: 1 Example 2: Code: void vp9_remove_common(VP9_COMMON *cm) { vp9_free_context_buffers(cm); vpx_free(cm->fc); cm->fc = NULL; vpx_free(cm->frame_contexts); cm->frame_contexts = NULL; } Commit Message: DO NOT MERGE libvpx: Cherry-pick 8b4c315 from upstream Description from upstream: vp9_alloc_context_buffers: clear cm->mi* on failure this fixes a crash in vp9_dec_setup_mi() via vp9_init_context_buffers() should decoding continue and the decoder resyncs on a smaller frame Bug: 30593752 Change-Id: Iafbf1c4114062bf796f51a6b03be71328f7bcc69 (cherry picked from commit 737c8493693243838128788fe9c3abc51f17338e) (cherry picked from commit 3e88ffac8c80b76e15286ef8a7b3bd8fa246c761) CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int c, l; xmlChar stop; xmlChar *ret = NULL; const xmlChar *cur = NULL; xmlParserInputPtr input; if (RAW == '"') stop = '"'; else if (RAW == '\'') stop = '\''; else { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } /* * The content of the entity definition is copied in a buffer. */ ctxt->instate = XML_PARSER_ENTITY_VALUE; input = ctxt->input; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } NEXT; c = CUR_CHAR(l); /* * NOTE: 4.4.5 Included in Literal * When a parameter entity reference appears in a literal entity * value, ... a single or double quote character in the replacement * text is always treated as a normal data character and will not * terminate the literal. * In practice it means we stop the loop only when back at parsing * the initial entity and the quote is found */ while (((IS_CHAR(c)) && ((c != stop) || /* checked */ (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } COPY_BUF(l,buf,len,c); NEXTL(l); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ xmlPopInput(ctxt); GROW; c = CUR_CHAR(l); if (c == 0) { GROW; c = CUR_CHAR(l); } } buf[len] = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } /* * Raise problem w.r.t. '&' and '%' being used in non-entities * reference constructs. Note Charref will be handled in * xmlStringDecodeEntities() */ cur = buf; while (*cur != 0) { /* non input consuming */ if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { xmlChar *name; xmlChar tmp = *cur; cur++; name = xmlParseStringName(ctxt, &cur); if ((name == NULL) || (*cur != ';')) { xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, "EntityValue: '%c' forbidden except for entities references\n", tmp); } if ((tmp == '%') && (ctxt->inSubset == 1) && (ctxt->inputNr == 1)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); } if (name != NULL) xmlFree(name); if (*cur == 0) break; } cur++; } /* * Then PEReference entities are substituted. */ if (c != stop) { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); xmlFree(buf); } else { NEXT; /* * NOTE: 4.4.7 Bypassed * When a general entity reference appears in the EntityValue in * an entity declaration, it is bypassed and left as is. * so XML_SUBSTITUTE_REF is not set here. */ ++ctxt->depth; ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, 0, 0, 0); --ctxt->depth; if (orig != NULL) *orig = buf; else xmlFree(buf); } return(ret); } Commit Message: DO NOT MERGE: Add validation for eternal enities https://bugzilla.gnome.org/show_bug.cgi?id=780691 Bug: 36556310 Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648 (cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049) CWE ID: CWE-611 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void TabStripGtk::TabDetachedAt(TabContents* contents, int index) { GenerateIdealBounds(); StartRemoveTabAnimation(index, contents->web_contents()); GetTabAt(index)->set_closing(true); } 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 Target: 1 Example 2: Code: static void msix_handle_mask_update(PCIDevice *dev, int vector, bool was_masked) { bool is_masked = msix_is_masked(dev, vector); if (is_masked == was_masked) { return; } msix_fire_vector_notifier(dev, vector, is_masked); if (!is_masked && msix_is_pending(dev, vector)) { msix_clr_pending(dev, vector); msix_notify(dev, vector); } } Commit Message: CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() { RenderFrameHostImpl* rfh = GetMainFrame(); return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr; } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, "%d", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError("Could not create lock file in %s\n", tmp); (void) sprintf(pid_str, "%10ld\n", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY|O_NOFOLLOW); if (lfd < 0) { unlink(tmp); FatalError("Can't read lock file %s\n", LockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\0'; sscanf(pid_str, "%d", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", LockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) FatalError("Could not create server lock file: %s\n", LockFile); StillLocking = FALSE; } Commit Message: CWE ID: CWE-362 Target: 1 Example 2: Code: void jspSoftKill() { jsvUnLock(execInfo.hiddenRoot); execInfo.hiddenRoot = 0; jsvUnLock(execInfo.root); execInfo.root = 0; } Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static u32 FFD_RegisterMimeTypes(const GF_InputService *plug) { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) gf_service_register_mime(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2]); return i/3; } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, --, NULL */ const char *args[11]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); } Commit Message: a-a-i-d-to-abrt-cache: make own random temporary directory The set-user-ID wrapper must use own new temporary directory in order to avoid security issues with unpacking specially crafted debuginfo packages that might be used to create files or symlinks anywhere on the file system as the abrt user. Withot the forking code the temporary directory would remain on the filesystem in the case where all debuginfo data are already available. This is caused by the fact that the underlying libreport functionality accepts path to a desired temporary directory and creates it only if necessary. Otherwise, the directory is not touched at all. This commit addresses CVE-2015-5273 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59 Target: 1 Example 2: Code: void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) { unsigned count; unsigned char *p; uint32_t *a; count = (ctx->bits[0] >> 3) & 0x3F; p = ctx->in + count; *p++ = 0x80; count = 64 - 1 - count; if (count < 8) { memset(p, 0, count); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); memset(ctx->in, 0, 56); } else { memset(p, 0, count - 8); } byteReverse(ctx->in, 14); a = (uint32_t *) ctx->in; a[14] = ctx->bits[0]; a[15] = ctx->bits[1]; MD5Transform(ctx->buf, (uint32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset((char *) ctx, 0, sizeof(*ctx)); } Commit Message: Fix crash in multipart handling Close cesanta/dev#6974 PUBLISHED_FROM=4d4e4a46eceba10aec8dacb7f8f58bd078c92307 CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void SVGStartElement(void *context,const xmlChar *name, const xmlChar **attributes) { char *color, id[MaxTextExtent], token[MaxTextExtent], **tokens, *units; const char *keyword, *p, *value; int number_tokens; SVGInfo *svg_info; register ssize_t i, j; /* Called when an opening tag has been processed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.startElement(%s", name); svg_info=(SVGInfo *) context; svg_info->n++; svg_info->scale=(double *) ResizeQuantumMemory(svg_info->scale, svg_info->n+1UL,sizeof(*svg_info->scale)); if (svg_info->scale == (double *) NULL) { (void) ThrowMagickException(svg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",name); return; } svg_info->scale[svg_info->n]=svg_info->scale[svg_info->n-1]; color=AcquireString("none"); units=AcquireString("userSpaceOnUse"); value=(const char *) NULL; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i+=2) { keyword=(const char *) attributes[i]; value=(const char *) attributes[i+1]; switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"cx") == 0) { svg_info->element.cx= GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"cy") == 0) { svg_info->element.cy= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fx") == 0) { svg_info->element.major= GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"fy") == 0) { svg_info->element.minor= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { svg_info->bounds.height= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } case 'I': case 'i': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,value,MaxTextExtent); break; } break; } case 'R': case 'r': { if (LocaleCompare(keyword,"r") == 0) { svg_info->element.angle= GetUserSpaceCoordinateValue(svg_info,0,value); break; } break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { svg_info->bounds.width= GetUserSpaceCoordinateValue(svg_info,1,value); break; } break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { svg_info->bounds.x=GetUserSpaceCoordinateValue(svg_info,1,value)- svg_info->center.x; break; } if (LocaleCompare(keyword,"x1") == 0) { svg_info->segment.x1=GetUserSpaceCoordinateValue(svg_info,1, value); break; } if (LocaleCompare(keyword,"x2") == 0) { svg_info->segment.x2=GetUserSpaceCoordinateValue(svg_info,1, value); break; } break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { svg_info->bounds.y=GetUserSpaceCoordinateValue(svg_info,-1,value)- svg_info->center.y; break; } if (LocaleCompare(keyword,"y1") == 0) { svg_info->segment.y1= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } if (LocaleCompare(keyword,"y2") == 0) { svg_info->segment.y2= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } default: break; } } if (strchr((char *) name,':') != (char *) NULL) { /* Skip over namespace. */ for ( ; *name != ':'; name++) ; name++; } switch (*name) { case 'C': case 'c': { if (LocaleCompare((const char *) name,"circle") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } if (LocaleCompare((const char *) name,"clipPath") == 0) { (void) FormatLocaleFile(svg_info->file,"push clip-path '%s'\n",id); break; } break; } case 'D': case 'd': { if (LocaleCompare((const char *) name,"defs") == 0) { (void) FormatLocaleFile(svg_info->file,"push defs\n"); break; } break; } case 'E': case 'e': { if (LocaleCompare((const char *) name,"ellipse") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } break; } case 'G': case 'g': { if (LocaleCompare((const char *) name,"g") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } break; } case 'I': case 'i': { if (LocaleCompare((const char *) name,"image") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } break; } case 'L': case 'l': { if (LocaleCompare((const char *) name,"line") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } if (LocaleCompare((const char *) name,"linearGradient") == 0) { (void) FormatLocaleFile(svg_info->file, "push gradient '%s' linear %g,%g %g,%g\n",id, svg_info->segment.x1,svg_info->segment.y1,svg_info->segment.x2, svg_info->segment.y2); break; } break; } case 'P': case 'p': { if (LocaleCompare((const char *) name,"path") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } if (LocaleCompare((const char *) name,"pattern") == 0) { (void) FormatLocaleFile(svg_info->file, "push pattern '%s' %g,%g %g,%g\n",id, svg_info->bounds.x,svg_info->bounds.y,svg_info->bounds.width, svg_info->bounds.height); break; } if (LocaleCompare((const char *) name,"polygon") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } if (LocaleCompare((const char *) name,"polyline") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } break; } case 'R': case 'r': { if (LocaleCompare((const char *) name,"radialGradient") == 0) { (void) FormatLocaleFile(svg_info->file, "push gradient '%s' radial %g,%g %g,%g %g\n", id,svg_info->element.cx,svg_info->element.cy, svg_info->element.major,svg_info->element.minor, svg_info->element.angle); break; } if (LocaleCompare((const char *) name,"rect") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } break; } case 'S': case 's': { if (LocaleCompare((const char *) name,"svg") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } break; } case 'T': case 't': { if (LocaleCompare((const char *) name,"text") == 0) { (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); svg_info->bounds.x=0.0; svg_info->bounds.y=0.0; svg_info->bounds.width=0.0; svg_info->bounds.height=0.0; break; } if (LocaleCompare((const char *) name,"tspan") == 0) { if (*svg_info->text != '\0') { DrawInfo *draw_info; TypeMetric metrics; char *text; text=EscapeString(svg_info->text,'\''); (void) FormatLocaleFile(svg_info->file,"text %g,%g '%s'\n", svg_info->bounds.x-svg_info->center.x,svg_info->bounds.y- svg_info->center.y,text); text=DestroyString(text); draw_info=CloneDrawInfo(svg_info->image_info,(DrawInfo *) NULL); draw_info->pointsize=svg_info->pointsize; draw_info->text=AcquireString(svg_info->text); (void) ConcatenateString(&draw_info->text," "); GetTypeMetrics(svg_info->image,draw_info,&metrics); svg_info->bounds.x+=metrics.width; draw_info=DestroyDrawInfo(draw_info); *svg_info->text='\0'; } (void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); break; } break; } default: break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i+=2) { keyword=(const char *) attributes[i]; value=(const char *) attributes[i+1]; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %s = %s",keyword,value); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"angle") == 0) { (void) FormatLocaleFile(svg_info->file,"angle %g\n", GetUserSpaceCoordinateValue(svg_info,0,value)); break; } break; } case 'C': case 'c': { if (LocaleCompare(keyword,"clip-path") == 0) { (void) FormatLocaleFile(svg_info->file,"clip-path '%s'\n",value); break; } if (LocaleCompare(keyword,"clip-rule") == 0) { (void) FormatLocaleFile(svg_info->file,"clip-rule '%s'\n",value); break; } if (LocaleCompare(keyword,"clipPathUnits") == 0) { (void) CloneString(&units,value); (void) FormatLocaleFile(svg_info->file,"clip-units '%s'\n",value); break; } if (LocaleCompare(keyword,"color") == 0) { (void) CloneString(&color,value); break; } if (LocaleCompare(keyword,"cx") == 0) { svg_info->element.cx= GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"cy") == 0) { svg_info->element.cy= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } case 'D': case 'd': { if (LocaleCompare(keyword,"d") == 0) { (void) CloneString(&svg_info->vertices,value); break; } if (LocaleCompare(keyword,"dx") == 0) { svg_info->bounds.x+=GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"dy") == 0) { svg_info->bounds.y+= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { if (LocaleCompare(value,"currentColor") == 0) { (void) FormatLocaleFile(svg_info->file,"fill '%s'\n",color); break; } (void) FormatLocaleFile(svg_info->file,"fill '%s'\n",value); break; } if (LocaleCompare(keyword,"fillcolor") == 0) { (void) FormatLocaleFile(svg_info->file,"fill '%s'\n",value); break; } if (LocaleCompare(keyword,"fill-rule") == 0) { (void) FormatLocaleFile(svg_info->file,"fill-rule '%s'\n",value); break; } if (LocaleCompare(keyword,"fill-opacity") == 0) { (void) FormatLocaleFile(svg_info->file,"fill-opacity '%s'\n", value); break; } if (LocaleCompare(keyword,"font-family") == 0) { (void) FormatLocaleFile(svg_info->file,"font-family '%s'\n", value); break; } if (LocaleCompare(keyword,"font-stretch") == 0) { (void) FormatLocaleFile(svg_info->file,"font-stretch '%s'\n", value); break; } if (LocaleCompare(keyword,"font-style") == 0) { (void) FormatLocaleFile(svg_info->file,"font-style '%s'\n",value); break; } if (LocaleCompare(keyword,"font-size") == 0) { svg_info->pointsize=GetUserSpaceCoordinateValue(svg_info,0,value); (void) FormatLocaleFile(svg_info->file,"font-size %g\n", svg_info->pointsize); break; } if (LocaleCompare(keyword,"font-weight") == 0) { (void) FormatLocaleFile(svg_info->file,"font-weight '%s'\n", value); break; } break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gradientTransform") == 0) { AffineMatrix affine, current, transform; GetAffineMatrix(&transform); (void) LogMagickEvent(CoderEvent,GetMagickModule()," "); tokens=GetTransformTokens(context,value,&number_tokens); for (j=0; j < (number_tokens-1); j+=2) { keyword=(char *) tokens[j]; if (keyword == (char *) NULL) continue; value=(char *) tokens[j+1]; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %s: %s",keyword,value); current=transform; GetAffineMatrix(&affine); switch (*keyword) { case 'M': case 'm': { if (LocaleCompare(keyword,"matrix") == 0) { p=(const char *) value; GetMagickToken(p,&p,token); affine.sx=StringToDouble(value,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.rx=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.ry=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.sy=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.tx=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.ty=StringToDouble(token,(char **) NULL); break; } break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { double angle; angle=GetUserSpaceCoordinateValue(svg_info,0,value); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { for (p=(const char *) value; *p != '\0'; p++) if ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) break; affine.sx=GetUserSpaceCoordinateValue(svg_info,1,value); affine.sy=affine.sx; if (*p != '\0') affine.sy= GetUserSpaceCoordinateValue(svg_info,-1,p+1); svg_info->scale[svg_info->n]=ExpandAffine(&affine); break; } if (LocaleCompare(keyword,"skewX") == 0) { affine.sx=svg_info->affine.sx; affine.ry=tan(DegreesToRadians(fmod( GetUserSpaceCoordinateValue(svg_info,1,value), 360.0))); affine.sy=svg_info->affine.sy; break; } if (LocaleCompare(keyword,"skewY") == 0) { affine.sx=svg_info->affine.sx; affine.rx=tan(DegreesToRadians(fmod( GetUserSpaceCoordinateValue(svg_info,-1,value), 360.0))); affine.sy=svg_info->affine.sy; break; } break; } case 'T': case 't': { if (LocaleCompare(keyword,"translate") == 0) { for (p=(const char *) value; *p != '\0'; p++) if ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) break; affine.tx=GetUserSpaceCoordinateValue(svg_info,1,value); affine.ty=affine.tx; if (*p != '\0') affine.ty= GetUserSpaceCoordinateValue(svg_info,-1,p+1); break; } break; } default: break; } transform.sx=affine.sx*current.sx+affine.ry*current.rx; transform.rx=affine.rx*current.sx+affine.sy*current.rx; transform.ry=affine.sx*current.ry+affine.ry*current.sy; transform.sy=affine.rx*current.ry+affine.sy*current.sy; transform.tx=affine.tx*current.sx+affine.ty*current.ry+ current.tx; transform.ty=affine.tx*current.rx+affine.ty*current.sy+ current.ty; } (void) FormatLocaleFile(svg_info->file, "affine %g %g %g %g %g %g\n",transform.sx, transform.rx,transform.ry,transform.sy,transform.tx, transform.ty); for (j=0; tokens[j] != (char *) NULL; j++) tokens[j]=DestroyString(tokens[j]); tokens=(char **) RelinquishMagickMemory(tokens); break; } if (LocaleCompare(keyword,"gradientUnits") == 0) { (void) CloneString(&units,value); (void) FormatLocaleFile(svg_info->file,"gradient-units '%s'\n", value); break; } break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { svg_info->bounds.height= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } if (LocaleCompare(keyword,"href") == 0) { (void) CloneString(&svg_info->url,value); break; } break; } case 'M': case 'm': { if (LocaleCompare(keyword,"major") == 0) { svg_info->element.major= GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"minor") == 0) { svg_info->element.minor= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } case 'O': case 'o': { if (LocaleCompare(keyword,"offset") == 0) { (void) CloneString(&svg_info->offset,value); break; } if (LocaleCompare(keyword,"opacity") == 0) { (void) FormatLocaleFile(svg_info->file,"opacity '%s'\n",value); break; } break; } case 'P': case 'p': { if (LocaleCompare(keyword,"path") == 0) { (void) CloneString(&svg_info->url,value); break; } if (LocaleCompare(keyword,"points") == 0) { (void) CloneString(&svg_info->vertices,value); break; } break; } case 'R': case 'r': { if (LocaleCompare(keyword,"r") == 0) { svg_info->element.major= GetUserSpaceCoordinateValue(svg_info,1,value); svg_info->element.minor= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } if (LocaleCompare(keyword,"rotate") == 0) { double angle; angle=GetUserSpaceCoordinateValue(svg_info,0,value); (void) FormatLocaleFile(svg_info->file,"translate %g,%g\n", svg_info->bounds.x,svg_info->bounds.y); svg_info->bounds.x=0; svg_info->bounds.y=0; (void) FormatLocaleFile(svg_info->file,"rotate %g\n",angle); break; } if (LocaleCompare(keyword,"rx") == 0) { if (LocaleCompare((const char *) name,"ellipse") == 0) svg_info->element.major= GetUserSpaceCoordinateValue(svg_info,1,value); else svg_info->radius.x= GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"ry") == 0) { if (LocaleCompare((const char *) name,"ellipse") == 0) svg_info->element.minor= GetUserSpaceCoordinateValue(svg_info,-1,value); else svg_info->radius.y= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } case 'S': case 's': { if (LocaleCompare(keyword,"stop-color") == 0) { (void) CloneString(&svg_info->stop_color,value); break; } if (LocaleCompare(keyword,"stroke") == 0) { if (LocaleCompare(value,"currentColor") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke '%s'\n",color); break; } (void) FormatLocaleFile(svg_info->file,"stroke '%s'\n",value); break; } if (LocaleCompare(keyword,"stroke-antialiasing") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-antialias %d\n", LocaleCompare(value,"true") == 0); break; } if (LocaleCompare(keyword,"stroke-dasharray") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-dasharray %s\n", value); break; } if (LocaleCompare(keyword,"stroke-dashoffset") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-dashoffset %s\n", value); break; } if (LocaleCompare(keyword,"stroke-linecap") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-linecap '%s'\n", value); break; } if (LocaleCompare(keyword,"stroke-linejoin") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-linejoin '%s'\n", value); break; } if (LocaleCompare(keyword,"stroke-miterlimit") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-miterlimit '%s'\n", value); break; } if (LocaleCompare(keyword,"stroke-opacity") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-opacity '%s'\n", value); break; } if (LocaleCompare(keyword,"stroke-width") == 0) { (void) FormatLocaleFile(svg_info->file,"stroke-width %g\n", GetUserSpaceCoordinateValue(svg_info,1,value)); break; } if (LocaleCompare(keyword,"style") == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," "); tokens=GetStyleTokens(context,value,&number_tokens); for (j=0; j < (number_tokens-1); j+=2) { keyword=(char *) tokens[j]; value=(char *) tokens[j+1]; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %s: %s",keyword,value); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"clip-path") == 0) { (void) FormatLocaleFile(svg_info->file, "clip-path '%s'\n",value); break; } if (LocaleCompare(keyword,"clip-rule") == 0) { (void) FormatLocaleFile(svg_info->file, "clip-rule '%s'\n",value); break; } if (LocaleCompare(keyword,"clipPathUnits") == 0) { (void) CloneString(&units,value); (void) FormatLocaleFile(svg_info->file, "clip-units '%s'\n",value); break; } if (LocaleCompare(keyword,"color") == 0) { (void) CloneString(&color,value); break; } break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { if (LocaleCompare(value,"currentColor") == 0) { (void) FormatLocaleFile(svg_info->file, "fill '%s'\n",color); break; } if (LocaleCompare(value,"#00000000") == 0) (void) FormatLocaleFile(svg_info->file, "fill '#000000'\n"); else (void) FormatLocaleFile(svg_info->file,"fill '%s'\n", value); break; } if (LocaleCompare(keyword,"fillcolor") == 0) { (void) FormatLocaleFile(svg_info->file,"fill '%s'\n", value); break; } if (LocaleCompare(keyword,"fill-rule") == 0) { (void) FormatLocaleFile(svg_info->file, "fill-rule '%s'\n",value); break; } if (LocaleCompare(keyword,"fill-opacity") == 0) { (void) FormatLocaleFile(svg_info->file, "fill-opacity '%s'\n",value); break; } if (LocaleCompare(keyword,"font-family") == 0) { (void) FormatLocaleFile(svg_info->file, "font-family '%s'\n",value); break; } if (LocaleCompare(keyword,"font-stretch") == 0) { (void) FormatLocaleFile(svg_info->file, "font-stretch '%s'\n",value); break; } if (LocaleCompare(keyword,"font-style") == 0) { (void) FormatLocaleFile(svg_info->file, "font-style '%s'\n",value); break; } if (LocaleCompare(keyword,"font-size") == 0) { svg_info->pointsize=GetUserSpaceCoordinateValue( svg_info,0,value); (void) FormatLocaleFile(svg_info->file,"font-size %g\n", svg_info->pointsize); break; } if (LocaleCompare(keyword,"font-weight") == 0) { (void) FormatLocaleFile(svg_info->file, "font-weight '%s'\n",value); break; } break; } case 'O': case 'o': { if (LocaleCompare(keyword,"offset") == 0) { (void) FormatLocaleFile(svg_info->file,"offset %g\n", GetUserSpaceCoordinateValue(svg_info,1,value)); break; } if (LocaleCompare(keyword,"opacity") == 0) { (void) FormatLocaleFile(svg_info->file, "opacity '%s'\n",value); break; } break; } case 'S': case 's': { if (LocaleCompare(keyword,"stop-color") == 0) { (void) CloneString(&svg_info->stop_color,value); break; } if (LocaleCompare(keyword,"stroke") == 0) { if (LocaleCompare(value,"currentColor") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke '%s'\n",color); break; } if (LocaleCompare(value,"#00000000") == 0) (void) FormatLocaleFile(svg_info->file, "fill '#000000'\n"); else (void) FormatLocaleFile(svg_info->file, "stroke '%s'\n",value); break; } if (LocaleCompare(keyword,"stroke-antialiasing") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-antialias %d\n", LocaleCompare(value,"true") == 0); break; } if (LocaleCompare(keyword,"stroke-dasharray") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-dasharray %s\n",value); break; } if (LocaleCompare(keyword,"stroke-dashoffset") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-dashoffset %s\n", value); break; } if (LocaleCompare(keyword,"stroke-linecap") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-linecap '%s'\n",value); break; } if (LocaleCompare(keyword,"stroke-linejoin") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-linejoin '%s'\n", value); break; } if (LocaleCompare(keyword,"stroke-miterlimit") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-miterlimit '%s'\n", value); break; } if (LocaleCompare(keyword,"stroke-opacity") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-opacity '%s'\n",value); break; } if (LocaleCompare(keyword,"stroke-width") == 0) { (void) FormatLocaleFile(svg_info->file, "stroke-width %g\n", GetUserSpaceCoordinateValue(svg_info,1,value)); break; } break; } case 't': case 'T': { if (LocaleCompare(keyword,"text-align") == 0) { (void) FormatLocaleFile(svg_info->file, "text-align '%s'\n",value); break; } if (LocaleCompare(keyword,"text-anchor") == 0) { (void) FormatLocaleFile(svg_info->file, "text-anchor '%s'\n",value); break; } if (LocaleCompare(keyword,"text-decoration") == 0) { if (LocaleCompare(value,"underline") == 0) (void) FormatLocaleFile(svg_info->file, "decorate underline\n"); if (LocaleCompare(value,"line-through") == 0) (void) FormatLocaleFile(svg_info->file, "decorate line-through\n"); if (LocaleCompare(value,"overline") == 0) (void) FormatLocaleFile(svg_info->file, "decorate overline\n"); break; } if (LocaleCompare(keyword,"text-antialiasing") == 0) { (void) FormatLocaleFile(svg_info->file, "text-antialias %d\n", LocaleCompare(value,"true") == 0); break; } break; } default: break; } } for (j=0; tokens[j] != (char *) NULL; j++) tokens[j]=DestroyString(tokens[j]); tokens=(char **) RelinquishMagickMemory(tokens); break; } break; } case 'T': case 't': { if (LocaleCompare(keyword,"text-align") == 0) { (void) FormatLocaleFile(svg_info->file,"text-align '%s'\n", value); break; } if (LocaleCompare(keyword,"text-anchor") == 0) { (void) FormatLocaleFile(svg_info->file,"text-anchor '%s'\n", value); break; } if (LocaleCompare(keyword,"text-decoration") == 0) { if (LocaleCompare(value,"underline") == 0) (void) FormatLocaleFile(svg_info->file,"decorate underline\n"); if (LocaleCompare(value,"line-through") == 0) (void) FormatLocaleFile(svg_info->file, "decorate line-through\n"); if (LocaleCompare(value,"overline") == 0) (void) FormatLocaleFile(svg_info->file,"decorate overline\n"); break; } if (LocaleCompare(keyword,"text-antialiasing") == 0) { (void) FormatLocaleFile(svg_info->file,"text-antialias %d\n", LocaleCompare(value,"true") == 0); break; } if (LocaleCompare(keyword,"transform") == 0) { AffineMatrix affine, current, transform; GetAffineMatrix(&transform); (void) LogMagickEvent(CoderEvent,GetMagickModule()," "); tokens=GetTransformTokens(context,value,&number_tokens); for (j=0; j < (number_tokens-1); j+=2) { keyword=(char *) tokens[j]; value=(char *) tokens[j+1]; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %s: %s",keyword,value); current=transform; GetAffineMatrix(&affine); switch (*keyword) { case 'M': case 'm': { if (LocaleCompare(keyword,"matrix") == 0) { p=(const char *) value; GetMagickToken(p,&p,token); affine.sx=StringToDouble(value,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.rx=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.ry=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.sy=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.tx=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); affine.ty=StringToDouble(token,(char **) NULL); break; } break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { double angle, x, y; p=(const char *) value; GetMagickToken(p,&p,token); angle=StringToDouble(value,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); affine.tx=x; affine.ty=y; svg_info->center.x=x; svg_info->center.y=y; break; } break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { for (p=(const char *) value; *p != '\0'; p++) if ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) break; affine.sx=GetUserSpaceCoordinateValue(svg_info,1,value); affine.sy=affine.sx; if (*p != '\0') affine.sy=GetUserSpaceCoordinateValue(svg_info,-1, p+1); svg_info->scale[svg_info->n]=ExpandAffine(&affine); break; } if (LocaleCompare(keyword,"skewX") == 0) { affine.sx=svg_info->affine.sx; affine.ry=tan(DegreesToRadians(fmod( GetUserSpaceCoordinateValue(svg_info,1,value), 360.0))); affine.sy=svg_info->affine.sy; break; } if (LocaleCompare(keyword,"skewY") == 0) { affine.sx=svg_info->affine.sx; affine.rx=tan(DegreesToRadians(fmod( GetUserSpaceCoordinateValue(svg_info,-1,value), 360.0))); affine.sy=svg_info->affine.sy; break; } break; } case 'T': case 't': { if (LocaleCompare(keyword,"translate") == 0) { for (p=(const char *) value; *p != '\0'; p++) if ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) break; affine.tx=GetUserSpaceCoordinateValue(svg_info,1,value); affine.ty=affine.tx; if (*p != '\0') affine.ty=GetUserSpaceCoordinateValue(svg_info,-1, p+1); break; } break; } default: break; } transform.sx=affine.sx*current.sx+affine.ry*current.rx; transform.rx=affine.rx*current.sx+affine.sy*current.rx; transform.ry=affine.sx*current.ry+affine.ry*current.sy; transform.sy=affine.rx*current.ry+affine.sy*current.sy; transform.tx=affine.tx*current.sx+affine.ty*current.ry+ current.tx; transform.ty=affine.tx*current.rx+affine.ty*current.sy+ current.ty; } (void) FormatLocaleFile(svg_info->file, "affine %g %g %g %g %g %g\n",transform.sx,transform.rx, transform.ry,transform.sy,transform.tx,transform.ty); for (j=0; tokens[j] != (char *) NULL; j++) tokens[j]=DestroyString(tokens[j]); tokens=(char **) RelinquishMagickMemory(tokens); break; } break; } case 'V': case 'v': { if (LocaleCompare(keyword,"verts") == 0) { (void) CloneString(&svg_info->vertices,value); break; } if (LocaleCompare(keyword,"viewBox") == 0) { p=(const char *) value; GetMagickToken(p,&p,token); svg_info->view_box.x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); svg_info->view_box.y=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); svg_info->view_box.width=StringToDouble(token, (char **) NULL); if (svg_info->bounds.width == 0) svg_info->bounds.width=svg_info->view_box.width; GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); svg_info->view_box.height=StringToDouble(token, (char **) NULL); if (svg_info->bounds.height == 0) svg_info->bounds.height=svg_info->view_box.height; break; } break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { svg_info->bounds.width= GetUserSpaceCoordinateValue(svg_info,1,value); break; } break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { svg_info->bounds.x=GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"xlink:href") == 0) { (void) CloneString(&svg_info->url,value); break; } if (LocaleCompare(keyword,"x1") == 0) { svg_info->segment.x1= GetUserSpaceCoordinateValue(svg_info,1,value); break; } if (LocaleCompare(keyword,"x2") == 0) { svg_info->segment.x2= GetUserSpaceCoordinateValue(svg_info,1,value); break; } break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { svg_info->bounds.y=GetUserSpaceCoordinateValue(svg_info,-1,value); break; } if (LocaleCompare(keyword,"y1") == 0) { svg_info->segment.y1= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } if (LocaleCompare(keyword,"y2") == 0) { svg_info->segment.y2= GetUserSpaceCoordinateValue(svg_info,-1,value); break; } break; } default: break; } } if (LocaleCompare((const char *) name,"svg") == 0) { if (svg_info->document->encoding != (const xmlChar *) NULL) (void) FormatLocaleFile(svg_info->file,"encoding \"%s\"\n", (const char *) svg_info->document->encoding); if (attributes != (const xmlChar **) NULL) { double sx, sy, tx, ty; if ((svg_info->view_box.width == 0.0) || (svg_info->view_box.height == 0.0)) svg_info->view_box=svg_info->bounds; svg_info->width=(size_t) floor(svg_info->bounds.width+0.5); svg_info->height=(size_t) floor(svg_info->bounds.height+0.5); (void) FormatLocaleFile(svg_info->file,"viewbox 0 0 %.20g %.20g\n", (double) svg_info->width,(double) svg_info->height); sx=(double) svg_info->width/svg_info->view_box.width; sy=(double) svg_info->height/svg_info->view_box.height; tx=svg_info->view_box.x != 0.0 ? (double) -sx*svg_info->view_box.x : 0.0; ty=svg_info->view_box.y != 0.0 ? (double) -sy*svg_info->view_box.y : 0.0; (void) FormatLocaleFile(svg_info->file,"affine %g 0 0 %g %g %g\n", sx,sy,tx,ty); } } (void) LogMagickEvent(CoderEvent,GetMagickModule()," )"); units=DestroyString(units); if (color != (char *) NULL) color=DestroyString(color); } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: validate_T(void) /* Validate the above table - this just builds the above values */ { unsigned int i; for (i=0; i<TTABLE_SIZE; ++i) { if (transform_info[i].when & TRANSFORM_R) read_transforms |= transform_info[i].transform; if (transform_info[i].when & TRANSFORM_W) write_transforms |= transform_info[i].transform; } /* Reversible transforms are those which are supported on both read and * write. */ rw_transforms = read_transforms & write_transforms; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: _rpc_update_time(slurm_msg_t *msg) { int rc = SLURM_SUCCESS; uid_t req_uid = g_slurm_auth_get_uid(msg->auth_cred, conf->auth_info); if ((req_uid != conf->slurm_user_id) && (req_uid != 0)) { rc = ESLURM_USER_ID_MISSING; error("Security violation, uid %d can't update time limit", req_uid); goto done; } /* if (shm_update_job_timelimit(req->job_id, req->expiration_time) < 0) { */ /* error("updating lifetime for job %u: %m", req->job_id); */ /* rc = ESLURM_INVALID_JOB_ID; */ /* } else */ /* debug("reset job %u lifetime", req->job_id); */ done: slurm_send_rc_msg(msg, rc); } Commit Message: Fix security issue in _prolog_error(). Fix security issue caused by insecure file path handling triggered by the failure of a Prolog script. To exploit this a user needs to anticipate or cause the Prolog to fail for their job. (This commit is slightly different from the fix to the 15.08 branch.) CVE-2016-10030. CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) if (strstr(origin, origins[x])) {origin_ok = true; break;} if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; ucc->ws_mask = 0; return UNCURL_OK; } Commit Message: origin matching must come at str end CWE ID: CWE-352 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415 Target: 1 Example 2: Code: static int cp2112_i2c_write_read_req(void *buf, u8 slave_address, u8 *addr, int addr_length, int read_length) { struct cp2112_write_read_req_report *report = buf; if (read_length < 1 || read_length > 512 || addr_length > sizeof(report->target_address)) return -EINVAL; report->report = CP2112_DATA_WRITE_READ_REQUEST; report->slave_address = slave_address << 1; report->length = cpu_to_be16(read_length); report->target_address_length = addr_length; memcpy(report->target_address, addr, addr_length); return addr_length + 5; } Commit Message: HID: cp2112: fix gpio-callback error handling In case of a zero-length report, the gpio direction_input callback would currently return success instead of an errno. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <[email protected]> # 4.9 Signed-off-by: Johan Hovold <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-388 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void mbedtls_strerror( int ret, char *buf, size_t buflen ) { ((void) ret); if( buflen > 0 ) buf[0] = '\0'; } Commit Message: Only return VERIFY_FAILED from a single point Everything else is a fatal error. Also improve documentation about that for the vrfy callback. CWE ID: CWE-287 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: ALWAYS_INLINE bool GLES2DecoderImpl::CheckMultiDrawArraysVertices( const char* function_name, bool instanced, const GLint* firsts, const GLsizei* counts, const GLsizei* primcounts, GLsizei drawcount, GLuint* total_max_vertex_accessed, GLsizei* total_max_primcount) { DCHECK_GE(drawcount, 0); for (GLsizei draw_id = 0; draw_id < drawcount; ++draw_id) { GLint first = firsts[draw_id]; GLsizei count = counts[draw_id]; GLsizei primcount = instanced ? primcounts[draw_id] : 1; if (first < 0) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "first < 0"); return false; } if (count < 0) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "count < 0"); return false; } if (primcount < 0) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "primcount < 0"); return false; } if (count == 0 || primcount == 0) { LOCAL_RENDER_WARNING("Render count or primcount is 0."); continue; } base::CheckedNumeric<GLuint> checked_max_vertex = first; checked_max_vertex += count - 1; GLuint max_vertex_accessed = 0; if (!checked_max_vertex.AssignIfValid(&max_vertex_accessed)) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "first + count overflow"); return false; } if (!IsDrawValid(function_name, max_vertex_accessed, instanced, primcount)) { return false; } *total_max_vertex_accessed = std::max(*total_max_vertex_accessed, max_vertex_accessed); *total_max_primcount = std::max(*total_max_primcount, primcount); } return true; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "SetImeConfig: IBus connection is not alive"; return false; } bool is_preload_engines = false; std::vector<std::string> string_list; if ((value.type == ImeConfigValue::kValueTypeStringList) && (section == kGeneralSectionName) && (config_name == kPreloadEnginesConfigName)) { FilterInputMethods(value.string_list_value, &string_list); is_preload_engines = true; } else { string_list = value.string_list_value; } GVariant* variant = NULL; switch (value.type) { case ImeConfigValue::kValueTypeString: variant = g_variant_new_string(value.string_value.c_str()); break; case ImeConfigValue::kValueTypeInt: variant = g_variant_new_int32(value.int_value); break; case ImeConfigValue::kValueTypeBool: variant = g_variant_new_boolean(value.bool_value); break; case ImeConfigValue::kValueTypeStringList: GVariantBuilder variant_builder; g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as")); const size_t size = string_list.size(); // don't use string_list_value. for (size_t i = 0; i < size; ++i) { g_variant_builder_add(&variant_builder, "s", string_list[i].c_str()); } variant = g_variant_builder_end(&variant_builder); break; } if (!variant) { LOG(ERROR) << "SetImeConfig: variant is NULL"; return false; } DCHECK(g_variant_is_floating(variant)); ibus_config_set_value_async(ibus_config_, section.c_str(), config_name.c_str(), variant, -1, // use the default ibus timeout NULL, // cancellable SetImeConfigCallback, g_object_ref(ibus_config_)); if (is_preload_engines) { DLOG(INFO) << "SetImeConfig: " << section << "/" << config_name << ": " << value.ToString(); } return true; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: auth_select_file(struct sc_card *card, const struct sc_path *in_path, struct sc_file **file_out) { struct sc_path path; struct sc_file *tmp_file = NULL; size_t offs, ii; int rv; LOG_FUNC_CALLED(card->ctx); assert(card != NULL && in_path != NULL); memcpy(&path, in_path, sizeof(struct sc_path)); sc_log(card->ctx, "in_path; type=%d, path=%s, out %p", in_path->type, sc_print_path(in_path), file_out); sc_log(card->ctx, "current path; type=%d, path=%s", auth_current_df->path.type, sc_print_path(&auth_current_df->path)); if (auth_current_ef) sc_log(card->ctx, "current file; type=%d, path=%s", auth_current_ef->path.type, sc_print_path(&auth_current_ef->path)); if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) { sc_file_free(auth_current_ef); auth_current_ef = NULL; rv = iso_ops->select_file(card, &path, &tmp_file); LOG_TEST_RET(card->ctx, rv, "select file failed"); if (!tmp_file) return SC_ERROR_OBJECT_NOT_FOUND; if (path.type == SC_PATH_TYPE_PARENT) { memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path)); if (tmp_file->path.len > 2) tmp_file->path.len -= 2; sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { if (tmp_file->type == SC_FILE_TYPE_DF) { sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path); sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { sc_file_free(auth_current_ef); sc_file_dup(&auth_current_ef, tmp_file); sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path); } } if (file_out) sc_file_dup(file_out, tmp_file); sc_file_free(tmp_file); } else if (path.type == SC_PATH_TYPE_DF_NAME) { rv = iso_ops->select_file(card, &path, NULL); if (rv) { sc_file_free(auth_current_ef); auth_current_ef = NULL; } LOG_TEST_RET(card->ctx, rv, "select file failed"); } else { for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2) if (path.value[offs] != auth_current_df->path.value[offs] || path.value[offs + 1] != auth_current_df->path.value[offs + 1]) break; sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs); if (offs && offs < auth_current_df->path.len) { size_t deep = auth_current_df->path.len - offs; sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u", deep); for (ii=0; ii<deep; ii+=2) { struct sc_path tmp_path; memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_PARENT; rv = auth_select_file (card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } if (path.len - offs > 0) { struct sc_path tmp_path; memset(&tmp_path, 0, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_FILE_ID; tmp_path.len = 2; for (ii=0; ii < path.len - offs; ii+=2) { memcpy(tmp_path.value, path.value + offs + ii, 2); rv = auth_select_file(card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } else if (path.len - offs == 0 && file_out) { if (sc_compare_path(&path, &auth_current_df->path)) sc_file_dup(file_out, auth_current_df); else if (auth_current_ef) sc_file_dup(file_out, auth_current_ef); else LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF"); } } LOG_FUNC_RETURN(card->ctx, 0); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 1 Example 2: Code: void HTMLSelectElement::restoreFormControlState(const FormControlState& state) { recalcListItems(); const Vector<HTMLElement*>& items = listItems(); size_t itemsSize = items.size(); if (!itemsSize) return; for (size_t i = 0; i < itemsSize; ++i) { if (!items[i]->hasLocalName(optionTag)) continue; toHTMLOptionElement(items[i])->setSelectedState(false); } if (!multiple()) { size_t foundIndex = searchOptionsForValue(state[0], 0, itemsSize); if (foundIndex != kNotFound) toHTMLOptionElement(items[foundIndex])->setSelectedState(true); } else { size_t startIndex = 0; for (size_t i = 0; i < state.valueSize(); ++i) { const String& value = state[i]; size_t foundIndex = searchOptionsForValue(value, startIndex, itemsSize); if (foundIndex == kNotFound) foundIndex = searchOptionsForValue(value, 0, startIndex); if (foundIndex == kNotFound) continue; toHTMLOptionElement(items[foundIndex])->setSelectedState(true); startIndex = foundIndex + 1; } } setOptionsChangedOnRenderer(); setNeedsValidityCheck(); } Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment. This virtual function should return true if the form control can hanlde 'autofocucs' attribute if it is specified. Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent because interactiveness is required for autofocus capability. BUG=none TEST=none; no behavior changes. Review URL: https://codereview.chromium.org/143343003 git-svn-id: svn://svn.chromium.org/blink/trunk@165432 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GF_Err gen_sample_entry_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SampleEntryBox *ptr = (GF_SampleEntryBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_data(bs, ptr->reserved, 6); gf_bs_write_u16(bs, ptr->dataReferenceIndex); return gf_isom_box_array_write(s, ptr->protections, bs); } Commit Message: prevent dref memleak on invalid input (#1183) CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool GesturePoint::IsSecondClickInsideManhattanSquare( const TouchEvent& event) const { int manhattanDistance = abs(event.x() - last_tap_position_.x()) + abs(event.y() - last_tap_position_.y()); return manhattanDistance < kMaximumTouchMoveInPixelsForClick; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: const AtomicString& ServiceWorkerContainer::interfaceName() const { return EventTargetNames::ServiceWorkerContainer; } Commit Message: Check CSP before registering ServiceWorkers Service Worker registrations should be subject to the same CSP checks as other workers. The spec doesn't say this explicitly (https://www.w3.org/TR/CSP2/#directive-child-src-workers says "Worker or SharedWorker constructors"), but it seems to be in the spirit of things, and it matches Firefox's behavior. BUG=579801 Review URL: https://codereview.chromium.org/1861253004 Cr-Commit-Position: refs/heads/master@{#385775} CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) { print_preview_context_.OnPrintPreview(); UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent", PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX); if (!print_preview_context_.source_frame()) { DidFinishPrinting(FAIL_PREVIEW); return; } if (!UpdatePrintSettings(print_preview_context_.source_frame(), print_preview_context_.source_node(), settings)) { if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) { Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings( routing_id(), print_pages_params_ ? print_pages_params_->params.document_cookie : 0)); notify_browser_of_print_failure_ = false; // Already sent. } DidFinishPrinting(FAIL_PREVIEW); return; } if (print_pages_params_->params.is_first_request && !print_preview_context_.IsModifiable()) { PrintHostMsg_SetOptionsFromDocument_Params options; if (SetOptionsFromPdfDocument(&options)) Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), options)); } is_print_ready_metafile_sent_ = false; print_pages_params_->params.supports_alpha_blend = true; bool generate_draft_pages = false; if (!settings.GetBoolean(kSettingGenerateDraftData, &generate_draft_pages)) { NOTREACHED(); } print_preview_context_.set_generate_draft_pages(generate_draft_pages); PrepareFrameForPreviewDocument(); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const { if (interstitial_page_) return interstitial_page_->GetView(); if (render_frame_host_) return render_frame_host_->GetView(); return nullptr; } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20 Target: 1 Example 2: Code: static int usb_req_set_sel(struct usb_device *udev, enum usb3_link_state state) { struct usb_set_sel_req *sel_values; unsigned long long u1_sel; unsigned long long u1_pel; unsigned long long u2_sel; unsigned long long u2_pel; int ret; if (udev->state != USB_STATE_CONFIGURED) return 0; /* Convert SEL and PEL stored in ns to us */ u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000); u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000); u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000); u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000); /* * Make sure that the calculated SEL and PEL values for the link * state we're enabling aren't bigger than the max SEL/PEL * value that will fit in the SET SEL control transfer. * Otherwise the device would get an incorrect idea of the exit * latency for the link state, and could start a device-initiated * U1/U2 when the exit latencies are too high. */ if ((state == USB3_LPM_U1 && (u1_sel > USB3_LPM_MAX_U1_SEL_PEL || u1_pel > USB3_LPM_MAX_U1_SEL_PEL)) || (state == USB3_LPM_U2 && (u2_sel > USB3_LPM_MAX_U2_SEL_PEL || u2_pel > USB3_LPM_MAX_U2_SEL_PEL))) { dev_dbg(&udev->dev, "Device-initiated %s disabled due to long SEL %llu us or PEL %llu us\n", usb3_lpm_names[state], u1_sel, u1_pel); return -EINVAL; } /* * If we're enabling device-initiated LPM for one link state, * but the other link state has a too high SEL or PEL value, * just set those values to the max in the Set SEL request. */ if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL) u1_sel = USB3_LPM_MAX_U1_SEL_PEL; if (u1_pel > USB3_LPM_MAX_U1_SEL_PEL) u1_pel = USB3_LPM_MAX_U1_SEL_PEL; if (u2_sel > USB3_LPM_MAX_U2_SEL_PEL) u2_sel = USB3_LPM_MAX_U2_SEL_PEL; if (u2_pel > USB3_LPM_MAX_U2_SEL_PEL) u2_pel = USB3_LPM_MAX_U2_SEL_PEL; /* * usb_enable_lpm() can be called as part of a failed device reset, * which may be initiated by an error path of a mass storage driver. * Therefore, use GFP_NOIO. */ sel_values = kmalloc(sizeof *(sel_values), GFP_NOIO); if (!sel_values) return -ENOMEM; sel_values->u1_sel = u1_sel; sel_values->u1_pel = u1_pel; sel_values->u2_sel = cpu_to_le16(u2_sel); sel_values->u2_pel = cpu_to_le16(u2_pel); ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_SEL, USB_RECIP_DEVICE, 0, 0, sel_values, sizeof *(sel_values), USB_CTRL_SET_TIMEOUT); kfree(sel_values); return ret; } Commit Message: USB: fix invalid memory access in hub_activate() Commit 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") changed the hub_activate() routine to make part of it run in a workqueue. However, the commit failed to take a reference to the usb_hub structure or to lock the hub interface while doing so. As a result, if a hub is plugged in and quickly unplugged before the work routine can run, the routine will try to access memory that has been deallocated. Or, if the hub is unplugged while the routine is running, the memory may be deallocated while it is in active use. This patch fixes the problem by taking a reference to the usb_hub at the start of hub_activate() and releasing it at the end (when the work is finished), and by locking the hub interface while the work routine is running. It also adds a check at the start of the routine to see if the hub has already been disconnected, in which nothing should be done. Signed-off-by: Alan Stern <[email protected]> Reported-by: Alexandru Cornea <[email protected]> Tested-by: Alexandru Cornea <[email protected]> Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OMX_ERRORTYPE omx_video::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { OMX_ERRORTYPE ret1 = OMX_ErrorNone; unsigned int nBufferIndex ; DEBUG_PRINT_LOW("ETB: buffer = %p, buffer->pBuffer[%p]", buffer, buffer->pBuffer); if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: Empty this buffer in Invalid State"); return OMX_ErrorInvalidState; } if (buffer == NULL || (buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) { DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> buffer is null or buffer size is invalid"); return OMX_ErrorBadParameter; } if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) { DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> OMX Version Invalid"); return OMX_ErrorVersionMismatch; } if (buffer->nInputPortIndex != (OMX_U32)PORT_INDEX_IN) { DEBUG_PRINT_ERROR("ERROR: Bad port index to call empty_this_buffer"); return OMX_ErrorBadPortIndex; } if (!m_sInPortDef.bEnabled) { DEBUG_PRINT_ERROR("ERROR: Cannot call empty_this_buffer while I/P port is disabled"); return OMX_ErrorIncorrectStateOperation; } nBufferIndex = buffer - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr); if (nBufferIndex > m_sInPortDef.nBufferCountActual ) { DEBUG_PRINT_ERROR("ERROR: ETB: Invalid buffer index[%d]", nBufferIndex); return OMX_ErrorBadParameter; } m_etb_count++; DEBUG_PRINT_LOW("DBG: i/p nTimestamp = %u", (unsigned)buffer->nTimeStamp); post_event ((unsigned long)hComp,(unsigned long)buffer,m_input_msg_id); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27903498 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVenc problem #3) CRs-Fixed: 1010088 Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: jas_image_t *jas_image_create0() { jas_image_t *image; if (!(image = jas_malloc(sizeof(jas_image_t)))) { return 0; } image->tlx_ = 0; image->tly_ = 0; image->brx_ = 0; image->bry_ = 0; image->clrspc_ = JAS_CLRSPC_UNKNOWN; image->numcmpts_ = 0; image->maxcmpts_ = 0; image->cmpts_ = 0; image->inmem_ = true; //// image->inmem_ = true; image->cmprof_ = 0; return image; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 1 Example 2: Code: void LocalDOMWindow::setStatus(const String& string) { status_ = string; } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void btif_hl_display_calling_process_name(void) { char name[16]; prctl(BTIF_IF_GET_NAME, name, 0, 0, 0); BTIF_TRACE_DEBUG("Process name (%s)", name); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static size_t StringSize(const uint8_t *start, uint8_t encoding) { //// return includes terminator; if unterminated, returns > limit if (encoding == 0x00 || encoding == 0x03) { return strlen((const char *)start) + 1; } size_t n = 0; while (start[n] != '\0' || start[n + 1] != '\0') { n += 2; } return n + 2; } Commit Message: DO NOT MERGE: defensive parsing of mp3 album art information several points in stagefrights mp3 album art code used strlen() to parse user-supplied strings that may be unterminated, resulting in reading beyond the end of a buffer. This changes the code to use strnlen() for 8-bit encodings and strengthens the parsing of 16-bit encodings similarly. It also reworks how we watch for the end-of-buffer to avoid all over-reads. Bug: 32377688 Test: crafted mp3's w/ good/bad cover art. See what showed in play music Change-Id: Ia9f526d71b21ef6a61acacf616b573753cd21df6 (cherry picked from commit fa0806b594e98f1aed3ebcfc6a801b4c0056f9eb) CWE ID: CWE-200 Target: 1 Example 2: Code: R_API bool r_config_save_char(RConfigHold *h, ...) { va_list ap; char *key; if (!h->list_char) { h->list_char = r_list_newf ((RListFree) free); if (!h->list_char) { return false; } } va_start (ap, h); while ((key = va_arg (ap, char *))) { RConfigHoldChar *hc = R_NEW0 (RConfigHoldChar); if (!hc) { continue; } hc->key = key; hc->value = r_config_get (h->cfg, key); r_list_append (h->list_char, hc); } va_end (ap); return true; } Commit Message: Fix #7698 - UAF in r_config_set when loading a dex CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AwContents::ScrollContainerViewTo(gfx::Vector2d new_value) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return; Java_AwContents_scrollContainerViewTo( env, obj.obj(), new_value.x(), new_value.y()); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: compile_length_bag_node(BagNode* node, regex_t* reg) { int len; int tlen; if (node->type == BAG_OPTION) return compile_length_option_node(node, reg); if (NODE_BAG_BODY(node)) { tlen = compile_length_tree(NODE_BAG_BODY(node), reg); if (tlen < 0) return tlen; } else tlen = 0; switch (node->type) { case BAG_MEMORY: #ifdef USE_CALL if (node->m.regnum == 0 && NODE_IS_CALLED(node)) { len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; return len; } if (NODE_IS_CALLED(node)) { len = SIZE_OP_MEMORY_START_PUSH + tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH); else len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END); } else if (NODE_IS_RECURSION(node)) { len = SIZE_OP_MEMORY_START_PUSH; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC); } else #endif { if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum)) len = SIZE_OP_MEMORY_START_PUSH; else len = SIZE_OP_MEMORY_START; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END); } break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { int v; QuantNode* qn; qn = QUANT_(NODE_BAG_BODY(node)); tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (tlen < 0) return tlen; v = onig_positive_int_multiply(qn->lower, tlen); if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP; } else { len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END; } break; case BAG_IF_ELSE: { Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; len = compile_length_tree(cond, reg); if (len < 0) return len; len += SIZE_OP_PUSH; len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Then)) { tlen = compile_length_tree(Then, reg); if (tlen < 0) return tlen; len += tlen; } if (IS_NOT_NULL(Else)) { len += SIZE_OP_JUMP; tlen = compile_length_tree(Else, reg); if (tlen < 0) return tlen; len += tlen; } } break; case BAG_OPTION: /* never come here, but set for escape warning */ len = 0; break; } return len; } Commit Message: Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode. CWE ID: CWE-476 Target: 1 Example 2: Code: static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } Commit Message: Added check for out of bounds read (https://github.com/ImageMagick/ImageMagick/issues/108). CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SetVideoType(MediaStreamType video_type) { DCHECK(IsVideoMediaType(video_type) || video_type == MEDIA_NO_SERVICE); video_type_ = video_type; } Commit Message: Fix MediaObserver notifications in MediaStreamManager. This CL fixes the stream type used to notify MediaObserver about cancelled MediaStream requests. Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate that all stream types should be cancelled. However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this way and the request to update the UI is ignored. This CL sends a separate notification for each stream type so that the UI actually gets updated for all stream types in use. Bug: 816033 Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405 Reviewed-on: https://chromium-review.googlesource.com/939630 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#540122} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ExtensionTtsController::CheckSpeechStatus() { if (!current_utterance_) return; if (!current_utterance_->extension_id().empty()) return; if (GetPlatformImpl()->IsSpeaking() == false) { FinishCurrentUtterance(); SpeakNextUtterance(); } if (current_utterance_ && current_utterance_->extension_id().empty()) { MessageLoop::current()->PostDelayedTask( FROM_HERE, method_factory_.NewRunnableMethod( &ExtensionTtsController::CheckSpeechStatus), kSpeechCheckDelayIntervalMs); } } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: void WebPluginProxy::AcceleratedFrameBuffersDidSwap( gfx::PluginWindowHandle window, uint64 surface_handle) { Send(new PluginHostMsg_AcceleratedSurfaceBuffersSwapped( route_id_, window, surface_handle)); } 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: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void nlmclnt_unlock_callback(struct rpc_task *task, void *data) { struct nlm_rqst *req = data; u32 status = ntohl(req->a_res.status); if (RPC_ASSASSINATED(task)) goto die; if (task->tk_status < 0) { dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status); goto retry_rebind; } if (status == NLM_LCK_DENIED_GRACE_PERIOD) { rpc_delay(task, NLMCLNT_GRACE_WAIT); goto retry_unlock; } if (status != NLM_LCK_GRANTED) printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status); die: return; retry_rebind: nlm_rebind_host(req->a_host); retry_unlock: rpc_restart_call(task); } Commit Message: NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> Cc: [email protected] CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Cluster::Cluster() : m_pSegment(NULL), m_element_start(0), m_index(0), m_pos(0), m_element_size(0), m_timecode(0), m_entries(NULL), m_entries_size(0), m_entries_count(0) //means "no entries" { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: void rds_rdma_drop_keys(struct rds_sock *rs) { struct rds_mr *mr; struct rb_node *node; unsigned long flags; /* Release any MRs associated with this socket */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); while ((node = rb_first(&rs->rs_rdma_keys))) { mr = rb_entry(node, struct rds_mr, r_rb_node); if (mr->r_trans == rs->rs_transport) mr->r_invalidate = 0; rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); rds_destroy_mr(mr); rds_mr_put(mr); spin_lock_irqsave(&rs->rs_rdma_lock, flags); } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (rs->rs_transport && rs->rs_transport->flush_mrs) rs->rs_transport->flush_mrs(); } Commit Message: rds: Fix NULL pointer dereference in __rds_rdma_map This is a fix for syzkaller719569, where memory registration was attempted without any underlying transport being loaded. Analysis of the case reveals that it is the setsockopt() RDS_GET_MR (2) and RDS_GET_MR_FOR_DEST (7) that are vulnerable. Here is an example stack trace when the bug is hit: BUG: unable to handle kernel NULL pointer dereference at 00000000000000c0 IP: __rds_rdma_map+0x36/0x440 [rds] PGD 2f93d03067 P4D 2f93d03067 PUD 2f93d02067 PMD 0 Oops: 0000 [#1] SMP Modules linked in: bridge stp llc tun rpcsec_gss_krb5 nfsv4 dns_resolver nfs fscache rds binfmt_misc sb_edac intel_powerclamp coretemp kvm_intel kvm irqbypass crct10dif_pclmul c rc32_pclmul ghash_clmulni_intel pcbc aesni_intel crypto_simd glue_helper cryptd iTCO_wdt mei_me sg iTCO_vendor_support ipmi_si mei ipmi_devintf nfsd shpchp pcspkr i2c_i801 ioatd ma ipmi_msghandler wmi lpc_ich mfd_core auth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2 mgag200 i2c_algo_bit drm_kms_helper ixgbe syscopyarea ahci sysfillrect sysimgblt libahci mdio fb_sys_fops ttm ptp libata sd_mod mlx4_core drm crc32c_intel pps_core megaraid_sas i2c_core dca dm_mirror dm_region_hash dm_log dm_mod CPU: 48 PID: 45787 Comm: repro_set2 Not tainted 4.14.2-3.el7uek.x86_64 #2 Hardware name: Oracle Corporation ORACLE SERVER X5-2L/ASM,MOBO TRAY,2U, BIOS 31110000 03/03/2017 task: ffff882f9190db00 task.stack: ffffc9002b994000 RIP: 0010:__rds_rdma_map+0x36/0x440 [rds] RSP: 0018:ffffc9002b997df0 EFLAGS: 00010202 RAX: 0000000000000000 RBX: ffff882fa2182580 RCX: 0000000000000000 RDX: 0000000000000000 RSI: ffffc9002b997e40 RDI: ffff882fa2182580 RBP: ffffc9002b997e30 R08: 0000000000000000 R09: 0000000000000002 R10: ffff885fb29e3838 R11: 0000000000000000 R12: ffff882fa2182580 R13: ffff882fa2182580 R14: 0000000000000002 R15: 0000000020000ffc FS: 00007fbffa20b700(0000) GS:ffff882fbfb80000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00000000000000c0 CR3: 0000002f98a66006 CR4: 00000000001606e0 Call Trace: rds_get_mr+0x56/0x80 [rds] rds_setsockopt+0x172/0x340 [rds] ? __fget_light+0x25/0x60 ? __fdget+0x13/0x20 SyS_setsockopt+0x80/0xe0 do_syscall_64+0x67/0x1b0 entry_SYSCALL64_slow_path+0x25/0x25 RIP: 0033:0x7fbff9b117f9 RSP: 002b:00007fbffa20aed8 EFLAGS: 00000293 ORIG_RAX: 0000000000000036 RAX: ffffffffffffffda RBX: 00000000000c84a4 RCX: 00007fbff9b117f9 RDX: 0000000000000002 RSI: 0000400000000114 RDI: 000000000000109b RBP: 00007fbffa20af10 R08: 0000000000000020 R09: 00007fbff9dd7860 R10: 0000000020000ffc R11: 0000000000000293 R12: 0000000000000000 R13: 00007fbffa20b9c0 R14: 00007fbffa20b700 R15: 0000000000000021 Code: 41 56 41 55 49 89 fd 41 54 53 48 83 ec 18 8b 87 f0 02 00 00 48 89 55 d0 48 89 4d c8 85 c0 0f 84 2d 03 00 00 48 8b 87 00 03 00 00 <48> 83 b8 c0 00 00 00 00 0f 84 25 03 00 0 0 48 8b 06 48 8b 56 08 The fix is to check the existence of an underlying transport in __rds_rdma_map(). Signed-off-by: Håkon Bugge <[email protected]> Reported-by: syzbot <[email protected]> Acked-by: Santosh Shilimkar <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void region16_clear(REGION16* region) { assert(region); assert(region->data); if ((region->data->size > 0) && (region->data != &empty_region)) free(region->data); region->data = &empty_region; ZeroMemory(&region->extents, sizeof(region->extents)); } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_text_compress(png_structp png_ptr, png_charp text, png_size_t text_len, int compression, compression_state *comp) { int ret; comp->num_output_ptr = 0; comp->max_output_ptr = 0; comp->output_ptr = NULL; comp->input = NULL; comp->input_len = 0; /* We may just want to pass the text right through */ if (compression == PNG_TEXT_COMPRESSION_NONE) { comp->input = text; comp->input_len = text_len; return((int)text_len); } if (compression >= PNG_TEXT_COMPRESSION_LAST) { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char msg[50]; png_snprintf(msg, 50, "Unknown compression type %d", compression); png_warning(png_ptr, msg); #else png_warning(png_ptr, "Unknown compression type"); #endif } /* We can't write the chunk until we find out how much data we have, * which means we need to run the compressor first and save the * output. This shouldn't be a problem, as the vast majority of * comments should be reasonable, but we will set up an array of * malloc'd pointers to be sure. * * If we knew the application was well behaved, we could simplify this * greatly by assuming we can always malloc an output buffer large * enough to hold the compressed text ((1001 * text_len / 1000) + 12) * and malloc this directly. The only time this would be a bad idea is * if we can't malloc more than 64K and we have 64K of random input * data, or if the input string is incredibly large (although this * wouldn't cause a failure, just a slowdown due to swapping). */ /* Set up the compression buffers */ png_ptr->zstream.avail_in = (uInt)text_len; png_ptr->zstream.next_in = (Bytef *)text; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf; /* This is the same compression loop as in png_write_row() */ do { /* Compress the data */ ret = deflate(&png_ptr->zstream, Z_NO_FLUSH); if (ret != Z_OK) { /* Error */ if (png_ptr->zstream.msg != NULL) png_error(png_ptr, png_ptr->zstream.msg); else png_error(png_ptr, "zlib error"); } /* Check to see if we need more room */ if (!(png_ptr->zstream.avail_out)) { /* Make sure the output array has room */ if (comp->num_output_ptr >= comp->max_output_ptr) { int old_max; old_max = comp->max_output_ptr; comp->max_output_ptr = comp->num_output_ptr + 4; if (comp->output_ptr != NULL) { png_charpp old_ptr; old_ptr = comp->output_ptr; comp->output_ptr = (png_charpp)png_malloc(png_ptr, (png_uint_32) (comp->max_output_ptr * png_sizeof(png_charpp))); png_memcpy(comp->output_ptr, old_ptr, old_max * png_sizeof(png_charp)); png_free(png_ptr, old_ptr); } else comp->output_ptr = (png_charpp)png_malloc(png_ptr, (png_uint_32) (comp->max_output_ptr * png_sizeof(png_charp))); } /* Save the data */ comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf, png_ptr->zbuf_size); comp->num_output_ptr++; /* and reset the buffer */ png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_out = png_ptr->zbuf; } /* Continue until we don't have any more to compress */ } while (png_ptr->zstream.avail_in); /* Finish the compression */ do { /* Tell zlib we are finished */ ret = deflate(&png_ptr->zstream, Z_FINISH); if (ret == Z_OK) { /* Check to see if we need more room */ if (!(png_ptr->zstream.avail_out)) { /* Check to make sure our output array has room */ if (comp->num_output_ptr >= comp->max_output_ptr) { int old_max; old_max = comp->max_output_ptr; comp->max_output_ptr = comp->num_output_ptr + 4; if (comp->output_ptr != NULL) { png_charpp old_ptr; old_ptr = comp->output_ptr; /* This could be optimized to realloc() */ comp->output_ptr = (png_charpp)png_malloc(png_ptr, (png_uint_32)(comp->max_output_ptr * png_sizeof(png_charp))); png_memcpy(comp->output_ptr, old_ptr, old_max * png_sizeof(png_charp)); png_free(png_ptr, old_ptr); } else comp->output_ptr = (png_charpp)png_malloc(png_ptr, (png_uint_32)(comp->max_output_ptr * png_sizeof(png_charp))); } /* Save the data */ comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf, png_ptr->zbuf_size); comp->num_output_ptr++; /* and reset the buffer pointers */ png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_out = png_ptr->zbuf; } } else if (ret != Z_STREAM_END) { /* We got an error */ if (png_ptr->zstream.msg != NULL) png_error(png_ptr, png_ptr->zstream.msg); else png_error(png_ptr, "zlib error"); } } while (ret != Z_STREAM_END); /* Text length is number of buffers plus last buffer */ text_len = png_ptr->zbuf_size * comp->num_output_ptr; if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out; return((int)text_len); } 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 Target: 1 Example 2: Code: JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, TestMediaQueryListListener* impl) { return wrap<JSTestMediaQueryListListener>(exec, globalObject, impl); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xfs_icache_inode_is_allocated( struct xfs_mount *mp, struct xfs_trans *tp, xfs_ino_t ino, bool *inuse) { struct xfs_inode *ip; int error; error = xfs_iget(mp, tp, ino, XFS_IGET_INCORE, 0, &ip); if (error) return error; *inuse = !!(VFS_I(ip)->i_mode); IRELE(ip); return 0; } Commit Message: xfs: validate cached inodes are free when allocated A recent fuzzed filesystem image cached random dcache corruption when the reproducer was run. This often showed up as panics in lookup_slow() on a null inode->i_ops pointer when doing pathwalks. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000 .... Call Trace: lookup_slow+0x44/0x60 walk_component+0x3dd/0x9f0 link_path_walk+0x4a7/0x830 path_lookupat+0xc1/0x470 filename_lookup+0x129/0x270 user_path_at_empty+0x36/0x40 path_listxattr+0x98/0x110 SyS_listxattr+0x13/0x20 do_syscall_64+0xf5/0x280 entry_SYSCALL_64_after_hwframe+0x42/0xb7 but had many different failure modes including deadlocks trying to lock the inode that was just allocated or KASAN reports of use-after-free violations. The cause of the problem was a corrupt INOBT on a v4 fs where the root inode was marked as free in the inobt record. Hence when we allocated an inode, it chose the root inode to allocate, found it in the cache and re-initialised it. We recently fixed a similar inode allocation issue caused by inobt record corruption problem in xfs_iget_cache_miss() in commit ee457001ed6c ("xfs: catch inode allocation state mismatch corruption"). This change adds similar checks to the cache-hit path to catch it, and turns the reproducer into a corruption shutdown situation. Reported-by: Wen Xu <[email protected]> Signed-Off-By: Dave Chinner <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Carlos Maiolino <[email protected]> Reviewed-by: Darrick J. Wong <[email protected]> [darrick: fix typos in comment] Signed-off-by: Darrick J. Wong <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem, struct param_mem *mem) { uint64_t shm_ref = READ_ONCE(rmem->shm_ref); mem->mobj = mobj_reg_shm_get_by_cookie(shm_ref); if (!mem->mobj) return TEE_ERROR_BAD_PARAMETERS; mem->offs = READ_ONCE(rmem->offs); mem->size = READ_ONCE(rmem->size); return TEE_SUCCESS; } Commit Message: core: ensure that supplied range matches MOBJ In set_rmem_param() if the MOBJ is found by the cookie it's verified to represent non-secure shared memory. Prior to this patch the supplied sub-range to be used of the MOBJ was not checked here and relied on later checks further down the chain. Those checks seems to be enough for user TAs, but not for pseudo TAs where the size isn't checked. This patch adds a check for offset and size to see that they remain inside the memory covered by the MOBJ. Fixes: OP-TEE-2018-0004: "Unchecked parameters are passed through from REE". Signed-off-by: Jens Wiklander <[email protected]> Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8) Reviewed-by: Joakim Bech <[email protected]> Reported-by: Riscure <[email protected]> Reported-by: Alyssa Milburn <[email protected]> Acked-by: Etienne Carriere <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int ptype_seq_show(struct seq_file *seq, void *v) { struct packet_type *pt = v; if (v == SEQ_START_TOKEN) seq_puts(seq, "Type Device Function\n"); else if (pt->dev == NULL || dev_net(pt->dev) == seq_file_net(seq)) { if (pt->type == htons(ETH_P_ALL)) seq_puts(seq, "ALL "); else seq_printf(seq, "%04x", ntohs(pt->type)); seq_printf(seq, " %-8s %pF\n", pt->dev ? pt->dev->name : "", pt->func); } return 0; } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OMX_ERRORTYPE SoftVPXEncoder::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool PermissionsData::CanCaptureVisiblePage( const GURL& document_url, int tab_id, std::string* error, CaptureRequirement capture_requirement) const { bool has_active_tab = false; bool has_all_urls = false; bool has_page_capture = false; url::Origin origin = url::Origin::Create(document_url); const GURL origin_url = origin.GetURL(); { base::AutoLock auto_lock(runtime_lock_); if (location_ != Manifest::COMPONENT && IsPolicyBlockedHostUnsafe(origin_url)) { if (error) *error = extension_misc::kPolicyBlockedScripting; return false; } const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id); has_active_tab = tab_permissions && tab_permissions->HasAPIPermission(APIPermission::kTab); const URLPattern all_urls(URLPattern::SCHEME_ALL, URLPattern::kAllUrlsPattern); has_all_urls = active_permissions_unsafe_->explicit_hosts().ContainsPattern(all_urls); has_page_capture = active_permissions_unsafe_->HasAPIPermission( APIPermission::kPageCapture); } std::string access_error; if (capture_requirement == CaptureRequirement::kActiveTabOrAllUrls) { if (!has_active_tab && !has_all_urls) { if (error) *error = manifest_errors::kAllURLOrActiveTabNeeded; return false; } if (GetPageAccess(origin_url, tab_id, &access_error) == PageAccess::kAllowed) return true; } else { DCHECK_EQ(CaptureRequirement::kPageCapture, capture_requirement); if (!has_page_capture) { if (error) *error = manifest_errors::kPageCaptureNeeded; } if ((origin_url.SchemeIs(url::kHttpScheme) || origin_url.SchemeIs(url::kHttpsScheme)) && !origin.IsSameOriginWith(url::Origin::Create( ExtensionsClient::Get()->GetWebstoreBaseURL()))) { return true; } } if (origin_url.host() == extension_id_) return true; bool allowed_with_active_tab = origin_url.SchemeIs(content::kChromeUIScheme) || origin_url.SchemeIs(kExtensionScheme) || document_url.SchemeIs(url::kDataScheme) || origin.IsSameOriginWith( url::Origin::Create(ExtensionsClient::Get()->GetWebstoreBaseURL())); if (!allowed_with_active_tab) { if (error) *error = access_error; return false; } if (has_active_tab) return true; if (error) *error = manifest_errors::kActiveTabPermissionNotGranted; return false; } Commit Message: [Extensions] Have URLPattern::Contains() properly check schemes Have URLPattern::Contains() properly check the schemes of the patterns when evaluating if one pattern contains another. This is important in order to prevent extensions from requesting chrome:-scheme permissions via the permissions API when <all_urls> is specified as an optional permission. Bug: 859600,918470 Change-Id: If04d945ad0c939e84a80d83502c0f84b6ef0923d Reviewed-on: https://chromium-review.googlesource.com/c/1396561 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#621410} CWE ID: CWE-79 Target: 1 Example 2: Code: __be32 try_6rd(struct in6_addr *v6dst, struct ip_tunnel *tunnel) { __be32 dst = 0; #ifdef CONFIG_IPV6_SIT_6RD if (ipv6_prefix_equal(v6dst, &tunnel->ip6rd.prefix, tunnel->ip6rd.prefixlen)) { unsigned int pbw0, pbi0; int pbi1; u32 d; pbw0 = tunnel->ip6rd.prefixlen >> 5; pbi0 = tunnel->ip6rd.prefixlen & 0x1f; d = (ntohl(v6dst->s6_addr32[pbw0]) << pbi0) >> tunnel->ip6rd.relay_prefixlen; pbi1 = pbi0 - tunnel->ip6rd.relay_prefixlen; if (pbi1 > 0) d |= ntohl(v6dst->s6_addr32[pbw0 + 1]) >> (32 - pbi1); dst = tunnel->ip6rd.relay_prefix | htonl(d); } #else if (v6dst->s6_addr16[0] == htons(0x2002)) { /* 6to4 v6 addr has 16 bits prefix, 32 v4addr, 16 SLA, ... */ memcpy(&dst, &v6dst->s6_addr16[1], 4); } #endif return dst; } Commit Message: net: don't allow CAP_NET_ADMIN to load non-netdev kernel modules Since a8f80e8ff94ecba629542d9b4b5f5a8ee3eb565c any process with CAP_NET_ADMIN may load any module from /lib/modules/. This doesn't mean that CAP_NET_ADMIN is a superset of CAP_SYS_MODULE as modules are limited to /lib/modules/**. However, CAP_NET_ADMIN capability shouldn't allow anybody load any module not related to networking. This patch restricts an ability of autoloading modules to netdev modules with explicit aliases. This fixes CVE-2011-1019. Arnd Bergmann suggested to leave untouched the old pre-v2.6.32 behavior of loading netdev modules by name (without any prefix) for processes with CAP_SYS_MODULE to maintain the compatibility with network scripts that use autoloading netdev modules by aliases like "eth0", "wlan0". Currently there are only three users of the feature in the upstream kernel: ipip, ip_gre and sit. root@albatros:~# capsh --drop=$(seq -s, 0 11),$(seq -s, 13 34) -- root@albatros:~# grep Cap /proc/$$/status CapInh: 0000000000000000 CapPrm: fffffff800001000 CapEff: fffffff800001000 CapBnd: fffffff800001000 root@albatros:~# modprobe xfs FATAL: Error inserting xfs (/lib/modules/2.6.38-rc6-00001-g2bf4ca3/kernel/fs/xfs/xfs.ko): Operation not permitted root@albatros:~# lsmod | grep xfs root@albatros:~# ifconfig xfs xfs: error fetching interface information: Device not found root@albatros:~# lsmod | grep xfs root@albatros:~# lsmod | grep sit root@albatros:~# ifconfig sit sit: error fetching interface information: Device not found root@albatros:~# lsmod | grep sit root@albatros:~# ifconfig sit0 sit0 Link encap:IPv6-in-IPv4 NOARP MTU:1480 Metric:1 root@albatros:~# lsmod | grep sit sit 10457 0 tunnel4 2957 1 sit For CAP_SYS_MODULE module loading is still relaxed: root@albatros:~# grep Cap /proc/$$/status CapInh: 0000000000000000 CapPrm: ffffffffffffffff CapEff: ffffffffffffffff CapBnd: ffffffffffffffff root@albatros:~# ifconfig xfs xfs: error fetching interface information: Device not found root@albatros:~# lsmod | grep xfs xfs 745319 0 Reference: https://lkml.org/lkml/2011/2/24/203 Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Michael Tokarev <[email protected]> Acked-by: David S. Miller <[email protected]> Acked-by: Kees Cook <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: H264SwDecRet H264SwDecInit(H264SwDecInst *decInst, u32 noOutputReordering) { u32 rv = 0; decContainer_t *pDecCont; DEC_API_TRC("H264SwDecInit#"); /* check that right shift on negative numbers is performed signed */ /*lint -save -e* following check causes multiple lint messages */ if ( ((-1)>>1) != (-1) ) { DEC_API_TRC("H264SwDecInit# ERROR: Right shift is not signed"); return(H264SWDEC_INITFAIL); } /*lint -restore */ if (decInst == NULL) { DEC_API_TRC("H264SwDecInit# ERROR: decInst == NULL"); return(H264SWDEC_PARAM_ERR); } pDecCont = (decContainer_t *)H264SwDecMalloc(sizeof(decContainer_t)); if (pDecCont == NULL) { DEC_API_TRC("H264SwDecInit# ERROR: Memory allocation failed"); return(H264SWDEC_MEMFAIL); } #ifdef H264DEC_TRACE sprintf(pDecCont->str, "H264SwDecInit# decInst %p noOutputReordering %d", (void*)decInst, noOutputReordering); DEC_API_TRC(pDecCont->str); #endif rv = h264bsdInit(&pDecCont->storage, noOutputReordering); if (rv != HANTRO_OK) { H264SwDecRelease(pDecCont); return(H264SWDEC_MEMFAIL); } pDecCont->decStat = INITIALIZED; pDecCont->picNumber = 0; #ifdef H264DEC_TRACE sprintf(pDecCont->str, "H264SwDecInit# OK: return %p", (void*)pDecCont); DEC_API_TRC(pDecCont->str); #endif *decInst = (decContainer_t *)pDecCont; return(H264SWDEC_OK); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: static void Com_WriteCDKey( const char *filename, const char *ikey ) { fileHandle_t f; char fbuffer[MAX_OSPATH]; char key[17]; #ifndef _WIN32 mode_t savedumask; #endif Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename); Q_strncpyz( key, ikey, 17 ); if ( !CL_CDKeyValidate( key, NULL ) ) { return; } #ifndef _WIN32 savedumask = umask(0077); #endif f = FS_SV_FOpenFileWrite( fbuffer ); if ( !f ) { Com_Printf ("Couldn't write CD key to %s.\n", fbuffer ); goto out; } FS_Write( key, 16, f ); FS_Printf( f, "\n// generated by RTCW, do not modify\r\n" ); FS_Printf( f, "// Do not give this file to ANYONE.\r\n" ); #ifdef __APPLE__ FS_Printf( f, "// Aspyr will NOT ask you to send this file to them.\r\n" ); #else FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n" ); #endif FS_FCloseFile( f ); out: #ifndef _WIN32 umask(savedumask); #else ; #endif } Commit Message: All: Merge some file writing extension checks CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: XGetDeviceControl( register Display *dpy, XDevice *dev, int control) { XDeviceControl *Device = NULL; XDeviceControl *Sav = NULL; xDeviceState *d = NULL; xDeviceState *sav = NULL; xGetDeviceControlReq *req; xGetDeviceControlReply rep; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Add_XChangeDeviceControl, info) == -1) return NULL; GetReq(GetDeviceControl, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetDeviceControl; req->deviceid = dev->device_id; req->control = control; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) goto out; if (rep.length > 0) { unsigned long nbytes; size_t size = 0; if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; d = Xmalloc(nbytes); } _XEatDataWords(dpy, rep.length); goto out; } sav = d; _XRead(dpy, (char *)d, nbytes); /* In theory, we should just be able to use d->length to get the size. * Turns out that a number of X servers (up to and including server * 1.4) sent the wrong length value down the wire. So to not break * apps that run against older servers, we have to calculate the size * manually. */ switch (d->control) { case DEVICE_RESOLUTION: { xDeviceResolutionState *r; size_t val_size; size_t val_size; r = (xDeviceResolutionState *) d; if (r->num_valuators >= (INT_MAX / (3 * sizeof(int)))) goto out; val_size = 3 * sizeof(int) * r->num_valuators; if ((sizeof(xDeviceResolutionState) + val_size) > nbytes) break; } case DEVICE_ABS_CALIB: { if (sizeof(xDeviceAbsCalibState) > nbytes) goto out; size = sizeof(XDeviceAbsCalibState); break; } case DEVICE_ABS_AREA: { if (sizeof(xDeviceAbsAreaState) > nbytes) goto out; size = sizeof(XDeviceAbsAreaState); break; } case DEVICE_CORE: { if (sizeof(xDeviceCoreState) > nbytes) goto out; size = sizeof(XDeviceCoreState); break; } default: if (d->length > nbytes) goto out; size = d->length; break; } Device = Xmalloc(size); if (!Device) goto out; Sav = Device; d = sav; switch (control) { case DEVICE_RESOLUTION: { int *iptr, *iptr2; xDeviceResolutionState *r; XDeviceResolutionState *R; unsigned int i; r = (xDeviceResolutionState *) d; R = (XDeviceResolutionState *) Device; R->control = DEVICE_RESOLUTION; R->length = sizeof(XDeviceResolutionState); R->num_valuators = r->num_valuators; iptr = (int *)(R + 1); iptr2 = (int *)(r + 1); R->resolutions = iptr; R->min_resolutions = iptr + R->num_valuators; R->max_resolutions = iptr + (2 * R->num_valuators); for (i = 0; i < (3 * R->num_valuators); i++) *iptr++ = *iptr2++; break; } case DEVICE_ABS_CALIB: { xDeviceAbsCalibState *c = (xDeviceAbsCalibState *) d; XDeviceAbsCalibState *C = (XDeviceAbsCalibState *) Device; C->control = DEVICE_ABS_CALIB; C->length = sizeof(XDeviceAbsCalibState); C->min_x = c->min_x; C->max_x = c->max_x; C->min_y = c->min_y; C->max_y = c->max_y; C->flip_x = c->flip_x; C->flip_y = c->flip_y; C->rotation = c->rotation; C->button_threshold = c->button_threshold; break; } case DEVICE_ABS_AREA: { xDeviceAbsAreaState *a = (xDeviceAbsAreaState *) d; XDeviceAbsAreaState *A = (XDeviceAbsAreaState *) Device; A->control = DEVICE_ABS_AREA; A->length = sizeof(XDeviceAbsAreaState); A->offset_x = a->offset_x; A->offset_y = a->offset_y; A->width = a->width; A->height = a->height; A->screen = a->screen; A->following = a->following; break; } case DEVICE_CORE: { xDeviceCoreState *c = (xDeviceCoreState *) d; XDeviceCoreState *C = (XDeviceCoreState *) Device; C->control = DEVICE_CORE; C->length = sizeof(XDeviceCoreState); C->status = c->status; C->iscore = c->iscore; break; } case DEVICE_ENABLE: { xDeviceEnableState *e = (xDeviceEnableState *) d; XDeviceEnableState *E = (XDeviceEnableState *) Device; E->control = DEVICE_ENABLE; E->length = sizeof(E); E->enable = e->enable; break; } default: break; } } Commit Message: CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr; struct inet_sock *inet = inet_sk(sk); struct dccp_sock *dp = dccp_sk(sk); __be16 orig_sport, orig_dport; __be32 daddr, nexthop; struct flowi4 fl4; struct rtable *rt; int err; dp->dccps_role = DCCP_ROLE_CLIENT; if (addr_len < sizeof(struct sockaddr_in)) return -EINVAL; if (usin->sin_family != AF_INET) return -EAFNOSUPPORT; nexthop = daddr = usin->sin_addr.s_addr; if (inet->opt != NULL && inet->opt->srr) { if (daddr == 0) return -EINVAL; nexthop = inet->opt->faddr; } orig_sport = inet->inet_sport; orig_dport = usin->sin_port; rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, IPPROTO_DCCP, orig_sport, orig_dport, sk, true); if (IS_ERR(rt)) return PTR_ERR(rt); if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) { ip_rt_put(rt); return -ENETUNREACH; } if (inet->opt == NULL || !inet->opt->srr) daddr = rt->rt_dst; if (inet->inet_saddr == 0) inet->inet_saddr = rt->rt_src; inet->inet_rcv_saddr = inet->inet_saddr; inet->inet_dport = usin->sin_port; inet->inet_daddr = daddr; inet_csk(sk)->icsk_ext_hdr_len = 0; if (inet->opt != NULL) inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen; /* * Socket identity is still unknown (sport may be zero). * However we set state to DCCP_REQUESTING and not releasing socket * lock select source port, enter ourselves into the hash tables and * complete initialization after this. */ dccp_set_state(sk, DCCP_REQUESTING); err = inet_hash_connect(&dccp_death_row, sk); if (err != 0) goto failure; rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport, inet->inet_sport, inet->inet_dport, sk); if (IS_ERR(rt)) { rt = NULL; goto failure; } /* OK, now commit destination to socket. */ sk_setup_caps(sk, &rt->dst); dp->dccps_iss = secure_dccp_sequence_number(inet->inet_saddr, inet->inet_daddr, inet->inet_sport, inet->inet_dport); inet->inet_id = dp->dccps_iss ^ jiffies; err = dccp_connect(sk); rt = NULL; if (err != 0) goto failure; out: return err; failure: /* * This unhashes the socket and releases the local port, if necessary. */ dccp_set_state(sk, DCCP_CLOSED); ip_rt_put(rt); sk->sk_route_caps = 0; inet->inet_dport = 0; goto out; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: bool V8Float64Array::HasInstance(v8::Handle<v8::Value> value) { return GetRawTemplate()->HasInstance(value); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int dcbnl_ieee_fill(struct sk_buff *skb, struct net_device *netdev) { struct nlattr *ieee, *app; struct dcb_app_type *itr; const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops; int dcbx; int err; if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name)) return -EMSGSIZE; ieee = nla_nest_start(skb, DCB_ATTR_IEEE); if (!ieee) return -EMSGSIZE; if (ops->ieee_getets) { struct ieee_ets ets; err = ops->ieee_getets(netdev, &ets); if (!err && nla_put(skb, DCB_ATTR_IEEE_ETS, sizeof(ets), &ets)) return -EMSGSIZE; } if (ops->ieee_getmaxrate) { struct ieee_maxrate maxrate; err = ops->ieee_getmaxrate(netdev, &maxrate); if (!err) { err = nla_put(skb, DCB_ATTR_IEEE_MAXRATE, sizeof(maxrate), &maxrate); if (err) return -EMSGSIZE; } } if (ops->ieee_getpfc) { struct ieee_pfc pfc; err = ops->ieee_getpfc(netdev, &pfc); if (!err && nla_put(skb, DCB_ATTR_IEEE_PFC, sizeof(pfc), &pfc)) return -EMSGSIZE; } app = nla_nest_start(skb, DCB_ATTR_IEEE_APP_TABLE); if (!app) return -EMSGSIZE; spin_lock(&dcb_lock); list_for_each_entry(itr, &dcb_app_list, list) { if (itr->ifindex == netdev->ifindex) { err = nla_put(skb, DCB_ATTR_IEEE_APP, sizeof(itr->app), &itr->app); if (err) { spin_unlock(&dcb_lock); return -EMSGSIZE; } } } if (netdev->dcbnl_ops->getdcbx) dcbx = netdev->dcbnl_ops->getdcbx(netdev); else dcbx = -EOPNOTSUPP; spin_unlock(&dcb_lock); nla_nest_end(skb, app); /* get peer info if available */ if (ops->ieee_peer_getets) { struct ieee_ets ets; err = ops->ieee_peer_getets(netdev, &ets); if (!err && nla_put(skb, DCB_ATTR_IEEE_PEER_ETS, sizeof(ets), &ets)) return -EMSGSIZE; } if (ops->ieee_peer_getpfc) { struct ieee_pfc pfc; err = ops->ieee_peer_getpfc(netdev, &pfc); if (!err && nla_put(skb, DCB_ATTR_IEEE_PEER_PFC, sizeof(pfc), &pfc)) return -EMSGSIZE; } if (ops->peer_getappinfo && ops->peer_getapptable) { err = dcbnl_build_peer_app(netdev, skb, DCB_ATTR_IEEE_PEER_APP, DCB_ATTR_IEEE_APP_UNSPEC, DCB_ATTR_IEEE_APP); if (err) return -EMSGSIZE; } nla_nest_end(skb, ieee); if (dcbx >= 0) { err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx); if (err) return -EMSGSIZE; } return 0; } Commit Message: dcbnl: fix various netlink info leaks The dcb netlink interface leaks stack memory in various places: * perm_addr[] buffer is only filled at max with 12 of the 32 bytes but copied completely, * no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand, so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes for ieee_pfc structs, etc., * the same is true for CEE -- no in-kernel driver fills the whole struct, Prevent all of the above stack info leaks by properly initializing the buffers/structures involved. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: UserSelectionScreen::UpdateAndReturnUserListForMojo() { std::vector<ash::mojom::LoginUserInfoPtr> user_info_list; const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (user_manager::UserList::const_iterator it = users_to_send_.begin(); it != users_to_send_.end(); ++it) { const AccountId& account_id = (*it)->GetAccountId(); bool is_owner = owner == account_id; const bool is_public_account = ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(*it) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; ash::mojom::LoginUserInfoPtr login_user_info = ash::mojom::LoginUserInfo::New(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; FillUserMojoStruct(*it, is_owner, is_signin_to_add, initial_auth_type, public_session_recommended_locales, login_user_info.get()); login_user_info->can_remove = CanRemoveUser(*it); if (is_public_account && LoginScreenClient::HasInstance()) { LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts( account_id, login_user_info->public_account_info->default_locale); } user_info_list.push_back(std::move(login_user_info)); } return user_info_list; } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID: Target: 1 Example 2: Code: void impeg2d_format_convert(dec_state_t *ps_dec, pic_buf_t *ps_src_pic, iv_yuv_buf_t *ps_disp_frm_buf, UWORD32 u4_start_row, UWORD32 u4_num_rows) { UWORD8 *pu1_src_y,*pu1_src_u,*pu1_src_v; UWORD8 *pu1_dst_y,*pu1_dst_u,*pu1_dst_v; if((NULL == ps_src_pic) || (NULL == ps_src_pic->pu1_y) || (0 == u4_num_rows)) return; pu1_src_y = ps_src_pic->pu1_y + (u4_start_row * ps_dec->u2_frame_width); pu1_src_u = ps_src_pic->pu1_u + ((u4_start_row >> 1) * (ps_dec->u2_frame_width >> 1)); pu1_src_v = ps_src_pic->pu1_v + ((u4_start_row >> 1) *(ps_dec->u2_frame_width >> 1)); pu1_dst_y = (UWORD8 *)ps_disp_frm_buf->pv_y_buf + (u4_start_row * ps_dec->u4_frm_buf_stride); pu1_dst_u = (UWORD8 *)ps_disp_frm_buf->pv_u_buf +((u4_start_row >> 1)*(ps_dec->u4_frm_buf_stride >> 1)); pu1_dst_v = (UWORD8 *)ps_disp_frm_buf->pv_v_buf +((u4_start_row >> 1)*(ps_dec->u4_frm_buf_stride >> 1)); if (IV_YUV_420P == ps_dec->i4_chromaFormat) { ps_dec->pf_copy_yuv420p_buf(pu1_src_y, pu1_src_u, pu1_src_v, pu1_dst_y, pu1_dst_u, pu1_dst_v, ps_dec->u2_horizontal_size, u4_num_rows, ps_dec->u2_frame_width, (ps_dec->u2_frame_width >> 1), (ps_dec->u2_frame_width >> 1), ps_dec->u4_frm_buf_stride, (ps_dec->u4_frm_buf_stride >> 1), (ps_dec->u4_frm_buf_stride >> 1)); } else if (IV_YUV_422ILE == ps_dec->i4_chromaFormat) { void *pv_yuv422i; UWORD32 u2_height,u2_width,u2_stride_y,u2_stride_u,u2_stride_v; UWORD32 u2_stride_yuv422i; pv_yuv422i = (UWORD8 *)ps_disp_frm_buf->pv_y_buf + ((ps_dec->u2_vertical_size)*(ps_dec->u4_frm_buf_stride)); u2_height = u4_num_rows; u2_width = ps_dec->u2_horizontal_size; u2_stride_y = ps_dec->u2_frame_width; u2_stride_u = u2_stride_y >> 1; u2_stride_v = u2_stride_u; u2_stride_yuv422i = (0 == ps_dec->u4_frm_buf_stride) ? ps_dec->u2_horizontal_size : ps_dec->u4_frm_buf_stride; ps_dec->pf_fmt_conv_yuv420p_to_yuv422ile(pu1_src_y, pu1_src_u, pu1_src_v, pv_yuv422i, u2_width, u2_height, u2_stride_y, u2_stride_u, u2_stride_v, u2_stride_yuv422i); } else if((ps_dec->i4_chromaFormat == IV_YUV_420SP_UV) || (ps_dec->i4_chromaFormat == IV_YUV_420SP_VU)) { UWORD32 dest_inc_Y=0,dest_inc_UV=0; WORD32 convert_uv_only; pu1_dst_u = (UWORD8 *)ps_disp_frm_buf->pv_u_buf +((u4_start_row >> 1)*(ps_dec->u4_frm_buf_stride)); dest_inc_Y = ps_dec->u4_frm_buf_stride; dest_inc_UV = ((ps_dec->u4_frm_buf_stride + 1) >> 1) << 1; convert_uv_only = 0; if(1 == ps_dec->u4_share_disp_buf) convert_uv_only = 1; if(pu1_src_y == pu1_dst_y) convert_uv_only = 1; if(ps_dec->i4_chromaFormat == IV_YUV_420SP_UV) { ps_dec->pf_fmt_conv_yuv420p_to_yuv420sp_uv(pu1_src_y, pu1_src_u, pu1_src_v, pu1_dst_y, pu1_dst_u, u4_num_rows, ps_dec->u2_horizontal_size, ps_dec->u2_frame_width, ps_dec->u2_frame_width >> 1, ps_dec->u2_frame_width >> 1, dest_inc_Y, dest_inc_UV, convert_uv_only); } else { ps_dec->pf_fmt_conv_yuv420p_to_yuv420sp_vu(pu1_src_y, pu1_src_u, pu1_src_v, pu1_dst_y, pu1_dst_u, u4_num_rows, ps_dec->u2_horizontal_size, ps_dec->u2_frame_width, ps_dec->u2_frame_width >> 1, ps_dec->u2_frame_width >> 1, dest_inc_Y, dest_inc_UV, convert_uv_only); } } } Commit Message: Adding Error Check for f_code Parameters In MPEG1, the valid range for the forward and backward f_code parameters is [1, 7]. Adding a check to enforce this. Without the check, the value could be 0. We read (f_code - 1) bits from the stream and reading a negative number of bits from the stream is undefined. Bug: 64550583 Test: monitored temp ALOGD() output Change-Id: Ia452cd43a28e9d566401f515947164635361782f (cherry picked from commit 71d734b83d72e8a59f73f1230982da97615d2689) CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ipmi_si_port_setup(struct si_sm_io *io) { unsigned int addr = io->addr_data; int idx; if (!addr) return -ENODEV; io->io_cleanup = port_cleanup; /* * Figure out the actual inb/inw/inl/etc routine to use based * upon the register size. */ switch (io->regsize) { case 1: io->inputb = port_inb; io->outputb = port_outb; break; case 2: io->inputb = port_inw; io->outputb = port_outw; break; case 4: io->inputb = port_inl; io->outputb = port_outl; break; default: dev_warn(io->dev, "Invalid register size: %d\n", io->regsize); return -EINVAL; } /* * Some BIOSes reserve disjoint I/O regions in their ACPI * tables. This causes problems when trying to register the * entire I/O region. Therefore we must register each I/O * port separately. */ for (idx = 0; idx < io->io_size; idx++) { if (request_region(addr + idx * io->regspacing, io->regsize, DEVICE_NAME) == NULL) { /* Undo allocations */ while (idx--) release_region(addr + idx * io->regspacing, io->regsize); return -EIO; } } return 0; } Commit Message: ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: [email protected] Reported-by: NuoHan Qiao <[email protected]> Suggested-by: Corey Minyard <[email protected]> Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[email protected]> CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL jsFloat64ArrayPrototypeFunctionFoo(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSFloat64Array::s_info)) return throwVMTypeError(exec); JSFloat64Array* castedThis = jsCast<JSFloat64Array*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSFloat64Array::s_info); Float64Array* impl = static_cast<Float64Array*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); Float32Array* array(toFloat32Array(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->foo(array))); return JSValue::encode(result); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: static int isofs_fill_super(struct super_block *s, void *data, int silent) { struct buffer_head *bh = NULL, *pri_bh = NULL; struct hs_primary_descriptor *h_pri = NULL; struct iso_primary_descriptor *pri = NULL; struct iso_supplementary_descriptor *sec = NULL; struct iso_directory_record *rootp; struct inode *inode; struct iso9660_options opt; struct isofs_sb_info *sbi; unsigned long first_data_zone; int joliet_level = 0; int iso_blknum, block; int orig_zonesize; int table, error = -EINVAL; unsigned int vol_desc_start; save_mount_options(s, data); sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; s->s_fs_info = sbi; if (!parse_options((char *)data, &opt)) goto out_freesbi; /* * First of all, get the hardware blocksize for this device. * If we don't know what it is, or the hardware blocksize is * larger than the blocksize the user specified, then use * that value. */ /* * What if bugger tells us to go beyond page size? */ opt.blocksize = sb_min_blocksize(s, opt.blocksize); sbi->s_high_sierra = 0; /* default is iso9660 */ vol_desc_start = (opt.sbsector != -1) ? opt.sbsector : isofs_get_last_session(s,opt.session); for (iso_blknum = vol_desc_start+16; iso_blknum < vol_desc_start+100; iso_blknum++) { struct hs_volume_descriptor *hdp; struct iso_volume_descriptor *vdp; block = iso_blknum << (ISOFS_BLOCK_BITS - s->s_blocksize_bits); if (!(bh = sb_bread(s, block))) goto out_no_read; vdp = (struct iso_volume_descriptor *)bh->b_data; hdp = (struct hs_volume_descriptor *)bh->b_data; /* * Due to the overlapping physical location of the descriptors, * ISO CDs can match hdp->id==HS_STANDARD_ID as well. To ensure * proper identification in this case, we first check for ISO. */ if (strncmp (vdp->id, ISO_STANDARD_ID, sizeof vdp->id) == 0) { if (isonum_711(vdp->type) == ISO_VD_END) break; if (isonum_711(vdp->type) == ISO_VD_PRIMARY) { if (pri == NULL) { pri = (struct iso_primary_descriptor *)vdp; /* Save the buffer in case we need it ... */ pri_bh = bh; bh = NULL; } } #ifdef CONFIG_JOLIET else if (isonum_711(vdp->type) == ISO_VD_SUPPLEMENTARY) { sec = (struct iso_supplementary_descriptor *)vdp; if (sec->escape[0] == 0x25 && sec->escape[1] == 0x2f) { if (opt.joliet) { if (sec->escape[2] == 0x40) joliet_level = 1; else if (sec->escape[2] == 0x43) joliet_level = 2; else if (sec->escape[2] == 0x45) joliet_level = 3; printk(KERN_DEBUG "ISO 9660 Extensions: " "Microsoft Joliet Level %d\n", joliet_level); } goto root_found; } else { /* Unknown supplementary volume descriptor */ sec = NULL; } } #endif } else { if (strncmp (hdp->id, HS_STANDARD_ID, sizeof hdp->id) == 0) { if (isonum_711(hdp->type) != ISO_VD_PRIMARY) goto out_freebh; sbi->s_high_sierra = 1; opt.rock = 0; h_pri = (struct hs_primary_descriptor *)vdp; goto root_found; } } /* Just skip any volume descriptors we don't recognize */ brelse(bh); bh = NULL; } /* * If we fall through, either no volume descriptor was found, * or else we passed a primary descriptor looking for others. */ if (!pri) goto out_unknown_format; brelse(bh); bh = pri_bh; pri_bh = NULL; root_found: if (joliet_level && (pri == NULL || !opt.rock)) { /* This is the case of Joliet with the norock mount flag. * A disc with both Joliet and Rock Ridge is handled later */ pri = (struct iso_primary_descriptor *) sec; } if(sbi->s_high_sierra){ rootp = (struct iso_directory_record *) h_pri->root_directory_record; sbi->s_nzones = isonum_733(h_pri->volume_space_size); sbi->s_log_zone_size = isonum_723(h_pri->logical_block_size); sbi->s_max_size = isonum_733(h_pri->volume_space_size); } else { if (!pri) goto out_freebh; rootp = (struct iso_directory_record *) pri->root_directory_record; sbi->s_nzones = isonum_733(pri->volume_space_size); sbi->s_log_zone_size = isonum_723(pri->logical_block_size); sbi->s_max_size = isonum_733(pri->volume_space_size); } sbi->s_ninodes = 0; /* No way to figure this out easily */ orig_zonesize = sbi->s_log_zone_size; /* * If the zone size is smaller than the hardware sector size, * this is a fatal error. This would occur if the disc drive * had sectors that were 2048 bytes, but the filesystem had * blocks that were 512 bytes (which should only very rarely * happen.) */ if (orig_zonesize < opt.blocksize) goto out_bad_size; /* RDE: convert log zone size to bit shift */ switch (sbi->s_log_zone_size) { case 512: sbi->s_log_zone_size = 9; break; case 1024: sbi->s_log_zone_size = 10; break; case 2048: sbi->s_log_zone_size = 11; break; default: goto out_bad_zone_size; } s->s_magic = ISOFS_SUPER_MAGIC; /* * With multi-extent files, file size is only limited by the maximum * size of a file system, which is 8 TB. */ s->s_maxbytes = 0x80000000000LL; /* Set this for reference. Its not currently used except on write which we don't have .. */ first_data_zone = isonum_733(rootp->extent) + isonum_711(rootp->ext_attr_length); sbi->s_firstdatazone = first_data_zone; #ifndef BEQUIET printk(KERN_DEBUG "ISOFS: Max size:%ld Log zone size:%ld\n", sbi->s_max_size, 1UL << sbi->s_log_zone_size); printk(KERN_DEBUG "ISOFS: First datazone:%ld\n", sbi->s_firstdatazone); if(sbi->s_high_sierra) printk(KERN_DEBUG "ISOFS: Disc in High Sierra format.\n"); #endif /* * If the Joliet level is set, we _may_ decide to use the * secondary descriptor, but can't be sure until after we * read the root inode. But before reading the root inode * we may need to change the device blocksize, and would * rather release the old buffer first. So, we cache the * first_data_zone value from the secondary descriptor. */ if (joliet_level) { pri = (struct iso_primary_descriptor *) sec; rootp = (struct iso_directory_record *) pri->root_directory_record; first_data_zone = isonum_733(rootp->extent) + isonum_711(rootp->ext_attr_length); } /* * We're all done using the volume descriptor, and may need * to change the device blocksize, so release the buffer now. */ brelse(pri_bh); brelse(bh); /* * Force the blocksize to 512 for 512 byte sectors. The file * read primitives really get it wrong in a bad way if we don't * do this. * * Note - we should never be setting the blocksize to something * less than the hardware sector size for the device. If we * do, we would end up having to read larger buffers and split * out portions to satisfy requests. * * Note2- the idea here is that we want to deal with the optimal * zonesize in the filesystem. If we have it set to something less, * then we have horrible problems with trying to piece together * bits of adjacent blocks in order to properly read directory * entries. By forcing the blocksize in this way, we ensure * that we will never be required to do this. */ sb_set_blocksize(s, orig_zonesize); sbi->s_nls_iocharset = NULL; #ifdef CONFIG_JOLIET if (joliet_level && opt.utf8 == 0) { char *p = opt.iocharset ? opt.iocharset : CONFIG_NLS_DEFAULT; sbi->s_nls_iocharset = load_nls(p); if (! sbi->s_nls_iocharset) { /* Fail only if explicit charset specified */ if (opt.iocharset) goto out_freesbi; sbi->s_nls_iocharset = load_nls_default(); } } #endif s->s_op = &isofs_sops; s->s_export_op = &isofs_export_ops; sbi->s_mapping = opt.map; sbi->s_rock = (opt.rock ? 2 : 0); sbi->s_rock_offset = -1; /* initial offset, will guess until SP is found*/ sbi->s_cruft = opt.cruft; sbi->s_hide = opt.hide; sbi->s_showassoc = opt.showassoc; sbi->s_uid = opt.uid; sbi->s_gid = opt.gid; sbi->s_uid_set = opt.uid_set; sbi->s_gid_set = opt.gid_set; sbi->s_utf8 = opt.utf8; sbi->s_nocompress = opt.nocompress; sbi->s_overriderockperm = opt.overriderockperm; /* * It would be incredibly stupid to allow people to mark every file * on the disk as suid, so we merely allow them to set the default * permissions. */ if (opt.fmode != ISOFS_INVALID_MODE) sbi->s_fmode = opt.fmode & 0777; else sbi->s_fmode = ISOFS_INVALID_MODE; if (opt.dmode != ISOFS_INVALID_MODE) sbi->s_dmode = opt.dmode & 0777; else sbi->s_dmode = ISOFS_INVALID_MODE; /* * Read the root inode, which _may_ result in changing * the s_rock flag. Once we have the final s_rock value, * we then decide whether to use the Joliet descriptor. */ inode = isofs_iget(s, sbi->s_firstdatazone, 0); if (IS_ERR(inode)) goto out_no_root; /* * Fix for broken CDs with Rock Ridge and empty ISO root directory but * correct Joliet root directory. */ if (sbi->s_rock == 1 && joliet_level && rootdir_empty(s, sbi->s_firstdatazone)) { printk(KERN_NOTICE "ISOFS: primary root directory is empty. " "Disabling Rock Ridge and switching to Joliet."); sbi->s_rock = 0; } /* * If this disk has both Rock Ridge and Joliet on it, then we * want to use Rock Ridge by default. This can be overridden * by using the norock mount option. There is still one other * possibility that is not taken into account: a Rock Ridge * CD with Unicode names. Until someone sees such a beast, it * will not be supported. */ if (sbi->s_rock == 1) { joliet_level = 0; } else if (joliet_level) { sbi->s_rock = 0; if (sbi->s_firstdatazone != first_data_zone) { sbi->s_firstdatazone = first_data_zone; printk(KERN_DEBUG "ISOFS: changing to secondary root\n"); iput(inode); inode = isofs_iget(s, sbi->s_firstdatazone, 0); if (IS_ERR(inode)) goto out_no_root; } } if (opt.check == 'u') { /* Only Joliet is case insensitive by default */ if (joliet_level) opt.check = 'r'; else opt.check = 's'; } sbi->s_joliet_level = joliet_level; /* Make sure the root inode is a directory */ if (!S_ISDIR(inode->i_mode)) { printk(KERN_WARNING "isofs_fill_super: root inode is not a directory. " "Corrupted media?\n"); goto out_iput; } table = 0; if (joliet_level) table += 2; if (opt.check == 'r') table++; s->s_d_op = &isofs_dentry_ops[table]; /* get the root dentry */ s->s_root = d_make_root(inode); if (!(s->s_root)) { error = -ENOMEM; goto out_no_inode; } kfree(opt.iocharset); return 0; /* * Display error messages and free resources. */ out_iput: iput(inode); goto out_no_inode; out_no_root: error = PTR_ERR(inode); if (error != -ENOMEM) printk(KERN_WARNING "%s: get root inode failed\n", __func__); out_no_inode: #ifdef CONFIG_JOLIET unload_nls(sbi->s_nls_iocharset); #endif goto out_freesbi; out_no_read: printk(KERN_WARNING "%s: bread failed, dev=%s, iso_blknum=%d, block=%d\n", __func__, s->s_id, iso_blknum, block); goto out_freebh; out_bad_zone_size: printk(KERN_WARNING "ISOFS: Bad logical zone size %ld\n", sbi->s_log_zone_size); goto out_freebh; out_bad_size: printk(KERN_WARNING "ISOFS: Logical zone size(%d) < hardware blocksize(%u)\n", orig_zonesize, opt.blocksize); goto out_freebh; out_unknown_format: if (!silent) printk(KERN_WARNING "ISOFS: Unable to identify CD-ROM format.\n"); out_freebh: brelse(bh); brelse(pri_bh); out_freesbi: kfree(opt.iocharset); kfree(sbi); s->s_fs_info = NULL; return error; } Commit Message: isofs: Fix unbounded recursion when processing relocated directories We did not check relocated directory in any way when processing Rock Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL entry pointing to another CL entry leading to possibly unbounded recursion in kernel code and thus stack overflow or deadlocks (if there is a loop created from CL entries). Fix the problem by not allowing CL entry to point to a directory entry with CL entry (such use makes no good sense anyway) and by checking whether CL entry doesn't point to itself. CC: [email protected] Reported-by: Chris Evans <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc) { struct scsi_device *SDev; struct scsi_sense_hdr sshdr; int result, err = 0, retries = 0; SDev = cd->device; retry: if (!scsi_block_when_processing_errors(SDev)) { err = -ENODEV; goto out; } result = scsi_execute(SDev, cgc->cmd, cgc->data_direction, cgc->buffer, cgc->buflen, (unsigned char *)cgc->sense, &sshdr, cgc->timeout, IOCTL_RETRIES, 0, 0, NULL); /* Minimal error checking. Ignore cases we know about, and report the rest. */ if (driver_byte(result) != 0) { switch (sshdr.sense_key) { case UNIT_ATTENTION: SDev->changed = 1; if (!cgc->quiet) sr_printk(KERN_INFO, cd, "disc change detected.\n"); if (retries++ < 10) goto retry; err = -ENOMEDIUM; break; case NOT_READY: /* This happens if there is no disc in drive */ if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) { /* sense: Logical unit is in process of becoming ready */ if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready yet.\n"); if (retries++ < 10) { /* sleep 2 sec and try again */ ssleep(2); goto retry; } else { /* 20 secs are enough? */ err = -ENOMEDIUM; break; } } if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready. Make sure there " "is a disc in the drive.\n"); err = -ENOMEDIUM; break; case ILLEGAL_REQUEST: err = -EIO; if (sshdr.asc == 0x20 && sshdr.ascq == 0x00) /* sense: Invalid command operation code */ err = -EDRIVE_CANT_DO_THIS; break; default: err = -EIO; } } /* Wake up a process waiting for device */ out: cgc->stat = err; return err; } Commit Message: sr: pass down correctly sized SCSI sense buffer We're casting the CDROM layer request_sense to the SCSI sense buffer, but the former is 64 bytes and the latter is 96 bytes. As we generally allocate these on the stack, we end up blowing up the stack. Fix this by wrapping the scsi_execute() call with a properly sized sense buffer, and copying back the bits for the CDROM layer. Cc: [email protected] Reported-by: Piotr Gabriel Kosinski <[email protected]> Reported-by: Daniel Shapira <[email protected]> Tested-by: Kees Cook <[email protected]> Fixes: 82ed4db499b8 ("block: split scsi_request out of struct request") Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SoftAAC2::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } UCHAR* inBuffer[FILEREAD_MAX_LAYERS]; UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0}; UINT bytesValid[FILEREAD_MAX_LAYERS] = {0}; List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) { if (!inQueue.empty()) { INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0; if (mInputBufferCount == 0 && !(inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) { ALOGE("first buffer should have OMX_BUFFERFLAG_CODECCONFIG set"); inHeader->nFlags |= OMX_BUFFERFLAG_CODECCONFIG; } if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) != 0) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; inBuffer[0] = inHeader->pBuffer + inHeader->nOffset; inBufferLength[0] = inHeader->nFilledLen; AAC_DECODER_ERROR decoderErr = aacDecoder_ConfigRaw(mAACDecoder, inBuffer, inBufferLength); if (decoderErr != AAC_DEC_OK) { ALOGW("aacDecoder_ConfigRaw decoderErr = 0x%4.4x", decoderErr); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); return; } mInputBufferCount++; mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); mLastInHeader = NULL; inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; configureDownmix(); if (mStreamInfo->sampleRate && mStreamInfo->numChannels) { ALOGI("Initially configuring decoder: %d Hz, %d channels", mStreamInfo->sampleRate, mStreamInfo->numChannels); notify(OMX_EventPortSettingsChanged, 1, 0, NULL); mOutputPortSettingsChange = AWAITING_DISABLED; } return; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); mLastInHeader = NULL; inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; continue; } if (mIsADTS) { size_t adtsHeaderSize = 0; const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset; bool signalError = false; if (inHeader->nFilledLen < 7) { ALOGE("Audio data too short to contain even the ADTS header. " "Got %d bytes.", inHeader->nFilledLen); hexdump(adtsHeader, inHeader->nFilledLen); signalError = true; } else { bool protectionAbsent = (adtsHeader[1] & 1); unsigned aac_frame_length = ((adtsHeader[3] & 3) << 11) | (adtsHeader[4] << 3) | (adtsHeader[5] >> 5); if (inHeader->nFilledLen < aac_frame_length) { ALOGE("Not enough audio data for the complete frame. " "Got %d bytes, frame size according to the ADTS " "header is %u bytes.", inHeader->nFilledLen, aac_frame_length); hexdump(adtsHeader, inHeader->nFilledLen); signalError = true; } else { adtsHeaderSize = (protectionAbsent ? 7 : 9); inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize; inBufferLength[0] = aac_frame_length - adtsHeaderSize; inHeader->nOffset += adtsHeaderSize; inHeader->nFilledLen -= adtsHeaderSize; } } if (signalError) { mSignalledError = true; notify(OMX_EventError, OMX_ErrorStreamCorrupt, ERROR_MALFORMED, NULL); return; } mBufferSizes.add(inBufferLength[0]); if (mLastInHeader != inHeader) { mBufferTimestamps.add(inHeader->nTimeStamp); mLastInHeader = inHeader; } else { int64_t currentTime = mBufferTimestamps.top(); currentTime += mStreamInfo->aacSamplesPerFrame * 1000000ll / mStreamInfo->aacSampleRate; mBufferTimestamps.add(currentTime); } } else { inBuffer[0] = inHeader->pBuffer + inHeader->nOffset; inBufferLength[0] = inHeader->nFilledLen; mLastInHeader = inHeader; mBufferTimestamps.add(inHeader->nTimeStamp); mBufferSizes.add(inHeader->nFilledLen); } bytesValid[0] = inBufferLength[0]; INT prevSampleRate = mStreamInfo->sampleRate; INT prevNumChannels = mStreamInfo->numChannels; aacDecoder_Fill(mAACDecoder, inBuffer, inBufferLength, bytesValid); mDrcWrap.submitStreamData(mStreamInfo); mDrcWrap.update(); UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0]; inHeader->nFilledLen -= inBufferUsedLength; inHeader->nOffset += inBufferUsedLength; AAC_DECODER_ERROR decoderErr; int numLoops = 0; do { if (outputDelayRingBufferSpaceLeft() < (mStreamInfo->frameSize * mStreamInfo->numChannels)) { ALOGV("skipping decode: not enough space left in ringbuffer"); break; } int numConsumed = mStreamInfo->numTotalBytes; decoderErr = aacDecoder_DecodeFrame(mAACDecoder, tmpOutBuffer, 2048 * MAX_CHANNEL_COUNT, 0 /* flags */); numConsumed = mStreamInfo->numTotalBytes - numConsumed; numLoops++; if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) { break; } mDecodedSizes.add(numConsumed); if (decoderErr != AAC_DEC_OK) { ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); } if (bytesValid[0] != 0) { ALOGE("bytesValid[0] != 0 should never happen"); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } size_t numOutBytes = mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels; if (decoderErr == AAC_DEC_OK) { if (!outputDelayRingBufferPutSamples(tmpOutBuffer, mStreamInfo->frameSize * mStreamInfo->numChannels)) { mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); return; } } else { ALOGW("AAC decoder returned error 0x%4.4x, substituting silence", decoderErr); memset(tmpOutBuffer, 0, numOutBytes); // TODO: check for overflow if (!outputDelayRingBufferPutSamples(tmpOutBuffer, mStreamInfo->frameSize * mStreamInfo->numChannels)) { mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); return; } if (inHeader) { inHeader->nFilledLen = 0; } aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1); mBufferSizes.pop(); int n = 0; for (int i = 0; i < numLoops; i++) { n += mDecodedSizes.itemAt(mDecodedSizes.size() - numLoops + i); } mBufferSizes.add(n); } /* * AAC+/eAAC+ streams can be signalled in two ways: either explicitly * or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual * rate system and the sampling rate in the final output is actually * doubled compared with the core AAC decoder sampling rate. * * Explicit signalling is done by explicitly defining SBR audio object * type in the bitstream. Implicit signalling is done by embedding * SBR content in AAC extension payload specific to SBR, and hence * requires an AAC decoder to perform pre-checks on actual audio frames. * * Thus, we could not say for sure whether a stream is * AAC+/eAAC+ until the first data frame is decoded. */ if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1 if (mStreamInfo->sampleRate != prevSampleRate || mStreamInfo->numChannels != prevNumChannels) { ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels", prevSampleRate, mStreamInfo->sampleRate, prevNumChannels, mStreamInfo->numChannels); notify(OMX_EventPortSettingsChanged, 1, 0, NULL); mOutputPortSettingsChange = AWAITING_DISABLED; if (inHeader && inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; mInputBufferCount++; inQueue.erase(inQueue.begin()); mLastInHeader = NULL; inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } return; } } else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) { ALOGW("Invalid AAC stream"); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); return; } if (inHeader && inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; mInputBufferCount++; inQueue.erase(inQueue.begin()); mLastInHeader = NULL; inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } else { ALOGV("inHeader->nFilledLen = %d", inHeader ? inHeader->nFilledLen : 0); } } while (decoderErr == AAC_DEC_OK); } int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels; if (!mEndOfInput && mOutputDelayCompensated < outputDelay) { int32_t toCompensate = outputDelay - mOutputDelayCompensated; int32_t discard = outputDelayRingBufferSamplesAvailable(); if (discard > toCompensate) { discard = toCompensate; } int32_t discarded = outputDelayRingBufferGetSamples(0, discard); mOutputDelayCompensated += discarded; continue; } if (mEndOfInput) { while (mOutputDelayCompensated > 0) { INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; mDrcWrap.submitStreamData(mStreamInfo); mDrcWrap.update(); AAC_DECODER_ERROR decoderErr = aacDecoder_DecodeFrame(mAACDecoder, tmpOutBuffer, 2048 * MAX_CHANNEL_COUNT, AACDEC_FLUSH); if (decoderErr != AAC_DEC_OK) { ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); } int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels; if (tmpOutBufferSamples > mOutputDelayCompensated) { tmpOutBufferSamples = mOutputDelayCompensated; } outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples); mOutputDelayCompensated -= tmpOutBufferSamples; } } while (!outQueue.empty() && outputDelayRingBufferSamplesAvailable() >= mStreamInfo->frameSize * mStreamInfo->numChannels) { BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (outHeader->nOffset != 0) { ALOGE("outHeader->nOffset != 0 is not handled"); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset); int samplesize = mStreamInfo->numChannels * sizeof(int16_t); if (outHeader->nOffset + mStreamInfo->frameSize * samplesize > outHeader->nAllocLen) { ALOGE("buffer overflow"); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } int available = outputDelayRingBufferSamplesAvailable(); int numSamples = outHeader->nAllocLen / sizeof(int16_t); if (numSamples > available) { numSamples = available; } int64_t currentTime = 0; if (available) { int numFrames = numSamples / (mStreamInfo->frameSize * mStreamInfo->numChannels); numSamples = numFrames * (mStreamInfo->frameSize * mStreamInfo->numChannels); ALOGV("%d samples available (%d), or %d frames", numSamples, available, numFrames); int64_t *nextTimeStamp = &mBufferTimestamps.editItemAt(0); currentTime = *nextTimeStamp; int32_t *currentBufLeft = &mBufferSizes.editItemAt(0); for (int i = 0; i < numFrames; i++) { int32_t decodedSize = mDecodedSizes.itemAt(0); mDecodedSizes.removeAt(0); ALOGV("decoded %d of %d", decodedSize, *currentBufLeft); if (*currentBufLeft > decodedSize) { *currentBufLeft -= decodedSize; *nextTimeStamp += mStreamInfo->aacSamplesPerFrame * 1000000ll / mStreamInfo->aacSampleRate; ALOGV("adjusted nextTimeStamp/size to %lld/%d", (long long) *nextTimeStamp, *currentBufLeft); } else { if (mBufferTimestamps.size() > 0) { mBufferTimestamps.removeAt(0); nextTimeStamp = &mBufferTimestamps.editItemAt(0); mBufferSizes.removeAt(0); currentBufLeft = &mBufferSizes.editItemAt(0); ALOGV("moved to next time/size: %lld/%d", (long long) *nextTimeStamp, *currentBufLeft); } numFrames = i + 1; numSamples = numFrames * mStreamInfo->frameSize * mStreamInfo->numChannels; break; } } ALOGV("getting %d from ringbuffer", numSamples); int32_t ns = outputDelayRingBufferGetSamples(outBuffer, numSamples); if (ns != numSamples) { ALOGE("not a complete frame of samples available"); mSignalledError = true; notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } } outHeader->nFilledLen = numSamples * sizeof(int16_t); if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; mEndOfOutput = true; } else { outHeader->nFlags = 0; } outHeader->nTimeStamp = currentTime; mOutputBufferCount++; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; ALOGV("out timestamp %lld / %d", outHeader->nTimeStamp, outHeader->nFilledLen); notifyFillBufferDone(outHeader); outHeader = NULL; } if (mEndOfInput) { int ringBufAvail = outputDelayRingBufferSamplesAvailable(); if (!outQueue.empty() && ringBufAvail < mStreamInfo->frameSize * mStreamInfo->numChannels) { if (!mEndOfOutput) { mEndOfOutput = true; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset); int32_t ns = outputDelayRingBufferGetSamples(outBuffer, ringBufAvail); if (ns < 0) { ns = 0; } outHeader->nFilledLen = ns; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outHeader->nTimeStamp = mBufferTimestamps.itemAt(0); mBufferTimestamps.clear(); mBufferSizes.clear(); mDecodedSizes.clear(); mOutputBufferCount++; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } break; // if outQueue not empty but no more output } } } } Commit Message: SoftAAC2: fix crash on all-zero adts buffer Bug: 29153599 Change-Id: I1cb81c054098b86cf24f024f8479909ca7bc85a6 CWE ID: CWE-20 Target: 1 Example 2: Code: static s32 atl2_get_speed_and_duplex(struct atl2_hw *hw, u16 *speed, u16 *duplex) { s32 ret_val; u16 phy_data; /* Read PHY Specific Status Register (17) */ ret_val = atl2_read_phy_reg(hw, MII_ATLX_PSSR, &phy_data); if (ret_val) return ret_val; if (!(phy_data & MII_ATLX_PSSR_SPD_DPLX_RESOLVED)) return ATLX_ERR_PHY_RES; switch (phy_data & MII_ATLX_PSSR_SPEED) { case MII_ATLX_PSSR_100MBS: *speed = SPEED_100; break; case MII_ATLX_PSSR_10MBS: *speed = SPEED_10; break; default: return ATLX_ERR_PHY_SPEED; } if (phy_data & MII_ATLX_PSSR_DPLX) *duplex = FULL_DUPLEX; else *duplex = HALF_DUPLEX; return 0; } Commit Message: atl2: Disable unimplemented scatter/gather feature atl2 includes NETIF_F_SG in hw_features even though it has no support for non-linear skbs. This bug was originally harmless since the driver does not claim to implement checksum offload and that used to be a requirement for SG. Now that SG and checksum offload are independent features, if you explicitly enable SG *and* use one of the rare protocols that can use SG without checkusm offload, this potentially leaks sensitive information (before you notice that it just isn't working). Therefore this obscure bug has been designated CVE-2016-2117. Reported-by: Justin Yackoski <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> Fixes: ec5f06156423 ("net: Kill link between CSUM and SG features.") Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void HTMLInputElement::HandleBlurEvent() { input_type_->DisableSecureTextInput(); input_type_view_->HandleBlurEvent(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append) { unsigned nSyms = darray_size(expr->keysym_list.syms); unsigned numEntries = darray_size(append->keysym_list.syms); darray_append(expr->keysym_list.symsMapIndex, nSyms); darray_append(expr->keysym_list.symsNumEntries, numEntries); darray_concat(expr->keysym_list.syms, append->keysym_list.syms); FreeStmt((ParseCommon *) &append); return expr; } Commit Message: xkbcomp: fix pointer value for FreeStmt Signed-off-by: Peter Hutterer <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: static int ip_vs_genl_parse_service(struct net *net, struct ip_vs_service_user_kern *usvc, struct nlattr *nla, int full_entry, struct ip_vs_service **ret_svc) { struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1]; struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr; struct ip_vs_service *svc; /* Parse mandatory identifying service fields first */ if (nla == NULL || nla_parse_nested(attrs, IPVS_SVC_ATTR_MAX, nla, ip_vs_svc_policy)) return -EINVAL; nla_af = attrs[IPVS_SVC_ATTR_AF]; nla_protocol = attrs[IPVS_SVC_ATTR_PROTOCOL]; nla_addr = attrs[IPVS_SVC_ATTR_ADDR]; nla_port = attrs[IPVS_SVC_ATTR_PORT]; nla_fwmark = attrs[IPVS_SVC_ATTR_FWMARK]; if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr)))) return -EINVAL; memset(usvc, 0, sizeof(*usvc)); usvc->af = nla_get_u16(nla_af); #ifdef CONFIG_IP_VS_IPV6 if (usvc->af != AF_INET && usvc->af != AF_INET6) #else if (usvc->af != AF_INET) #endif return -EAFNOSUPPORT; if (nla_fwmark) { usvc->protocol = IPPROTO_TCP; usvc->fwmark = nla_get_u32(nla_fwmark); } else { usvc->protocol = nla_get_u16(nla_protocol); nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr)); usvc->port = nla_get_u16(nla_port); usvc->fwmark = 0; } if (usvc->fwmark) svc = __ip_vs_svc_fwm_find(net, usvc->af, usvc->fwmark); else svc = __ip_vs_service_find(net, usvc->af, usvc->protocol, &usvc->addr, usvc->port); *ret_svc = svc; /* If a full entry was requested, check for the additional fields */ if (full_entry) { struct nlattr *nla_sched, *nla_flags, *nla_pe, *nla_timeout, *nla_netmask; struct ip_vs_flags flags; nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME]; nla_pe = attrs[IPVS_SVC_ATTR_PE_NAME]; nla_flags = attrs[IPVS_SVC_ATTR_FLAGS]; nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT]; nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK]; if (!(nla_sched && nla_flags && nla_timeout && nla_netmask)) return -EINVAL; nla_memcpy(&flags, nla_flags, sizeof(flags)); /* prefill flags from service if it already exists */ if (svc) usvc->flags = svc->flags; /* set new flags from userland */ usvc->flags = (usvc->flags & ~flags.mask) | (flags.flags & flags.mask); usvc->sched_name = nla_data(nla_sched); usvc->pe_name = nla_pe ? nla_data(nla_pe) : NULL; usvc->timeout = nla_get_u32(nla_timeout); usvc->netmask = nla_get_u32(nla_netmask); } return 0; } Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT) If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is not set, __ip_vs_get_timeouts() does not fully initialize the structure that gets copied to userland and that for leaks up to 12 bytes of kernel stack. Add an explicit memset(0) before passing the structure to __ip_vs_get_timeouts() to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Wensong Zhang <[email protected]> Cc: Simon Horman <[email protected]> Cc: Julian Anastasov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ext4_set_inode_flags(struct inode *inode) { unsigned int flags = EXT4_I(inode)->i_flags; unsigned int new_fl = 0; if (flags & EXT4_SYNC_FL) new_fl |= S_SYNC; if (flags & EXT4_APPEND_FL) new_fl |= S_APPEND; if (flags & EXT4_IMMUTABLE_FL) new_fl |= S_IMMUTABLE; if (flags & EXT4_NOATIME_FL) new_fl |= S_NOATIME; if (flags & EXT4_DIRSYNC_FL) new_fl |= S_DIRSYNC; if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode)) new_fl |= S_DAX; inode_set_flags(inode, new_fl, S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX); } Commit Message: ext4: fix data exposure after a crash Huang has reported that in his powerfail testing he is seeing stale block contents in some of recently allocated blocks although he mounts ext4 in data=ordered mode. After some investigation I have found out that indeed when delayed allocation is used, we don't add inode to transaction's list of inodes needing flushing before commit. Originally we were doing that but commit f3b59291a69d removed the logic with a flawed argument that it is not needed. The problem is that although for delayed allocated blocks we write their contents immediately after allocating them, there is no guarantee that the IO scheduler or device doesn't reorder things and thus transaction allocating blocks and attaching them to inode can reach stable storage before actual block contents. Actually whenever we attach freshly allocated blocks to inode using a written extent, we should add inode to transaction's ordered inode list to make sure we properly wait for block contents to be written before committing the transaction. So that is what we do in this patch. This also handles other cases where stale data exposure was possible - like filling hole via mmap in data=ordered,nodelalloc mode. The only exception to the above rule are extending direct IO writes where blkdev_direct_IO() waits for IO to complete before increasing i_size and thus stale data exposure is not possible. For now we don't complicate the code with optimizing this special case since the overhead is pretty low. In case this is observed to be a performance problem we can always handle it using a special flag to ext4_map_blocks(). CC: [email protected] Fixes: f3b59291a69d0b734be1fc8be489fef2dd846d3d Reported-by: "HUANG Weller (CM/ESW12-CN)" <[email protected]> Tested-by: "HUANG Weller (CM/ESW12-CN)" <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ssize_t socket_write_and_transfer_fd(const socket_t *socket, const void *buf, size_t count, int fd) { assert(socket != NULL); assert(buf != NULL); if (fd == INVALID_FD) return socket_write(socket, buf, count); struct msghdr msg; struct iovec iov; char control_buf[CMSG_SPACE(sizeof(int))]; iov.iov_base = (void *)buf; iov.iov_len = count; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = control_buf; msg.msg_controllen = sizeof(control_buf); msg.msg_name = NULL; msg.msg_namelen = 0; struct cmsghdr *header = CMSG_FIRSTHDR(&msg); header->cmsg_level = SOL_SOCKET; header->cmsg_type = SCM_RIGHTS; header->cmsg_len = CMSG_LEN(sizeof(int)); *(int *)CMSG_DATA(header) = fd; ssize_t ret = sendmsg(socket->fd, &msg, MSG_DONTWAIT); close(fd); return ret; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 1 Example 2: Code: Page* Document::page() const { return m_frame ? m_frame->page() : 0; } Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document The member is used only in Document, thus no reason to stay in SecurityContext. TEST=none BUG=none [email protected], abarth, haraken, hayato Review URL: https://codereview.chromium.org/27615003 git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: next_format(png_bytep colour_type, png_bytep bit_depth, unsigned int* palette_number, int no_low_depth_gray) { if (*bit_depth == 0) { *colour_type = 0; if (no_low_depth_gray) *bit_depth = 8; else *bit_depth = 1; *palette_number = 0; return 1; } if (*colour_type == 3) { /* Add multiple palettes for colour type 3. */ if (++*palette_number < PALETTE_COUNT(*bit_depth)) return 1; *palette_number = 0; } *bit_depth = (png_byte)(*bit_depth << 1); /* Palette images are restricted to 8 bit depth */ if (*bit_depth <= 8 # ifdef DO_16BIT || (*colour_type != 3 && *bit_depth <= 16) # endif ) return 1; /* Move to the next color type, or return 0 at the end. */ switch (*colour_type) { case 0: *colour_type = 2; *bit_depth = 8; return 1; case 2: *colour_type = 3; *bit_depth = 1; return 1; case 3: *colour_type = 4; *bit_depth = 8; return 1; case 4: *colour_type = 6; *bit_depth = 8; return 1; default: return 0; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AutofillManager::OnLoadedAutofillHeuristics( const std::string& heuristic_xml) { UploadRequired upload_required; FormStructure::ParseQueryResponse(heuristic_xml, form_structures_.get(), &upload_required, *metric_logger_); } Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses BUG=84693 TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest Review URL: http://codereview.chromium.org/6969090 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static void ceph_key_destroy(struct key *key) { struct ceph_crypto_key *ckey = key->payload.data; ceph_crypto_key_destroy(ckey); kfree(ckey); } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void VectorClamp(DDSVector4 *value) { value->x = MinF(1.0f,MaxF(0.0f,value->x)); value->y = MinF(1.0f,MaxF(0.0f,value->y)); value->z = MinF(1.0f,MaxF(0.0f,value->z)); value->w = MinF(1.0f,MaxF(0.0f,value->w)); } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PlatformSensorProviderAndroid::CreateAbsoluteOrientationQuaternionSensor( JNIEnv* env, mojo::ScopedSharedBufferMapping mapping, const CreateSensorCallback& callback) { ScopedJavaLocalRef<jobject> sensor = Java_PlatformSensorProvider_createSensor( env, j_object_, static_cast<jint>(mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION)); if (sensor.obj()) { auto concrete_sensor = base::MakeRefCounted<PlatformSensorAndroid>( mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION, std::move(mapping), this, sensor); callback.Run(concrete_sensor); } else { auto sensor_fusion_algorithm = std::make_unique<OrientationQuaternionFusionAlgorithmUsingEulerAngles>( true /* absolute */); PlatformSensorFusion::Create(std::move(mapping), this, std::move(sensor_fusion_algorithm), callback); } } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Target: 1 Example 2: Code: CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = b ? cJSON_True : cJSON_False; } return item; } Commit Message: Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays CWE ID: CWE-754 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: viz::LocalSurfaceIdAllocation Compositor::RequestNewChildLocalSurfaceId() { const uint32_t child_sequence_number = host_->GenerateChildSurfaceSequenceNumberSync(); const viz::LocalSurfaceId current_id = host_->local_surface_id_allocation_from_parent().local_surface_id(); return viz::LocalSurfaceIdAllocation( viz::LocalSurfaceId(current_id.parent_sequence_number(), child_sequence_number, current_id.embed_token()), base::TimeTicks::Now()); } Commit Message: Fix PIP window being blank after minimize/show DesktopWindowTreeHostX11::SetVisible only made the call into OnNativeWidgetVisibilityChanged when transitioning from shown to minimized and not vice versa. This is because this change https://chromium-review.googlesource.com/c/chromium/src/+/1437263 considered IsVisible to be true when minimized, which made IsVisible always true in this case. This caused layers to be hidden but never shown again. This is a reland of: https://chromium-review.googlesource.com/c/chromium/src/+/1580103 Bug: 949199 Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617 Reviewed-by: Scott Violet <[email protected]> Commit-Queue: enne <[email protected]> Cr-Commit-Position: refs/heads/master@{#654280} CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int hugetlb_reserve_pages(struct inode *inode, long from, long to, struct vm_area_struct *vma, vm_flags_t vm_flags) { long ret, chg; struct hstate *h = hstate_inode(inode); struct hugepage_subpool *spool = subpool_inode(inode); /* * Only apply hugepage reservation if asked. At fault time, an * attempt will be made for VM_NORESERVE to allocate a page * without using reserves */ if (vm_flags & VM_NORESERVE) return 0; /* * Shared mappings base their reservation on the number of pages that * are already allocated on behalf of the file. Private mappings need * to reserve the full area even if read-only as mprotect() may be * called to make the mapping read-write. Assume !vma is a shm mapping */ if (!vma || vma->vm_flags & VM_MAYSHARE) chg = region_chg(&inode->i_mapping->private_list, from, to); else { struct resv_map *resv_map = resv_map_alloc(); if (!resv_map) return -ENOMEM; chg = to - from; set_vma_resv_map(vma, resv_map); set_vma_resv_flags(vma, HPAGE_RESV_OWNER); } if (chg < 0) return chg; /* There must be enough pages in the subpool for the mapping */ if (hugepage_subpool_get_pages(spool, chg)) return -ENOSPC; /* * Check enough hugepages are available for the reservation. * Hand the pages back to the subpool if there are not */ ret = hugetlb_acct_memory(h, chg); if (ret < 0) { hugepage_subpool_put_pages(spool, chg); return ret; } /* * Account for the reservations made. Shared mappings record regions * that have reservations as they are shared by multiple VMAs. * When the last VMA disappears, the region map says how much * the reservation was and the page cache tells how much of * the reservation was consumed. Private mappings are per-VMA and * only the consumed reservations are tracked. When the VMA * disappears, the original reservation is the VMA size and the * consumed reservations are stored in the map. Hence, nothing * else has to be done for private mappings here */ if (!vma || vma->vm_flags & VM_MAYSHARE) region_add(&inode->i_mapping->private_list, from, to); return 0; } Commit Message: hugetlb: fix resv_map leak in error path When called for anonymous (non-shared) mappings, hugetlb_reserve_pages() does a resv_map_alloc(). It depends on code in hugetlbfs's vm_ops->close() to release that allocation. However, in the mmap() failure path, we do a plain unmap_region() without the remove_vma() which actually calls vm_ops->close(). This is a decent fix. This leak could get reintroduced if new code (say, after hugetlb_reserve_pages() in hugetlbfs_file_mmap()) decides to return an error. But, I think it would have to unroll the reservation anyway. Christoph's test case: http://marc.info/?l=linux-mm&m=133728900729735 This patch applies to 3.4 and later. A version for earlier kernels is at https://lkml.org/lkml/2012/5/22/418. Signed-off-by: Dave Hansen <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: KOSAKI Motohiro <[email protected]> Reported-by: Christoph Lameter <[email protected]> Tested-by: Christoph Lameter <[email protected]> Cc: Andrea Arcangeli <[email protected]> Cc: <[email protected]> [2.6.32+] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static void stop_ep_timer(struct iwch_ep *ep) { PDBG("%s ep %p\n", __func__, ep); if (!timer_pending(&ep->timer)) { WARN(1, "%s timer stopped when its not running! ep %p state %u\n", __func__, ep, ep->com.state); return; } del_timer_sync(&ep->timer); put_ep(&ep->com); } Commit Message: iw_cxgb3: Fix incorrectly returning error on success The cxgb3_*_send() functions return NET_XMIT_ values, which are positive integers values. So don't treat positive return values as an error. Signed-off-by: Steve Wise <[email protected]> Signed-off-by: Hariprasad Shenai <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static gint read_all_used_files(GDataInputStream* f, MenuCache* cache, MenuCacheFileDir*** all_used_files) { char *line; gsize len; int i, n; MenuCacheFileDir** dirs; line = g_data_input_stream_read_line(f, &len, cache->cancellable, NULL); if(G_UNLIKELY(line == NULL)) return -1; n = atoi( line ); g_free(line); if (G_UNLIKELY(n <= 0)) return n; dirs = g_new0( MenuCacheFileDir *, n ); for( i = 0; i < n; ++i ) { line = g_data_input_stream_read_line(f, &len, cache->cancellable, NULL); if(G_UNLIKELY(line == NULL)) { while (i-- > 0) menu_cache_file_dir_unref(dirs[i]); g_free(dirs); return -1; } dirs[i] = g_new(MenuCacheFileDir, 1); dirs[i]->n_ref = 1; dirs[i]->dir = line; /* don't include \n */ } *all_used_files = dirs; return n; } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long long Block::GetTimeCode(const Cluster* pCluster) const { if (pCluster == 0) return m_timecode; const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; //unscaled timecode units } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev, struct rtnl_link_stats64 *storage) { const struct net_device_ops *ops = dev->netdev_ops; if (ops->ndo_get_stats64) { memset(storage, 0, sizeof(*storage)); ops->ndo_get_stats64(dev, storage); } else if (ops->ndo_get_stats) { netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev)); } else { netdev_stats_to_stats64(storage, &dev->stats); } storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped); storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped); storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler); return storage; } Commit Message: tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <[email protected]> Cc: Jason Wang <[email protected]> Cc: "Michael S. Tsirkin" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb, struct net_device *dev) { struct net_bridge *br = netdev_priv(dev); struct net_bridge_mdb_htable *mdb; struct nlattr *nest, *nest2; int i, err = 0; int idx = 0, s_idx = cb->args[1]; if (br->multicast_disabled) return 0; mdb = rcu_dereference(br->mdb); if (!mdb) return 0; nest = nla_nest_start(skb, MDBA_MDB); if (nest == NULL) return -EMSGSIZE; for (i = 0; i < mdb->max; i++) { struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p, **pp; struct net_bridge_port *port; hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) { if (idx < s_idx) goto skip; nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY); if (nest2 == NULL) { err = -EMSGSIZE; goto out; } for (pp = &mp->ports; (p = rcu_dereference(*pp)) != NULL; pp = &p->next) { port = p->port; if (port) { struct br_mdb_entry e; memset(&e, 0, sizeof(e)); e.ifindex = port->dev->ifindex; e.state = p->state; if (p->addr.proto == htons(ETH_P_IP)) e.addr.u.ip4 = p->addr.u.ip4; #if IS_ENABLED(CONFIG_IPV6) if (p->addr.proto == htons(ETH_P_IPV6)) e.addr.u.ip6 = p->addr.u.ip6; #endif e.addr.proto = p->addr.proto; if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) { nla_nest_cancel(skb, nest2); err = -EMSGSIZE; goto out; } } } nla_nest_end(skb, nest2); skip: idx++; } } out: cb->args[1] = idx; nla_nest_end(skb, nest); return err; } Commit Message: bridge: fix some kernel warning in multicast timer Several people reported the warning: "kernel BUG at kernel/timer.c:729!" and the stack trace is: #7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905 #8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge] #9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge] #10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge] #11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge] #12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc #13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6 #14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad #15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17 #16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68 #17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101 #18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8 #19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun] #20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun] #21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1 #22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe #23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f #24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1 #25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292 this is due to I forgot to check if mp->timer is armed in br_multicast_del_pg(). This bug is introduced by commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry when query is received). Same for __br_mdb_del(). Tested-by: poma <[email protected]> Reported-by: LiYonghua <[email protected]> Reported-by: Robert Hancock <[email protected]> Cc: Herbert Xu <[email protected]> Cc: Stephen Hemminger <[email protected]> Cc: "David S. Miller" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CameraSource::dataCallbackTimestamp(int64_t timestampUs, int32_t msgType __unused, const sp<IMemory> &data) { ALOGV("dataCallbackTimestamp: timestamp %lld us", (long long)timestampUs); Mutex::Autolock autoLock(mLock); if (!mStarted || (mNumFramesReceived == 0 && timestampUs < mStartTimeUs)) { ALOGV("Drop frame at %lld/%lld us", (long long)timestampUs, (long long)mStartTimeUs); releaseOneRecordingFrame(data); return; } if (skipCurrentFrame(timestampUs)) { releaseOneRecordingFrame(data); return; } if (mNumFramesReceived > 0) { if (timestampUs <= mLastFrameTimestampUs) { ALOGW("Dropping frame with backward timestamp %lld (last %lld)", (long long)timestampUs, (long long)mLastFrameTimestampUs); releaseOneRecordingFrame(data); return; } if (timestampUs - mLastFrameTimestampUs > mGlitchDurationThresholdUs) { ++mNumGlitches; } } mLastFrameTimestampUs = timestampUs; if (mNumFramesReceived == 0) { mFirstFrameTimeUs = timestampUs; if (mStartTimeUs > 0) { if (timestampUs < mStartTimeUs) { releaseOneRecordingFrame(data); return; } mStartTimeUs = timestampUs - mStartTimeUs; } } ++mNumFramesReceived; CHECK(data != NULL && data->size() > 0); mFramesReceived.push_back(data); int64_t timeUs = mStartTimeUs + (timestampUs - mFirstFrameTimeUs); mFrameTimes.push_back(timeUs); ALOGV("initial delay: %" PRId64 ", current time stamp: %" PRId64, mStartTimeUs, timeUs); mFrameAvailableCondition.signal(); } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200 Target: 1 Example 2: Code: void OxideQQuickWebView::setPreferences(OxideQWebPreferences* prefs) { Q_D(OxideQQuickWebView); if (prefs == this->preferences()) { return; } if (!d->proxy_) { d->construct_props_->preferences = prefs; } else { d->proxy_->setPreferences(prefs); } emit preferencesChanged(); } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void sas_ata_set_dmamode(struct ata_port *ap, struct ata_device *ata_dev) { struct domain_device *dev = ap->private_data; struct sas_internal *i = dev_to_sas_internal(dev); if (i->dft->lldd_ata_set_dmamode) i->dft->lldd_ata_set_dmamode(dev); } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); if ( p + num_groups * 12 > valid->limit ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: static bool SystemUsesChromiumEVMetadata() { #if defined(USE_OPENSSL) return false; #elif defined(OS_MACOSX) return false; #else return true; #endif } Commit Message: Tests were marked as Flaky. BUG=151811,151810 [email protected],[email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/10968052 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158204 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 [email protected] Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool GLES2DecoderImpl::CheckFramebufferValid( Framebuffer* framebuffer, GLenum target, const char* func_name) { if (!framebuffer) { if (backbuffer_needs_clear_bits_) { glClearColor(0, 0, 0, (GLES2Util::GetChannelsForFormat( offscreen_target_color_format_) & 0x0008) != 0 ? 0 : 1); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); glClear(backbuffer_needs_clear_bits_); backbuffer_needs_clear_bits_ = 0; RestoreClearState(); } return true; } if (framebuffer_manager()->IsComplete(framebuffer)) { return true; } GLenum completeness = framebuffer->IsPossiblyComplete(); if (completeness != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete"); return false; } if (renderbuffer_manager()->HaveUnclearedRenderbuffers() || texture_manager()->HaveUnclearedMips()) { if (!framebuffer->IsCleared()) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (clear)"); return false; } ClearUnclearedAttachments(target, framebuffer); } } if (!framebuffer_manager()->IsComplete(framebuffer)) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (check)"); return false; } framebuffer_manager()->MarkAsComplete(framebuffer); } return true; } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void Document::setContentLanguage(const String& language) { if (m_contentLanguage == language) return; m_contentLanguage = language; styleResolverChanged(DeferRecalcStyle); } Commit Message: Unreviewed, rolling out r147402. http://trac.webkit.org/changeset/147402 https://bugs.webkit.org/show_bug.cgi?id=112903 Source/WebCore: * dom/Document.cpp: (WebCore::Document::processHttpEquiv): * loader/DocumentLoader.cpp: (WebCore::DocumentLoader::responseReceived): LayoutTests: * http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html: * http/tests/security/XFrameOptions/x-frame-options-deny.html: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BaseRenderingContext2D::BaseRenderingContext2D() : clip_antialiasing_(kNotAntiAliased) { state_stack_.push_back(CanvasRenderingContext2DState::Create()); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <[email protected]> Commit-Queue: Chris Harrelson <[email protected]> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200 Target: 1 Example 2: Code: nfsd4_open_confirm(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open_confirm *oc) { __be32 status; struct nfs4_openowner *oo; struct nfs4_ol_stateid *stp; struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); dprintk("NFSD: nfsd4_open_confirm on file %pd\n", cstate->current_fh.fh_dentry); status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0); if (status) return status; status = nfs4_preprocess_seqid_op(cstate, oc->oc_seqid, &oc->oc_req_stateid, NFS4_OPEN_STID, &stp, nn); if (status) goto out; oo = openowner(stp->st_stateowner); status = nfserr_bad_stateid; if (oo->oo_flags & NFS4_OO_CONFIRMED) { mutex_unlock(&stp->st_mutex); goto put_stateid; } oo->oo_flags |= NFS4_OO_CONFIRMED; nfs4_inc_and_copy_stateid(&oc->oc_resp_stateid, &stp->st_stid); mutex_unlock(&stp->st_mutex); dprintk("NFSD: %s: success, seqid=%d stateid=" STATEID_FMT "\n", __func__, oc->oc_seqid, STATEID_VAL(&stp->st_stid.sc_stateid)); nfsd4_client_record_create(oo->oo_owner.so_client); status = nfs_ok; put_stateid: nfs4_put_stid(&stp->st_stid); out: nfsd4_bump_seqid(cstate, status); return status; } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::OnBeforeUnloadACK( bool proceed, const base::TimeTicks& renderer_before_unload_start_time, const base::TimeTicks& renderer_before_unload_end_time) { TRACE_EVENT_ASYNC_END1("navigation", "RenderFrameHostImpl BeforeUnload", this, "FrameTreeNode id", frame_tree_node_->frame_tree_node_id()); if (!is_waiting_for_beforeunload_ack_) { return; } DCHECK(!send_before_unload_start_time_.is_null()); base::TimeTicks before_unload_end_time = renderer_before_unload_end_time; if (!renderer_before_unload_start_time.is_null() && !renderer_before_unload_end_time.is_null()) { base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now(); if (!base::TimeTicks::IsConsistentAcrossProcesses()) { InterProcessTimeTicksConverter converter( LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_), LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time), RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time), RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time)); LocalTimeTicks browser_before_unload_end_time = converter.ToLocalTimeTicks( RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time)); before_unload_end_time = browser_before_unload_end_time.ToTimeTicks(); bool is_skew_additive = false; if (converter.IsSkewAdditiveForMetrics()) { is_skew_additive = true; base::TimeDelta skew = converter.GetSkewForMetrics(); if (skew >= base::TimeDelta()) { UMA_HISTOGRAM_TIMES( "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew); } else { UMA_HISTOGRAM_TIMES( "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew); } } UMA_HISTOGRAM_BOOLEAN( "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser", is_skew_additive); } base::TimeDelta on_before_unload_overhead_time = (receive_before_unload_ack_time - send_before_unload_start_time_) - (renderer_before_unload_end_time - renderer_before_unload_start_time); UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime", on_before_unload_overhead_time); frame_tree_node_->navigator()->LogBeforeUnloadTime( renderer_before_unload_start_time, renderer_before_unload_end_time); } is_waiting_for_beforeunload_ack_ = false; if (beforeunload_timeout_) beforeunload_timeout_->Stop(); send_before_unload_start_time_ = base::TimeTicks(); if (IsBrowserSideNavigationEnabled() && unload_ack_is_for_navigation_) { frame_tree_node_->navigator()->OnBeforeUnloadACK( frame_tree_node_, proceed); } else { frame_tree_node_->render_manager()->OnBeforeUnloadACK( unload_ack_is_for_navigation_, proceed, before_unload_end_time); } if (!proceed) render_view_host_->GetDelegate()->DidCancelLoading(); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif EVP_MD_CTX_init(&md_ctx); /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg_k & (SSL_kDHE|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (alg_k & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_a=s->s3->tmp.new_cipher->algorithm_auth; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kDHE) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* Check curve is one of our preferences, if not server has * sent an invalid curve. ECParameters is 3 bytes. */ if (!tls1_check_curve(s, p, 3)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE); goto f_err; } if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (SSL_USE_SIGALGS(s)) { int rv; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) goto err; else if (rv == 0) { goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { /* Might be wrong key type, check it */ if (ssl3_check_cert_and_algorithm(s)) /* Otherwise this shouldn't happen */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } Commit Message: Only allow ephemeral RSA keys in export ciphersuites. OpenSSL clients would tolerate temporary RSA keys in non-export ciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which enabled this server side. Remove both options as they are a protocol violation. Thanks to Karthikeyan Bhargavan for reporting this issue. (CVE-2015-0204) Reviewed-by: Matt Caswell <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: void AudioRendererHost::OnAssociateStreamWithProducer(int stream_id, int render_view_id) { DVLOG(1) << "AudioRendererHost@" << this << "::OnAssociateStreamWithProducer(stream_id=" << stream_id << ", render_view_id=" << render_view_id << ")"; } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) return; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 phaseFrac; EAS_I32 acc0; const EAS_SAMPLE *pSamples; EAS_I32 samp1; EAS_I32 samp2; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum; phaseFrac = (EAS_I32)pWTVoice->phaseFrac; /* fetch adjacent samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif while (numSamples--) { /* linear interpolation */ acc0 = samp2 - samp1; acc0 = acc0 * phaseFrac; /*lint -e{704} <avoid divide>*/ acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS); /* save new output sample in buffer */ /*lint -e{704} <avoid divide>*/ *pOutputBuffer++ = (EAS_I16)(acc0 >> 2); /* increment phase */ phaseFrac += phaseInc; /*lint -e{704} <avoid divide>*/ acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS; /* next sample */ if (acc0 > 0) { /* advance sample pointer */ pSamples += acc0; phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK); /* fetch new samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif } } /* save pointer and phase */ pWTVoice->phaseAccum = (EAS_U32) pSamples; pWTVoice->phaseFrac = (EAS_U32) phaseFrac; } Commit Message: Sonivox: sanity check numSamples. Bug: 26366256 Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc CWE ID: CWE-119 Target: 1 Example 2: Code: static void atl2_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct atl2_adapter *adapter = netdev_priv(netdev); wol->supported = WAKE_MAGIC; wol->wolopts = 0; if (adapter->wol & ATLX_WUFC_EX) wol->wolopts |= WAKE_UCAST; if (adapter->wol & ATLX_WUFC_MC) wol->wolopts |= WAKE_MCAST; if (adapter->wol & ATLX_WUFC_BC) wol->wolopts |= WAKE_BCAST; if (adapter->wol & ATLX_WUFC_MAG) wol->wolopts |= WAKE_MAGIC; if (adapter->wol & ATLX_WUFC_LNKC) wol->wolopts |= WAKE_PHY; } Commit Message: atl2: Disable unimplemented scatter/gather feature atl2 includes NETIF_F_SG in hw_features even though it has no support for non-linear skbs. This bug was originally harmless since the driver does not claim to implement checksum offload and that used to be a requirement for SG. Now that SG and checksum offload are independent features, if you explicitly enable SG *and* use one of the rare protocols that can use SG without checkusm offload, this potentially leaks sensitive information (before you notice that it just isn't working). Therefore this obscure bug has been designated CVE-2016-2117. Reported-by: Justin Yackoski <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> Fixes: ec5f06156423 ("net: Kill link between CSUM and SG features.") Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct sk_buff **udp_gro_receive(struct sk_buff **head, struct sk_buff *skb, struct udphdr *uh) { struct udp_offload_priv *uo_priv; struct sk_buff *p, **pp = NULL; struct udphdr *uh2; unsigned int off = skb_gro_offset(skb); int flush = 1; if (NAPI_GRO_CB(skb)->udp_mark || (skb->ip_summed != CHECKSUM_PARTIAL && NAPI_GRO_CB(skb)->csum_cnt == 0 && !NAPI_GRO_CB(skb)->csum_valid)) goto out; /* mark that this skb passed once through the udp gro layer */ NAPI_GRO_CB(skb)->udp_mark = 1; rcu_read_lock(); uo_priv = rcu_dereference(udp_offload_base); for (; uo_priv != NULL; uo_priv = rcu_dereference(uo_priv->next)) { if (net_eq(read_pnet(&uo_priv->net), dev_net(skb->dev)) && uo_priv->offload->port == uh->dest && uo_priv->offload->callbacks.gro_receive) goto unflush; } goto out_unlock; unflush: flush = 0; for (p = *head; p; p = p->next) { if (!NAPI_GRO_CB(p)->same_flow) continue; uh2 = (struct udphdr *)(p->data + off); /* Match ports and either checksums are either both zero * or nonzero. */ if ((*(u32 *)&uh->source != *(u32 *)&uh2->source) || (!uh->check ^ !uh2->check)) { NAPI_GRO_CB(p)->same_flow = 0; continue; } } skb_gro_pull(skb, sizeof(struct udphdr)); /* pull encapsulating udp header */ skb_gro_postpull_rcsum(skb, uh, sizeof(struct udphdr)); NAPI_GRO_CB(skb)->proto = uo_priv->offload->ipproto; pp = uo_priv->offload->callbacks.gro_receive(head, skb, uo_priv->offload); out_unlock: rcu_read_unlock(); out: NAPI_GRO_CB(skb)->flush |= flush; return pp; } Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation. When drivers express support for TSO of encapsulated packets, they only mean that they can do it for one layer of encapsulation. Supporting additional levels would mean updating, at a minimum, more IP length fields and they are unaware of this. No encapsulation device expresses support for handling offloaded encapsulated packets, so we won't generate these types of frames in the transmit path. However, GRO doesn't have a check for multiple levels of encapsulation and will attempt to build them. UDP tunnel GRO actually does prevent this situation but it only handles multiple UDP tunnels stacked on top of each other. This generalizes that solution to prevent any kind of tunnel stacking that would cause problems. Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack") Signed-off-by: Jesse Gross <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-400 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: server_input_global_request(int type, u_int32_t seq, void *ctxt) { char *rtype; int want_reply; int r, success = 0, allocated_listen_port = 0; struct sshbuf *resp = NULL; rtype = packet_get_string(NULL); want_reply = packet_get_char(); debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply); /* -R style forwarding */ if (strcmp(rtype, "tcpip-forward") == 0) { struct passwd *pw; struct Forward fwd; pw = the_authctxt->pw; if (pw == NULL || !the_authctxt->valid) fatal("server_input_global_request: no/invalid user"); memset(&fwd, 0, sizeof(fwd)); fwd.listen_host = packet_get_string(NULL); fwd.listen_port = (u_short)packet_get_int(); debug("server_input_global_request: tcpip-forward listen %s port %d", fwd.listen_host, fwd.listen_port); /* check permissions */ if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 || no_port_forwarding_flag || options.disable_forwarding || (!want_reply && fwd.listen_port == 0) || (fwd.listen_port != 0 && !bind_permitted(fwd.listen_port, pw->pw_uid))) { success = 0; packet_send_debug("Server has disabled port forwarding."); } else { /* Start listening on the port */ success = channel_setup_remote_fwd_listener(&fwd, &allocated_listen_port, &options.fwd_opts); } free(fwd.listen_host); if ((resp = sshbuf_new()) == NULL) fatal("%s: sshbuf_new", __func__); if (allocated_listen_port != 0 && (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0) fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r)); } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) { struct Forward fwd; memset(&fwd, 0, sizeof(fwd)); fwd.listen_host = packet_get_string(NULL); fwd.listen_port = (u_short)packet_get_int(); debug("%s: cancel-tcpip-forward addr %s port %d", __func__, fwd.listen_host, fwd.listen_port); success = channel_cancel_rport_listener(&fwd); free(fwd.listen_host); } else if (strcmp(rtype, "[email protected]") == 0) { struct Forward fwd; memset(&fwd, 0, sizeof(fwd)); fwd.listen_path = packet_get_string(NULL); debug("server_input_global_request: streamlocal-forward listen path %s", fwd.listen_path); /* check permissions */ if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0 || no_port_forwarding_flag || options.disable_forwarding) { success = 0; packet_send_debug("Server has disabled port forwarding."); } else { /* Start listening on the socket */ success = channel_setup_remote_fwd_listener( &fwd, NULL, &options.fwd_opts); } free(fwd.listen_path); } else if (strcmp(rtype, "[email protected]") == 0) { struct Forward fwd; memset(&fwd, 0, sizeof(fwd)); fwd.listen_path = packet_get_string(NULL); debug("%s: cancel-streamlocal-forward path %s", __func__, fwd.listen_path); success = channel_cancel_rport_listener(&fwd); free(fwd.listen_path); } else if (strcmp(rtype, "[email protected]") == 0) { no_more_sessions = 1; success = 1; } else if (strcmp(rtype, "[email protected]") == 0) { success = server_input_hostkeys_prove(&resp); } if (want_reply) { packet_start(success ? SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE); if (success && resp != NULL) ssh_packet_put_raw(active_state, sshbuf_ptr(resp), sshbuf_len(resp)); packet_send(); packet_write_wait(); } free(rtype); sshbuf_free(resp); return 0; } Commit Message: disable Unix-domain socket forwarding when privsep is disabled CWE ID: CWE-264 Target: 1 Example 2: Code: static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b) { a->tv_sec -= b->tv_sec; a->tv_nsec -= b->tv_nsec; if (a->tv_nsec < 0) { a->tv_nsec += 1000000000; a->tv_sec--; } } Commit Message: stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime. Might have introduced a memory leak, don't have time to check. :( Should the other hex2bin()'s be checked? Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this. CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void record_recent_object(struct object *obj, struct strbuf *path, const char *last, void *data) { sha1_array_append(&recent_objects, obj->oid.hash); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cmsPipeline* DefaultICCintents(cmsContext ContextID, cmsUInt32Number nProfiles, cmsUInt32Number TheIntents[], cmsHPROFILE hProfiles[], cmsBool BPC[], cmsFloat64Number AdaptationStates[], cmsUInt32Number dwFlags) { cmsPipeline* Lut = NULL; cmsPipeline* Result; cmsHPROFILE hProfile; cmsMAT3 m; cmsVEC3 off; cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut, CurrentColorSpace; cmsProfileClassSignature ClassSig; cmsUInt32Number i, Intent; if (nProfiles == 0) return NULL; Result = cmsPipelineAlloc(ContextID, 0, 0); if (Result == NULL) return NULL; CurrentColorSpace = cmsGetColorSpace(hProfiles[0]); for (i=0; i < nProfiles; i++) { cmsBool lIsDeviceLink, lIsInput; hProfile = hProfiles[i]; ClassSig = cmsGetDeviceClass(hProfile); lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass ); if ((i == 0) && !lIsDeviceLink) { lIsInput = TRUE; } else { lIsInput = (CurrentColorSpace != cmsSigXYZData) && (CurrentColorSpace != cmsSigLabData); } Intent = TheIntents[i]; if (lIsInput || lIsDeviceLink) { ColorSpaceIn = cmsGetColorSpace(hProfile); ColorSpaceOut = cmsGetPCS(hProfile); } else { ColorSpaceIn = cmsGetPCS(hProfile); ColorSpaceOut = cmsGetColorSpace(hProfile); } if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) { cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch"); goto Error; } if (lIsDeviceLink || ((ClassSig == cmsSigNamedColorClass) && (nProfiles == 1))) { Lut = _cmsReadDevicelinkLUT(hProfile, Intent); if (Lut == NULL) goto Error; if (ClassSig == cmsSigAbstractClass && i > 0) { if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error; } else { _cmsMAT3identity(&m); _cmsVEC3init(&off, 0, 0, 0); } if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error; } else { if (lIsInput) { Lut = _cmsReadInputLUT(hProfile, Intent); if (Lut == NULL) goto Error; } else { Lut = _cmsReadOutputLUT(hProfile, Intent); if (Lut == NULL) goto Error; if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error; if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error; } } if (!cmsPipelineCat(Result, Lut)) goto Error; cmsPipelineFree(Lut); CurrentColorSpace = ColorSpaceOut; } return Result; Error: cmsPipelineFree(Lut); if (Result != NULL) cmsPipelineFree(Result); return NULL; cmsUNUSED_PARAMETER(dwFlags); } Commit Message: Fix a double free on error recovering CWE ID: Target: 1 Example 2: Code: ResourcePriority ImageResource::PriorityFromObservers() { return GetContent()->PriorityFromObservers(); } Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin Partial revert of https://chromium-review.googlesource.com/535694. Bug: 799477 Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3 Reviewed-on: https://chromium-review.googlesource.com/898427 Commit-Queue: Hiroshige Hayashizaki <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Takeshi Yoshino <[email protected]> Cr-Commit-Position: refs/heads/master@{#535176} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static sk_sp<SkImage> premulSkImageToUnPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(input->width()) * info.bytesPerPixel()); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: m_authenticate(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *agent_p = NULL; struct Client *saslserv_p = NULL; /* They really should use CAP for their own sake. */ if(!IsCapable(source_p, CLICAP_SASL)) return 0; if (strlen(client_p->id) == 3) { exit_client(client_p, client_p, client_p, "Mixing client and server protocol"); return 0; } saslserv_p = find_named_client(ConfigFileEntry.sasl_service); if (saslserv_p == NULL || !IsService(saslserv_p)) { sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(source_p->localClient->sasl_complete) { *source_p->localClient->sasl_agent = '\0'; source_p->localClient->sasl_complete = 0; } if(strlen(parv[1]) > 400) { sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(!*source_p->id) { /* Allocate a UID. */ strcpy(source_p->id, generate_uid()); add_to_id_hash(source_p->id, source_p); } if(*source_p->localClient->sasl_agent) agent_p = find_id(source_p->localClient->sasl_agent); if(agent_p == NULL) { sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, source_p->host, source_p->sockhost); if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL) sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1], source_p->certfp); else sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1]); rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN); } else sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s", me.id, agent_p->servptr->name, source_p->id, agent_p->id, parv[1]); source_p->localClient->sasl_out++; return 0; } Commit Message: SASL: Disallow beginning : and space anywhere in AUTHENTICATE parameter This is a FIX FOR A SECURITY VULNERABILITY. All Charybdis users must apply this fix if you support SASL on your servers, or unload m_sasl.so in the meantime. CWE ID: CWE-285 Target: 1 Example 2: Code: static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageGaussianBlur(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } Commit Message: CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const { return readTypedVector(val, &Parcel::readUtf8FromUtf16); } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a (cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719) CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Dispatcher::AddStatus(const std::string& pattern) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendStatus, NULL); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: void WebsiteSettings::PresentSiteIdentity() { DCHECK_NE(site_identity_status_, SITE_IDENTITY_STATUS_UNKNOWN); DCHECK_NE(site_connection_status_, SITE_CONNECTION_STATUS_UNKNOWN); WebsiteSettingsUI::IdentityInfo info; if (site_identity_status_ == SITE_IDENTITY_STATUS_EV_CERT) info.site_identity = UTF16ToUTF8(organization_name()); else info.site_identity = site_url_.host(); info.connection_status = site_connection_status_; info.connection_status_description = UTF16ToUTF8(site_connection_details_); info.identity_status = site_identity_status_; info.identity_status_description = UTF16ToUTF8(site_identity_details_); info.cert_id = cert_id_; info.show_ssl_decision_revoke_button = show_ssl_decision_revoke_button_; ui_->SetIdentityInfo(info); } 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: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int fpr_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { #ifdef CONFIG_VSX double buf[33]; int i; #endif flush_fp_to_thread(target); #ifdef CONFIG_VSX /* copy to local buffer then write that out */ for (i = 0; i < 32 ; i++) buf[i] = target->thread.TS_FPR(i); memcpy(&buf[32], &target->thread.fpscr, sizeof(double)); return user_regset_copyout(&pos, &count, &kbuf, &ubuf, buf, 0, -1); #else BUILD_BUG_ON(offsetof(struct thread_struct, fpscr) != offsetof(struct thread_struct, TS_FPR(32))); return user_regset_copyout(&pos, &count, &kbuf, &ubuf, &target->thread.fpr, 0, -1); #endif } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void exit_sem(struct task_struct *tsk) { struct sem_undo_list *ulp; ulp = tsk->sysvsem.undo_list; if (!ulp) return; tsk->sysvsem.undo_list = NULL; if (!atomic_dec_and_test(&ulp->refcnt)) return; for (;;) { struct sem_array *sma; struct sem_undo *un; struct list_head tasks; int semid; int i; rcu_read_lock(); un = list_entry_rcu(ulp->list_proc.next, struct sem_undo, list_proc); if (&un->list_proc == &ulp->list_proc) semid = -1; else semid = un->semid; rcu_read_unlock(); if (semid == -1) break; sma = sem_lock_check(tsk->nsproxy->ipc_ns, un->semid); /* exit_sem raced with IPC_RMID, nothing to do */ if (IS_ERR(sma)) continue; un = __lookup_undo(ulp, semid); if (un == NULL) { /* exit_sem raced with IPC_RMID+semget() that created * exactly the same semid. Nothing to do. */ sem_unlock(sma); continue; } /* remove un from the linked lists */ assert_spin_locked(&sma->sem_perm.lock); list_del(&un->list_id); spin_lock(&ulp->lock); list_del_rcu(&un->list_proc); spin_unlock(&ulp->lock); /* perform adjustments registered in un */ for (i = 0; i < sma->sem_nsems; i++) { struct sem * semaphore = &sma->sem_base[i]; if (un->semadj[i]) { semaphore->semval += un->semadj[i]; /* * Range checks of the new semaphore value, * not defined by sus: * - Some unices ignore the undo entirely * (e.g. HP UX 11i 11.22, Tru64 V5.1) * - some cap the value (e.g. FreeBSD caps * at 0, but doesn't enforce SEMVMX) * * Linux caps the semaphore value, both at 0 * and at SEMVMX. * * Manfred <[email protected]> */ if (semaphore->semval < 0) semaphore->semval = 0; if (semaphore->semval > SEMVMX) semaphore->semval = SEMVMX; semaphore->sempid = task_tgid_vnr(current); } } /* maybe some queued-up processes were waiting for this */ INIT_LIST_HEAD(&tasks); do_smart_update(sma, NULL, 0, 1, &tasks); sem_unlock(sma); wake_up_sem_queue_do(&tasks); kfree_rcu(un, rcu); } kfree(ulp); } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: static void coroutine_fn v9fs_rename(void *opaque) { int32_t fid; ssize_t err = 0; size_t offset = 7; V9fsString name; int32_t newdirfid; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dds", &fid, &newdirfid, &name); if (err < 0) { goto out_nofid; } if (name_is_illegal(name.data)) { err = -ENOENT; goto out_nofid; } if (!strcmp(".", name.data) || !strcmp("..", name.data)) { err = -EISDIR; goto out_nofid; } fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; } if (fidp->fid_type != P9_FID_NONE) { err = -EINVAL; goto out; } /* if fs driver is not path based, return EOPNOTSUPP */ if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) { err = -EOPNOTSUPP; goto out; } v9fs_path_write_lock(s); err = v9fs_complete_rename(pdu, fidp, newdirfid, &name); v9fs_path_unlock(s); if (!err) { err = offset; } out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&name); } Commit Message: CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ Commit Message: CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock_iocb *siocb = kiocb_to_siocb(kiocb); struct scm_cookie scm; struct sock *sk = sock->sk; struct netlink_sock *nlk = nlk_sk(sk); int noblock = flags&MSG_DONTWAIT; size_t copied; struct sk_buff *skb, *data_skb; int err, ret; if (flags&MSG_OOB) return -EOPNOTSUPP; copied = 0; skb = skb_recv_datagram(sk, flags, noblock, &err); if (skb == NULL) goto out; data_skb = skb; #ifdef CONFIG_COMPAT_NETLINK_MESSAGES if (unlikely(skb_shinfo(skb)->frag_list)) { /* * If this skb has a frag_list, then here that means that we * will have to use the frag_list skb's data for compat tasks * and the regular skb's data for normal (non-compat) tasks. * * If we need to send the compat skb, assign it to the * 'data_skb' variable so that it will be used below for data * copying. We keep 'skb' for everything else, including * freeing both later. */ if (flags & MSG_CMSG_COMPAT) data_skb = skb_shinfo(skb)->frag_list; } #endif msg->msg_namelen = 0; copied = data_skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(data_skb); err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied); if (msg->msg_name) { struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name; addr->nl_family = AF_NETLINK; addr->nl_pad = 0; addr->nl_pid = NETLINK_CB(skb).portid; addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group); msg->msg_namelen = sizeof(*addr); } if (nlk->flags & NETLINK_RECV_PKTINFO) netlink_cmsg_recv_pktinfo(msg, skb); if (NULL == siocb->scm) { memset(&scm, 0, sizeof(scm)); siocb->scm = &scm; } siocb->scm->creds = *NETLINK_CREDS(skb); if (flags & MSG_TRUNC) copied = data_skb->len; skb_free_datagram(sk, skb); if (nlk->cb_running && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) { ret = netlink_dump(sk); if (ret) { sk->sk_err = ret; sk->sk_error_report(sk); } } scm_recv(sock, msg, siocb->scm, flags); out: netlink_rcv_wake(sk); return err ? : copied; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static uint32_t PushImpl(Handle<JSArray> receiver, Arguments* args, uint32_t push_size) { Handle<FixedArrayBase> backing_store(receiver->elements()); return Subclass::AddArguments(receiver, backing_store, args, push_size, AT_END); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hid_start_in(struct hid_device *hid) { unsigned long flags; int rc = 0; struct usbhid_device *usbhid = hid->driver_data; spin_lock_irqsave(&usbhid->lock, flags); if (test_bit(HID_IN_POLLING, &usbhid->iofl) && !test_bit(HID_DISCONNECTED, &usbhid->iofl) && !test_bit(HID_SUSPENDED, &usbhid->iofl) && !test_and_set_bit(HID_IN_RUNNING, &usbhid->iofl)) { rc = usb_submit_urb(usbhid->urbin, GFP_ATOMIC); if (rc != 0) { clear_bit(HID_IN_RUNNING, &usbhid->iofl); if (rc == -ENOSPC) set_bit(HID_NO_BANDWIDTH, &usbhid->iofl); } else { clear_bit(HID_NO_BANDWIDTH, &usbhid->iofl); } } spin_unlock_irqrestore(&usbhid->lock, flags); return rc; } Commit Message: HID: usbhid: fix out-of-bounds bug The hid descriptor identifies the length and type of subordinate descriptors for a device. If the received hid descriptor is smaller than the size of the struct hid_descriptor, it is possible to cause out-of-bounds. In addition, if bNumDescriptors of the hid descriptor have an incorrect value, this can also cause out-of-bounds while approaching hdesc->desc[n]. So check the size of hid descriptor and bNumDescriptors. BUG: KASAN: slab-out-of-bounds in usbhid_parse+0x9b1/0xa20 Read of size 1 at addr ffff88006c5f8edf by task kworker/1:2/1261 CPU: 1 PID: 1261 Comm: kworker/1:2 Not tainted 4.14.0-rc1-42251-gebb2c2437d80 #169 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 Workqueue: usb_hub_wq hub_event Call Trace: __dump_stack lib/dump_stack.c:16 dump_stack+0x292/0x395 lib/dump_stack.c:52 print_address_description+0x78/0x280 mm/kasan/report.c:252 kasan_report_error mm/kasan/report.c:351 kasan_report+0x22f/0x340 mm/kasan/report.c:409 __asan_report_load1_noabort+0x19/0x20 mm/kasan/report.c:427 usbhid_parse+0x9b1/0xa20 drivers/hid/usbhid/hid-core.c:1004 hid_add_device+0x16b/0xb30 drivers/hid/hid-core.c:2944 usbhid_probe+0xc28/0x1100 drivers/hid/usbhid/hid-core.c:1369 usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26e/0x3d0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932 generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174 usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26e/0x3d0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457 hub_port_connect drivers/usb/core/hub.c:4903 hub_port_connect_change drivers/usb/core/hub.c:5009 port_event drivers/usb/core/hub.c:5115 hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195 process_one_work+0xc7f/0x1db0 kernel/workqueue.c:2119 worker_thread+0x221/0x1850 kernel/workqueue.c:2253 kthread+0x3a1/0x470 kernel/kthread.c:231 ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431 Cc: [email protected] Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Jaejoong Kim <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Acked-by: Alan Stern <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: start_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { bmp_source_ptr source = (bmp_source_ptr)sinfo; U_CHAR bmpfileheader[14]; U_CHAR bmpinfoheader[64]; #define GET_2B(array, offset) \ ((unsigned short)UCH(array[offset]) + \ (((unsigned short)UCH(array[offset + 1])) << 8)) #define GET_4B(array, offset) \ ((unsigned int)UCH(array[offset]) + \ (((unsigned int)UCH(array[offset + 1])) << 8) + \ (((unsigned int)UCH(array[offset + 2])) << 16) + \ (((unsigned int)UCH(array[offset + 3])) << 24)) unsigned int bfOffBits; unsigned int headerSize; int biWidth; int biHeight; unsigned short biPlanes; unsigned int biCompression; int biXPelsPerMeter, biYPelsPerMeter; unsigned int biClrUsed = 0; int mapentrysize = 0; /* 0 indicates no colormap */ int bPad; JDIMENSION row_width = 0; /* Read and verify the bitmap file header */ if (!ReadOK(source->pub.input_file, bmpfileheader, 14)) ERREXIT(cinfo, JERR_INPUT_EOF); if (GET_2B(bmpfileheader, 0) != 0x4D42) /* 'BM' */ ERREXIT(cinfo, JERR_BMP_NOT); bfOffBits = GET_4B(bmpfileheader, 10); /* We ignore the remaining fileheader fields */ /* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows), * or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which. */ if (!ReadOK(source->pub.input_file, bmpinfoheader, 4)) ERREXIT(cinfo, JERR_INPUT_EOF); headerSize = GET_4B(bmpinfoheader, 0); if (headerSize < 12 || headerSize > 64) ERREXIT(cinfo, JERR_BMP_BADHEADER); if (!ReadOK(source->pub.input_file, bmpinfoheader + 4, headerSize - 4)) ERREXIT(cinfo, JERR_INPUT_EOF); switch (headerSize) { case 12: /* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */ biWidth = (int)GET_2B(bmpinfoheader, 4); biHeight = (int)GET_2B(bmpinfoheader, 6); biPlanes = GET_2B(bmpinfoheader, 8); source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 10); switch (source->bits_per_pixel) { case 8: /* colormapped image */ mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */ TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, biWidth, biHeight); break; case 24: /* RGB image */ TRACEMS2(cinfo, 1, JTRC_BMP_OS2, biWidth, biHeight); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); break; } break; case 40: case 64: /* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */ /* or OS/2 2.x header, which has additional fields that we ignore */ biWidth = (int)GET_4B(bmpinfoheader, 4); biHeight = (int)GET_4B(bmpinfoheader, 8); biPlanes = GET_2B(bmpinfoheader, 12); source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 14); biCompression = GET_4B(bmpinfoheader, 16); biXPelsPerMeter = (int)GET_4B(bmpinfoheader, 24); biYPelsPerMeter = (int)GET_4B(bmpinfoheader, 28); biClrUsed = GET_4B(bmpinfoheader, 32); /* biSizeImage, biClrImportant fields are ignored */ switch (source->bits_per_pixel) { case 8: /* colormapped image */ mapentrysize = 4; /* Windows uses RGBQUAD colormap */ TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, biWidth, biHeight); break; case 24: /* RGB image */ TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight); break; case 32: /* RGB image + Alpha channel */ TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); break; } if (biCompression != 0) ERREXIT(cinfo, JERR_BMP_COMPRESSED); if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) { /* Set JFIF density parameters from the BMP data */ cinfo->X_density = (UINT16)(biXPelsPerMeter / 100); /* 100 cm per meter */ cinfo->Y_density = (UINT16)(biYPelsPerMeter / 100); cinfo->density_unit = 2; /* dots/cm */ } break; default: ERREXIT(cinfo, JERR_BMP_BADHEADER); return; } if (biWidth <= 0 || biHeight <= 0) ERREXIT(cinfo, JERR_BMP_EMPTY); if (biPlanes != 1) ERREXIT(cinfo, JERR_BMP_BADPLANES); /* Compute distance to bitmap data --- will adjust for colormap below */ bPad = bfOffBits - (headerSize + 14); /* Read the colormap, if any */ if (mapentrysize > 0) { if (biClrUsed <= 0) biClrUsed = 256; /* assume it's 256 */ else if (biClrUsed > 256) ERREXIT(cinfo, JERR_BMP_BADCMAP); /* Allocate space to store the colormap */ source->colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)biClrUsed, (JDIMENSION)3); /* and read it from the file */ read_colormap(source, (int)biClrUsed, mapentrysize); /* account for size of colormap */ bPad -= biClrUsed * mapentrysize; } /* Skip any remaining pad bytes */ if (bPad < 0) /* incorrect bfOffBits value? */ ERREXIT(cinfo, JERR_BMP_BADHEADER); while (--bPad >= 0) { (void)read_byte(source); } /* Compute row width in file, including padding to 4-byte boundary */ switch (source->bits_per_pixel) { case 8: if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_RGB; if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_GRAYSCALE) cinfo->input_components = 1; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); row_width = (JDIMENSION)biWidth; break; case 24: if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_BGR; if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); row_width = (JDIMENSION)(biWidth * 3); break; case 32: if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_BGRA; if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); row_width = (JDIMENSION)(biWidth * 4); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); } while ((row_width & 3) != 0) row_width++; source->row_width = row_width; if (source->use_inversion_array) { /* Allocate space for inversion array, prepare for preload pass */ source->whole_image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE, row_width, (JDIMENSION)biHeight, (JDIMENSION)1); source->pub.get_pixel_rows = preload_image; if (cinfo->progress != NULL) { cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress; progress->total_extra_passes++; /* count file input as separate pass */ } } else { source->iobuffer = (U_CHAR *) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, row_width); switch (source->bits_per_pixel) { case 8: source->pub.get_pixel_rows = get_8bit_row; break; case 24: source->pub.get_pixel_rows = get_24bit_row; break; case 32: source->pub.get_pixel_rows = get_32bit_row; break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); } } /* Allocate one-row buffer for returned data */ source->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)(biWidth * cinfo->input_components), (JDIMENSION)1); source->pub.buffer_height = 1; cinfo->data_precision = 8; cinfo->image_width = (JDIMENSION)biWidth; cinfo->image_height = (JDIMENSION)biHeight; } Commit Message: tjLoadImage(): Fix FPE triggered by malformed BMP In rdbmp.c, it is necessary to guard against 32-bit overflow/wraparound when allocating the row buffer, because since BMP files have 32-bit width and height fields, the value of biWidth can be up to 4294967295. Specifically, if biWidth is 1073741824 and cinfo->input_components = 4, then the samplesperrow argument in alloc_sarray() would wrap around to 0, and a division by zero error would occur at line 458 in jmemmgr.c. If biWidth is set to a higher value, then samplesperrow would wrap around to a small number, which would likely cause a buffer overflow (this has not been tested or verified.) CWE ID: CWE-369 Target: 1 Example 2: Code: GLenum GLES2DecoderImpl::AdjustGetPname(GLenum pname) { if (GL_MAX_SAMPLES == pname && features().use_img_for_multisampled_render_to_texture) { return GL_MAX_SAMPLES_IMG; } return pname; } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { static const int intoffset[] = { 0, 4, 2, 1 }; static const int intjump[] = { 8, 8, 4, 2 }; int rc; DATA32 *ptr; GifFileType *gif; GifRowType *rows; GifRecordType rec; ColorMapObject *cmap; int i, j, done, bg, r, g, b, w = 0, h = 0; float per = 0.0, per_inc; int last_per = 0, last_y = 0; int transp; int fd; done = 0; rows = NULL; transp = -1; /* if immediate_load is 1, then dont delay image laoding as below, or */ /* already data in this image - dont load it again */ if (im->data) return 0; fd = open(im->real_file, O_RDONLY); if (fd < 0) return 0; #if GIFLIB_MAJOR >= 5 gif = DGifOpenFileHandle(fd, NULL); #else gif = DGifOpenFileHandle(fd); #endif if (!gif) { close(fd); return 0; } rc = 0; /* Failure */ do { if (DGifGetRecordType(gif, &rec) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(gif) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } w = gif->Image.Width; h = gif->Image.Height; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit2; rows = calloc(h, sizeof(GifRowType *)); if (!rows) goto quit2; for (i = 0; i < h; i++) { rows[i] = malloc(w * sizeof(GifPixelType)); if (!rows[i]) goto quit; } if (gif->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(gif, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(gif, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; GifByteType *ext; ext = NULL; DGifGetExtension(gif, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(gif, &ext); } } } while (rec != TERMINATE_RECORD_TYPE); if (transp >= 0) { SET_FLAG(im->flags, F_HAS_ALPHA); } else { UNSET_FLAG(im->flags, F_HAS_ALPHA); } /* set the format string member to the lower-case full extension */ /* name for the format - so example names would be: */ /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ im->w = w; im->h = h; if (!im->format) im->format = strdup("gif"); if (im->loader || immediate_load || progress) { bg = gif->SBackGroundColor; cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); if (!im->data) goto quit; ptr = im->data; per_inc = 100.0 / (((float)w) * h); for (i = 0; i < h; i++) *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; } per += per_inc; if (progress && (((int)per) != last_per) && (((int)per) % progress_granularity == 0)) { last_per = (int)per; if (!(progress(im, (int)per, 0, last_y, w, i))) { rc = 2; goto quit; } last_y = i; } } Commit Message: CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void _xml_unparsedEntityDeclHandler(void *userData, const XML_Char *entityName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName) { xml_parser *parser = (xml_parser *)userData; if (parser && parser->unparsedEntityDeclHandler) { zval *retval, *args[6]; args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding); args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding); args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding); args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding); args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) { zval_ptr_dtor(&retval); } } } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: base::WeakPtr<JsController> ProfileSyncService::GetJsController() { return sync_js_controller_.AsWeakPtr(); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) { struct r_bin_dyldcache_obj_t *bin; if (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) { return NULL; } memset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t)); if (!buf) { return r_bin_dyldcache_free (bin); } bin->b = r_buf_new(); if (!r_buf_set_bytes (bin->b, buf, size)) { return r_bin_dyldcache_free (bin); } if (!r_bin_dyldcache_init (bin)) { return r_bin_dyldcache_free (bin); } bin->size = size; return bin; } Commit Message: Fix #12374 - oobread crash in truncated dyldcache ##bin CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, SplashCoord *mat, GBool glyphMode) { SplashBitmap *scaledMask; SplashClipResult clipRes, clipRes2; SplashPipe pipe; int scaledWidth, scaledHeight, t0, t1; SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11; SplashCoord vx[4], vy[4]; int xMin, yMin, xMax, yMax; ImageSection section[3]; int nSections; int y, xa, xb, x, i, xx, yy; vx[0] = mat[4]; vy[0] = mat[5]; vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5]; vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5]; vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5]; xMin = imgCoordMungeLowerC(vx[0], glyphMode); xMax = imgCoordMungeUpperC(vx[0], glyphMode); yMin = imgCoordMungeLowerC(vy[0], glyphMode); yMax = imgCoordMungeUpperC(vy[0], glyphMode); for (i = 1; i < 4; ++i) { t0 = imgCoordMungeLowerC(vx[i], glyphMode); if (t0 < xMin) { xMin = t0; } t0 = imgCoordMungeUpperC(vx[i], glyphMode); if (t0 > xMax) { xMax = t0; } t1 = imgCoordMungeLowerC(vy[i], glyphMode); if (t1 < yMin) { yMin = t1; } t1 = imgCoordMungeUpperC(vy[i], glyphMode); if (t1 > yMax) { yMax = t1; } } clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1); opClipRes = clipRes; if (clipRes == splashClipAllOutside) { return; } if (mat[0] >= 0) { t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) - imgCoordMungeLowerC(mat[4], glyphMode); } else { t0 = imgCoordMungeUpperC(mat[4], glyphMode) - imgCoordMungeLowerC(mat[0] + mat[4], glyphMode); } if (mat[1] >= 0) { t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) - imgCoordMungeLowerC(mat[5], glyphMode); } else { t1 = imgCoordMungeUpperC(mat[5], glyphMode) - imgCoordMungeLowerC(mat[1] + mat[5], glyphMode); } scaledWidth = t0 > t1 ? t0 : t1; if (mat[2] >= 0) { t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) - imgCoordMungeLowerC(mat[4], glyphMode); } else { t0 = imgCoordMungeUpperC(mat[4], glyphMode) - imgCoordMungeLowerC(mat[2] + mat[4], glyphMode); } if (mat[3] >= 0) { t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) - imgCoordMungeLowerC(mat[5], glyphMode); } else { t1 = imgCoordMungeUpperC(mat[5], glyphMode) - imgCoordMungeLowerC(mat[3] + mat[5], glyphMode); } scaledHeight = t0 > t1 ? t0 : t1; if (scaledWidth == 0) { scaledWidth = 1; } if (scaledHeight == 0) { scaledHeight = 1; } r00 = mat[0] / scaledWidth; r01 = mat[1] / scaledWidth; r10 = mat[2] / scaledHeight; r11 = mat[3] / scaledHeight; det = r00 * r11 - r01 * r10; if (splashAbs(det) < 1e-6) { return; } ir00 = r11 / det; ir01 = -r01 / det; ir10 = -r10 / det; ir11 = r00 / det; scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, scaledWidth, scaledHeight); if (scaledMask->data == NULL) { error(errInternal, -1, "scaledMask->data is NULL in Splash::scaleMaskYuXu"); delete scaledMask; return; } i = (vy[2] <= vy[3]) ? 2 : 3; if (vy[1] <= vy[i]) { i = 1; } if (vy[0] < vy[i] || (i != 3 && vy[0] == vy[i])) { i = 0; } if (vy[i] == vy[(i+1) & 3]) { section[0].y0 = imgCoordMungeLowerC(vy[i], glyphMode); section[0].y1 = imgCoordMungeUpperC(vy[(i+2) & 3], glyphMode) - 1; if (vx[i] < vx[(i+1) & 3]) { section[0].ia0 = i; section[0].ia1 = (i+3) & 3; section[0].ib0 = (i+1) & 3; section[0].ib1 = (i+2) & 3; } else { section[0].ia0 = (i+1) & 3; section[0].ia1 = (i+2) & 3; section[0].ib0 = i; section[0].ib1 = (i+3) & 3; } nSections = 1; } else { section[0].y0 = imgCoordMungeLowerC(vy[i], glyphMode); section[2].y1 = imgCoordMungeUpperC(vy[(i+2) & 3], glyphMode) - 1; section[0].ia0 = section[0].ib0 = i; section[2].ia1 = section[2].ib1 = (i+2) & 3; if (vx[(i+1) & 3] < vx[(i+3) & 3]) { section[0].ia1 = section[2].ia0 = (i+1) & 3; section[0].ib1 = section[2].ib0 = (i+3) & 3; } else { section[0].ia1 = section[2].ia0 = (i+3) & 3; section[0].ib1 = section[2].ib0 = (i+1) & 3; } if (vy[(i+1) & 3] < vy[(i+3) & 3]) { section[1].y0 = imgCoordMungeLowerC(vy[(i+1) & 3], glyphMode); section[2].y0 = imgCoordMungeUpperC(vy[(i+3) & 3], glyphMode); if (vx[(i+1) & 3] < vx[(i+3) & 3]) { section[1].ia0 = (i+1) & 3; section[1].ia1 = (i+2) & 3; section[1].ib0 = i; section[1].ib1 = (i+3) & 3; } else { section[1].ia0 = i; section[1].ia1 = (i+3) & 3; section[1].ib0 = (i+1) & 3; section[1].ib1 = (i+2) & 3; } } else { section[1].y0 = imgCoordMungeLowerC(vy[(i+3) & 3], glyphMode); section[2].y0 = imgCoordMungeUpperC(vy[(i+1) & 3], glyphMode); if (vx[(i+1) & 3] < vx[(i+3) & 3]) { section[1].ia0 = i; section[1].ia1 = (i+1) & 3; section[1].ib0 = (i+3) & 3; section[1].ib1 = (i+2) & 3; } else { section[1].ia0 = (i+3) & 3; section[1].ia1 = (i+2) & 3; section[1].ib0 = i; section[1].ib1 = (i+1) & 3; } } section[0].y1 = section[1].y0 - 1; section[1].y1 = section[2].y0 - 1; nSections = 3; } for (i = 0; i < nSections; ++i) { section[i].xa0 = vx[section[i].ia0]; section[i].ya0 = vy[section[i].ia0]; section[i].xa1 = vx[section[i].ia1]; section[i].ya1 = vy[section[i].ia1]; section[i].xb0 = vx[section[i].ib0]; section[i].yb0 = vy[section[i].ib0]; section[i].xb1 = vx[section[i].ib1]; section[i].yb1 = vy[section[i].ib1]; section[i].dxdya = (section[i].xa1 - section[i].xa0) / (section[i].ya1 - section[i].ya0); section[i].dxdyb = (section[i].xb1 - section[i].xb0) / (section[i].yb1 - section[i].yb0); } pipeInit(&pipe, 0, 0, state->fillPattern, NULL, (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); if (vectorAntialias) { drawAAPixelInit(); } if (nSections == 1) { if (section[0].y0 == section[0].y1) { ++section[0].y1; clipRes = opClipRes = splashClipPartial; } } else { if (section[0].y0 == section[2].y1) { ++section[1].y1; clipRes = opClipRes = splashClipPartial; } } for (i = 0; i < nSections; ++i) { for (y = section[i].y0; y <= section[i].y1; ++y) { xa = imgCoordMungeLowerC(section[i].xa0 + ((SplashCoord)y + 0.5 - section[i].ya0) * section[i].dxdya, glyphMode); xb = imgCoordMungeUpperC(section[i].xb0 + ((SplashCoord)y + 0.5 - section[i].yb0) * section[i].dxdyb, glyphMode); if (xa == xb) { ++xb; } if (clipRes != splashClipAllInside) { clipRes2 = state->clip->testSpan(xa, xb - 1, y); } else { clipRes2 = clipRes; } for (x = xa; x < xb; ++x) { xx = splashFloor(((SplashCoord)x + 0.5 - mat[4]) * ir00 + ((SplashCoord)y + 0.5 - mat[5]) * ir10); yy = splashFloor(((SplashCoord)x + 0.5 - mat[4]) * ir01 + ((SplashCoord)y + 0.5 - mat[5]) * ir11); if (xx < 0) { xx = 0; } else if (xx >= scaledWidth) { xx = scaledWidth - 1; } if (yy < 0) { yy = 0; } else if (yy >= scaledHeight) { yy = scaledHeight - 1; } pipe.shape = scaledMask->data[yy * scaledWidth + xx]; if (vectorAntialias && clipRes2 != splashClipAllInside) { drawAAPixel(&pipe, x, y); } else { drawPixel(&pipe, x, y, clipRes2 == splashClipAllInside); } } } } delete scaledMask; } Commit Message: CWE ID: Target: 1 Example 2: Code: LayoutUnit LayoutBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const { if (m_floatingObjects && m_floatingObjects->hasLeftObjects()) return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight); return fixedOffset; } Commit Message: Consistently check if a block can handle pagination strut propagation. https://codereview.chromium.org/1360753002 got it right for inline child layout, but did nothing for block child layout. BUG=329421 [email protected],[email protected] Review URL: https://codereview.chromium.org/1387553002 Cr-Commit-Position: refs/heads/master@{#352429} CWE ID: CWE-22 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int srpt_release_sdev(struct srpt_device *sdev) { struct srpt_rdma_ch *ch, *tmp_ch; int res; WARN_ON_ONCE(irqs_disabled()); BUG_ON(!sdev); spin_lock_irq(&sdev->spinlock); list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) __srpt_close_ch(ch); spin_unlock_irq(&sdev->spinlock); res = wait_event_interruptible(sdev->ch_releaseQ, srpt_ch_list_empty(sdev)); if (res) pr_err("%s: interrupted.\n", __func__); return 0; } Commit Message: IB/srpt: Simplify srpt_handle_tsk_mgmt() Let the target core check task existence instead of the SRP target driver. Additionally, let the target core check the validity of the task management request instead of the ib_srpt driver. This patch fixes the following kernel crash: BUG: unable to handle kernel NULL pointer dereference at 0000000000000001 IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt] Oops: 0002 [#1] SMP Call Trace: [<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt] [<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt] [<ffffffff8109726f>] kthread+0xcf/0xe0 [<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0 Signed-off-by: Bart Van Assche <[email protected]> Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr") Tested-by: Alex Estrin <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Cc: Nicholas Bellinger <[email protected]> Cc: Sagi Grimberg <[email protected]> Cc: stable <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool_t auth_gssapi_unwrap_data( OM_uint32 *major, OM_uint32 *minor, gss_ctx_id_t context, uint32_t seq_num, XDR *in_xdrs, bool_t (*xdr_func)(), caddr_t xdr_ptr) { gss_buffer_desc in_buf, out_buf; XDR temp_xdrs; uint32_t verf_seq_num; int conf, qop; unsigned int length; PRINTF(("gssapi_unwrap_data: starting\n")); *major = GSS_S_COMPLETE; *minor = 0; /* assumption */ in_buf.value = NULL; out_buf.value = NULL; if (! xdr_bytes(in_xdrs, (char **) &in_buf.value, &length, (unsigned int) -1)) { PRINTF(("gssapi_unwrap_data: deserializing encrypted data failed\n")); temp_xdrs.x_op = XDR_FREE; (void)xdr_bytes(&temp_xdrs, (char **) &in_buf.value, &length, (unsigned int) -1); return FALSE; } in_buf.length = length; *major = gss_unseal(minor, context, &in_buf, &out_buf, &conf, &qop); free(in_buf.value); if (*major != GSS_S_COMPLETE) return FALSE; PRINTF(("gssapi_unwrap_data: %llu bytes data, %llu bytes sealed\n", (unsigned long long)out_buf.length, (unsigned long long)in_buf.length)); xdrmem_create(&temp_xdrs, out_buf.value, out_buf.length, XDR_DECODE); /* deserialize the sequence number */ if (! xdr_u_int32(&temp_xdrs, &verf_seq_num)) { PRINTF(("gssapi_unwrap_data: deserializing verf_seq_num failed\n")); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return FALSE; } if (verf_seq_num != seq_num) { PRINTF(("gssapi_unwrap_data: seq %d specified, read %d\n", seq_num, verf_seq_num)); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return FALSE; } PRINTF(("gssapi_unwrap_data: unwrap seq_num %d okay\n", verf_seq_num)); /* deserialize the arguments into xdr_ptr */ if (! (*xdr_func)(&temp_xdrs, xdr_ptr)) { PRINTF(("gssapi_unwrap_data: deserializing arguments failed\n")); gss_release_buffer(minor, &out_buf); xdr_free(xdr_func, xdr_ptr); XDR_DESTROY(&temp_xdrs); return FALSE; } PRINTF(("gssapi_unwrap_data: succeeding\n\n")); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return TRUE; } Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421] [MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free partial deserialization results upon failure to deserialize. This responsibility belongs to the callers, svctcp_getargs() and svcudp_getargs(); doing it in the unwrap function results in freeing the results twice. In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers we are freeing, as other XDR functions such as xdr_bytes() and xdr_string(). ticket: 8056 (new) target_version: 1.13.1 tags: pullup CWE ID: Target: 1 Example 2: Code: static void btif_hl_reset_mdep_filter(UINT8 app_idx) { btif_hl_app_cb_t *p_acb =BTIF_HL_GET_APP_CB_PTR(app_idx); p_acb->filter.num_elems = 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ pcap_close(fp); if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } Commit Message: In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs. CWE ID: CWE-918 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void VarianceTest<VarianceFunctionType>::OneQuarterTest() { memset(src_, 255, block_size_); const int half = block_size_ / 2; memset(ref_, 255, half); memset(ref_ + half, 0, half); unsigned int sse; unsigned int var; REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255 / 4; EXPECT_EQ(expected, var); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: SPL_METHOD(MultipleIterator, attachIterator) { spl_SplObjectStorage *intern; zval *iterator = NULL, *info = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|z!", &iterator, zend_ce_iterator, &info) == FAILURE) { return; } intern = Z_SPLOBJSTORAGE_P(getThis()); if (info != NULL) { spl_SplObjectStorageElement *element; if (Z_TYPE_P(info) != IS_LONG && Z_TYPE_P(info) != IS_STRING) { zend_throw_exception(spl_ce_InvalidArgumentException, "Info must be NULL, integer or string", 0); return; } zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos); while ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) != NULL) { if (fast_is_identical_function(info, &element->inf)) { zend_throw_exception(spl_ce_InvalidArgumentException, "Key duplication error", 0); return; } zend_hash_move_forward_ex(&intern->storage, &intern->pos); } } spl_object_storage_attach(intern, getThis(), iterator, info); } Commit Message: Fix bug #73257 and bug #73258 - SplObjectStorage unserialize allows use of non-object as key CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Create3DesKeysFromNtlmHash( base::span<const uint8_t, kNtlmHashLen> ntlm_hash, base::span<uint8_t, 24> keys) { Splay56To64(ntlm_hash.data(), keys.data()); Splay56To64(ntlm_hash.data() + 7, keys.data() + 8); keys[16] = ntlm_hash[14]; keys[17] = ntlm_hash[14] << 7 | ntlm_hash[15] >> 1; keys[18] = ntlm_hash[15] << 6; memset(keys.data() + 19, 0, 5); } Commit Message: [base] Make dynamic container to static span conversion explicit This change disallows implicit conversions from dynamic containers to static spans. This conversion can cause CHECK failures, and thus should be done carefully. Requiring explicit construction makes it more obvious when this happens. To aid usability, appropriate base::make_span<size_t> overloads are added. Bug: 877931 Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d Reviewed-on: https://chromium-review.googlesource.com/1189985 Reviewed-by: Ryan Sleevi <[email protected]> Reviewed-by: Balazs Engedy <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Commit-Queue: Jan Wilken Dörrie <[email protected]> Cr-Commit-Position: refs/heads/master@{#586657} CWE ID: CWE-22 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SSLManager::OnSSLCertificateError( base::WeakPtr<SSLErrorHandler::Delegate> delegate, const content::GlobalRequestID& id, const ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) { DCHECK(delegate); DVLOG(1) << "OnSSLCertificateError() cert_error: " << net::MapCertStatusToNetError(ssl_info.cert_status) << " id: " << id.child_id << "," << id.request_id << " resource_type: " << resource_type << " url: " << url.spec() << " render_process_id: " << render_process_id << " render_view_id: " << render_view_id << " cert_status: " << std::hex << ssl_info.cert_status; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SSLCertErrorHandler::Dispatch, new SSLCertErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id, ssl_info, fatal))); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void test_at() { assert_true_rule( "rule test { \ strings: $a = \"ssi\" \ condition: $a at 2 and $a at 5 }", "mississippi"); assert_true_rule( "rule test { \ strings: $a = \"mis\" \ condition: $a at ~0xFF & 0xFF }", "mississippi"); assert_true_rule_blob( "rule test { \ strings: $a = { 00 00 00 00 ?? 74 65 78 74 } \ condition: $a at 308}", PE32_FILE); } Commit Message: Fix heap overflow (reported by Jurriaan Bremer) When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static enum nl_mmap_status netlink_get_status(const struct nl_mmap_hdr *hdr) { smp_rmb(); flush_dcache_page(pgvec_to_page(hdr)); return hdr->nm_status; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int class_index, int *methods, int *sym_count) { struct r_bin_t *rbin = binfile->rbin; char *class_name; int z; const ut8 *p, *p_end; if (!c) { return; } class_name = dex_class_name (bin, c); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func if (!class_name || !*class_name) { return; } RBinClass *cls = R_NEW0 (RBinClass); if (!cls) { return; } cls->name = class_name; cls->index = class_index; cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE; cls->methods = r_list_new (); if (!cls->methods) { free (cls); return; } cls->fields = r_list_new (); if (!cls->fields) { r_list_free (cls->methods); free (cls); return; } r_list_append (bin->classes_list, cls); if (dexdump) { rbin->cb_printf (" Class descriptor : '%s;'\n", class_name); rbin->cb_printf ( " Access flags : 0x%04x (%s)\n", c->access_flags, createAccessFlagStr (c->access_flags, kAccessForClass)); rbin->cb_printf (" Superclass : '%s'\n", dex_class_super_name (bin, c)); rbin->cb_printf (" Interfaces -\n"); } if (c->interfaces_offset > 0 && bin->header.data_offset < c->interfaces_offset && c->interfaces_offset < bin->header.data_offset + bin->header.data_size) { p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL); int types_list_size = r_read_le32(p); if (types_list_size < 0 || types_list_size >= bin->header.types_size ) { return; } for (z = 0; z < types_list_size; z++) { int t = r_read_le16 (p + 4 + z * 2); if (t > 0 && t < bin->header.types_size ) { int tid = bin->types[t].descriptor_id; if (dexdump) { rbin->cb_printf ( " #%d : '%s'\n", z, getstr (bin, tid)); } } } } if (!c || !c->class_data_offset) { if (dexdump) { rbin->cb_printf ( " Static fields -\n Instance fields " "-\n Direct methods -\n Virtual methods " "-\n"); } } else { if (bin->header.class_offset > c->class_data_offset || c->class_data_offset < bin->header.class_offset + bin->header.class_size * DEX_CLASS_SIZE) { return; } p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL); p_end = p + binfile->buf->length - c->class_data_offset; c->class_data = (struct dex_class_data_item_t *)malloc ( sizeof (struct dex_class_data_item_t)); p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size); p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size); if (dexdump) { rbin->cb_printf (" Static fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->static_fields_size, true); if (dexdump) { rbin->cb_printf (" Instance fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->instance_fields_size, false); if (dexdump) { rbin->cb_printf (" Direct methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->direct_methods_size, methods, true); if (dexdump) { rbin->cb_printf (" Virtual methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->virtual_methods_size, methods, false); } if (dexdump) { char *source_file = getstr (bin, c->source_file); if (!source_file) { rbin->cb_printf ( " source_file_idx : %d (unknown)\n\n", c->source_file); } else { rbin->cb_printf (" source_file_idx : %d (%s)\n\n", c->source_file, source_file); } } } Commit Message: Fix #6816 - null deref in r_read_* CWE ID: CWE-476 Target: 1 Example 2: Code: gst_qtdemux_clip_buffer (GstQTDemux * qtdemux, QtDemuxStream * stream, GstBuffer * buf) { gint64 start, stop, cstart, cstop, diff; GstClockTime timestamp = GST_CLOCK_TIME_NONE, duration = GST_CLOCK_TIME_NONE; guint8 *data; guint size; gint num_rate, denom_rate; gint frame_size; gboolean clip_data; data = GST_BUFFER_DATA (buf); size = GST_BUFFER_SIZE (buf); /* depending on the type, setup the clip parameters */ if (stream->subtype == FOURCC_soun) { frame_size = stream->bytes_per_frame; num_rate = GST_SECOND; denom_rate = (gint) stream->rate; clip_data = TRUE; } else if (stream->subtype == FOURCC_vide) { frame_size = size; num_rate = stream->fps_n; denom_rate = stream->fps_d; clip_data = FALSE; } else goto wrong_type; /* we can only clip if we have a valid timestamp */ timestamp = GST_BUFFER_TIMESTAMP (buf); if (!GST_CLOCK_TIME_IS_VALID (timestamp)) goto no_timestamp; if (GST_BUFFER_DURATION_IS_VALID (buf)) { duration = GST_BUFFER_DURATION (buf); } else { duration = gst_util_uint64_scale_int (size / frame_size, num_rate, denom_rate); } start = timestamp; stop = start + duration; if (!gst_segment_clip (&stream->segment, GST_FORMAT_TIME, start, stop, &cstart, &cstop)) goto clipped; /* see if some clipping happened */ diff = cstart - start; if (diff > 0) { timestamp = cstart; duration -= diff; if (clip_data) { /* bring clipped time to samples and to bytes */ diff = gst_util_uint64_scale_int (diff, denom_rate, num_rate); diff *= frame_size; GST_DEBUG_OBJECT (qtdemux, "clipping start to %" GST_TIME_FORMAT " %" G_GUINT64_FORMAT " bytes", GST_TIME_ARGS (cstart), diff); data += diff; size -= diff; } } diff = stop - cstop; if (diff > 0) { duration -= diff; if (clip_data) { /* bring clipped time to samples and then to bytes */ diff = gst_util_uint64_scale_int (diff, denom_rate, num_rate); diff *= frame_size; GST_DEBUG_OBJECT (qtdemux, "clipping stop to %" GST_TIME_FORMAT " %" G_GUINT64_FORMAT " bytes", GST_TIME_ARGS (cstop), diff); size -= diff; } } GST_BUFFER_TIMESTAMP (buf) = timestamp; GST_BUFFER_DURATION (buf) = duration; GST_BUFFER_SIZE (buf) = size; GST_BUFFER_DATA (buf) = data; return buf; /* dropped buffer */ wrong_type: { GST_DEBUG_OBJECT (qtdemux, "unknown stream type"); return buf; } no_timestamp: { GST_DEBUG_OBJECT (qtdemux, "no timestamp on buffer"); return buf; } clipped: { GST_DEBUG_OBJECT (qtdemux, "clipped buffer"); gst_buffer_unref (buf); return NULL; } } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __net_init sit_init_net(struct net *net) { struct sit_net *sitn = net_generic(net, sit_net_id); struct ip_tunnel *t; int err; sitn->tunnels[0] = sitn->tunnels_wc; sitn->tunnels[1] = sitn->tunnels_l; sitn->tunnels[2] = sitn->tunnels_r; sitn->tunnels[3] = sitn->tunnels_r_l; if (!net_has_fallback_tunnels(net)) return 0; sitn->fb_tunnel_dev = alloc_netdev(sizeof(struct ip_tunnel), "sit0", NET_NAME_UNKNOWN, ipip6_tunnel_setup); if (!sitn->fb_tunnel_dev) { err = -ENOMEM; goto err_alloc_dev; } dev_net_set(sitn->fb_tunnel_dev, net); sitn->fb_tunnel_dev->rtnl_link_ops = &sit_link_ops; /* FB netdevice is special: we have one, and only one per netns. * Allowing to move it to another netns is clearly unsafe. */ sitn->fb_tunnel_dev->features |= NETIF_F_NETNS_LOCAL; err = register_netdev(sitn->fb_tunnel_dev); if (err) goto err_reg_dev; ipip6_tunnel_clone_6rd(sitn->fb_tunnel_dev, sitn); ipip6_fb_tunnel_init(sitn->fb_tunnel_dev); t = netdev_priv(sitn->fb_tunnel_dev); strcpy(t->parms.name, sitn->fb_tunnel_dev->name); return 0; err_reg_dev: ipip6_dev_free(sitn->fb_tunnel_dev); err_alloc_dev: return err; } Commit Message: net: sit: fix memory leak in sit_init_net() If register_netdev() is failed to register sitn->fb_tunnel_dev, it will go to err_reg_dev and forget to free netdev(sitn->fb_tunnel_dev). BUG: memory leak unreferenced object 0xffff888378daad00 (size 512): comm "syz-executor.1", pid 4006, jiffies 4295121142 (age 16.115s) hex dump (first 32 bytes): 00 e6 ed c0 83 88 ff ff 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ backtrace: [<00000000d6dcb63e>] kvmalloc include/linux/mm.h:577 [inline] [<00000000d6dcb63e>] kvzalloc include/linux/mm.h:585 [inline] [<00000000d6dcb63e>] netif_alloc_netdev_queues net/core/dev.c:8380 [inline] [<00000000d6dcb63e>] alloc_netdev_mqs+0x600/0xcc0 net/core/dev.c:8970 [<00000000867e172f>] sit_init_net+0x295/0xa40 net/ipv6/sit.c:1848 [<00000000871019fa>] ops_init+0xad/0x3e0 net/core/net_namespace.c:129 [<00000000319507f6>] setup_net+0x2ba/0x690 net/core/net_namespace.c:314 [<0000000087db4f96>] copy_net_ns+0x1dc/0x330 net/core/net_namespace.c:437 [<0000000057efc651>] create_new_namespaces+0x382/0x730 kernel/nsproxy.c:107 [<00000000676f83de>] copy_namespaces+0x2ed/0x3d0 kernel/nsproxy.c:165 [<0000000030b74bac>] copy_process.part.27+0x231e/0x6db0 kernel/fork.c:1919 [<00000000fff78746>] copy_process kernel/fork.c:1713 [inline] [<00000000fff78746>] _do_fork+0x1bc/0xe90 kernel/fork.c:2224 [<000000001c2e0d1c>] do_syscall_64+0xc8/0x580 arch/x86/entry/common.c:290 [<00000000ec48bd44>] entry_SYSCALL_64_after_hwframe+0x49/0xbe [<0000000039acff8a>] 0xffffffffffffffff Signed-off-by: Mao Wenan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-772 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long mkvparser::ParseElementHeader( IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume length of size if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq, void *buf, unsigned int len) { struct net_device *dev = vi->dev; struct virtnet_stats *stats = this_cpu_ptr(vi->stats); struct sk_buff *skb; struct virtio_net_hdr_mrg_rxbuf *hdr; if (unlikely(len < vi->hdr_len + ETH_HLEN)) { pr_debug("%s: short packet %i\n", dev->name, len); dev->stats.rx_length_errors++; if (vi->mergeable_rx_bufs) { unsigned long ctx = (unsigned long)buf; void *base = mergeable_ctx_to_buf_address(ctx); put_page(virt_to_head_page(base)); } else if (vi->big_packets) { give_pages(rq, buf); } else { dev_kfree_skb(buf); } return; } if (vi->mergeable_rx_bufs) skb = receive_mergeable(dev, vi, rq, (unsigned long)buf, len); else if (vi->big_packets) skb = receive_big(dev, vi, rq, buf, len); else skb = receive_small(vi, buf, len); if (unlikely(!skb)) return; hdr = skb_vnet_hdr(skb); u64_stats_update_begin(&stats->rx_syncp); stats->rx_bytes += skb->len; stats->rx_packets++; u64_stats_update_end(&stats->rx_syncp); if (hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { pr_debug("Needs csum!\n"); if (!skb_partial_csum_set(skb, virtio16_to_cpu(vi->vdev, hdr->hdr.csum_start), virtio16_to_cpu(vi->vdev, hdr->hdr.csum_offset))) goto frame_err; } else if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID) { skb->ip_summed = CHECKSUM_UNNECESSARY; } skb->protocol = eth_type_trans(skb, dev); pr_debug("Receiving skb proto 0x%04x len %i type %i\n", ntohs(skb->protocol), skb->len, skb->pkt_type); if (hdr->hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) { pr_debug("GSO!\n"); switch (hdr->hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) { case VIRTIO_NET_HDR_GSO_TCPV4: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; break; case VIRTIO_NET_HDR_GSO_UDP: skb_shinfo(skb)->gso_type = SKB_GSO_UDP; break; case VIRTIO_NET_HDR_GSO_TCPV6: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6; break; default: net_warn_ratelimited("%s: bad gso type %u.\n", dev->name, hdr->hdr.gso_type); goto frame_err; } if (hdr->hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN) skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; skb_shinfo(skb)->gso_size = virtio16_to_cpu(vi->vdev, hdr->hdr.gso_size); if (skb_shinfo(skb)->gso_size == 0) { net_warn_ratelimited("%s: zero gso size.\n", dev->name); goto frame_err; } /* Header must be checked, and gso_segs computed. */ skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; skb_shinfo(skb)->gso_segs = 0; } skb_mark_napi_id(skb, &rq->napi); netif_receive_skb(skb); return; frame_err: dev->stats.rx_frame_errors++; dev_kfree_skb(skb); } Commit Message: virtio-net: drop NETIF_F_FRAGLIST virtio declares support for NETIF_F_FRAGLIST, but assumes that there are at most MAX_SKB_FRAGS + 2 fragments which isn't always true with a fraglist. A longer fraglist in the skb will make the call to skb_to_sgvec overflow the sg array, leading to memory corruption. Drop NETIF_F_FRAGLIST so we only get what we can handle. Cc: Michael S. Tsirkin <[email protected]> Signed-off-by: Jason Wang <[email protected]> Acked-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BluetoothOptionsHandler::GenerateFakeDiscoveredDevice( const std::string& name, const std::string& address, const std::string& icon, bool paired, bool connected) { DictionaryValue device; device.SetString("name", name); device.SetString("address", address); device.SetString("icon", icon); device.SetBoolean("paired", paired); device.SetBoolean("connected", connected); web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", device); } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: static void dbus_bus_acquired(GDBusConnection *connection, const gchar *name, gpointer user_data) { struct tcmur_handler **handler; tcmu_dbg("bus %s acquired\n", name); manager = g_dbus_object_manager_server_new("/org/kernel/TCMUService1"); darray_foreach(handler, g_runner_handlers) { dbus_export_handler(*handler, G_CALLBACK(on_check_config)); } dbus_handler_manager1_init(connection); g_dbus_object_manager_server_set_connection(manager, connection); } Commit Message: fixed local DoS when UnregisterHandler was called for a not existing handler Any user with DBUS access could cause a SEGFAULT in tcmu-runner by running something like this: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:123 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PopupContainer::refresh(const IntRect& targetControlRect) { IntPoint location = m_frameView->contentsToWindow(targetControlRect.location()); location.move(0, targetControlRect.height()); listBox()->setBaseWidth(max(m_originalFrameRect.width() - kBorderSize * 2, 0)); listBox()->updateFromElement(); IntSize originalSize = size(); IntRect widgetRect = layoutAndCalculateWidgetRect(targetControlRect.height(), location); if (originalSize != widgetRect.size()) { ChromeClientChromium* chromeClient = chromeClientChromium(); if (chromeClient) { IntPoint widgetLocation = chromeClient->screenToRootView(widgetRect.location()); widgetRect.setLocation(widgetLocation); setFrameRect(widgetRect); } } invalidate(); } Commit Message: [REGRESSION] Refreshed autofill popup renders garbage https://bugs.webkit.org/show_bug.cgi?id=83255 http://code.google.com/p/chromium/issues/detail?id=118374 The code used to update only the PopupContainer coordinates as if they were the coordinates relative to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer, so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's location should be (0, 0) (and their sizes should always be equal). Reviewed by Kent Tamura. No new tests, as the popup appearance is not testable in WebKit. * platform/chromium/PopupContainer.cpp: (WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed. (WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect() for passing into chromeClient. (WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container. (WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly. * platform/chromium/PopupContainer.h: (PopupContainer): git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool DataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20 Target: 1 Example 2: Code: int WebLocalFrameImpl::SelectNearestFindMatch(const WebFloatPoint& point, WebRect* selection_rect) { return EnsureTextFinder().SelectNearestFindMatch(point, selection_rect); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int btsock_thread_init() { static int initialized; APPL_TRACE_DEBUG("in initialized:%d", initialized); if(!initialized) { initialized = 1; int h; for(h = 0; h < MAX_THREAD; h++) { ts[h].cmd_fdr = ts[h].cmd_fdw = -1; ts[h].used = 0; ts[h].thread_id = -1; ts[h].poll_count = 0; ts[h].callback = NULL; ts[h].cmd_callback = NULL; } } return TRUE; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: base::string16 GetAppForProtocolUsingRegistry(const GURL& url) { base::string16 command_to_launch; base::string16 cmd_key_path = base::ASCIIToUTF16(url.scheme()); base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } cmd_key_path = base::ASCIIToUTF16(url.scheme() + "\\shell\\open\\command"); base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return base::string16(); } Commit Message: Validate external protocols before launching on Windows Bug: 889459 Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef Reviewed-on: https://chromium-review.googlesource.com/c/1256208 Reviewed-by: Greg Thompson <[email protected]> Commit-Queue: Mustafa Emre Acer <[email protected]> Cr-Commit-Position: refs/heads/master@{#597611} CWE ID: CWE-20 Target: 1 Example 2: Code: static void hid_scan_collection(struct hid_parser *parser, unsigned type) { struct hid_device *hid = parser->device; int i; if (((parser->global.usage_page << 16) == HID_UP_SENSOR) && type == HID_COLLECTION_PHYSICAL) hid->group = HID_GROUP_SENSOR_HUB; if (hid->vendor == USB_VENDOR_ID_MICROSOFT && (hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3 || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_2 || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_JP || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_3 || hid->product == USB_DEVICE_ID_MS_POWER_COVER) && hid->group == HID_GROUP_MULTITOUCH) hid->group = HID_GROUP_GENERIC; if ((parser->global.usage_page << 16) == HID_UP_GENDESK) for (i = 0; i < parser->local.usage_index; i++) if (parser->local.usage[i] == HID_GD_POINTER) parser->scan_flags |= HID_SCAN_FLAG_GD_POINTER; if ((parser->global.usage_page << 16) >= HID_UP_MSVENDOR) parser->scan_flags |= HID_SCAN_FLAG_VENDOR_SPECIFIC; } Commit Message: HID: core: prevent out-of-bound readings Plugging a Logitech DJ receiver with KASAN activated raises a bunch of out-of-bound readings. The fields are allocated up to MAX_USAGE, meaning that potentially, we do not have enough fields to fit the incoming values. Add checks and silence KASAN. Signed-off-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PrintMsg_Print_Params GetCssPrintParams( WebKit::WebFrame* frame, int page_index, const PrintMsg_Print_Params& page_params) { PrintMsg_Print_Params page_css_params = page_params; int dpi = GetDPI(&page_params); using printing::ConvertUnit; using printing::kPixelsPerInch; WebKit::WebSize page_size_in_pixels( ConvertUnit(page_params.page_size.width(), dpi, kPixelsPerInch), ConvertUnit(page_params.page_size.height(), dpi, kPixelsPerInch)); int margin_top_in_pixels = ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch); int margin_right_in_pixels = ConvertUnit( page_params.page_size.width() - page_params.content_size.width() - page_params.margin_left, dpi, kPixelsPerInch); int margin_bottom_in_pixels = ConvertUnit( page_params.page_size.height() - page_params.content_size.height() - page_params.margin_top, dpi, kPixelsPerInch); int margin_left_in_pixels = ConvertUnit( page_params.margin_left, dpi, kPixelsPerInch); WebKit::WebSize original_page_size_in_pixels = page_size_in_pixels; if (frame) { frame->pageSizeAndMarginsInPixels(page_index, page_size_in_pixels, margin_top_in_pixels, margin_right_in_pixels, margin_bottom_in_pixels, margin_left_in_pixels); } int new_content_width = page_size_in_pixels.width - margin_left_in_pixels - margin_right_in_pixels; int new_content_height = page_size_in_pixels.height - margin_top_in_pixels - margin_bottom_in_pixels; if (new_content_width < 1 || new_content_height < 1) { CHECK(frame != NULL); page_css_params = GetCssPrintParams(NULL, page_index, page_params); return page_css_params; } page_css_params.content_size = gfx::Size( ConvertUnit(new_content_width, kPixelsPerInch, dpi), ConvertUnit(new_content_height, kPixelsPerInch, dpi)); if (original_page_size_in_pixels != page_size_in_pixels) { page_css_params.page_size = gfx::Size( ConvertUnit(page_size_in_pixels.width, kPixelsPerInch, dpi), ConvertUnit(page_size_in_pixels.height, kPixelsPerInch, dpi)); } else { page_css_params.page_size = page_params.page_size; } page_css_params.margin_top = ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi); page_css_params.margin_left = ConvertUnit(margin_left_in_pixels, kPixelsPerInch, dpi); return page_css_params; } Commit Message: Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ~ScopedRequest() { if (requested_) { owner_->delegate_->StopEnumerateDevices(request_id_); } } 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 Target: 1 Example 2: Code: void testUriUserInfoHostPort1() { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; const char * const input = "http" "://" "abc:def" "@" "localhost"; TEST_ASSERT(0 == uriParseUriA(&stateA, input)); TEST_ASSERT(uriA.userInfo.first == input + 4 + 3); TEST_ASSERT(uriA.userInfo.afterLast == input + 4 + 3 + 7); TEST_ASSERT(uriA.hostText.first == input + 4 + 3 + 7 + 1); TEST_ASSERT(uriA.hostText.afterLast == input + 4 + 3 + 7 + 1 + 9); TEST_ASSERT(uriA.portText.first == NULL); TEST_ASSERT(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex Reported by Google Autofuzz team CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void faad_resetbits(bitfile *ld, int bits) { uint32_t tmp; int words = bits >> 5; int remainder = bits & 0x1F; ld->bytes_left = ld->buffer_size - words*4; if (ld->bytes_left >= 4) { tmp = getdword(&ld->start[words]); ld->bytes_left -= 4; } else { tmp = getdword_n(&ld->start[words], ld->bytes_left); ld->bytes_left = 0; } ld->bufa = tmp; if (ld->bytes_left >= 4) { tmp = getdword(&ld->start[words+1]); ld->bytes_left -= 4; } else { tmp = getdword_n(&ld->start[words+1], ld->bytes_left); ld->bytes_left = 0; } ld->bufb = tmp; ld->bits_left = 32 - remainder; ld->tail = &ld->start[words+2]; /* recheck for reading too many bytes */ ld->error = 0; } Commit Message: Fix a couple buffer overflows https://hackerone.com/reports/502816 https://hackerone.com/reports/507858 https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch CWE ID: CWE-119 Target: 1 Example 2: Code: LogLuvFixupTags(TIFF* tif) { (void) tif; return (1); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void updateLogicalWidthForRightAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth) { if (isLeftToRightDirection) { if (trailingSpaceRun) { totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth(); trailingSpaceRun->m_box->setLogicalWidth(0); } if (totalLogicalWidth < availableLogicalWidth) logicalLeft += availableLogicalWidth - totalLogicalWidth; return; } if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun) { trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth)); totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth(); } else logicalLeft += availableLogicalWidth - totalLogicalWidth; } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } Commit Message: ... CWE ID: CWE-754 Target: 1 Example 2: Code: int snd_usb_create_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { typedef int (*quirk_func_t)(struct snd_usb_audio *, struct usb_interface *, struct usb_driver *, const struct snd_usb_audio_quirk *); static const quirk_func_t quirk_funcs[] = { [QUIRK_IGNORE_INTERFACE] = ignore_interface_quirk, [QUIRK_COMPOSITE] = create_composite_quirk, [QUIRK_AUTODETECT] = create_autodetect_quirks, [QUIRK_MIDI_STANDARD_INTERFACE] = create_any_midi_quirk, [QUIRK_MIDI_FIXED_ENDPOINT] = create_any_midi_quirk, [QUIRK_MIDI_YAMAHA] = create_any_midi_quirk, [QUIRK_MIDI_ROLAND] = create_any_midi_quirk, [QUIRK_MIDI_MIDIMAN] = create_any_midi_quirk, [QUIRK_MIDI_NOVATION] = create_any_midi_quirk, [QUIRK_MIDI_RAW_BYTES] = create_any_midi_quirk, [QUIRK_MIDI_EMAGIC] = create_any_midi_quirk, [QUIRK_MIDI_CME] = create_any_midi_quirk, [QUIRK_MIDI_AKAI] = create_any_midi_quirk, [QUIRK_MIDI_FTDI] = create_any_midi_quirk, [QUIRK_MIDI_CH345] = create_any_midi_quirk, [QUIRK_AUDIO_STANDARD_INTERFACE] = create_standard_audio_quirk, [QUIRK_AUDIO_FIXED_ENDPOINT] = create_fixed_stream_quirk, [QUIRK_AUDIO_EDIROL_UAXX] = create_uaxx_quirk, [QUIRK_AUDIO_ALIGN_TRANSFER] = create_align_transfer_quirk, [QUIRK_AUDIO_STANDARD_MIXER] = create_standard_mixer_quirk, }; if (quirk->type < QUIRK_TYPE_COUNT) { return quirk_funcs[quirk->type](chip, iface, driver, quirk); } else { usb_audio_err(chip, "invalid quirk type %d\n", quirk->type); return -ENXIO; } } Commit Message: ALSA: usb-audio: Fix NULL dereference in create_fixed_stream_quirk() create_fixed_stream_quirk() may cause a NULL-pointer dereference by accessing the non-existing endpoint when a USB device with a malformed USB descriptor is used. This patch avoids it simply by adding a sanity check of bNumEndpoints before the accesses. Bugzilla: https://bugzilla.suse.com/show_bug.cgi?id=971125 Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SubpelVarianceTest<vp9_subp_avg_variance_fn_t>::RefTest() { for (int x = 0; x < 16; ++x) { for (int y = 0; y < 16; ++y) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); sec_[j] = rnd.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; unsigned int var1; REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1, sec_)); const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_, log2width_, log2height_, x, y, &sse2); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MaxTextExtent], text[MaxTextExtent]; Image *image; IndexPacket *indexes; long type, x_offset, y, y_offset; MagickBooleanType status; MagickPixelPacket pixel; QuantumAny range; register ssize_t i, x; register PixelPacket *q; ssize_t count; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) return(ReadTEXTImage(image_info,image,text,exception)); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ; image->depth=depth; LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->matte=MagickFalse; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->matte=MagickTrue; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->colorspace=(ColorspaceType) type; (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); (void) SetImageBackgroundColor(image); range=GetQuantumRange(image->depth); for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, index, opacity, red; red=0.0; green=0.0; blue=0.0; index=0.0; opacity=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) break; switch (image->colorspace) { case GRAYColorspace: { if (image->matte != MagickFalse) { count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&opacity); green=red; blue=red; break; } count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset, &y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->matte != MagickFalse) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&index,&opacity); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&index); break; } default: { if (image->matte != MagickFalse) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&opacity); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,&y_offset, &red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; index*=0.01*range; opacity*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=ScaleAnyToQuantum((QuantumAny) (red+0.5),range); pixel.green=ScaleAnyToQuantum((QuantumAny) (green+0.5),range); pixel.blue=ScaleAnyToQuantum((QuantumAny) (blue+0.5),range); pixel.index=ScaleAnyToQuantum((QuantumAny) (index+0.5),range); pixel.opacity=ScaleAnyToQuantum((QuantumAny) (opacity+0.5),range); q=GetAuthenticPixels(image,x_offset,y_offset,1,1,exception); if (q == (PixelPacket *) NULL) continue; SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); if (image->colorspace == CMYKColorspace) { indexes=GetAuthenticIndexQueue(image); SetPixelIndex(indexes,pixel.index); } if (image->matte != MagickFalse) SetPixelAlpha(q,pixel.opacity); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static bmp_info_t *bmp_getinfo(jas_stream_t *in) { bmp_info_t *info; int i; bmp_palent_t *palent; if (!(info = bmp_info_create())) { return 0; } if (bmp_getint32(in, &info->len) || info->len != 40 || bmp_getint32(in, &info->width) || bmp_getint32(in, &info->height) || bmp_getint16(in, &info->numplanes) || bmp_getint16(in, &info->depth) || bmp_getint32(in, &info->enctype) || bmp_getint32(in, &info->siz) || bmp_getint32(in, &info->hres) || bmp_getint32(in, &info->vres) || bmp_getint32(in, &info->numcolors) || bmp_getint32(in, &info->mincolors)) { bmp_info_destroy(info); return 0; } if (info->height < 0) { info->topdown = 1; info->height = -info->height; } else { info->topdown = 0; } if (info->width <= 0 || info->height <= 0 || info->numplanes <= 0 || info->depth <= 0 || info->numcolors < 0 || info->mincolors < 0) { bmp_info_destroy(info); return 0; } if (info->enctype != BMP_ENC_RGB) { jas_eprintf("unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } if (info->numcolors > 0) { if (!(info->palents = jas_alloc2(info->numcolors, sizeof(bmp_palent_t)))) { bmp_info_destroy(info); return 0; } } else { info->palents = 0; } for (i = 0; i < info->numcolors; ++i) { palent = &info->palents[i]; if ((palent->blu = jas_stream_getc(in)) == EOF || (palent->grn = jas_stream_getc(in)) == EOF || (palent->red = jas_stream_getc(in)) == EOF || (palent->res = jas_stream_getc(in)) == EOF) { bmp_info_destroy(info); return 0; } } return info; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register z_crc_t c; register const z_crc_t FAR *buf4; c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const z_crc_t FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf4++; buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(ZSWAP32(c)); } Commit Message: Avoid pre-decrement of pointer in big-endian CRC calculation. There was a small optimization for PowerPCs to pre-increment a pointer when accessing a word, instead of post-incrementing. This required prefacing the loop with a decrement of the pointer, possibly pointing before the object passed. This is not compliant with the C standard, for which decrementing a pointer before its allocated memory is undefined. When tested on a modern PowerPC with a modern compiler, the optimization no longer has any effect. Due to all that, and per the recommendation of a security audit of the zlib code by Trail of Bits and TrustInSoft, in support of the Mozilla Foundation, this "optimization" was removed, in order to avoid the possibility of undefined behavior. CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual ssize_t readAt(off64_t offset, void *buffer, size_t size) { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); data.writeInt64(offset); data.writeInt32(size); status_t err = remote()->transact(READ_AT, data, &reply); if (err != OK) { ALOGE("remote readAt failed"); return UNKNOWN_ERROR; } int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } int32_t len = reply.readInt32(); if (len > 0) { memcpy(buffer, mMemory->pointer(), len); } return len; } Commit Message: Add some sanity checks Bug: 19400722 Change-Id: Ib3afdf73fd4647eeea5721c61c8b72dbba0647f6 CWE ID: CWE-119 Target: 1 Example 2: Code: void XSLTProcessor::reset() { m_stylesheet.clear(); m_stylesheetRootNode.clear(); m_parameters.clear(); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AppLayerProtoDetectThreadCtx *AppLayerProtoDetectGetCtxThread(void) { SCEnter(); AppLayerProtoDetectThreadCtx *alpd_tctx = NULL; MpmCtx *mpm_ctx; MpmThreadCtx *mpm_tctx; int i, j; PatIntId max_pat_id = 0; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { if (max_pat_id == 0) { max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } else if (alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id && max_pat_id < alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id) { max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } } } alpd_tctx = SCMalloc(sizeof(*alpd_tctx)); if (alpd_tctx == NULL) goto error; memset(alpd_tctx, 0, sizeof(*alpd_tctx)); /* Get the max pat id for all the mpm ctxs. */ if (PmqSetup(&alpd_tctx->pmq) < 0) goto error; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { mpm_ctx = &alpd_ctx.ctx_ipp[i].ctx_pm[j].mpm_ctx; mpm_tctx = &alpd_tctx->mpm_tctx[i][j]; mpm_table[mpm_ctx->mpm_type].InitThreadCtx(mpm_ctx, mpm_tctx); } } alpd_tctx->spm_thread_ctx = SpmMakeThreadCtx(alpd_ctx.spm_global_thread_ctx); if (alpd_tctx->spm_thread_ctx == NULL) { goto error; } goto end; error: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); alpd_tctx = NULL; end: SCReturnPtr(alpd_tctx, "AppLayerProtoDetectThreadCtx"); } Commit Message: proto/detect: workaround dns misdetected as dcerpc The DCERPC UDP detection would misfire on DNS with transaction ID 0x0400. This would happen as the protocol detection engine gives preference to pattern based detection over probing parsers for performance reasons. This hack/workaround fixes this specific case by still running the probing parser if DCERPC has been detected on UDP. The probing parser result will take precedence. Bug #2736. CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: NO_INLINE JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a) { assert(!a || jsvIsName(a)); JSP_ASSERT_MATCH(LEX_ARROW_FUNCTION); funcVar = jspeAddNamedFunctionParameter(funcVar, a); bool expressionOnly = lex->tk!='{'; jspeFunctionDefinitionInternal(funcVar, expressionOnly); if (execInfo.thisVar) { jsvObjectSetChild(funcVar, JSPARSE_FUNCTION_THIS_NAME, execInfo.thisVar); } return funcVar; } NO_INLINE JsVar *jspeExpressionOrArrowFunction() { JsVar *a = 0; JsVar *funcVar = 0; bool allNames = true; while (lex->tk!=')' && !JSP_SHOULDNT_PARSE) { if (allNames && a) { funcVar = jspeAddNamedFunctionParameter(funcVar, a); } jsvUnLock(a); a = jspeAssignmentExpression(); if (!(jsvIsName(a) && jsvIsString(a))) allNames = false; if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',', jsvUnLock2(a,funcVar), 0); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(a,funcVar), 0); if (allNames && lex->tk==LEX_ARROW_FUNCTION) { funcVar = jspeArrowFunction(funcVar, a); jsvUnLock(a); return funcVar; } else { jsvUnLock(funcVar); return a; } } NO_INLINE JsVar *jspeClassDefinition(bool parseNamedClass) { JsVar *classFunction = 0; JsVar *classPrototype = 0; JsVar *classInternalName = 0; bool actuallyCreateClass = JSP_SHOULD_EXECUTE; if (actuallyCreateClass) classFunction = jsvNewWithFlags(JSV_FUNCTION); if (parseNamedClass && lex->tk==LEX_ID) { if (classFunction) classInternalName = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_ID); } if (classFunction) { JsVar *prototypeName = jsvFindChildFromString(classFunction, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(classFunction, prototypeName); // make sure it's an object classPrototype = jsvSkipName(prototypeName); jsvUnLock(prototypeName); } if (lex->tk==LEX_R_EXTENDS) { JSP_ASSERT_MATCH(LEX_R_EXTENDS); JsVar *extendsFrom = actuallyCreateClass ? jsvSkipNameAndUnLock(jspGetNamedVariable(jslGetTokenValueAsString(lex))) : 0; JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock4(extendsFrom,classFunction,classInternalName,classPrototype),0); if (classPrototype) { if (jsvIsFunction(extendsFrom)) { jsvObjectSetChild(classPrototype, JSPARSE_INHERITS_VAR, extendsFrom); jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_CODE_NAME, jsvNewFromString("if(this.__proto__.__proto__)this.__proto__.__proto__.apply(this,arguments)")); } else jsExceptionHere(JSET_SYNTAXERROR, "'extends' argument should be a function, got %t", extendsFrom); } jsvUnLock(extendsFrom); } JSP_MATCH_WITH_CLEANUP_AND_RETURN('{',jsvUnLock3(classFunction,classInternalName,classPrototype),0); while ((lex->tk==LEX_ID || lex->tk==LEX_R_STATIC) && !jspIsInterrupted()) { bool isStatic = lex->tk==LEX_R_STATIC; if (isStatic) JSP_ASSERT_MATCH(LEX_R_STATIC); JsVar *funcName = jslGetTokenValueAsVar(lex); JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock3(classFunction,classInternalName,classPrototype),0); JsVar *method = jspeFunctionDefinition(false); if (classFunction && classPrototype) { if (jsvIsStringEqual(funcName, "get") || jsvIsStringEqual(funcName, "set")) { jsExceptionHere(JSET_SYNTAXERROR, "'get' and 'set' and not supported in Espruino"); } else if (jsvIsStringEqual(funcName, "constructor")) { jswrap_function_replaceWith(classFunction, method); } else { funcName = jsvMakeIntoVariableName(funcName, 0); jsvSetValueOfName(funcName, method); jsvAddName(isStatic ? classFunction : classPrototype, funcName); } } jsvUnLock2(method,funcName); } jsvUnLock(classPrototype); if (classInternalName) jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_NAME_NAME, classInternalName); JSP_MATCH_WITH_CLEANUP_AND_RETURN('}',jsvUnLock(classFunction),0); return classFunction; } #endif NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; } NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); jsvUnLock(a); a = oldValue; } } return a; } NO_INLINE JsVar *jspePostfixExpression() { JsVar *a; if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); a = jspePostfixExpression(); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); } } else a = jspeFactorFunctionCall(); return __jspePostfixExpression(a); } NO_INLINE JsVar *jspeUnaryExpression() { if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { short tk = lex->tk; JSP_ASSERT_MATCH(tk); if (!JSP_SHOULD_EXECUTE) { return jspeUnaryExpression(); } if (tk=='!') { // logical not return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='~') { // bitwise not return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='-') { // unary minus return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped } else if (tk=='+') { // unary plus (convert to number) JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); JsVar *r = jsvAsNumber(v); // names already skipped jsvUnLock(v); return r; } assert(0); return 0; } else return jspePostfixExpression(); } unsigned int jspeGetBinaryExpressionPrecedence(int op) { switch (op) { case LEX_OROR: return 1; break; case LEX_ANDAND: return 2; break; case '|' : return 3; break; case '^' : return 4; break; case '&' : return 5; break; case LEX_EQUAL: case LEX_NEQUAL: case LEX_TYPEEQUAL: case LEX_NTYPEEQUAL: return 6; case LEX_LEQUAL: case LEX_GEQUAL: case '<': case '>': case LEX_R_INSTANCEOF: return 7; case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; case LEX_LSHIFT: case LEX_RSHIFT: case LEX_RSHIFTUNSIGNED: return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 10; default: return 0; } } NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { /* This one's a bit strange. Basically all the ops have their own precedence, it's not * like & and | share the same precedence. We don't want to recurse for each one, * so instead we do this. * * We deal with an expression in recursion ONLY if it's of higher precedence * than the current one, otherwise we stick in the while loop. */ unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); while (precedence && precedence>lastPrecedence) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (op==LEX_ANDAND || op==LEX_OROR) { bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); if ((!aValue && op==LEX_ANDAND) || (aValue && op==LEX_OROR)) { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); JSP_RESTORE_EXECUTE(); } else { jsvUnLock(a); a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); } } else { // else it's a more 'normal' logical expression - just use Maths JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); if (JSP_SHOULD_EXECUTE) { if (op==LEX_R_IN) { JsVar *av = jsvSkipName(a); // needle JsVar *bv = jsvSkipName(b); // haystack if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values av = jsvAsArrayIndexAndUnLock(av); JsVar *varFound = jspGetVarNamedField( bv, av, true); jsvUnLock(a); a = jsvNewFromBool(varFound!=0); jsvUnLock(varFound); } else {// else it will be undefined jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv); jsvUnLock(a); a = 0; } jsvUnLock2(av, bv); } else if (op==LEX_R_INSTANCEOF) { bool inst = false; JsVar *av = jsvSkipName(a); JsVar *bv = jsvSkipName(b); if (!jsvIsFunction(bv)) { jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv); } else { if (jsvIsObject(av) || jsvIsFunction(av)) { JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); while (proto) { if (proto == bproto) inst=true; JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); jsvUnLock(proto); proto = childProto; } if (jspIsConstructor(bv, "Object")) inst = true; jsvUnLock(bproto); } if (!inst) { const char *name = jswGetBasicObjectName(av); if (name) { inst = jspIsConstructor(bv, name); } if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && jspIsConstructor(bv, "Object")) inst = true; } } jsvUnLock3(av, bv, a); a = jsvNewFromBool(inst); } else { // --------------------------------------------- NORMAL JsVar *res = jsvMathsOpSkipNames(a, b, op); jsvUnLock(a); a = res; } } jsvUnLock(b); } precedence = jspeGetBinaryExpressionPrecedence(lex->tk); } return a; } JsVar *jspeBinaryExpression() { return __jspeBinaryExpression(jspeUnaryExpression(),0); } NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { if (lex->tk=='?') { JSP_ASSERT_MATCH('?'); if (!JSP_SHOULD_EXECUTE) { jsvUnLock(jspeAssignmentExpression()); JSP_MATCH(':'); jsvUnLock(jspeAssignmentExpression()); } else { bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); jsvUnLock(lhs); if (first) { lhs = jspeAssignmentExpression(); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); } else { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); JSP_MATCH(':'); lhs = jspeAssignmentExpression(); } } } return lhs; } JsVar *jspeConditionalExpression() { return __jspeConditionalExpression(jspeBinaryExpression()); } NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } JsVar *jspeAssignmentExpression() { return __jspeAssignmentExpression(jspeConditionalExpression()); } NO_INLINE JsVar *jspeExpression() { while (!JSP_SHOULDNT_PARSE) { JsVar *a = jspeAssignmentExpression(); if (lex->tk!=',') return a; jsvCheckReferenceError(a); jsvUnLock(a); JSP_ASSERT_MATCH(','); } return 0; } /** Parse a block `{ ... }` but assume brackets are already parsed */ NO_INLINE void jspeBlockNoBrackets() { if (JSP_SHOULD_EXECUTE) { while (lex->tk && lex->tk!='}') { JsVar *a = jspeStatement(); jsvCheckReferenceError(a); jsvUnLock(a); if (JSP_HAS_ERROR) { if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, "at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); } } } if (JSP_SHOULDNT_PARSE) return; } } else { int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; JSP_ASSERT_MATCH(lex->tk); } } return; } Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437) CWE ID: CWE-125 Target: 1 Example 2: Code: explicit UseSynchronousResizeModeVisitor(bool enable) : enable_(enable) {} Commit Message: content: Rename webkit_test_helpers.{cc,h} to blink_test_helpers.{cc,h} Now that webkit/ is gone, we are preparing ourselves for the merge of third_party/WebKit into //blink. BUG=None BUG=content_shell && content_unittests [email protected] Review URL: https://codereview.chromium.org/1118183003 Cr-Commit-Position: refs/heads/master@{#328202} CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CreateSimpleArtifactWithOpacity(TestPaintArtifact& artifact, float opacity, bool include_preceding_chunk, bool include_subsequent_chunk) { if (include_preceding_chunk) AddSimpleRectChunk(artifact); auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), opacity); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); if (include_subsequent_chunk) AddSimpleRectChunk(artifact); Update(artifact.Build()); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = mWidth * mHeight * 3 / 2; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); } Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec Bug: 27833616 Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0 CWE ID: CWE-20 Target: 1 Example 2: Code: ksba_name_release (ksba_name_t name) { int i; if (!name) return; if (name->ref_count < 1) { fprintf (stderr, "BUG: trying to release an already released name\n"); return; } if (--name->ref_count) return; for (i=0; i < name->n_names; i++) xfree (name->names[i]); xfree (name->names); name->n_names = 0; xfree (name); } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t Camera2Client::storeMetaDataInBuffers(bool enabled) { ATRACE_CALL(); Mutex::Autolock icl(mBinderSerializationLock); status_t res; if ( (res = checkPid(__FUNCTION__) ) != OK) return res; SharedParameters::Lock l(mParameters); switch (l.mParameters.state) { case Parameters::RECORD: case Parameters::VIDEO_SNAPSHOT: ALOGE("%s: Camera %d: Can't be called in state %s", __FUNCTION__, mCameraId, Parameters::getStateName(l.mParameters.state)); return INVALID_OPERATION; default: break; } l.mParameters.storeMetadataInBuffers = enabled; return OK; } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: TestFlashMessageLoop::TestFlashMessageLoop(TestingInstance* instance) : TestCase(instance), message_loop_(NULL), callback_factory_(this) { } Commit Message: Fix PPB_Flash_MessageLoop. This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop. BUG=569496 Review URL: https://codereview.chromium.org/1559113002 Cr-Commit-Position: refs/heads/master@{#374529} CWE ID: CWE-264 Target: 1 Example 2: Code: bool IsInnerInterstitialPageConnected(InterstitialPage* interstitial_page) { InterstitialPageImpl* impl = static_cast<InterstitialPageImpl*>(interstitial_page); RenderWidgetHostViewBase* rwhvb = static_cast<RenderWidgetHostViewBase*>(impl->GetView()); EXPECT_TRUE(rwhvb->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* rwhvcf = static_cast<RenderWidgetHostViewChildFrame*>(rwhvb); CrossProcessFrameConnector* frame_connector = static_cast<CrossProcessFrameConnector*>( rwhvcf->FrameConnectorForTesting()); WebContentsImpl* inner_web_contents = static_cast<WebContentsImpl*>(impl->GetWebContents()); FrameTreeNode* outer_node = FrameTreeNode::GloballyFindByID( inner_web_contents->GetOuterDelegateFrameTreeNodeId()); return outer_node->current_frame_host()->GetView() == frame_connector->GetParentRenderWidgetHostView(); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nick Carter <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#553867} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static u8 nfc_llcp_ssap(struct sk_buff *pdu) { return pdu->data[1] & 0x3f; } Commit Message: net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails KASAN report this: BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc] Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401 CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 kasan_report+0x171/0x18d mm/kasan/report.c:321 memcpy+0x1f/0x50 mm/kasan/common.c:130 nfc_llcp_build_gb+0x37f/0x540 [nfc] nfc_llcp_register_device+0x6eb/0xb50 [nfc] nfc_register_device+0x50/0x1d0 [nfc] nfcsim_device_new+0x394/0x67d [nfcsim] ? 0xffffffffc1080000 nfcsim_init+0x6b/0x1000 [nfcsim] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 nfc_llcp_build_tlv will return NULL on fails, caller should check it, otherwise will trigger a NULL dereference. Reported-by: Hulk Robot <[email protected]> Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames") Fixes: d646960f7986 ("NFC: Initial LLCP support") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ScreenOrientationDispatcherHost::OnUnlockRequest( RenderFrameHost* render_frame_host) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_.get()) return; provider_->UnlockOrientation(); } Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 1 Example 2: Code: static void vnc_release_modifiers(VncState *vs) { static const int keycodes[] = { /* shift, control, alt keys, both left & right */ 0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8, }; int i, keycode; if (!qemu_console_is_graphic(NULL)) { return; } for (i = 0; i < ARRAY_SIZE(keycodes); i++) { keycode = keycodes[i]; if (!vs->modifiers_state[keycode]) { continue; } qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false); } } Commit Message: CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const { assert(m_pos >= m_element_start); pEntry = NULL; if (index < 0) return -1; //generic error if (m_entries_count < 0) return E_BUFFER_NOT_FULL; assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (index < m_entries_count) { pEntry = m_entries[index]; assert(pEntry); return 1; //found entry } if (m_element_size < 0) //we don't know cluster end yet return E_BUFFER_NOT_FULL; //underflow const long long element_stop = m_element_start + m_element_size; if (m_pos >= element_stop) return 0; //nothing left to parse return E_BUFFER_NOT_FULL; //underflow, since more remains to be parsed } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: void TabStripGtk::StartMiniTabAnimation(int index) { StopAnimation(); active_animation_.reset(new MiniTabAnimation(this, index)); active_animation_->Start(); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ax25_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; void __user *argp = (void __user *)arg; int res = 0; lock_sock(sk); switch (cmd) { case TIOCOUTQ: { long amount; amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; res = put_user(amount, (int __user *)argp); break; } case TIOCINQ: { struct sk_buff *skb; long amount = 0L; /* These two are safe on a single CPU system as only user tasks fiddle here */ if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) amount = skb->len; res = put_user(amount, (int __user *) argp); break; } case SIOCGSTAMP: res = sock_get_timestamp(sk, argp); break; case SIOCGSTAMPNS: res = sock_get_timestampns(sk, argp); break; case SIOCAX25ADDUID: /* Add a uid to the uid/call map table */ case SIOCAX25DELUID: /* Delete a uid from the uid/call map table */ case SIOCAX25GETUID: { struct sockaddr_ax25 sax25; if (copy_from_user(&sax25, argp, sizeof(sax25))) { res = -EFAULT; break; } res = ax25_uid_ioctl(cmd, &sax25); break; } case SIOCAX25NOUID: { /* Set the default policy (default/bar) */ long amount; if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } if (get_user(amount, (long __user *)argp)) { res = -EFAULT; break; } if (amount < 0 || amount > AX25_NOUID_BLOCK) { res = -EINVAL; break; } ax25_uid_policy = amount; res = 0; break; } case SIOCADDRT: case SIOCDELRT: case SIOCAX25OPTRT: if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } res = ax25_rt_ioctl(cmd, argp); break; case SIOCAX25CTLCON: if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } res = ax25_ctl_ioctl(cmd, argp); break; case SIOCAX25GETINFO: case SIOCAX25GETINFOOLD: { ax25_cb *ax25 = sk_to_ax25(sk); struct ax25_info_struct ax25_info; ax25_info.t1 = ax25->t1 / HZ; ax25_info.t2 = ax25->t2 / HZ; ax25_info.t3 = ax25->t3 / HZ; ax25_info.idle = ax25->idle / (60 * HZ); ax25_info.n2 = ax25->n2; ax25_info.t1timer = ax25_display_timer(&ax25->t1timer) / HZ; ax25_info.t2timer = ax25_display_timer(&ax25->t2timer) / HZ; ax25_info.t3timer = ax25_display_timer(&ax25->t3timer) / HZ; ax25_info.idletimer = ax25_display_timer(&ax25->idletimer) / (60 * HZ); ax25_info.n2count = ax25->n2count; ax25_info.state = ax25->state; ax25_info.rcv_q = sk_rmem_alloc_get(sk); ax25_info.snd_q = sk_wmem_alloc_get(sk); ax25_info.vs = ax25->vs; ax25_info.vr = ax25->vr; ax25_info.va = ax25->va; ax25_info.vs_max = ax25->vs; /* reserved */ ax25_info.paclen = ax25->paclen; ax25_info.window = ax25->window; /* old structure? */ if (cmd == SIOCAX25GETINFOOLD) { static int warned = 0; if (!warned) { printk(KERN_INFO "%s uses old SIOCAX25GETINFO\n", current->comm); warned=1; } if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct_deprecated))) { res = -EFAULT; break; } } else { if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct))) { res = -EINVAL; break; } } res = 0; break; } case SIOCAX25ADDFWD: case SIOCAX25DELFWD: { struct ax25_fwd_struct ax25_fwd; if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } if (copy_from_user(&ax25_fwd, argp, sizeof(ax25_fwd))) { res = -EFAULT; break; } res = ax25_fwd_ioctl(cmd, &ax25_fwd); break; } case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFMETRIC: case SIOCSIFMETRIC: res = -EINVAL; break; default: res = -ENOIOCTLCMD; break; } release_sock(sk); return res; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: uint8_t* input() const { return input_ + BorderTop() * kOuterBlockSize + BorderLeft(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: bool ipv6_opt_accepted(const struct sock *sk, const struct sk_buff *skb, const struct inet6_skb_parm *opt) { const struct ipv6_pinfo *np = inet6_sk(sk); if (np->rxopt.all) { if (((opt->flags & IP6SKB_HOPBYHOP) && (np->rxopt.bits.hopopts || np->rxopt.bits.ohopopts)) || (ip6_flowinfo((struct ipv6hdr *) skb_network_header(skb)) && np->rxopt.bits.rxflow) || (opt->srcrt && (np->rxopt.bits.srcrt || np->rxopt.bits.osrcrt)) || ((opt->dst1 || opt->dst0) && (np->rxopt.bits.dstopts || np->rxopt.bits.odstopts))) return true; } return false; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ModuleExport void UnregisterAAIImage(void) { (void) UnregisterMagickInfo("AAI"); } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document* document, const String& markup, const String& baseURL, FragmentScriptingPermission scriptingPermission) { RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document); RefPtr<DocumentFragment> fragment = Range::createDocumentFragmentForElement(markup, fakeBody.get(), scriptingPermission); if (fragment && !baseURL.isEmpty() && baseURL != blankURL() && baseURL != document->baseURL()) completeURLs(fragment.get(), baseURL); return fragment.release(); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264 Target: 1 Example 2: Code: int ZEXPORT inflatePrime(strm, bits, value) z_streamp strm; int bits; int value; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (bits < 0) { state->hold = 0; state->bits = 0; return Z_OK; } if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; value &= (1L << bits) - 1; state->hold += value << state->bits; state->bits += bits; return Z_OK; } Commit Message: Avoid shifts of negative values inflateMark(). The C standard says that bit shifts of negative integers is undefined. This casts to unsigned values to assure a known result. CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SetCard(const CreditCard& card) { std::vector<CreditCard> cards; cards.push_back(card); SetCards(&cards); } Commit Message: Fix OS_MACOS typos. Should be OS_MACOSX. BUG=163208 TEST=none Review URL: https://codereview.chromium.org/12829005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@189130 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( const GURL& page_url) const { if (page_url.host() == extension_misc::kBookmarkManagerId) return BookmarksUI::GetFaviconResourceBytes(); if (page_url.SchemeIs(chrome::kExtensionScheme)) { NOTREACHED(); return NULL; } if (!HasWebUIScheme(page_url)) return NULL; #if defined(OS_WIN) if (page_url.host() == chrome::kChromeUIConflictsHost) return ConflictsUI::GetFaviconResourceBytes(); #endif if (page_url.host() == chrome::kChromeUICrashesHost) return CrashesUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIHistoryHost) return HistoryUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIFlagsHost) return FlagsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISessionsHost) return SessionsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUIFlashHost) return FlashUI::GetFaviconResourceBytes(); #if !defined(OS_ANDROID) if (page_url.host() == chrome::kChromeUIDownloadsHost) return DownloadsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISettingsHost) return OptionsUI::GetFaviconResourceBytes(); if (page_url.host() == chrome::kChromeUISettingsFrameHost) return options2::OptionsUI::GetFaviconResourceBytes(); #endif if (page_url.host() == chrome::kChromeUIPluginsHost) return PluginsUI::GetFaviconResourceBytes(); return NULL; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: int LayoutCount() const { return GetDummyPageHolder().GetFrameView().LayoutCount(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: TestPaintArtifact& TestPaintArtifact::ScrollHitTest( scoped_refptr<const TransformPaintPropertyNode> scroll_offset) { return ScrollHitTest(NewClient(), scroll_offset); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec) { WORD16 *pi2_vld_out; UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; UWORD32 u4_frm_offset = 0; const dec_mb_params_t *ps_dec_mb_params; IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; pi2_vld_out = ps_dec->ai2_vld_buf; memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv)); ps_dec->u2_prev_intra_mb = 0; ps_dec->u2_first_mb = 1; ps_dec->u2_picture_width = ps_dec->u2_frame_width; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { ps_dec->u2_picture_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; WORD32 ret; UWORD32 u4_x_dst_offset = 0; UWORD32 u4_y_dst_offset = 0; UWORD8 *pu1_out_p; UWORD8 *pu1_pred; WORD32 u4_pred_strd; IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); if(ps_dec->e_pic_type == B_PIC) ret = impeg2d_dec_pnb_mb_params(ps_dec); else ret = impeg2d_dec_p_mb_params(ps_dec); if(ret) return IMPEG2D_MB_TEX_DECODE_ERR; IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width; pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset; if(ps_dec->u2_prev_intra_mb == 0) { UWORD32 offset_x, offset_y, stride; UWORD16 index = (ps_dec->u2_motion_type); /*only for non intra mb's*/ if(ps_dec->e_mb_pred == BIDIRECT) { ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index]; } else { ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; } stride = ps_dec->u2_picture_width; offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4); offset_y = (ps_dec->u2_mb_y << 4); ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x; stride = stride >> 1; ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride + (offset_x >> 1); ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride + (offset_x >> 1); PROFILE_DISABLE_MC_IF0 ps_dec_mb_params->pf_mc(ps_dec); } for(i = 0; i < NUM_LUMA_BLKS; ++i) { if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0) { e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, Y_LUMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } u4_x_offset = gai2_impeg2_blk_x_off[i]; if(ps_dec->u2_field_dct == 0) u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; else u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ; IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset; u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset, 8, u4_pred_strd, ps_dec->u2_picture_width << ps_dec->u2_field_dct, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } } /* For U and V blocks, divide the x and y offsets by 2. */ u4_x_dst_offset >>= 1; u4_y_dst_offset >>= 2; /* In case of chrominance blocks the DCT will be frame DCT */ /* i = 0, U component and i = 1 is V componet */ if((ps_dec->u2_cbp & 0x02) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, U_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } if((ps_dec->u2_cbp & 0x01) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, V_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } ps_dec->u2_num_mbs_left--; ps_dec->u2_first_mb = 0; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return e_error; } Commit Message: Fixed Memory Overflow Errors In function impeg2d_dec_p_b_slice, there was no check for num_mbs_left == 0 after skip_mbs function call. Hence, even though it should have returned as an error, it goes ahead to decode the frame and writes beyond the buffer allocated for output. Put a check for the same. Bug: 38207066 Test: before/after execution of PoC on angler/nyc-mr2-dev Change-Id: If4b7bea51032bf2fe2edd03f64a68847aa4f6a00 (cherry picked from commit 2df080153464bf57084d68ba3594e199bc140eb4) CWE ID: CWE-119 Target: 1 Example 2: Code: std::string EscapeCacheFileName(const std::string& filename) { std::string escaped; for (size_t i = 0; i < filename.size(); ++i) { char c = filename[i]; if (c == '%' || c == '.' || c == '/') { base::StringAppendF(&escaped, "%%%02X", c); } else { escaped.push_back(c); } } return escaped; } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SegmentInfo::~SegmentInfo() { delete[] m_pMuxingAppAsUTF8; m_pMuxingAppAsUTF8 = NULL; delete[] m_pWritingAppAsUTF8; m_pWritingAppAsUTF8 = NULL; delete[] m_pTitleAsUTF8; m_pTitleAsUTF8 = NULL; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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 Target: 1 Example 2: Code: int register_netdevice(struct net_device *dev) { int ret; struct net *net = dev_net(dev); BUG_ON(dev_boot_phase); ASSERT_RTNL(); might_sleep(); /* When net_device's are persistent, this will be fatal. */ BUG_ON(dev->reg_state != NETREG_UNINITIALIZED); BUG_ON(!net); spin_lock_init(&dev->addr_list_lock); netdev_set_addr_lockdep_class(dev); ret = dev_get_valid_name(net, dev, dev->name); if (ret < 0) goto out; /* Init, if this function is available */ if (dev->netdev_ops->ndo_init) { ret = dev->netdev_ops->ndo_init(dev); if (ret) { if (ret > 0) ret = -EIO; goto out; } } if (((dev->hw_features | dev->features) & NETIF_F_HW_VLAN_CTAG_FILTER) && (!dev->netdev_ops->ndo_vlan_rx_add_vid || !dev->netdev_ops->ndo_vlan_rx_kill_vid)) { netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n"); ret = -EINVAL; goto err_uninit; } ret = -EBUSY; if (!dev->ifindex) dev->ifindex = dev_new_index(net); else if (__dev_get_by_index(net, dev->ifindex)) goto err_uninit; /* Transfer changeable features to wanted_features and enable * software offloads (GSO and GRO). */ dev->hw_features |= NETIF_F_SOFT_FEATURES; dev->features |= NETIF_F_SOFT_FEATURES; if (dev->netdev_ops->ndo_udp_tunnel_add) { dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT; dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT; } dev->wanted_features = dev->features & dev->hw_features; if (!(dev->flags & IFF_LOOPBACK)) dev->hw_features |= NETIF_F_NOCACHE_COPY; /* If IPv4 TCP segmentation offload is supported we should also * allow the device to enable segmenting the frame with the option * of ignoring a static IP ID value. This doesn't enable the * feature itself but allows the user to enable it later. */ if (dev->hw_features & NETIF_F_TSO) dev->hw_features |= NETIF_F_TSO_MANGLEID; if (dev->vlan_features & NETIF_F_TSO) dev->vlan_features |= NETIF_F_TSO_MANGLEID; if (dev->mpls_features & NETIF_F_TSO) dev->mpls_features |= NETIF_F_TSO_MANGLEID; if (dev->hw_enc_features & NETIF_F_TSO) dev->hw_enc_features |= NETIF_F_TSO_MANGLEID; /* Make NETIF_F_HIGHDMA inheritable to VLAN devices. */ dev->vlan_features |= NETIF_F_HIGHDMA; /* Make NETIF_F_SG inheritable to tunnel devices. */ dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL; /* Make NETIF_F_SG inheritable to MPLS. */ dev->mpls_features |= NETIF_F_SG; ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev); ret = notifier_to_errno(ret); if (ret) goto err_uninit; ret = netdev_register_kobject(dev); if (ret) goto err_uninit; dev->reg_state = NETREG_REGISTERED; __netdev_update_features(dev); /* * Default initial state at registry is that the * device is present. */ set_bit(__LINK_STATE_PRESENT, &dev->state); linkwatch_init_dev(dev); dev_init_scheduler(dev); dev_hold(dev); list_netdevice(dev); add_device_randomness(dev->dev_addr, dev->addr_len); /* If the device has permanent device address, driver should * set dev_addr and also addr_assign_type should be set to * NET_ADDR_PERM (default value). */ if (dev->addr_assign_type == NET_ADDR_PERM) memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len); /* Notify protocols, that a new device appeared. */ ret = call_netdevice_notifiers(NETDEV_REGISTER, dev); ret = notifier_to_errno(ret); if (ret) { rollback_registered(dev); dev->reg_state = NETREG_UNREGISTERED; } /* * Prevent userspace races by waiting until the network * device is fully setup before sending notifications. */ if (!dev->rtnl_link_ops || dev->rtnl_link_state == RTNL_LINK_INITIALIZED) rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL); out: return ret; err_uninit: if (dev->netdev_ops->ndo_uninit) dev->netdev_ops->ndo_uninit(dev); if (dev->priv_destructor) dev->priv_destructor(dev); goto out; } Commit Message: tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <[email protected]> Cc: Jason Wang <[email protected]> Cc: "Michael S. Tsirkin" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; DCRaw *d = (DCRaw*)cinfo->client_data; nbytes = fread (jpeg_buffer, 1, 4096, d->ifp); swab ((const char *)jpeg_buffer, (char *)jpeg_buffer, nbytes); /*mingw UF*/ cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } Commit Message: Avoid overflow in ljpeg_start(). CWE ID: CWE-189 Output:
0