text
stringlengths
517
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static gboolean key_value_ok(gchar *key, gchar *value) { char *i; /* check key, it has to be valid filename and will end up in the * bugzilla */ for (i = key; *i != 0; i++) { if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' ')) return FALSE; } /* check value of 'basename', it has to be valid non-hidden directory * name */ if (strcmp(key, "basename") == 0 || strcmp(key, FILENAME_TYPE) == 0 ) { if (!str_is_correct_filename(value)) { error_msg("Value of '%s' ('%s') is not a valid directory name", key, value); return FALSE; } } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'daemon, dbus: allow only root to create CCpp, Koops, vmcore and xorg Florian Weimer <fweimer@redhat.com>: This prevents users from feeding things that are not actually coredumps and excerpts from /proc to these analyzers. For example, it should not be possible to trigger a rule with “EVENT=post-create analyzer=CCpp” using NewProblem Related: #1212861 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *sanitize_cookie_path(const char *cookie_path) { size_t len; char *new_path = strdup(cookie_path); if(!new_path) return NULL; /* some stupid site sends path attribute with '"'. */ if(new_path[0] == '\"') { memmove((void *)new_path, (const void *)(new_path + 1), strlen(new_path)); } if(new_path[strlen(new_path) - 1] == '\"') { new_path[strlen(new_path) - 1] = 0x0; } /* RFC6265 5.2.4 The Path Attribute */ if(new_path[0] != '/') { /* Let cookie-path be the default-path. */ free(new_path); new_path = strdup("/"); return new_path; } /* convert /hoge/ to /hoge */ len = strlen(new_path); if(1 < len && new_path[len - 1] == '/') { new_path[len - 1] = 0x0; } return new_path; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cookie: cookie parser out of boundary memory access The internal libcurl function called sanitize_cookie_path() that cleans up the path element as given to it from a remote site or when read from a file, did not properly validate the input. If given a path that consisted of a single double-quote, libcurl would index a newly allocated memory area with index -1 and assign a zero to it, thus destroying heap memory it wasn't supposed to. CVE-2015-3145 Bug: http://curl.haxx.se/docs/adv_20150422C.html Reported-by: Hanno Böck'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static PHP_FUNCTION(xmlwriter_open_uri) { char *valid_file = NULL; xmlwriter_object *intern; xmlTextWriterPtr ptr; char *source; char resolved_path[MAXPATHLEN + 1]; int source_len; #ifdef ZEND_ENGINE_2 zval *this = getThis(); ze_xmlwriter_object *ze_obj = NULL; #endif #ifndef ZEND_ENGINE_2 xmlOutputBufferPtr out_buffer; void *ioctx; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) { return; } #ifdef ZEND_ENGINE_2 if (this) { /* We do not use XMLWRITER_FROM_OBJECT, xmlwriter init function here */ ze_obj = (ze_xmlwriter_object*) zend_object_store_get_object(this TSRMLS_CC); } #endif if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string as source"); RETURN_FALSE; } valid_file = _xmlwriter_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to resolve file path"); RETURN_FALSE; } /* TODO: Fix either the PHP stream or libxml APIs: it can then detect when a given path is valid and not report out of memory error. Once it is done, remove the directory check in _xmlwriter_get_valid_file_path */ #ifndef ZEND_ENGINE_2 ioctx = php_xmlwriter_streams_IO_open_write_wrapper(valid_file TSRMLS_CC); if (ioctx == NULL) { RETURN_FALSE; } out_buffer = xmlOutputBufferCreateIO(php_xmlwriter_streams_IO_write, php_xmlwriter_streams_IO_close, ioctx, NULL); if (out_buffer == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create output buffer"); RETURN_FALSE; } ptr = xmlNewTextWriter(out_buffer); #else ptr = xmlNewTextWriterFilename(valid_file, 0); #endif if (!ptr) { RETURN_FALSE; } intern = emalloc(sizeof(xmlwriter_object)); intern->ptr = ptr; intern->output = NULL; #ifndef ZEND_ENGINE_2 intern->uri_output = out_buffer; #else if (this) { if (ze_obj->xmlwriter_ptr) { xmlwriter_free_resource_ptr(ze_obj->xmlwriter_ptr TSRMLS_CC); } ze_obj->xmlwriter_ptr = intern; RETURN_TRUE; } else #endif { ZEND_REGISTER_RESOURCE(return_value,intern,le_xmlwriter); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name) { INITIALIZE_LIBREPORT(); char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER); if (!type) { error_msg(_("Missing required item: '%s'"), FILENAME_ANALYZER); return NULL; } uid_t uid = (uid_t)-1L; char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID); if (uid_str) { char *endptr; errno = 0; long val = strtol(uid_str, &endptr, 10); if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val) { error_msg(_("uid value is not valid: '%s'"), uid_str); return NULL; } uid = (uid_t)val; } struct timeval tv; if (gettimeofday(&tv, NULL) < 0) { perror_msg("gettimeofday()"); return NULL; } char *problem_id = xasprintf("%s-%s.%ld-%lu"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid()); log_info("Saving to %s/%s with uid %d", base_dir_name, problem_id, uid); struct dump_dir *dd; if (base_dir_name) dd = try_dd_create(base_dir_name, problem_id, uid); else { /* Try /var/run/abrt */ dd = try_dd_create(LOCALSTATEDIR"/run/abrt", problem_id, uid); /* Try $HOME/tmp */ if (!dd) { char *home = getenv("HOME"); if (home && home[0]) { home = concat_path_file(home, "tmp"); /*mkdir(home, 0777); - do we want this? */ dd = try_dd_create(home, problem_id, uid); free(home); } } //TODO: try user's home dir obtained by getpwuid(getuid())? /* Try system temporary directory */ if (!dd) dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid); } if (!dd) /* try_dd_create() already emitted the error message */ goto ret; GHashTableIter iter; char *name; struct problem_item *value; g_hash_table_iter_init(&iter, problem_data); while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value)) { if (value->flags & CD_FLAG_BIN) { char *dest = concat_path_file(dd->dd_dirname, name); log_info("copying '%s' to '%s'", value->content, dest); off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH); if (copied < 0) error_msg("Can't copy %s to %s", value->content, dest); else log_info("copied %li bytes", (unsigned long)copied); free(dest); continue; } /* only files should contain '/' and those are handled earlier */ if (name[0] == '.' || strchr(name, '/')) { error_msg("Problem data field name contains disallowed chars: '%s'", name); continue; } dd_save_text(dd, name, value->content); } /* need to create basic files AFTER we save the pd to dump_dir * otherwise we can't skip already created files like in case when * reporting from anaconda where we can't read /etc/{system,redhat}-release * and os_release is taken from anaconda */ dd_create_basic_files(dd, uid, NULL); problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0'; char* new_path = concat_path_file(base_dir_name, problem_id); log_info("Renaming from '%s' to '%s'", dd->dd_dirname, new_path); dd_rename(dd, new_path); ret: free(problem_id); return dd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'dd: harden functions against directory traversal issues Test correctness of all accessed dump dir files in all dd* functions. Before this commit, the callers were allowed to pass strings like "../../etc/shadow" in the filename argument of all dd* functions. Related: #1214457 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (g_settings_privatereports) { struct stat statbuf; if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) { error_msg("Path '%s' isn't directory", dirname); return 404; /* Not Found */ } /* Get ABRT's group gid */ struct group *gr = getgrnam("abrt"); if (!gr) { error_msg("Group 'abrt' does not exist"); return 500; } if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname); return 403; } struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY); const bool complete = dd && problem_dump_dir_is_complete(dd); dd_close(dd); if (complete) { error_msg("Problem directory '%s' has already been processed", dirname); return 403; } } else if (!dump_dir_accessible_by_uid(dirname, client_uid)) { if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dirname); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid); return 403; /* Forbidden */ } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: //log("Reading from event fd %d", child_stdout_fd); /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); //log("Started notify, fd %d -> %d", fd, child_stdout_fd); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: add functions validating dump dir Move the code from abrt-server to shared library and fix the condition validating dump dir's path. As of now, abrt is allowed to process only direct sub-directories of the dump locations. Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int dd_delete_item(struct dump_dir *dd, const char *name) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ if (!str_is_correct_filename(name)) error_msg_and_die("Cannot delete item. '%s' is not a valid file name", name); char *path = concat_path_file(dd->dd_dirname, name); int res = unlink(path); if (res < 0) { if (errno == ENOENT) errno = res = 0; else perror_msg("Can't delete file '%s'", path); } free(path); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code Florian Weimer <fweimer@redhat.com>: dd_opendir() should keep a file handle (opened with O_DIRECTORY) and use openat() and similar functions to access files in it. ... The file system manipulation functions should guard against hard links (check that link count is <= 1, just as in the user coredump code in abrt-hook-ccpp), possibly after opening the file with O_PATH first to avoid side effects on open/close. Related: #1214745 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct dump_dir *dd_create_skeleton(const char *dir, uid_t uid, mode_t mode, int flags) { /* a little trick to copy read bits from file mode to exec bit of dir mode*/ mode_t dir_mode = mode | ((mode & 0444) >> 2); struct dump_dir *dd = dd_init(); dd->mode = mode; /* Unlike dd_opendir, can't use realpath: the directory doesn't exist yet, * realpath will always return NULL. We don't really have to: * dd_opendir(".") makes sense, dd_create(".") does not. */ dir = dd->dd_dirname = rm_trailing_slashes(dir); const char *last_component = strrchr(dir, '/'); if (last_component) last_component++; else last_component = dir; if (dot_or_dotdot(last_component)) { /* dd_create("."), dd_create(".."), dd_create("dir/."), * dd_create("dir/..") and similar are madness, refuse them. */ error_msg("Bad dir name '%s'", dir); dd_close(dd); return NULL; } /* Was creating it with mode 0700 and user as the owner, but this allows * the user to replace any file in the directory, changing security-sensitive data * (e.g. "uid", "analyzer", "executable") */ int r; if ((flags & DD_CREATE_PARENTS)) r = g_mkdir_with_parents(dd->dd_dirname, dir_mode); else r = mkdir(dd->dd_dirname, dir_mode); if (r != 0) { perror_msg("Can't create directory '%s'", dir); dd_close(dd); return NULL; } if (dd_lock(dd, CREATE_LOCK_USLEEP, /*flags:*/ 0) < 0) { dd_close(dd); return NULL; } /* mkdir's mode (above) can be affected by umask, fix it */ if (chmod(dir, dir_mode) == -1) { perror_msg("Can't change mode of '%s'", dir); dd_close(dd); return NULL; } dd->dd_uid = (uid_t)-1L; dd->dd_gid = (gid_t)-1L; if (uid != (uid_t)-1L) { dd->dd_uid = 0; dd->dd_uid = 0; #if DUMP_DIR_OWNED_BY_USER > 0 /* Check crashed application's uid */ struct passwd *pw = getpwuid(uid); if (pw) dd->dd_uid = pw->pw_uid; else error_msg("User %lu does not exist, using uid 0", (long)uid); /* Get ABRT's group gid */ struct group *gr = getgrnam("abrt"); if (gr) dd->dd_gid = gr->gr_gid; else error_msg("Group 'abrt' does not exist, using gid 0"); #else /* Get ABRT's user uid */ struct passwd *pw = getpwnam("abrt"); if (pw) dd->dd_uid = pw->pw_uid; else error_msg("User 'abrt' does not exist, using uid 0"); /* Get crashed application's gid */ pw = getpwuid(uid); if (pw) dd->dd_gid = pw->pw_gid; else error_msg("User %lu does not exist, using gid 0", (long)uid); #endif } return dd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code Florian Weimer <fweimer@redhat.com>: dd_opendir() should keep a file handle (opened with O_DIRECTORY) and use openat() and similar functions to access files in it. ... The file system manipulation functions should guard against hard links (check that link count is <= 1, just as in the user coredump code in abrt-hook-ccpp), possibly after opening the file with O_PATH first to avoid side effects on open/close. Related: #1214745 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void dd_unlock(struct dump_dir *dd) { if (dd->locked) { dd->locked = 0; unsigned dirname_len = strlen(dd->dd_dirname); char lock_buf[dirname_len + sizeof("/.lock")]; strcpy(lock_buf, dd->dd_dirname); strcpy(lock_buf + dirname_len, "/.lock"); xunlink(lock_buf); log_info("Unlocked '%s'", lock_buf); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code Florian Weimer <fweimer@redhat.com>: dd_opendir() should keep a file handle (opened with O_DIRECTORY) and use openat() and similar functions to access files in it. ... The file system manipulation functions should guard against hard links (check that link count is <= 1, just as in the user coredump code in abrt-hook-ccpp), possibly after opening the file with O_PATH first to avoid side effects on open/close. Related: #1214745 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MYSQL *db_connect(char *host, char *database, char *user, char *passwd) { MYSQL *mysql; if (verbose) fprintf(stdout, "Connecting to %s\n", host ? host : "localhost"); if (!(mysql= mysql_init(NULL))) return 0; if (opt_compress) mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS); if (opt_local_file) mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_file); #ifdef HAVE_OPENSSL if (opt_use_ssl) { mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl); mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath); } mysql_options(mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); if (opt_bind_addr) mysql_options(mysql,MYSQL_OPT_BIND,opt_bind_addr); #if defined (_WIN32) && !defined (EMBEDDED_LIBRARY) if (shared_memory_base_name) mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif if (opt_plugin_dir && *opt_plugin_dir) mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset); mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0); mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqlimport"); if (!(mysql_real_connect(mysql,host,user,passwd, database,opt_mysql_port,opt_mysql_unix_port, 0))) { ignore_errors=0; /* NO RETURN FROM db_error */ db_error(mysql); } mysql->reconnect= 0; if (verbose) fprintf(stdout, "Selecting database %s\n", database); if (mysql_select_db(mysql, database)) { ignore_errors=0; db_error(mysql); } return mysql; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption # Changed the meaning of the --ssl=1 option of all client binaries to mean force ssl, not try ssl and fail over to eunecrypted # Added a new MYSQL_OPT_SSL_ENFORCE mysql_options() option to specify that an ssl connection is required. # Added a new macro SSL_SET_OPTIONS() to the client SSL handling headers that sets all the relevant SSL options at once. # Revamped all of the current native clients to use the new macro # Removed some Windows line endings. # Added proper handling of the new option into the ssl helper headers. # If SSL is mandatory assume that the media is secure enough for the sha256 plugin to do unencrypted password exchange even before establishing a connection. # Set the default ssl cipher to DHE-RSA-AES256-SHA if none is specified. # updated test cases that require a non-default cipher to spawn a mysql command line tool binary since mysqltest has no support for specifying ciphers. # updated the replication slave connection code to always enforce SSL if any of the SSL config options is present. # test cases added and updated. # added a mysql_get_option() API to return mysql_options() values. Used the new API inside the sha256 plugin. # Fixed compilation warnings because of unused variables. # Fixed test failures (mysql_ssl and bug13115401) # Fixed whitespace issues. # Fully implemented the mysql_get_option() function. # Added a test case for mysql_get_option() # fixed some trailing whitespace issues # fixed some uint/int warnings in mysql_client_test.c # removed shared memory option from non-windows get_options tests # moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char **argv) { int error; my_bool first_argument_uses_wildcards=0; char *wild; MYSQL mysql; MY_INIT(argv[0]); if (load_defaults("my",load_default_groups,&argc,&argv)) exit(1); get_options(&argc,&argv); wild=0; if (argc) { char *pos= argv[argc-1], *to; for (to= pos ; *pos ; pos++, to++) { switch (*pos) { case '*': *pos= '%'; first_argument_uses_wildcards= 1; break; case '?': *pos= '_'; first_argument_uses_wildcards= 1; break; case '%': case '_': first_argument_uses_wildcards= 1; break; case '\\': pos++; default: break; } *to= *pos; } *to= *pos; /* just to copy a '\0' if '\\' was used */ } if (first_argument_uses_wildcards) wild= argv[--argc]; else if (argc == 3) /* We only want one field */ wild= argv[--argc]; if (argc > 2) { fprintf(stderr,"%s: Too many arguments\n",my_progname); exit(1); } mysql_init(&mysql); if (opt_compress) mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*)&opt_enable_cleartext_plugin); if (!(mysql_real_connect(&mysql,host,user,opt_password, (first_argument_uses_wildcards) ? "" : argv[0],opt_mysql_port,opt_mysql_unix_port, 0))) { fprintf(stderr,"%s: %s\n",my_progname,mysql_error(&mysql)); exit(1); } mysql.reconnect= 1; switch (argc) { case 0: error=list_dbs(&mysql,wild); break; case 1: if (opt_status) error=list_table_status(&mysql,argv[0],wild); else error=list_tables(&mysql,argv[0],wild); break; default: if (opt_status && ! wild) error=list_table_status(&mysql,argv[0],argv[1]); else error=list_fields(&mysql,argv[0],argv[1],wild); break; } mysql_close(&mysql); /* Close & free connection */ my_free(opt_password); #ifdef HAVE_SMEM my_free(shared_memory_base_name); #endif my_end(my_end_arg); exit(error ? 1 : 0); return 0; /* No compiler warnings */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ping_unhash(struct sock *sk) { struct inet_sock *isk = inet_sk(sk); pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num); if (sk_hashed(sk)) { write_lock_bh(&ping_table.lock); hlist_nulls_del(&sk->sk_nulls_node); sock_put(sk); isk->inet_num = 0; isk->inet_sport = 0; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); write_unlock_bh(&ping_table.lock); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ipv4: Missing sk_nulls_node_init() in ping_unhash(). If we don't do that, then the poison value is left in the ->pprev backlink. This can cause crashes if we do a disconnect, followed by a connect(). Tested-by: Linus Torvalds <torvalds@linux-foundation.org> Reported-by: Wen Xu <hotdog3645@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int is_integer(char *string) { if (isdigit(string[0]) || string[0] == '-' || string[0] == '+') { while (*++string && isdigit(*string)) ; /* deliberately empty */ if (!*string) return 1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes. - Don't overflow the small cs_start buffer (reported by Niels Thykier via the debian tracker (Jakub Wilk), found with a fuzzer ("American fuzzy lop")). - Cast arguments to <ctype.h> functions to unsigned char.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(chroot) { char *str; int ret, str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) { RETURN_FALSE; } ret = chroot(str); if (ret != 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s (errno %d)", strerror(errno), errno); RETURN_FALSE; } php_clear_stat_cache(1, NULL, 0 TSRMLS_CC); ret = chdir("/"); if (ret != 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s (errno %d)", strerror(errno), errno); RETURN_FALSE; } RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(pcntl_alarm) { long seconds; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &seconds) == FAILURE) return; RETURN_LONG ((long) alarm(seconds)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_login(ftpbuf_t *ftp, const char *user, const char *pass TSRMLS_DC) { #if HAVE_OPENSSL_EXT SSL_CTX *ctx = NULL; long ssl_ctx_options = SSL_OP_ALL; #endif if (ftp == NULL) { return 0; } #if HAVE_OPENSSL_EXT if (ftp->use_ssl && !ftp->ssl_active) { if (!ftp_putcmd(ftp, "AUTH", "TLS")) { return 0; } if (!ftp_getresp(ftp)) { return 0; } if (ftp->resp != 234) { if (!ftp_putcmd(ftp, "AUTH", "SSL")) { return 0; } if (!ftp_getresp(ftp)) { return 0; } if (ftp->resp != 334) { return 0; } else { ftp->old_ssl = 1; ftp->use_ssl_for_data = 1; } } ctx = SSL_CTX_new(SSLv23_client_method()); if (ctx == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to create the SSL context"); return 0; } #if OPENSSL_VERSION_NUMBER >= 0x0090605fL ssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; #endif SSL_CTX_set_options(ctx, ssl_ctx_options); ftp->ssl_handle = SSL_new(ctx); if (ftp->ssl_handle == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to create the SSL handle"); SSL_CTX_free(ctx); return 0; } SSL_set_fd(ftp->ssl_handle, ftp->fd); if (SSL_connect(ftp->ssl_handle) <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "SSL/TLS handshake failed"); SSL_shutdown(ftp->ssl_handle); SSL_free(ftp->ssl_handle); return 0; } ftp->ssl_active = 1; if (!ftp->old_ssl) { /* set protection buffersize to zero */ if (!ftp_putcmd(ftp, "PBSZ", "0")) { return 0; } if (!ftp_getresp(ftp)) { return 0; } /* enable data conn encryption */ if (!ftp_putcmd(ftp, "PROT", "P")) { return 0; } if (!ftp_getresp(ftp)) { return 0; } ftp->use_ssl_for_data = (ftp->resp >= 200 && ftp->resp <=299); } } #endif if (!ftp_putcmd(ftp, "USER", user)) { return 0; } if (!ftp_getresp(ftp)) { return 0; } if (ftp->resp == 230) { return 1; } if (ftp->resp != 331) { return 0; } if (!ftp_putcmd(ftp, "PASS", pass)) { return 0; } if (!ftp_getresp(ftp)) { return 0; } return (ftp->resp == 230); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_chmod(ftpbuf_t *ftp, const int mode, const char *filename, const int filename_len) { char *buffer; if (ftp == NULL || filename_len <= 0) { return 0; } spprintf(&buffer, 0, "CHMOD %o %s", mode, filename); if (!ftp_putcmd(ftp, "SITE", buffer)) { efree(buffer); return 0; } efree(buffer); if (!ftp_getresp(ftp) || ftp->resp != 200) { return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC) { php_stream *tmpstream = NULL; databuf_t *data = NULL; char *ptr; int ch, lastch; size_t size, rcvd; size_t lines; char **ret = NULL; char **entry; char *text; if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory."); return NULL; } if (!ftp_type(ftp, FTPTYPE_ASCII)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (!ftp_putcmd(ftp, cmd, path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) { goto bail; } /* some servers don't open a ftp-data connection if the directory is empty */ if (ftp->resp == 226) { ftp->data = data_close(ftp, data); php_stream_close(tmpstream); return ecalloc(1, sizeof(char*)); } /* pull data buffer into tmpfile */ if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; lines = 0; lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1 || rcvd > ((size_t)(-1))-size) { goto bail; } php_stream_write(tmpstream, data->buf, rcvd); size += rcvd; for (ptr = data->buf; rcvd; rcvd--, ptr++) { if (*ptr == '\n' && lastch == '\r') { lines++; } else { size++; } lastch = *ptr; } } ftp->data = data_close(ftp, data); php_stream_rewind(tmpstream); ret = safe_emalloc((lines + 1), sizeof(char*), size); entry = ret; text = (char*) (ret + lines + 1); *entry = text; lastch = 0; while ((ch = php_stream_getc(tmpstream)) != EOF) { if (ch == '\n' && lastch == '\r') { *(text - 1) = 0; *++entry = text; } else { *text++ = ch; } lastch = ch; } *entry = NULL; php_stream_close(tmpstream); if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) { efree(ret); return NULL; } return ret; bail: ftp->data = data_close(ftp, data); php_stream_close(tmpstream); if (ret) efree(ret); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'improve fix for Bug #69545'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tChecksumCheckResult ParaNdis_CheckRxChecksum( PARANDIS_ADAPTER *pContext, ULONG virtioFlags, tCompletePhysicalAddress *pPacketPages, ULONG ulPacketLength, ULONG ulDataOffset) { tOffloadSettingsFlags f = pContext->Offload.flags; tChecksumCheckResult res; tTcpIpPacketParsingResult ppr; ULONG flagsToCalculate = 0; res.value = 0; //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) { if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; } else { if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; } } ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete) { res.flags.IpOK = FALSE; res.flags.IpFailed = TRUE; return res; } if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) { pContext->extraStatistics.framesRxCSHwOK++; ppr.xxpCheckSum = ppresCSOK; } if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) { if (f.fRxIPChecksum) { res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; } if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPChecksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPChecksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } else if (ppr.ipStatus == ppresIPV6) { if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPv6Checksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPv6Checksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <yhindin@rehat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { ULONG tcpipDataAt; tTcpIpPacketParsingResult res = _res; tcpipDataAt = ipHeaderSize + sizeof(TCPHeader); res.xxpStatus = ppresXxpIncomplete; res.TcpUdp = ppresIsTCP; if (len >= tcpipDataAt) { TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); res.xxpStatus = ppresXxpKnown; tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader); res.XxpIpHeaderSize = tcpipDataAt; } else { DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt)); } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <yhindin@rehat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(imagefilledarc) { zval *IM; long cx, cy, w, h, ST, E, col, style; gdImagePtr im; int e, st; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col, &style) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); e = E; if (e < 0) { e %= 360; } st = ST; if (st < 0) { st %= 360; } gdImageFilledArc(im, cx, cy, w, h, st, e, col, style); RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf) { X509_STORE *store = NULL; store = X509_STORE_new(); /* Load the CAs we trust */ if (conf->ca_file || conf->ca_path) if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) { ERROR(LOG_PREFIX ": X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL)); ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file ); return NULL; } #ifdef X509_V_FLAG_CRL_CHECK if (conf->check_crl) X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK); #endif return store; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'Set X509_V_FLAG_CRL_CHECK_ALL'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process) { int ret, status; pid_t init_pid, pid, attached_pid, expected; struct lxc_proc_context_info *init_ctx; char* cwd; char* new_cwd; int ipc_sockets[2]; signed long personality; if (!options) options = &attach_static_default_options; init_pid = lxc_cmd_get_init_pid(name, lxcpath); if (init_pid < 0) { ERROR("failed to get the init pid"); return -1; } init_ctx = lxc_proc_get_context_info(init_pid); if (!init_ctx) { ERROR("failed to get context of the init process, pid = %ld", (long)init_pid); return -1; } personality = get_personality(name, lxcpath); if (init_ctx->personality < 0) { ERROR("Failed to get personality of the container"); lxc_proc_put_context_info(init_ctx); return -1; } init_ctx->personality = personality; if (!fetch_seccomp(name, lxcpath, init_ctx, options)) WARN("Failed to get seccomp policy"); cwd = getcwd(NULL, 0); /* determine which namespaces the container was created with * by asking lxc-start, if necessary */ if (options->namespaces == -1) { options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath); /* call failed */ if (options->namespaces == -1) { ERROR("failed to automatically determine the " "namespaces which the container unshared"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } } /* create a socket pair for IPC communication; set SOCK_CLOEXEC in order * to make sure we don't irritate other threads that want to fork+exec away * * IMPORTANT: if the initial process is multithreaded and another call * just fork()s away without exec'ing directly after, the socket fd will * exist in the forked process from the other thread and any close() in * our own child process will not really cause the socket to close properly, * potentiall causing the parent to hang. * * For this reason, while IPC is still active, we have to use shutdown() * if the child exits prematurely in order to signal that the socket * is closed and cannot assume that the child exiting will automatically * do that. * * IPC mechanism: (X is receiver) * initial process intermediate attached * X <--- send pid of * attached proc, * then exit * send 0 ------------------------------------> X * [do initialization] * X <------------------------------------ send 1 * [add to cgroup, ...] * send 2 ------------------------------------> X * close socket close socket * run program */ ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets); if (ret < 0) { SYSERROR("could not set up required IPC mechanism for attaching"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } /* create intermediate subprocess, three reasons: * 1. runs all pthread_atfork handlers and the * child will no longer be threaded * (we can't properly setns() in a threaded process) * 2. we can't setns() in the child itself, since * we want to make sure we are properly attached to * the pidns * 3. also, the initial thread has to put the attached * process into the cgroup, which we can only do if * we didn't already setns() (otherwise, user * namespaces will hate us) */ pid = fork(); if (pid < 0) { SYSERROR("failed to create first subprocess"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } if (pid) { pid_t to_cleanup_pid = pid; /* initial thread, we close the socket that is for the * subprocesses */ close(ipc_sockets[1]); free(cwd); /* attach to cgroup, if requested */ if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) { if (!cgroup_attach(name, lxcpath, pid)) goto cleanup_error; } /* Let the child process know to go ahead */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR("error using IPC to notify attached process for initialization (0)"); goto cleanup_error; } /* get pid from intermediate process */ ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL); if (ret <= 0) { if (ret != 0) ERROR("error using IPC to receive pid of attached process"); goto cleanup_error; } /* ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313 */ if (options->stdin_fd == 0) { signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); } /* reap intermediate process */ ret = wait_for_pid(pid); if (ret < 0) goto cleanup_error; /* we will always have to reap the grandchild now */ to_cleanup_pid = attached_pid; /* tell attached process it may start initializing */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR("error using IPC to notify attached process for initialization (0)"); goto cleanup_error; } /* wait for the attached process to finish initializing */ expected = 1; ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected); if (ret <= 0) { if (ret != 0) ERROR("error using IPC to receive notification from attached process (1)"); goto cleanup_error; } /* tell attached process we're done */ status = 2; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR("error using IPC to notify attached process for initialization (2)"); goto cleanup_error; } /* now shut down communication with child, we're done */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); lxc_proc_put_context_info(init_ctx); /* we're done, the child process should now execute whatever * it is that the user requested. The parent can now track it * with waitpid() or similar. */ *attached_process = attached_pid; return 0; cleanup_error: /* first shut down the socket, then wait for the pid, * otherwise the pid we're waiting for may never exit */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); if (to_cleanup_pid) (void) wait_for_pid(to_cleanup_pid); lxc_proc_put_context_info(init_ctx); return -1; } /* first subprocess begins here, we close the socket that is for the * initial thread */ close(ipc_sockets[0]); /* Wait for the parent to have setup cgroups */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_sockets[1], &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error communicating with child process"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach now, create another subprocess later, since pid namespaces * only really affect the children of the current process */ ret = lxc_attach_to_ns(init_pid, options->namespaces); if (ret < 0) { ERROR("failed to enter the namespace"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach succeeded, try to cwd */ if (options->initial_cwd) new_cwd = options->initial_cwd; else new_cwd = cwd; ret = chdir(new_cwd); if (ret < 0) WARN("could not change directory to '%s'", new_cwd); free(cwd); /* now create the real child process */ { struct attach_clone_payload payload = { .ipc_socket = ipc_sockets[1], .options = options, .init_ctx = init_ctx, .exec_function = exec_function, .exec_payload = exec_payload }; /* We use clone_parent here to make this subprocess a direct child of * the initial process. Then this intermediate process can exit and * the parent can directly track the attached process. */ pid = lxc_clone(attach_child_main, &payload, CLONE_PARENT); } /* shouldn't happen, clone() should always return positive pid */ if (pid <= 0) { SYSERROR("failed to create subprocess"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* tell grandparent the pid of the pid of the newly created child */ ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid)); if (ret != sizeof(pid)) { /* if this really happens here, this is very unfortunate, since the * parent will not know the pid of the attached process and will * not be able to wait for it (and we won't either due to CLONE_PARENT) * so the parent won't be able to reap it and the attached process * will remain a zombie */ ERROR("error using IPC to notify main process of pid of the attached process"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* the rest is in the hands of the initial and the attached process */ rexit(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'CVE-2015-1334: Don't use the container's /proc during attach A user could otherwise over-mount /proc and prevent the apparmor profile or selinux label from being written which combined with a modified /bin/sh or other commonly used binary would lead to unconfined code execution. Reported-by: Roman Fiedler Signed-off-by: Stéphane Graber <stgraber@ubuntu.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'sg_start_req(): make sure that there's not too many elements in iovec unfortunately, allowing an arbitrary 16bit value means a possibility of overflow in the calculation of total number of pages in bio_map_user_iov() - we rely on there being no more than PAGE_SIZE members of sum in the first loop there. If that sum wraps around, we end up allocating too small array of pointers to pages and it's easy to overflow it in the second loop. X-Coverup: TINC (and there's no lumber cartel either) Cc: stable@vger.kernel.org # way, way back Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Debug(const char *fmtstr, va_list args) { /* Ignored */ #ifdef VMX86_DEBUG sLog(log_warning, "Debug callback invoked. \n"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt) { int n; assert(cnt >= 0); assert(buf); JAS_DBGLOG(100, ("mem_read(%p, %p, %d)\n", obj, buf, cnt)); jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; n = m->len_ - m->pos_; cnt = JAS_MIN(n, cnt); memcpy(buf, &m->buf_[m->pos_], cnt); m->pos_ += cnt; return cnt; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void vnc_dpy_switch(DisplayChangeListener *dcl, DisplaySurface *surface) { VncDisplay *vd = container_of(dcl, VncDisplay, dcl); VncState *vs; vnc_abort_display_jobs(vd); /* server surface */ qemu_pixman_image_unref(vd->server); vd->ds = surface; vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT, surface_width(vd->ds), surface_height(vd->ds), NULL, 0); /* guest surface */ #if 0 /* FIXME */ if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel) console_color_init(ds); #endif qemu_pixman_image_unref(vd->guest.fb); vd->guest.fb = pixman_image_ref(surface->image); vd->guest.format = surface->format; VNC_SET_VISIBLE_PIXELS_DIRTY(vd->guest.dirty, surface_width(vd->ds), surface_height(vd->ds)); QTAILQ_FOREACH(vs, &vd->clients, next) { vnc_colordepth(vs); vnc_desktop_resize(vs); if (vs->vd->cursor) { vnc_cursor_define(vs); } VNC_SET_VISIBLE_PIXELS_DIRTY(vs->dirty, surface_width(vd->ds), surface_height(vd->ds)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <pl@kamp.de> Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplObjectStorage, serialize) { spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_SplObjectStorageElement *element; zval members, *pmembers, *flags; HashPosition pos; php_serialize_data_t var_hash; smart_str buf = {0}; if (zend_parse_parameters_none() == FAILURE) { return; } PHP_VAR_SERIALIZE_INIT(var_hash); /* storage */ smart_str_appendl(&buf, "x:", 2); MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, zend_hash_num_elements(&intern->storage)); php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC); zval_ptr_dtor(&flags); zend_hash_internal_pointer_reset_ex(&intern->storage, &pos); while(zend_hash_has_more_elements_ex(&intern->storage, &pos) == SUCCESS) { if (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &pos) == FAILURE) { smart_str_free(&buf); PHP_VAR_SERIALIZE_DESTROY(var_hash); RETURN_NULL(); } php_var_serialize(&buf, &element->obj, &var_hash TSRMLS_CC); smart_str_appendc(&buf, ','); php_var_serialize(&buf, &element->inf, &var_hash TSRMLS_CC); smart_str_appendc(&buf, ';'); zend_hash_move_forward_ex(&intern->storage, &pos); } /* members */ smart_str_appendl(&buf, "m:", 2); INIT_PZVAL(&members); Z_ARRVAL(members) = zend_std_get_properties(getThis() TSRMLS_CC); Z_TYPE(members) = IS_ARRAY; pmembers = &members; php_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */ /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.c) { RETURN_STRINGL(buf.c, buf.len, 0); } else { RETURN_NULL(); } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplObjectStorage, key) { spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->index); } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int spl_dllist_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */ { spl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_count) { zval *rv; zend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, "count", &rv); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); convert_to_long(intern->retval); *count = (long) Z_LVAL_P(intern->retval); return SUCCESS; } *count = 0; return FAILURE; } *count = spl_ptr_llist_count(intern->llist); return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int setpwnam(struct passwd *pwd) { FILE *fp = NULL, *pwf = NULL; int save_errno; int found; int namelen; int buflen = 256; int contlen, rc; char *linebuf = NULL; char *tmpname = NULL; char *atomic_dir = "/etc"; pw_init(); if ((fp = xfmkstemp(&tmpname, atomic_dir)) == NULL) return -1; /* ptmp should be owned by root.root or root.wheel */ if (fchown(fileno(fp), (uid_t) 0, (gid_t) 0) < 0) goto fail; /* acquire exclusive lock */ if (lckpwdf() < 0) goto fail; pwf = fopen(PASSWD_FILE, "r"); if (!pwf) goto fail; namelen = strlen(pwd->pw_name); linebuf = malloc(buflen); if (!linebuf) goto fail; /* parse the passwd file */ found = false; /* Do you wonder why I don't use getpwent? Read comments at top of * file */ while (fgets(linebuf, buflen, pwf) != NULL) { contlen = strlen(linebuf); while (linebuf[contlen - 1] != '\n' && !feof(pwf)) { char *tmp; /* Extend input buffer if it failed getting the whole line, * so now we double the buffer size */ buflen *= 2; tmp = realloc(linebuf, buflen); if (tmp == NULL) goto fail; linebuf = tmp; /* And fill the rest of the buffer */ if (fgets(&linebuf[contlen], buflen / 2, pwf) == NULL) break; contlen = strlen(linebuf); /* That was a lot of work for nothing. Gimme perl! */ } /* Is this the username we were sent to change? */ if (!found && linebuf[namelen] == ':' && !strncmp(linebuf, pwd->pw_name, namelen)) { /* Yes! So go forth in the name of the Lord and * change it! */ if (putpwent(pwd, fp) < 0) goto fail; found = true; continue; } /* Nothing in particular happened, copy input to output */ fputs(linebuf, fp); } /* xfmkstemp is too restrictive by default for passwd file */ if (fchmod(fileno(fp), 0644) < 0) goto fail; rc = close_stream(fp); fp = NULL; if (rc != 0) goto fail; fclose(pwf); /* I don't think I want to know if this failed */ pwf = NULL; if (!found) { errno = ENOENT; /* give me something better */ goto fail; } /* we don't care if we can't remove the backup file */ unlink(PASSWD_FILE ".OLD"); /* we don't care if we can't create the backup file */ ignore_result(link(PASSWD_FILE, PASSWD_FILE ".OLD")); /* we DO care if we can't rename to the passwd file */ if (rename(tmpname, PASSWD_FILE) < 0) goto fail; /* finally: success */ ulckpwdf(); return 0; fail: save_errno = errno; ulckpwdf(); if (fp != NULL) fclose(fp); if (tmpname != NULL) unlink(tmpname); free(tmpname); if (pwf != NULL) fclose(pwf); free(linebuf); errno = save_errno; return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'chsh, chfn, vipw: fix filenames collision The utils when compiled WITHOUT libuser then mkostemp()ing "/etc/%s.XXXXXX" where the filename prefix is argv[0] basename. An attacker could repeatedly execute the util with modified argv[0] and after many many attempts mkostemp() may generate suffix which makes sense. The result maybe temporary file with name like rc.status ld.so.preload or krb5.keytab, etc. Note that distros usually use libuser based ch{sh,fn} or stuff from shadow-utils. It's probably very minor security bug. Addresses: CVE-2015-5224 Signed-off-by: Karel Zak <kzak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int php_zip_add_file(struct zip *za, const char *filename, size_t filename_len, char *entry_name, size_t entry_name_len, long offset_start, long offset_len TSRMLS_DC) /* {{{ */ { struct zip_source *zs; int cur_idx; char resolved_path[MAXPATHLEN]; zval exists_flag; if (ZIP_OPENBASEDIR_CHECKPATH(filename)) { return -1; } if (!expand_filepath(filename, resolved_path TSRMLS_CC)) { return -1; } php_stat(resolved_path, strlen(resolved_path), FS_EXISTS, &exists_flag TSRMLS_CC); if (!Z_BVAL(exists_flag)) { return -1; } zs = zip_source_file(za, resolved_path, offset_start, offset_len); if (!zs) { return -1; } cur_idx = zip_name_locate(za, (const char *)entry_name, 0); /* TODO: fix _zip_replace */ if (cur_idx<0) { /* reset the error */ if (za->error.str) { _zip_error_fini(&za->error); } _zip_error_init(&za->error); } else { if (zip_delete(za, cur_idx) == -1) { zip_source_free(zs); return -1; } } if (zip_add(za, entry_name, zs) == -1) { return -1; } else { return 1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bilinear_box_make_weights (PixopsFilterDimension *dim, double scale) { int n = ceil (1/scale + 3.0); double *pixel_weights = g_malloc_n (sizeof (double) * SUBSAMPLE, n); double w; int offset, i; dim->offset = -1.0; dim->n = n; dim->weights = pixel_weights; for (offset = 0; offset < SUBSAMPLE; offset++) { double x = (double)offset / SUBSAMPLE; double a = x + 1 / scale; for (i = 0; i < n; i++) { w = linear_box_half (0.5 + i - a, 0.5 + i - x); w += linear_box_half (1.5 + x - i, 1.5 + a - i); *(pixel_weights++) = w * scale; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM The weights could grow very large under certain circumstances, in particular in security-relevant conditions, including the testsuite. By allowing the weight allocation to fail, this can be worked around. https://bugzilla.gnome.org/show_bug.cgi?id=754387'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void parse_data_for_row_pseudocolor(TGAContext *ctx) { guchar *s = ctx->in->data; guint upper_bound = ctx->pbuf->width; guchar *p = ctx->pptr; for (; upper_bound; upper_bound--, s++) { *p++ = ctx->cmap->cols[*s].r; *p++ = ctx->cmap->cols[*s].g; *p++ = ctx->cmap->cols[*s].b; if (ctx->hdr->cmap_bpp == 32) *p++ = ctx->cmap->cols[*s].a; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'tga: Wrap TGAColormap struct in its own API Instead of poking into it directly.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset, ssize_t size, void *private) { ext4_io_end_t *io_end = iocb->private; struct workqueue_struct *wq; /* if not async direct IO or dio with 0 bytes write, just return */ if (!io_end || !size) return; ext_debug("ext4_end_io_dio(): io_end 0x%p" "for inode %lu, iocb 0x%p, offset %llu, size %llu\n", iocb->private, io_end->inode->i_ino, iocb, offset, size); /* if not aio dio with unwritten extents, just free io and return */ if (io_end->flag != EXT4_IO_UNWRITTEN){ ext4_free_io_end(io_end); iocb->private = NULL; return; } io_end->offset = offset; io_end->size = size; wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq; /* queue the work to convert unwritten extents to written */ queue_work(wq, &io_end->work); /* Add the io_end to per-inode completed aio dio list*/ list_add_tail(&io_end->list, &EXT4_I(io_end->inode)->i_completed_io_list); iocb->private = NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], '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 <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ext4_invalidatepage(struct page *page, unsigned long offset) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); /* * If it's a full truncate we just forget about the pending dirtying */ if (offset == 0) ClearPageChecked(page); if (journal) jbd2_journal_invalidatepage(journal, page, offset); else block_invalidatepage(page, offset); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], '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 <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mount_entry_on_relative_rootfs(struct mntent *mntent, const char *rootfs) { char path[MAXPATHLEN]; int ret; /* relative to root mount point */ ret = snprintf(path, sizeof(path), "%s/%s", rootfs, mntent->mnt_dir); if (ret >= sizeof(path)) { ERROR("path name too long"); return -1; } return mount_entry_on_generic(mntent, path); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], '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 <serge.hallyn@ubuntu.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fill_autodev(const struct lxc_rootfs *rootfs) { int ret; char path[MAXPATHLEN]; int i; mode_t cmask; INFO("Creating initial consoles under container /dev"); ret = snprintf(path, MAXPATHLEN, "%s/dev", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= MAXPATHLEN) { ERROR("Error calculating container /dev location"); return -1; } if (!dir_exists(path)) // ignore, just don't try to fill in return 0; INFO("Populating container /dev"); cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH); for (i = 0; i < sizeof(lxc_devs) / sizeof(lxc_devs[0]); i++) { const struct lxc_devs *d = &lxc_devs[i]; ret = snprintf(path, MAXPATHLEN, "%s/dev/%s", rootfs->path ? rootfs->mount : "", d->name); if (ret < 0 || ret >= MAXPATHLEN) return -1; ret = mknod(path, d->mode, makedev(d->maj, d->min)); if (ret && errno != EEXIST) { char hostpath[MAXPATHLEN]; FILE *pathfile; // Unprivileged containers cannot create devices, so // bind mount the device from the host ret = snprintf(hostpath, MAXPATHLEN, "/dev/%s", d->name); if (ret < 0 || ret >= MAXPATHLEN) return -1; pathfile = fopen(path, "wb"); if (!pathfile) { SYSERROR("Failed to create device mount target '%s'", path); return -1; } fclose(pathfile); if (mount(hostpath, path, 0, MS_BIND, NULL) != 0) { SYSERROR("Failed bind mounting device %s from host into container", d->name); return -1; } } } umask(cmask); INFO("Populated container /dev"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], '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 <serge.hallyn@ubuntu.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx) { struct Vmxnet3_TxDesc txd; uint32_t txd_idx; uint32_t data_len; hwaddr data_pa; for (;;) { if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) { break; } vmxnet3_dump_tx_descr(&txd); if (!s->skip_current_tx_pkt) { data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE; data_pa = le64_to_cpu(txd.addr); if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt, data_pa, data_len)) { s->skip_current_tx_pkt = true; } } if (s->tx_sop) { vmxnet3_tx_retrieve_metadata(s, &txd); s->tx_sop = false; } if (txd.eop) { if (!s->skip_current_tx_pkt) { vmxnet_tx_pkt_parse(s->tx_pkt); if (s->needs_vlan) { vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet3_send_packet(s, qidx); } else { vmxnet3_on_tx_done_update_stats(s, qidx, VMXNET3_PKT_STATUS_ERROR); } vmxnet3_complete_packet(s, qidx, txd_idx); s->tx_sop = true; s->skip_current_tx_pkt = false; vmxnet_tx_pkt_reset(s->tx_pkt); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'net/vmxnet3: Refine l2 header validation Validation of l2 header length assumed minimal packet size as eth_header + 2 * vlan_header regardless of the actual protocol. This caused crash for valid non-IP packets shorter than 22 bytes, as 'tx_pkt->packet_type' hasn't been assigned for such packets, and 'vmxnet3_on_tx_done_update_stats()' expects it to be properly set. Refine header length validation in 'vmxnet_tx_pkt_parse_headers'. Check its return value during packet processing flow. As a side effect, in case IPv4 and IPv6 header validation failure, corrupt packets will be dropped. Signed-off-by: Dana Rubin <dana.rubin@ravellosystems.com> Signed-off-by: Shmulik Ladkani <shmulik.ladkani@ravellosystems.com> Signed-off-by: Jason Wang <jasowang@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: crypto_xmit( struct peer *peer, /* peer structure pointer */ struct pkt *xpkt, /* transmit packet pointer */ struct recvbuf *rbufp, /* receive buffer pointer */ int start, /* offset to extension field */ struct exten *ep, /* extension pointer */ keyid_t cookie /* session cookie */ ) { struct exten *fp; /* extension pointers */ struct cert_info *cp, *xp, *yp; /* cert info/value pointer */ sockaddr_u *srcadr_sin; /* source address */ u_int32 *pkt; /* packet pointer */ u_int opcode; /* extension field opcode */ char certname[MAXHOSTNAME + 1]; /* subject name buffer */ char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ tstamp_t tstamp; struct calendar tscal; u_int vallen; struct value vtemp; associd_t associd; int rval; int len; keyid_t tcookie; /* * Generate the requested extension field request code, length * and association ID. If this is a response and the host is not * synchronized, light the error bit and go home. */ pkt = (u_int32 *)xpkt + start / 4; fp = (struct exten *)pkt; opcode = ntohl(ep->opcode); if (peer != NULL) { srcadr_sin = &peer->srcadr; if (!(opcode & CRYPTO_RESP)) peer->opcode = ep->opcode; } else { srcadr_sin = &rbufp->recv_srcadr; } associd = (associd_t) ntohl(ep->associd); len = 8; fp->opcode = htonl((opcode & 0xffff0000) | len); fp->associd = ep->associd; rval = XEVNT_OK; tstamp = crypto_time(); switch (opcode & 0xffff0000) { /* * Send association request and response with status word and * host name. Note, this message is not signed and the filestamp * contains only the status word. */ case CRYPTO_ASSOC: case CRYPTO_ASSOC | CRYPTO_RESP: len = crypto_send(fp, &hostval, start); fp->fstamp = htonl(crypto_flags); break; /* * Send certificate request. Use the values from the extension * field. */ case CRYPTO_CERT: memset(&vtemp, 0, sizeof(vtemp)); vtemp.tstamp = ep->tstamp; vtemp.fstamp = ep->fstamp; vtemp.vallen = ep->vallen; vtemp.ptr = (u_char *)ep->pkt; len = crypto_send(fp, &vtemp, start); break; /* * Send sign request. Use the host certificate, which is self- * signed and may or may not be trusted. */ case CRYPTO_SIGN: (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL); if ((calcomp(&tscal, &(cert_host->first)) < 0) || (calcomp(&tscal, &(cert_host->last)) > 0)) rval = XEVNT_PER; else len = crypto_send(fp, &cert_host->cert, start); break; /* * Send certificate response. Use the name in the extension * field to find the certificate in the cache. If the request * contains no subject name, assume the name of this host. This * is for backwards compatibility. Private certificates are * never sent. * * There may be several certificates matching the request. First * choice is a self-signed trusted certificate; second choice is * any certificate signed by another host. There is no third * choice. */ case CRYPTO_CERT | CRYPTO_RESP: vallen = ntohl(ep->vallen); /* Must be <64k */ if (vallen == 0 || vallen > MAXHOSTNAME || len - VALUE_LEN < vallen) { rval = XEVNT_LEN; break; } /* * Find all public valid certificates with matching * subject. If a self-signed, trusted certificate is * found, use that certificate. If not, use the last non * self-signed certificate. */ memcpy(certname, ep->pkt, vallen); certname[vallen] = '\0'; xp = yp = NULL; for (cp = cinfo; cp != NULL; cp = cp->link) { if (cp->flags & (CERT_PRIV | CERT_ERROR)) continue; if (strcmp(certname, cp->subject) != 0) continue; if (strcmp(certname, cp->issuer) != 0) yp = cp; else if (cp ->flags & CERT_TRUST) xp = cp; continue; } /* * Be careful who you trust. If the certificate is not * found, return an empty response. Note that we dont * enforce lifetimes here. * * The timestamp and filestamp are taken from the * certificate value structure. For all certificates the * timestamp is the latest signature update time. For * host and imported certificates the filestamp is the * creation epoch. For signed certificates the filestamp * is the creation epoch of the trusted certificate at * the root of the certificate trail. In principle, this * allows strong checking for signature masquerade. */ if (xp == NULL) xp = yp; if (xp == NULL) break; if (tstamp == 0) break; len = crypto_send(fp, &xp->cert, start); break; /* * Send challenge in Schnorr (IFF) identity scheme. */ case CRYPTO_IFF: if (peer == NULL) break; /* hack attack */ if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Send response in Schnorr (IFF) identity scheme. */ case CRYPTO_IFF | CRYPTO_RESP: if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Send challenge in Guillou-Quisquater (GQ) identity scheme. */ case CRYPTO_GQ: if (peer == NULL) break; /* hack attack */ if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Send response in Guillou-Quisquater (GQ) identity scheme. */ case CRYPTO_GQ | CRYPTO_RESP: if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Send challenge in MV identity scheme. */ case CRYPTO_MV: if (peer == NULL) break; /* hack attack */ if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Send response in MV identity scheme. */ case CRYPTO_MV | CRYPTO_RESP: if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Send certificate sign response. The integrity of the request * certificate has already been verified on the receive side. * Sign the response using the local server key. Use the * filestamp from the request and use the timestamp as the * current time. Light the error bit if the certificate is * invalid or contains an unverified signature. */ case CRYPTO_SIGN | CRYPTO_RESP: if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Send public key and signature. Use the values from the public * key. */ case CRYPTO_COOK: len = crypto_send(fp, &pubkey, start); break; /* * Encrypt and send cookie and signature. Light the error bit if * anything goes wrong. */ case CRYPTO_COOK | CRYPTO_RESP: vallen = ntohl(ep->vallen); /* Must be <64k */ if ( vallen == 0 || (vallen >= MAX_VALLEN) || (opcode & 0x0000ffff) < VALUE_LEN + vallen) { rval = XEVNT_LEN; break; } if (peer == NULL) tcookie = cookie; else tcookie = peer->hcookie; if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp)) == XEVNT_OK) { len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; /* * Find peer and send autokey data and signature in broadcast * server and symmetric modes. Use the values in the autokey * structure. If no association is found, either the server has * restarted with new associations or some perp has replayed an * old message, in which case light the error bit. */ case CRYPTO_AUTO | CRYPTO_RESP: if (peer == NULL) { if ((peer = findpeerbyassoc(associd)) == NULL) { rval = XEVNT_ERR; break; } } peer->flags &= ~FLAG_ASSOC; len = crypto_send(fp, &peer->sndval, start); break; /* * Send leapseconds values and signature. Use the values from * the tai structure. If no table has been loaded, just send an * empty request. */ case CRYPTO_LEAP | CRYPTO_RESP: len = crypto_send(fp, &tai_leap, start); break; /* * Default - Send a valid command for unknown requests; send * an error response for unknown resonses. */ default: if (opcode & CRYPTO_RESP) rval = XEVNT_ERR; } /* * In case of error, flame the log. If a request, toss the * puppy; if a response, return so the sender can flame, too. */ if (rval != XEVNT_OK) { u_int32 uint32; uint32 = CRYPTO_ERROR; opcode |= uint32; fp->opcode |= htonl(uint32); snprintf(statstr, sizeof(statstr), "%04x %d %02x %s", opcode, associd, rval, eventstr(rval)); record_crypto_stats(srcadr_sin, statstr); DPRINTF(1, ("crypto_xmit: %s\n", statstr)); if (!(opcode & CRYPTO_RESP)) return (0); } DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n", crypto_flags, start, len, opcode >> 16, associd)); return (len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2014-9297'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cookedprint( int datatype, int length, const char *data, int status, int quiet, FILE *fp ) { char *name; char *value; char output_raw; int fmt; l_fp lfp; sockaddr_u hval; u_long uval; int narr; size_t len; l_fp lfparr[8]; char b[12]; char bn[2 * MAXVARLEN]; char bv[2 * MAXVALLEN]; UNUSED_ARG(datatype); if (!quiet) fprintf(fp, "status=%04x %s,\n", status, statustoa(datatype, status)); startoutput(); while (nextvar(&length, &data, &name, &value)) { fmt = varfmt(name); output_raw = 0; switch (fmt) { case PADDING: output_raw = '*'; break; case TS: if (!decodets(value, &lfp)) output_raw = '?'; else output(fp, name, prettydate(&lfp)); break; case HA: /* fallthru */ case NA: if (!decodenetnum(value, &hval)) { output_raw = '?'; } else if (fmt == HA){ output(fp, name, nntohost(&hval)); } else { output(fp, name, stoa(&hval)); } break; case RF: if (decodenetnum(value, &hval)) { if (ISREFCLOCKADR(&hval)) output(fp, name, refnumtoa(&hval)); else output(fp, name, stoa(&hval)); } else if (strlen(value) <= 4) { output(fp, name, value); } else { output_raw = '?'; } break; case LP: if (!decodeuint(value, &uval) || uval > 3) { output_raw = '?'; } else { b[0] = (0x2 & uval) ? '1' : '0'; b[1] = (0x1 & uval) ? '1' : '0'; b[2] = '\0'; output(fp, name, b); } break; case OC: if (!decodeuint(value, &uval)) { output_raw = '?'; } else { snprintf(b, sizeof(b), "%03lo", uval); output(fp, name, b); } break; case AR: if (!decodearr(value, &narr, lfparr)) output_raw = '?'; else outputarr(fp, name, narr, lfparr); break; case FX: if (!decodeuint(value, &uval)) output_raw = '?'; else output(fp, name, tstflags(uval)); break; default: fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n", name, value, fmt); output_raw = '?'; break; } if (output_raw != 0) { atoascii(name, MAXVARLEN, bn, sizeof(bn)); atoascii(value, MAXVALLEN, bv, sizeof(bv)); if (output_raw != '*') { len = strlen(bv); bv[len] = output_raw; bv[len+1] = '\0'; } output(fp, bn, bv); } } endoutput(fp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '[TALOS-CAN-0063] avoid buffer overrun in ntpq'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: iakerb_gss_init_sec_context(OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { OM_uint32 major_status = GSS_S_FAILURE; krb5_error_code code; iakerb_ctx_id_t ctx; krb5_gss_cred_id_t kcred; krb5_gss_name_t kname; krb5_boolean cred_locked = FALSE; int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); if (initialContextToken) { code = iakerb_alloc_context(&ctx); if (code != 0) { *minor_status = code; goto cleanup; } if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) { major_status = iakerb_gss_acquire_cred(minor_status, NULL, GSS_C_INDEFINITE, GSS_C_NULL_OID_SET, GSS_C_INITIATE, &ctx->defcred, NULL, NULL); if (GSS_ERROR(major_status)) goto cleanup; claimant_cred_handle = ctx->defcred; } } else { ctx = (iakerb_ctx_id_t)*context_handle; if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) claimant_cred_handle = ctx->defcred; } kname = (krb5_gss_name_t)target_name; major_status = kg_cred_resolve(minor_status, ctx->k5c, claimant_cred_handle, target_name); if (GSS_ERROR(major_status)) goto cleanup; cred_locked = TRUE; kcred = (krb5_gss_cred_id_t)claimant_cred_handle; major_status = GSS_S_FAILURE; if (initialContextToken) { code = iakerb_get_initial_state(ctx, kcred, kname, time_req, &ctx->state); if (code != 0) { *minor_status = code; goto cleanup; } *context_handle = (gss_ctx_id_t)ctx; } if (ctx->state != IAKERB_AP_REQ) { /* We need to do IAKERB. */ code = iakerb_initiator_step(ctx, kcred, kname, time_req, input_token, output_token); if (code == KRB5_BAD_MSIZE) major_status = GSS_S_DEFECTIVE_TOKEN; if (code != 0) { *minor_status = code; goto cleanup; } } if (ctx->state == IAKERB_AP_REQ) { krb5_gss_ctx_ext_rec exts; if (cred_locked) { k5_mutex_unlock(&kcred->lock); cred_locked = FALSE; } iakerb_make_exts(ctx, &exts); if (ctx->gssc == GSS_C_NO_CONTEXT) input_token = GSS_C_NO_BUFFER; /* IAKERB is finished, or we skipped to Kerberos directly. */ major_status = krb5_gss_init_sec_context_ext(minor_status, (gss_cred_id_t) kcred, &ctx->gssc, target_name, (gss_OID)gss_mech_iakerb, req_flags, time_req, input_chan_bindings, input_token, NULL, output_token, ret_flags, time_rec, &exts); if (major_status == GSS_S_COMPLETE) { *context_handle = ctx->gssc; ctx->gssc = GSS_C_NO_CONTEXT; iakerb_release_context(ctx); } if (actual_mech_type != NULL) *actual_mech_type = (gss_OID)gss_mech_krb5; } else { if (actual_mech_type != NULL) *actual_mech_type = (gss_OID)gss_mech_iakerb; if (ret_flags != NULL) *ret_flags = 0; if (time_rec != NULL) *time_rec = 0; major_status = GSS_S_CONTINUE_NEEDED; } cleanup: if (cred_locked) k5_mutex_unlock(&kcred->lock); if (initialContextToken && GSS_ERROR(major_status)) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return major_status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18'], 'message': 'Fix IAKERB context aliasing bugs [CVE-2015-2696] The IAKERB mechanism currently replaces its context handle with the krb5 mechanism 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 IAKERB context structure after context establishment and add new IAKERB entry points to refer to it with that type. Add initiate and established flags to the IAKERB context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2696: In MIT krb5 1.9 and later, applications which call gss_inquire_context() on a partially-established IAKERB context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted IAKERB 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 [ghudson@mit.edu: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: acc_ctx_hints(OM_uint32 *minor_status, gss_ctx_id_t *ctx, spnego_gss_cred_id_t spcred, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 tmpmin, ret; gss_OID_set supported_mechSet; spnego_gss_ctx_id_t sc = NULL; *mechListMIC = GSS_C_NO_BUFFER; supported_mechSet = GSS_C_NO_OID_SET; *return_token = NO_TOKEN_SEND; *negState = REJECT; *minor_status = 0; /* A hint request must be the first token received. */ if (*ctx != GSS_C_NO_CONTEXT) return GSS_S_DEFECTIVE_TOKEN; ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT, &supported_mechSet); if (ret != GSS_S_COMPLETE) goto cleanup; ret = make_NegHints(minor_status, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; sc = create_spnego_ctx(); if (sc == NULL) { ret = GSS_S_FAILURE; goto cleanup; } if (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) { ret = GSS_S_FAILURE; goto cleanup; } sc->internal_mech = GSS_C_NO_OID; *negState = ACCEPT_INCOMPLETE; *return_token = INIT_TOKEN_SEND; sc->firstpass = 1; *ctx = (gss_ctx_id_t)sc; sc = NULL; ret = GSS_S_COMPLETE; cleanup: release_spnego_ctx(&sc); gss_release_oid_set(&tmpmin, &supported_mechSet); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], '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 [ghudson@mit.edu: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: spnego_gss_wrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; ret = gss_wrap_iov(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], '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 [ghudson@mit.edu: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: spnego_gss_unwrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap(minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, qop_state); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], '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 [ghudson@mit.edu: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; size_t buffer_size = 0; size_t nbchars = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-5312 Another entity expansion issue For https://bugzilla.gnome.org/show_bug.cgi?id=756733 It is one case where the code in place to detect entities expansions failed to exit when the situation was detected, leading to DoS Problem reported by Kostya Serebryany @ Google Patch provided by David Drysdale @ Google'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _PUBLIC_ codepoint_t next_codepoint_handle(struct smb_iconv_handle *ic, const char *str, size_t *size) { return next_codepoint_handle_ext(ic, str, CH_UNIX, size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: Fix handling of unicode near string endings Until now next_codepoint_ext() and next_codepoint_handle_ext() were using strnlen(str, 5) to determine how much string they should try to decode. This ended up looking past the end of the string when it was not null terminated and the final character looked like a multi-byte encoding. The fix is to let the caller say how long the string can be. Bug: https://bugzilla.samba.org/show_bug.cgi?id=11599 Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz> Pair-programmed-with: Andrew Bartlett <abartlet@samba.org> Reviewed-by: Ralph Boehme <slow@samba.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_const_colorp palette, int num_palette) { png_uint_32 max_palette_length; png_debug1(1, "in %s storage function", "PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ? (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH; if (num_palette < 0 || num_palette > max_palette_length) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) png_error(png_ptr, "Invalid palette length"); else { png_warning(png_ptr, "Invalid palette length"); return; } } if ((num_palette > 0 && palette == NULL) || (num_palette == 0 # ifdef PNG_MNG_FEATURES_SUPPORTED && (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 # endif )) { png_error(png_ptr, "Invalid palette"); } /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. * * 1.6.0: the above statement appears to be incorrect; something has to set * the palette inside png_struct on read. */ png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead * of num_palette entries, in case of an invalid PNG file or incorrect * call to png_set_PLTE() with too-large sample values. */ png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr, PNG_MAX_PALETTE_LENGTH * (sizeof (png_color)))); if (num_palette > 0) memcpy(png_ptr->palette, palette, num_palette * (sizeof (png_color))); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; info_ptr->free_me |= PNG_FREE_PLTE; info_ptr->valid |= PNG_INFO_PLTE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Silently truncate over-length PLTE chunk while reading.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) { xmlChar *encoding = NULL; SKIP_BLANKS; if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g')) { SKIP(8); SKIP_BLANKS; if (RAW != '=') { xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL); return(NULL); } NEXT; SKIP_BLANKS; if (RAW == '"') { NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '"') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); xmlFree((xmlChar *) encoding); return(NULL); } else NEXT; } else if (RAW == '\''){ NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '\'') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); xmlFree((xmlChar *) encoding); return(NULL); } else NEXT; } else { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL); } /* * Non standard parsing, allowing the user to ignore encoding */ if (ctxt->options & XML_PARSE_IGNORE_ENC) { xmlFree((xmlChar *) encoding); return(NULL); } /* * UTF-16 encoding stwich has already taken place at this stage, * more over the little-endian/big-endian selection is already done */ if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST "UTF-16")) || (!xmlStrcasecmp(encoding, BAD_CAST "UTF16")))) { /* * If no encoding was passed to the parser, that we are * using UTF-16 and no decoder is present i.e. the * document is apparently UTF-8 compatible, then raise an * encoding mismatch fatal error */ if ((ctxt->encoding == NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_ENCODING, "Document labelled UTF-16 but has UTF-8 content\n"); } if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } /* * UTF-8 encoding is handled natively */ else if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST "UTF-8")) || (!xmlStrcasecmp(encoding, BAD_CAST "UTF8")))) { if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } else if (encoding != NULL) { xmlCharEncodingHandlerPtr handler; if (ctxt->input->encoding != NULL) xmlFree((xmlChar *) ctxt->input->encoding); ctxt->input->encoding = encoding; handler = xmlFindCharEncodingHandler((const char *) encoding); if (handler != NULL) { xmlSwitchToEncoding(ctxt, handler); } else { xmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "Unsupported encoding %s\n", encoding); return(NULL); } } } return(encoding); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fail parsing early on if encoding conversion failed For https://bugzilla.gnome.org/show_bug.cgi?id=751631 If we fail conversing the current input stream while processing the encoding declaration of the XMLDecl then it's safer to just abort there and not try to report further errors.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 new_size, u32 min_type) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_file_extent_item *fi; struct btrfs_key key; struct btrfs_key found_key; u64 extent_start = 0; u64 extent_num_bytes = 0; u64 extent_offset = 0; u64 item_end = 0; u64 last_size = new_size; u32 found_type = (u8)-1; int found_extent; int del_item; int pending_del_nr = 0; int pending_del_slot = 0; int extent_type = -1; int ret; int err = 0; u64 ino = btrfs_ino(inode); u64 bytes_deleted = 0; bool be_nice = 0; bool should_throttle = 0; bool should_end = 0; BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY); /* * for non-free space inodes and ref cows, we want to back off from * time to time */ if (!btrfs_is_free_space_inode(inode) && test_bit(BTRFS_ROOT_REF_COWS, &root->state)) be_nice = 1; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = -1; /* * We want to drop from the next block forward in case this new size is * not block aligned since we will be keeping the last block of the * extent just the way it is. */ if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root) btrfs_drop_extent_cache(inode, ALIGN(new_size, root->sectorsize), (u64)-1, 0); /* * This function is also used to drop the items in the log tree before * we relog the inode, so if root != BTRFS_I(inode)->root, it means * it is used to drop the loged items. So we shouldn't kill the delayed * items. */ if (min_type == 0 && root == BTRFS_I(inode)->root) btrfs_kill_delayed_inode_items(inode); key.objectid = ino; key.offset = (u64)-1; key.type = (u8)-1; search_again: /* * with a 16K leaf size and 128MB extents, you can actually queue * up a huge file in a single leaf. Most of the time that * bytes_deleted is > 0, it will be huge by the time we get here */ if (be_nice && bytes_deleted > 32 * 1024 * 1024) { if (btrfs_should_end_transaction(trans, root)) { err = -EAGAIN; goto error; } } path->leave_spinning = 1; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) { err = ret; goto out; } if (ret > 0) { /* there are no items in the tree for us to truncate, we're * done */ if (path->slots[0] == 0) goto out; path->slots[0]--; } while (1) { fi = NULL; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = found_key.type; if (found_key.objectid != ino) break; if (found_type < min_type) break; item_end = found_key.offset; if (found_type == BTRFS_EXTENT_DATA_KEY) { fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type != BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_num_bytes(leaf, fi); } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_inline_len(leaf, path->slots[0], fi); } item_end--; } if (found_type > min_type) { del_item = 1; } else { if (item_end < new_size) break; if (found_key.offset >= new_size) del_item = 1; else del_item = 0; } found_extent = 0; /* FIXME, shrink the extent if the ref count is only 1 */ if (found_type != BTRFS_EXTENT_DATA_KEY) goto delete; if (del_item) last_size = found_key.offset; else last_size = new_size; if (extent_type != BTRFS_FILE_EXTENT_INLINE) { u64 num_dec; extent_start = btrfs_file_extent_disk_bytenr(leaf, fi); if (!del_item) { u64 orig_num_bytes = btrfs_file_extent_num_bytes(leaf, fi); extent_num_bytes = ALIGN(new_size - found_key.offset, root->sectorsize); btrfs_set_file_extent_num_bytes(leaf, fi, extent_num_bytes); num_dec = (orig_num_bytes - extent_num_bytes); if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) && extent_start != 0) inode_sub_bytes(inode, num_dec); btrfs_mark_buffer_dirty(leaf); } else { extent_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); extent_offset = found_key.offset - btrfs_file_extent_offset(leaf, fi); /* FIXME blocksize != 4096 */ num_dec = btrfs_file_extent_num_bytes(leaf, fi); if (extent_start != 0) { found_extent = 1; if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) inode_sub_bytes(inode, num_dec); } } } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { /* * we can't truncate inline items that have had * special encodings */ if (!del_item && btrfs_file_extent_compression(leaf, fi) == 0 && btrfs_file_extent_encryption(leaf, fi) == 0 && btrfs_file_extent_other_encoding(leaf, fi) == 0) { u32 size = new_size - found_key.offset; if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) inode_sub_bytes(inode, item_end + 1 - new_size); /* * update the ram bytes to properly reflect * the new size of our item */ btrfs_set_file_extent_ram_bytes(leaf, fi, size); size = btrfs_file_extent_calc_inline_size(size); btrfs_truncate_item(root, path, size, 1); } else if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) { inode_sub_bytes(inode, item_end + 1 - found_key.offset); } } delete: if (del_item) { if (!pending_del_nr) { /* no pending yet, add ourselves */ pending_del_slot = path->slots[0]; pending_del_nr = 1; } else if (pending_del_nr && path->slots[0] + 1 == pending_del_slot) { /* hop on the pending chunk */ pending_del_nr++; pending_del_slot = path->slots[0]; } else { BUG(); } } else { break; } should_throttle = 0; if (found_extent && (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root)) { btrfs_set_path_blocking(path); bytes_deleted += extent_num_bytes; ret = btrfs_free_extent(trans, root, extent_start, extent_num_bytes, 0, btrfs_header_owner(leaf), ino, extent_offset, 0); BUG_ON(ret); if (btrfs_should_throttle_delayed_refs(trans, root)) btrfs_async_run_delayed_refs(root, trans->delayed_ref_updates * 2, 0); if (be_nice) { if (truncate_space_check(trans, root, extent_num_bytes)) { should_end = 1; } if (btrfs_should_throttle_delayed_refs(trans, root)) { should_throttle = 1; } } } if (found_type == BTRFS_INODE_ITEM_KEY) break; if (path->slots[0] == 0 || path->slots[0] != pending_del_slot || should_throttle || should_end) { if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } pending_del_nr = 0; } btrfs_release_path(path); if (should_throttle) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } /* * if we failed to refill our space rsv, bail out * and let the transaction restart */ if (should_end) { err = -EAGAIN; goto error; } goto search_again; } else { path->slots[0]--; } } out: if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) btrfs_abort_transaction(trans, root, ret); } error: if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) btrfs_ordered_update_i_size(inode, last_size, NULL); btrfs_free_path(path); if (be_nice && bytes_deleted > 32 * 1024 * 1024) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: stable@vger.kernel.org Signed-off-by: Filipe Manana <fdmanana@suse.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ldap_decode_attribs_bare(TALLOC_CTX *mem_ctx, struct asn1_data *data, struct ldb_message_element **attributes, int *num_attributes) { while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) { struct ldb_message_element attrib; ZERO_STRUCT(attrib); ldap_decode_attrib(mem_ctx, data, &attrib); add_attrib_to_array_talloc(mem_ctx, &attrib, attributes, num_attributes); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <jra@samba.org> Reviewed-by: Ronnie Sahlberg <ronniesahlberg@gmail.com> Autobuild-User(master): Jeremy Allison <jra@samba.org> Autobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104 (cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool asn1_write_BOOLEAN(struct asn1_data *data, bool v) { asn1_push_tag(data, ASN1_BOOLEAN); asn1_write_uint8(data, v ? 0xFF : 0); asn1_pop_tag(data); return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <jra@samba.org> Reviewed-by: Volker Lendecke <Volker.Lendecke@SerNet.DE> Autobuild-User(master): Jeremy Allison <jra@samba.org> Autobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104 (cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool asn1_write_enumerated(struct asn1_data *data, uint8_t v) { if (!asn1_push_tag(data, ASN1_ENUMERATED)) return false; asn1_write_uint8(data, v); asn1_pop_tag(data); return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <jra@samba.org> Reviewed-by: Volker Lendecke <Volker.Lendecke@SerNet.DE> Autobuild-User(master): Jeremy Allison <jra@samba.org> Autobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104 (cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SMBC_attr_server(TALLOC_CTX *ctx, SMBCCTX *context, const char *server, uint16_t port, const char *share, char **pp_workgroup, char **pp_username, char **pp_password) { int flags; struct cli_state *ipc_cli = NULL; struct rpc_pipe_client *pipe_hnd = NULL; NTSTATUS nt_status; SMBCSRV *srv=NULL; SMBCSRV *ipc_srv=NULL; /* * Use srv->cli->desthost and srv->cli->share instead of * server and share below to connect to the actual share, * i.e., a normal share or a referred share from * 'msdfs proxy' share. */ srv = SMBC_server(ctx, context, true, server, port, share, pp_workgroup, pp_username, pp_password); if (!srv) { return NULL; } server = smbXcli_conn_remote_name(srv->cli->conn); share = srv->cli->share; /* * See if we've already created this special connection. Reference * our "special" share name '*IPC$', which is an impossible real share * name due to the leading asterisk. */ ipc_srv = SMBC_find_server(ctx, context, server, "*IPC$", pp_workgroup, pp_username, pp_password); if (!ipc_srv) { /* We didn't find a cached connection. Get the password */ if (!*pp_password || (*pp_password)[0] == '\0') { /* ... then retrieve it now. */ SMBC_call_auth_fn(ctx, context, server, share, pp_workgroup, pp_username, pp_password); if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; return NULL; } } flags = 0; if (smbc_getOptionUseKerberos(context)) { flags |= CLI_FULL_CONNECTION_USE_KERBEROS; } if (smbc_getOptionUseCCache(context)) { flags |= CLI_FULL_CONNECTION_USE_CCACHE; } nt_status = cli_full_connection(&ipc_cli, lp_netbios_name(), server, NULL, 0, "IPC$", "?????", *pp_username, *pp_workgroup, *pp_password, flags, SMB_SIGNING_DEFAULT); if (! NT_STATUS_IS_OK(nt_status)) { DEBUG(1,("cli_full_connection failed! (%s)\n", nt_errstr(nt_status))); errno = ENOTSUP; return NULL; } if (context->internal->smb_encryption_level) { /* Attempt UNIX smb encryption. */ if (!NT_STATUS_IS_OK(cli_force_encryption(ipc_cli, *pp_username, *pp_password, *pp_workgroup))) { /* * context->smb_encryption_level == * 1 means don't fail if encryption can't be * negotiated, == 2 means fail if encryption * can't be negotiated. */ DEBUG(4,(" SMB encrypt failed on IPC$\n")); if (context->internal->smb_encryption_level == 2) { cli_shutdown(ipc_cli); errno = EPERM; return NULL; } } DEBUG(4,(" SMB encrypt ok on IPC$\n")); } ipc_srv = SMB_MALLOC_P(SMBCSRV); if (!ipc_srv) { errno = ENOMEM; cli_shutdown(ipc_cli); return NULL; } ZERO_STRUCTP(ipc_srv); ipc_srv->cli = ipc_cli; nt_status = cli_rpc_pipe_open_noauth( ipc_srv->cli, &ndr_table_lsarpc, &pipe_hnd); if (!NT_STATUS_IS_OK(nt_status)) { DEBUG(1, ("cli_nt_session_open fail!\n")); errno = ENOTSUP; cli_shutdown(ipc_srv->cli); free(ipc_srv); return NULL; } /* * Some systems don't support * SEC_FLAG_MAXIMUM_ALLOWED, but NT sends 0x2000000 * so we might as well do it too. */ nt_status = rpccli_lsa_open_policy( pipe_hnd, talloc_tos(), True, GENERIC_EXECUTE_ACCESS, &ipc_srv->pol); if (!NT_STATUS_IS_OK(nt_status)) { errno = SMBC_errno(context, ipc_srv->cli); cli_shutdown(ipc_srv->cli); free(ipc_srv); return NULL; } /* now add it to the cache (internal or external) */ errno = 0; /* let cache function set errno if it likes */ if (smbc_getFunctionAddCachedServer(context)(context, ipc_srv, server, "*IPC$", *pp_workgroup, *pp_username)) { DEBUG(3, (" Failed to add server to cache\n")); if (errno == 0) { errno = ENOMEM; } cli_shutdown(ipc_srv->cli); free(ipc_srv); return NULL; } DLIST_ADD(context->internal->servers, ipc_srv); } return ipc_srv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2015-5296: s3:libsmb: force signing when requiring encryption in SMBC_server_internal() BUG: https://bugzilla.samba.org/show_bug.cgi?id=11536 Signed-off-by: Stefan Metzmacher <metze@samba.org> Reviewed-by: Jeremy Allison <jra@samba.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pptp_connect(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; struct rtable *rt; struct flowi4 fl4; int error = 0; if (sp->sa_protocol != PX_PROTO_PPTP) return -EINVAL; if (lookup_chan_dst(sp->sa_addr.pptp.call_id, sp->sa_addr.pptp.sin_addr.s_addr)) return -EALREADY; lock_sock(sk); /* Check for already bound sockets */ if (sk->sk_state & PPPOX_CONNECTED) { error = -EBUSY; goto end; } /* Check for already disconnected sockets, on attempts to disconnect */ if (sk->sk_state & PPPOX_DEAD) { error = -EALREADY; goto end; } if (!opt->src_addr.sin_addr.s_addr || !sp->sa_addr.pptp.sin_addr.s_addr) { error = -EINVAL; goto end; } po->chan.private = sk; po->chan.ops = &pptp_chan_ops; rt = ip_route_output_ports(sock_net(sk), &fl4, sk, opt->dst_addr.sin_addr.s_addr, opt->src_addr.sin_addr.s_addr, 0, 0, IPPROTO_GRE, RT_CONN_FLAGS(sk), 0); if (IS_ERR(rt)) { error = -EHOSTUNREACH; goto end; } sk_setup_caps(sk, &rt->dst); po->chan.mtu = dst_mtu(&rt->dst); if (!po->chan.mtu) po->chan.mtu = PPP_MRU; ip_rt_put(rt); po->chan.mtu -= PPTP_HEADER_OVERHEAD; po->chan.hdrlen = 2 + sizeof(struct pptp_gre_header); error = ppp_register_channel(&po->chan); if (error) { pr_err("PPTP: failed to register PPP channel (%d)\n", error); goto end; } opt->dst_addr = sp->sa_addr.pptp; sk->sk_state = PPPOX_CONNECTED; end: release_sock(sk); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'pptp: verify sockaddr_len in pptp_bind() and pptp_connect() Reported-by: Dmitry Vyukov <dvyukov@gmail.com> Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void recv_additional_file_list(int f) { struct file_list *flist; int ndx = read_ndx(f); if (ndx == NDX_FLIST_EOF) { flist_eof = 1; if (DEBUG_GTE(FLIST, 3)) rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i()); change_local_filter_dir(NULL, 0, 0); } else { ndx = NDX_FLIST_OFFSET - ndx; if (ndx < 0 || ndx >= dir_flist->used) { ndx = NDX_FLIST_OFFSET - ndx; rprintf(FERROR, "[%s] Invalid dir index: %d (%d - %d)\n", who_am_i(), ndx, NDX_FLIST_OFFSET, NDX_FLIST_OFFSET - dir_flist->used + 1); exit_cleanup(RERR_PROTOCOL); } if (DEBUG_GTE(FLIST, 3)) { rprintf(FINFO, "[%s] receiving flist for dir %d\n", who_am_i(), ndx); } flist = recv_file_list(f); flist->parent_ndx = ndx; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'Complain if an inc-recursive path is not right for its dir. This ensures that a malicious sender can't use a just-sent symlink as a trasnfer path.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct tty_struct *tty = file_tty(file); struct tty_struct *real_tty; void __user *p = (void __user *)arg; int retval; struct tty_ldisc *ld; if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl")) return -EINVAL; real_tty = tty_pair_get_tty(tty); /* * Factor out some common prep work */ switch (cmd) { case TIOCSETD: case TIOCSBRK: case TIOCCBRK: case TCSBRK: case TCSBRKP: retval = tty_check_change(tty); if (retval) return retval; if (cmd != TIOCCBRK) { tty_wait_until_sent(tty, 0); if (signal_pending(current)) return -EINTR; } break; } /* * Now do the stuff. */ switch (cmd) { case TIOCSTI: return tiocsti(tty, p); case TIOCGWINSZ: return tiocgwinsz(real_tty, p); case TIOCSWINSZ: return tiocswinsz(real_tty, p); case TIOCCONS: return real_tty != tty ? -EINVAL : tioccons(file); case FIONBIO: return fionbio(file, p); case TIOCEXCL: set_bit(TTY_EXCLUSIVE, &tty->flags); return 0; case TIOCNXCL: clear_bit(TTY_EXCLUSIVE, &tty->flags); return 0; case TIOCGEXCL: { int excl = test_bit(TTY_EXCLUSIVE, &tty->flags); return put_user(excl, (int __user *)p); } case TIOCNOTTY: if (current->signal->tty != tty) return -ENOTTY; no_tty(); return 0; case TIOCSCTTY: return tiocsctty(real_tty, file, arg); case TIOCGPGRP: return tiocgpgrp(tty, real_tty, p); case TIOCSPGRP: return tiocspgrp(tty, real_tty, p); case TIOCGSID: return tiocgsid(tty, real_tty, p); case TIOCGETD: return put_user(tty->ldisc->ops->num, (int __user *)p); case TIOCSETD: return tiocsetd(tty, p); case TIOCVHANGUP: if (!capable(CAP_SYS_ADMIN)) return -EPERM; tty_vhangup(tty); return 0; case TIOCGDEV: { unsigned int ret = new_encode_dev(tty_devnum(real_tty)); return put_user(ret, (unsigned int __user *)p); } /* * Break handling */ case TIOCSBRK: /* Turn break on, unconditionally */ if (tty->ops->break_ctl) return tty->ops->break_ctl(tty, -1); return 0; case TIOCCBRK: /* Turn break off, unconditionally */ if (tty->ops->break_ctl) return tty->ops->break_ctl(tty, 0); return 0; case TCSBRK: /* SVID version: non-zero arg --> no break */ /* non-zero arg means wait for all output data * to be sent (performed above) but don't send break. * This is used by the tcdrain() termios function. */ if (!arg) return send_break(tty, 250); return 0; case TCSBRKP: /* support for POSIX tcsendbreak() */ return send_break(tty, arg ? arg*100 : 250); case TIOCMGET: return tty_tiocmget(tty, p); case TIOCMSET: case TIOCMBIC: case TIOCMBIS: return tty_tiocmset(tty, cmd, p); case TIOCGICOUNT: retval = tty_tiocgicount(tty, p); /* For the moment allow fall through to the old method */ if (retval != -EINVAL) return retval; break; case TCFLSH: switch (arg) { case TCIFLUSH: case TCIOFLUSH: /* flush tty buffer and allow ldisc to process ioctl */ tty_buffer_flush(tty, NULL); break; } break; case TIOCSSERIAL: tty_warn_deprecated_flags(p); break; } if (tty->ops->ioctl) { retval = tty->ops->ioctl(tty, cmd, arg); if (retval != -ENOIOCTLCMD) return retval; } ld = tty_ldisc_ref_wait(tty); retval = -EINVAL; if (ld->ops->ioctl) { retval = ld->ops->ioctl(tty, file, cmd, arg); if (retval == -ENOIOCTLCMD) retval = -ENOTTY; } tty_ldisc_deref(ld); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-362'], 'message': 'tty: Fix unsafe ldisc reference via ioctl(TIOCGETD) ioctl(TIOCGETD) retrieves the line discipline id directly from the ldisc because the line discipline id (c_line) in termios is untrustworthy; userspace may have set termios via ioctl(TCSETS*) without actually changing the line discipline via ioctl(TIOCSETD). However, directly accessing the current ldisc via tty->ldisc is unsafe; the ldisc ptr dereferenced may be stale if the line discipline is changing via ioctl(TIOCSETD) or hangup. Wait for the line discipline reference (just like read() or write()) to retrieve the "current" line discipline id. Cc: <stable@vger.kernel.org> Signed-off-by: Peter Hurley <peter@hurleysoftware.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: authreadkeys( const char *file ) { FILE *fp; char *line; char *token; keyid_t keyno; int keytype; char buf[512]; /* lots of room for line */ u_char keystr[32]; /* Bug 2537 */ size_t len; size_t j; u_int nerr; KeyDataT *list = NULL; KeyDataT *next = NULL; /* * Open file. Complain and return if it can't be opened. */ fp = fopen(file, "r"); if (fp == NULL) { msyslog(LOG_ERR, "authreadkeys: file '%s': %m", file); goto onerror; } INIT_SSL(); /* * Now read lines from the file, looking for key entries. Put * the data into temporary store for later propagation to avoid * two-pass processing. */ nerr = 0; while ((line = fgets(buf, sizeof buf, fp)) != NULL) { if (nerr > nerr_maxlimit) break; token = nexttok(&line); if (token == NULL) continue; /* * First is key number. See if it is okay. */ keyno = atoi(token); if (keyno == 0) { log_maybe(&nerr, "authreadkeys: cannot change key %s", token); continue; } if (keyno > NTP_MAXKEY) { log_maybe(&nerr, "authreadkeys: key %s > %d reserved for Autokey", token, NTP_MAXKEY); continue; } /* * Next is keytype. See if that is all right. */ token = nexttok(&line); if (token == NULL) { log_maybe(&nerr, "authreadkeys: no key type for key %d", keyno); continue; } #ifdef OPENSSL /* * The key type is the NID used by the message digest * algorithm. There are a number of inconsistencies in * the OpenSSL database. We attempt to discover them * here and prevent use of inconsistent data later. */ keytype = keytype_from_text(token, NULL); if (keytype == 0) { log_maybe(&nerr, "authreadkeys: invalid type for key %d", keyno); continue; } if (EVP_get_digestbynid(keytype) == NULL) { log_maybe(&nerr, "authreadkeys: no algorithm for key %d", keyno); continue; } #else /* !OPENSSL follows */ /* * The key type is unused, but is required to be 'M' or * 'm' for compatibility. */ if (!(*token == 'M' || *token == 'm')) { log_maybe(&nerr, "authreadkeys: invalid type for key %d", keyno); continue; } keytype = KEY_TYPE_MD5; #endif /* !OPENSSL */ /* * Finally, get key and insert it. If it is longer than 20 * characters, it is a binary string encoded in hex; * otherwise, it is a text string of printable ASCII * characters. */ token = nexttok(&line); if (token == NULL) { log_maybe(&nerr, "authreadkeys: no key for key %d", keyno); continue; } next = NULL; len = strlen(token); if (len <= 20) { /* Bug 2537 */ next = emalloc(sizeof(KeyDataT) + len); next->keyid = keyno; next->keytype = keytype; next->seclen = len; memcpy(next->secbuf, token, len); } else { static const char hex[] = "0123456789abcdef"; u_char temp; char *ptr; size_t jlim; jlim = min(len, 2 * sizeof(keystr)); for (j = 0; j < jlim; j++) { ptr = strchr(hex, tolower((unsigned char)token[j])); if (ptr == NULL) break; /* abort decoding */ temp = (u_char)(ptr - hex); if (j & 1) keystr[j / 2] |= temp; else keystr[j / 2] = temp << 4; } if (j < jlim) { log_maybe(&nerr, "authreadkeys: invalid hex digit for key %d", keyno); continue; } len = jlim/2; /* hmmmm.... what about odd length?!? */ next = emalloc(sizeof(KeyDataT) + len); next->keyid = keyno; next->keytype = keytype; next->seclen = len; memcpy(next->secbuf, keystr, len); } INSIST(NULL != next); next->next = list; list = next; } fclose(fp); if (nerr > nerr_maxlimit) { msyslog(LOG_ERR, "authreadkeys: rejecting file '%s' after %u errors (emergency break)", file, nerr); goto onerror; } if (nerr > 0) { msyslog(LOG_ERR, "authreadkeys: rejecting file '%s' after %u error(s)", file, nerr); goto onerror; } /* first remove old file-based keys */ auth_delkeys(); /* insert the new key material */ while (NULL != (next = list)) { list = next->next; MD5auth_setkey(next->keyid, next->keytype, next->secbuf, next->seclen); /* purge secrets from memory before free()ing it */ memset(next, 0, sizeof(*next) + next->seclen); free(next); } return (1); onerror: /* Mop up temporary storage before bailing out. */ while (NULL != (next = list)) { list = next->next; /* purge secrets from memory before free()ing it */ memset(next, 0, sizeof(*next) + next->seclen); free(next); } return (0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': '[Sec 2936] Skeleton Key: Any trusted key system can serve time. HStenn.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: nextvar( int *datalen, const char **datap, char **vname, char **vvalue ) { const char *cp; const char *np; const char *cpend; size_t srclen; size_t len; static char name[MAXVARLEN]; static char value[MAXVALLEN]; cp = *datap; cpend = cp + *datalen; /* * Space past commas and white space */ while (cp < cpend && (*cp == ',' || isspace((int)*cp))) cp++; if (cp >= cpend) return 0; /* * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace * over any white space and terminate it. */ srclen = strcspn(cp, ",=\r\n"); srclen = min(srclen, (size_t)(cpend - cp)); len = srclen; while (len > 0 && isspace((unsigned char)cp[len - 1])) len--; if (len > 0) memcpy(name, cp, len); name[len] = '\0'; *vname = name; cp += srclen; /* * Check if we hit the end of the buffer or a ','. If so we are done. */ if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') { if (cp < cpend) cp++; *datap = cp; *datalen = cpend - cp; *vvalue = NULL; return 1; } /* * So far, so good. Copy out the value */ cp++; /* past '=' */ while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n')) cp++; np = cp; if ('"' == *np) { do { np++; } while (np < cpend && '"' != *np); if (np < cpend && '"' == *np) np++; } else { while (np < cpend && ',' != *np && '\r' != *np) np++; } len = np - cp; if (np > cpend || len >= sizeof(value) || (np < cpend && ',' != *np && '\r' != *np)) return 0; memcpy(value, cp, len); /* * Trim off any trailing whitespace */ while (len > 0 && isspace((unsigned char)value[len - 1])) len--; value[len] = '\0'; /* * Return this. All done. */ if (np < cpend && ',' == *np) np++; *datap = np; *datalen = cpend - np; *vvalue = value; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': '[Bug 2937] (NTPQ) nextvar() missing length check'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: get_clkbug_info( sockaddr_u *srcadr, endpt *inter, struct req_pkt *inpkt ) { register int i; register struct info_clkbug *ic; register u_int32 *clkaddr; register int items; struct refclockbug bug; sockaddr_u addr; ZERO_SOCK(&addr); AF(&addr) = AF_INET; #ifdef ISC_PLATFORM_HAVESALEN addr.sa.sa_len = SOCKLEN(&addr); #endif SET_PORT(&addr, NTP_PORT); items = INFO_NITEMS(inpkt->err_nitems); clkaddr = (u_int32 *)&inpkt->u; ic = (struct info_clkbug *)prepare_pkt(srcadr, inter, inpkt, sizeof(struct info_clkbug)); while (items-- > 0) { NSRCADR(&addr) = *clkaddr++; if (!ISREFCLOCKADR(&addr) || NULL == findexistingpeer(&addr, NULL, NULL, -1, 0)) { req_ack(srcadr, inter, inpkt, INFO_ERR_NODATA); return; } ZERO(bug); refclock_buginfo(&addr, &bug); if (bug.nvalues == 0 && bug.ntimes == 0) { req_ack(srcadr, inter, inpkt, INFO_ERR_NODATA); return; } ic->clockadr = NSRCADR(&addr); i = bug.nvalues; if (i > NUMCBUGVALUES) i = NUMCBUGVALUES; ic->nvalues = (u_char)i; ic->svalues = htons((u_short) (bug.svalues & ((1<<i)-1))); while (--i >= 0) ic->values[i] = htonl(bug.values[i]); i = bug.ntimes; if (i > NUMCBUGTIMES) i = NUMCBUGTIMES; ic->ntimes = (u_char)i; ic->stimes = htonl(bug.stimes); while (--i >= 0) { HTONL_FP(&bug.times[i], &ic->times[i]); } ic = (struct info_clkbug *)more_pkt(); } flush_pkt(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '[Bug 2939] reslist NULL pointer dereference [Bug 2940] Stack exhaustion in recursive traversal of restriction list -- these two where fixed together --'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) { unsigned long int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': '[Sec 2942]: Off-path DoS attack on auth broadcast mode. HStenn.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void usage(void) { PRINT_VERSION; puts("Copyright (c) 2011, Oracle and/or its affiliates. " "All rights reserved.\n"); puts("Enable or disable plugins."); printf("\nUsage: %s [options] <plugin> ENABLE|DISABLE\n\nOptions:\n", my_progname); my_print_help(my_long_options); puts("\n"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Bug#21973610: BUFFER OVERFLOW ISSUES Description : Incorrect usage of sprintf/strcpy caused possible buffer overflow issues at various places. Solution : - Fixed mysql_plugin and mysqlshow - Fixed regex library issues Reviewed-By : Georgi Kodinov <georgi.kodinov@oracle.com> Reviewed-By : Venkata S Murthy Sidagam <venkata.sidagam@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CertManager::setPeerX509(X509* x) { if (x == 0) return; X509_NAME* issuer = x->GetIssuer(); X509_NAME* subject = x->GetSubject(); ASN1_STRING* before = x->GetBefore(); ASN1_STRING* after = x->GetAfter(); peerX509_ = NEW_YS X509(issuer->GetName(), issuer->GetLength(), subject->GetName(), subject->GetLength(), (const char*) before->data, before->length, (const char*) after->data, after->length); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': 'Bug #22738607: YASSL FUNCTION X509_NAME_GET_INDEX_BY_NID IS NOT WORKING AS EXPECTED.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t generic_perform_write(struct file *file, struct iov_iter *i, loff_t pos) { struct address_space *mapping = file->f_mapping; const struct address_space_operations *a_ops = mapping->a_ops; long status = 0; ssize_t written = 0; unsigned int flags = 0; /* * Copies from kernel address space cannot fail (NFSD is a big user). */ if (segment_eq(get_fs(), KERNEL_DS)) flags |= AOP_FLAG_UNINTERRUPTIBLE; do { struct page *page; pgoff_t index; /* Pagecache index for current page */ unsigned long offset; /* Offset into pagecache page */ unsigned long bytes; /* Bytes to write to page */ size_t copied; /* Bytes copied from user */ void *fsdata; offset = (pos & (PAGE_CACHE_SIZE - 1)); index = pos >> PAGE_CACHE_SHIFT; bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_count(i)); again: /* * Bring in the user page that we will copy from _first_. * Otherwise there's a nasty deadlock on copying from the * same page as we're writing to, without it being marked * up-to-date. * * Not only is this an optimisation, but it is also required * to check that the address is actually valid, when atomic * usercopies are used, below. */ if (unlikely(iov_iter_fault_in_readable(i, bytes))) { status = -EFAULT; break; } status = a_ops->write_begin(file, mapping, pos, bytes, flags, &page, &fsdata); if (unlikely(status)) break; pagefault_disable(); copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes); pagefault_enable(); flush_dcache_page(page); status = a_ops->write_end(file, mapping, pos, bytes, copied, page, fsdata); if (unlikely(status < 0)) break; copied = status; cond_resched(); if (unlikely(copied == 0)) { /* * If we were unable to copy any data at all, we must * fall back to a single segment length write. * * If we didn't fallback here, we could livelock * because not all segments in the iov can be copied at * once without a pagefault. */ bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_single_seg_count(i)); goto again; } iov_iter_advance(i, copied); pos += copied; written += copied; balance_dirty_pages_ratelimited(mapping); } while (iov_iter_count(i)); return written ? written : status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <npiggin@suse.de> Signed-off-by: Ingo Molnar <mingo@elte.hu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jas_matrix_divpow2(jas_matrix_t *matrix, int n) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { *data = (*data >= 0) ? ((*data) >> n) : (-((-(*data)) >> n)); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Added fix for CVE-2016-2089.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg1, *prime_arg2; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; size_t tlen1, tlen2, clen, slen; char *tdots1, *tdots2, *cdots, *sdots; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) || krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } tlen1 = strlen(prime_arg1); trunc_name(&tlen1, &tdots1); tlen2 = strlen(prime_arg2); trunc_name(&tlen2, &tdots2); clen = client_name.length; trunc_name(&clen, &cdots); slen = service_name.length; trunc_name(&slen, &sdots); ret.code = KADM5_OK; if (! CHANGEPW_SERVICE(rqstp)) { if (!kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->src, NULL)) ret.code = KADM5_AUTH_DELETE; /* any restrictions at all on the ADD kills the RENAME */ if (!kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->dest, &rp) || rp) { if (ret.code == KADM5_AUTH_DELETE) ret.code = KADM5_AUTH_INSUFFICIENT; else ret.code = KADM5_AUTH_ADD; } } else ret.code = KADM5_AUTH_INSUFFICIENT; if (ret.code != KADM5_OK) { /* okay to cast lengths to int because trunc_name limits max value */ krb5_klog_syslog(LOG_NOTICE, _("Unauthorized request: kadm5_rename_principal, " "%.*s%s to %.*s%s, " "client=%.*s%s, service=%.*s%s, addr=%s"), (int)tlen1, prime_arg1, tdots1, (int)tlen2, prime_arg2, tdots2, (int)clen, (char *)client_name.value, cdots, (int)slen, (char *)service_name.value, sdots, client_addr(rqstp->rq_xprt)); } else { ret.code = kadm5_rename_principal((void *)handle, arg->src, arg->dest); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); /* okay to cast lengths to int because trunc_name limits max value */ krb5_klog_syslog(LOG_NOTICE, _("Request: kadm5_rename_principal, " "%.*s%s to %.*s%s, %s, " "client=%.*s%s, service=%.*s%s, addr=%s"), (int)tlen1, prime_arg1, tdots1, (int)tlen2, prime_arg2, tdots2, errmsg ? errmsg : _("success"), (int)clen, (char *)client_name.value, cdots, (int)slen, (char *)service_name.value, sdots, client_addr(rqstp->rq_xprt)); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg1); free(prime_arg2); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: generic_ret *init_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp) { static generic_ret ret; gss_buffer_desc client_name, service_name; kadm5_server_handle_t handle; OM_uint32 minor_stat; const char *errmsg = NULL; size_t clen, slen; char *cdots, *sdots; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(*arg, rqstp, &handle))) goto exit_func; if (! (ret.code = check_handle((void *)handle))) { ret.api_version = handle->api_version; } free_server_handle(handle); if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (ret.code != 0) errmsg = krb5_get_error_message(NULL, ret.code); clen = client_name.length; trunc_name(&clen, &cdots); slen = service_name.length; trunc_name(&slen, &sdots); /* okay to cast lengths to int because trunc_name limits max value */ krb5_klog_syslog(LOG_NOTICE, _("Request: kadm5_init, %.*s%s, %s, " "client=%.*s%s, service=%.*s%s, addr=%s, " "vers=%d, flavor=%d"), (int)clen, (char *)client_name.value, cdots, errmsg ? errmsg : _("success"), (int)clen, (char *)client_name.value, cdots, (int)slen, (char *)service_name.value, sdots, client_addr(rqstp->rq_xprt), ret.api_version & ~(KADM5_API_VERSION_MASK), rqstp->rq_cred.oa_flavor); if (errmsg != NULL) krb5_free_error_message(NULL, errmsg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: return(&ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: uint64 ReadCodedSizeValue(const binary * InBuffer, uint32 & BufferSize, uint64 & SizeUnknown) { binary SizeBitMask = 1 << 7; uint64 Result = 0x7F; unsigned int SizeIdx, PossibleSizeLength = 0; binary PossibleSize[8]; memset(PossibleSize, 0, 8); SizeUnknown = 0x7F; // the last bit is discarded when computing the size for (SizeIdx = 0; SizeIdx < BufferSize && SizeIdx < 8; SizeIdx++) { if (InBuffer[0] & (SizeBitMask >> SizeIdx)) { // ID found PossibleSizeLength = SizeIdx + 1; SizeBitMask >>= SizeIdx; for (SizeIdx = 0; SizeIdx < PossibleSizeLength; SizeIdx++) { PossibleSize[SizeIdx] = InBuffer[SizeIdx]; } for (SizeIdx = 0; SizeIdx < PossibleSizeLength - 1; SizeIdx++) { Result <<= 7; Result |= 0xFF; } Result = 0; Result |= PossibleSize[0] & ~SizeBitMask; for (unsigned int i = 1; i<PossibleSizeLength; i++) { Result <<= 8; Result |= PossibleSize[i]; } BufferSize = PossibleSizeLength; return Result; } SizeUnknown <<= 7; SizeUnknown |= 0xFF; } BufferSize = 0; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'EbmlElement: don't read beyond end of buffer when reading variable length integers'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. 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; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #71323 - Output of stream_get_meta_data can be falsified by its input'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ __dec_zone_page_state(page, NR_FILE_PAGES); __inc_zone_page_state(newpage, NR_FILE_PAGES); if (!PageSwapCache(page) && PageSwapBacked(page)) { __dec_zone_page_state(page, NR_SHMEM); __inc_zone_page_state(newpage, NR_SHMEM); } spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'mm: migrate dirty page without clear_page_dirty_for_io etc clear_page_dirty_for_io() has accumulated writeback and memcg subtleties since v2.6.16 first introduced page migration; and the set_page_dirty() which completed its migration of PageDirty, later had to be moderated to __set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too. No actual problems seen with this procedure recently, but if you look into what the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually achieving, it turns out to be nothing more than moving the PageDirty flag, and its NR_FILE_DIRTY stat from one zone to another. It would be good to avoid a pile of irrelevant decrementations and incrementations, and improper event counting, and unnecessary descent of the radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which radix_tree_replace_slot() left in place anyway). Do the NR_FILE_DIRTY movement, like the other stats movements, while interrupts still disabled in migrate_page_move_mapping(); and don't even bother if the zone is the same. Do the PageDirty movement there under tree_lock too, where old page is frozen and newpage not yet visible: bearing in mind that as soon as newpage becomes visible in radix_tree, an un-page-locked set_page_dirty() might interfere (or perhaps that's just not possible: anything doing so should already hold an additional reference to the old page, preventing its migration; but play safe). But we do still need to transfer PageDirty in migrate_page_copy(), for those who don't go the mapping route through migrate_page_move_mapping(). Signed-off-by: Hugh Dickins <hughd@google.com> Cc: Christoph Lameter <cl@linux.com> Cc: "Kirill A. Shutemov" <kirill.shutemov@linux.intel.com> Cc: Rik van Riel <riel@redhat.com> Cc: Vlastimil Babka <vbabka@suse.cz> Cc: Davidlohr Bueso <dave@stgolabs.net> Cc: Oleg Nesterov <oleg@redhat.com> Cc: Sasha Levin <sasha.levin@oracle.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int snd_seq_ioctl_remove_events(struct snd_seq_client *client, void __user *arg) { struct snd_seq_remove_events info; if (copy_from_user(&info, arg, sizeof(info))) return -EFAULT; /* * Input mostly not implemented XXX. */ if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) { /* * No restrictions so for a user client we can clear * the whole fifo */ if (client->type == USER_CLIENT) snd_seq_fifo_clear(client->data.user.fifo); } if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT) snd_seq_queue_remove_cells(client->number, &info); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ALSA: seq: Fix missing NULL check at remove_events ioctl snd_seq_ioctl_remove_events() calls snd_seq_fifo_clear() unconditionally even if there is no FIFO assigned, and this leads to an Oops due to NULL dereference. The fix is just to add a proper NULL check. Reported-by: Dmitry Vyukov <dvyukov@google.com> Tested-by: Dmitry Vyukov <dvyukov@google.com> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int snd_timer_start_slave(struct snd_timer_instance *timeri) { unsigned long flags; spin_lock_irqsave(&slave_active_lock, flags); timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; if (timeri->master) list_add_tail(&timeri->active_list, &timeri->master->slave_active_head); spin_unlock_irqrestore(&slave_active_lock, flags); return 1; /* delayed start */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-200', 'CWE-362'], 'message': 'ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <dvyukov@google.com> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void rng_backend_request_entropy(RngBackend *s, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngBackendClass *k = RNG_BACKEND_GET_CLASS(s); if (k->request_entropy) { k->request_entropy(s, size, receive_entropy, opaque); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'rng: add request queue support to rng-random Requests are now created in the RngBackend parent class and the code path is shared by both rng-egd and rng-random. This commit fixes the rng-random implementation which processed only one request at a time and simply discarded all but the most recent one. In the guest this manifested as delayed completion of reads from virtio-rng, i.e. a read was completed only after another read was issued. By switching rng-random to use the same request queue as rng-egd, the unsafe stack-based allocation of the entropy buffer is eliminated and replaced with g_malloc. Signed-off-by: Ladi Prosek <lprosek@redhat.com> Reviewed-by: Amit Shah <amit.shah@redhat.com> Message-Id: <1456994238-9585-5-git-send-email-lprosek@redhat.com> Signed-off-by: Amit Shah <amit.shah@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int make_http_soap_request(zval *this_ptr, zend_string *buf, char *location, char *soapaction, int soap_version, zval *return_value) { zend_string *request; smart_str soap_headers = {0}; smart_str soap_headers_z = {0}; int err; php_url *phpurl = NULL; php_stream *stream; zval *trace, *tmp; int use_proxy = 0; int use_ssl; zend_string *http_body; char *content_type, *http_version, *cookie_itt; int http_close; zend_string *http_headers; char *connection; int http_1_1; int http_status; int content_type_xml = 0; zend_long redirect_max = 20; char *content_encoding; char *http_msg = NULL; zend_bool old_allow_url_fopen; php_stream_context *context = NULL; zend_bool has_authorization = 0; zend_bool has_proxy_authorization = 0; zend_bool has_cookies = 0; if (this_ptr == NULL || Z_TYPE_P(this_ptr) != IS_OBJECT) { return FALSE; } request = buf; /* Compress request */ if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "compression", sizeof("compression")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) { int level = Z_LVAL_P(tmp) & 0x0f; int kind = Z_LVAL_P(tmp) & SOAP_COMPRESSION_DEFLATE; if (level > 9) {level = 9;} if ((Z_LVAL_P(tmp) & SOAP_COMPRESSION_ACCEPT) != 0) { smart_str_append_const(&soap_headers_z,"Accept-Encoding: gzip, deflate\r\n"); } if (level > 0) { zval func; zval retval; zval params[3]; int n; ZVAL_STR_COPY(&params[0], buf); ZVAL_LONG(&params[1], level); if (kind == SOAP_COMPRESSION_DEFLATE) { n = 2; ZVAL_STRING(&func, "gzcompress"); smart_str_append_const(&soap_headers_z,"Content-Encoding: deflate\r\n"); } else { n = 3; ZVAL_STRING(&func, "gzencode"); smart_str_append_const(&soap_headers_z,"Content-Encoding: gzip\r\n"); ZVAL_LONG(&params[2], 0x1f); } if (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, n, params) == SUCCESS && Z_TYPE(retval) == IS_STRING) { zval_ptr_dtor(&params[0]); zval_ptr_dtor(&func); request = Z_STR(retval); } else { zval_ptr_dtor(&params[0]); zval_ptr_dtor(&func); if (request != buf) { zend_string_release(request); } smart_str_free(&soap_headers_z); return FALSE; } } } if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1)) != NULL) { php_stream_from_zval_no_verify(stream,tmp); if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) { use_proxy = Z_LVAL_P(tmp); } } else { stream = NULL; } if (location != NULL && location[0] != '\000') { phpurl = php_url_parse(location); } if (NULL != (tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_stream_context", sizeof("_stream_context")-1))) { context = php_stream_context_from_zval(tmp, 0); } if (context && (tmp = php_stream_context_get_option(context, "http", "max_redirects")) != NULL) { if (Z_TYPE_P(tmp) != IS_STRING || !is_numeric_string(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp), &redirect_max, NULL, 1)) { if (Z_TYPE_P(tmp) == IS_LONG) redirect_max = Z_LVAL_P(tmp); } } try_again: if (phpurl == NULL || phpurl->host == NULL) { if (phpurl != NULL) {php_url_free(phpurl);} if (request != buf) { zend_string_release(request); } add_soap_fault(this_ptr, "HTTP", "Unable to parse URL", NULL, NULL); smart_str_free(&soap_headers_z); return FALSE; } use_ssl = 0; if (phpurl->scheme != NULL && strcmp(phpurl->scheme, "https") == 0) { use_ssl = 1; } else if (phpurl->scheme == NULL || strcmp(phpurl->scheme, "http") != 0) { php_url_free(phpurl); if (request != buf) { zend_string_release(request); } add_soap_fault(this_ptr, "HTTP", "Unknown protocol. Only http and https are allowed.", NULL, NULL); smart_str_free(&soap_headers_z); return FALSE; } old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; if (use_ssl && php_stream_locate_url_wrapper("https://", NULL, STREAM_LOCATE_WRAPPERS_ONLY) == NULL) { php_url_free(phpurl); if (request != buf) { zend_string_release(request); } add_soap_fault(this_ptr, "HTTP", "SSL support is not available in this build", NULL, NULL); PG(allow_url_fopen) = old_allow_url_fopen; smart_str_free(&soap_headers_z); return FALSE; } if (phpurl->port == 0) { phpurl->port = use_ssl ? 443 : 80; } /* Check if request to the same host */ if (stream != NULL) { php_url *orig; if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1)) != NULL && (orig = (php_url *) zend_fetch_resource_ex(tmp, "httpurl", le_url)) != NULL && ((use_proxy && !use_ssl) || (((use_ssl && orig->scheme != NULL && strcmp(orig->scheme, "https") == 0) || (!use_ssl && orig->scheme == NULL) || (!use_ssl && strcmp(orig->scheme, "https") != 0)) && strcmp(orig->host, phpurl->host) == 0 && orig->port == phpurl->port))) { } else { php_stream_close(stream); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); stream = NULL; use_proxy = 0; } } /* Check if keep-alive connection is still opened */ if (stream != NULL && php_stream_eof(stream)) { php_stream_close(stream); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); stream = NULL; use_proxy = 0; } if (!stream) { stream = http_connect(this_ptr, phpurl, use_ssl, context, &use_proxy); if (stream) { php_stream_auto_cleanup(stream); add_property_resource(this_ptr, "httpsocket", stream->res); GC_REFCOUNT(stream->res)++; add_property_long(this_ptr, "_use_proxy", use_proxy); } else { php_url_free(phpurl); if (request != buf) { zend_string_release(request); } add_soap_fault(this_ptr, "HTTP", "Could not connect to host", NULL, NULL); PG(allow_url_fopen) = old_allow_url_fopen; smart_str_free(&soap_headers_z); return FALSE; } } PG(allow_url_fopen) = old_allow_url_fopen; if (stream) { zval *cookies, *login, *password; zend_resource *ret = zend_register_resource(phpurl, le_url); add_property_resource(this_ptr, "httpurl", ret); GC_REFCOUNT(ret)++; /*zend_list_addref(ret);*/ if (context && (tmp = php_stream_context_get_option(context, "http", "protocol_version")) != NULL && Z_TYPE_P(tmp) == IS_DOUBLE && Z_DVAL_P(tmp) == 1.0) { http_1_1 = 0; } else { http_1_1 = 1; } smart_str_append_const(&soap_headers, "POST "); if (use_proxy && !use_ssl) { smart_str_appends(&soap_headers, phpurl->scheme); smart_str_append_const(&soap_headers, "://"); smart_str_appends(&soap_headers, phpurl->host); smart_str_appendc(&soap_headers, ':'); smart_str_append_unsigned(&soap_headers, phpurl->port); } if (phpurl->path) { smart_str_appends(&soap_headers, phpurl->path); } else { smart_str_appendc(&soap_headers, '/'); } if (phpurl->query) { smart_str_appendc(&soap_headers, '?'); smart_str_appends(&soap_headers, phpurl->query); } if (phpurl->fragment) { smart_str_appendc(&soap_headers, '#'); smart_str_appends(&soap_headers, phpurl->fragment); } if (http_1_1) { smart_str_append_const(&soap_headers, " HTTP/1.1\r\n"); } else { smart_str_append_const(&soap_headers, " HTTP/1.0\r\n"); } smart_str_append_const(&soap_headers, "Host: "); smart_str_appends(&soap_headers, phpurl->host); if (phpurl->port != (use_ssl?443:80)) { smart_str_appendc(&soap_headers, ':'); smart_str_append_unsigned(&soap_headers, phpurl->port); } if (!http_1_1 || ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_keep_alive", sizeof("_keep_alive")-1)) != NULL && (Z_TYPE_P(tmp) == IS_FALSE || (Z_TYPE_P(tmp) == IS_LONG && Z_LVAL_P(tmp) == 0)))) { smart_str_append_const(&soap_headers, "\r\n" "Connection: close\r\n"); } else { smart_str_append_const(&soap_headers, "\r\n" "Connection: Keep-Alive\r\n"); } if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_user_agent", sizeof("_user_agent")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { if (Z_STRLEN_P(tmp) > 0) { smart_str_append_const(&soap_headers, "User-Agent: "); smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); smart_str_append_const(&soap_headers, "\r\n"); } } else if (context && (tmp = php_stream_context_get_option(context, "http", "user_agent")) != NULL && Z_TYPE_P(tmp) == IS_STRING) { if (Z_STRLEN_P(tmp) > 0) { smart_str_append_const(&soap_headers, "User-Agent: "); smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); smart_str_append_const(&soap_headers, "\r\n"); } } else if (FG(user_agent)) { smart_str_append_const(&soap_headers, "User-Agent: "); smart_str_appends(&soap_headers, FG(user_agent)); smart_str_append_const(&soap_headers, "\r\n"); } else { smart_str_append_const(&soap_headers, "User-Agent: PHP-SOAP/"PHP_VERSION"\r\n"); } smart_str_append_smart_str(&soap_headers, &soap_headers_z); if (soap_version == SOAP_1_2) { smart_str_append_const(&soap_headers,"Content-Type: application/soap+xml; charset=utf-8"); if (soapaction) { smart_str_append_const(&soap_headers,"; action=\""); smart_str_appends(&soap_headers, soapaction); smart_str_append_const(&soap_headers,"\""); } smart_str_append_const(&soap_headers,"\r\n"); } else { smart_str_append_const(&soap_headers,"Content-Type: text/xml; charset=utf-8\r\n"); if (soapaction) { smart_str_append_const(&soap_headers, "SOAPAction: \""); smart_str_appends(&soap_headers, soapaction); smart_str_append_const(&soap_headers, "\"\r\n"); } } smart_str_append_const(&soap_headers,"Content-Length: "); smart_str_append_long(&soap_headers, request->len); smart_str_append_const(&soap_headers, "\r\n"); /* HTTP Authentication */ if ((login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login")-1)) != NULL && Z_TYPE_P(login) == IS_STRING) { zval *digest; has_authorization = 1; if ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) != NULL) { if (Z_TYPE_P(digest) == IS_ARRAY) { char HA1[33], HA2[33], response[33], cnonce[33], nc[9]; PHP_MD5_CTX md5ctx; unsigned char hash[16]; PHP_MD5Init(&md5ctx); snprintf(cnonce, sizeof(cnonce), ZEND_LONG_FMT, php_rand()); PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, strlen(cnonce)); PHP_MD5Final(hash, &md5ctx); make_digest(cnonce, hash); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nc", sizeof("nc")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) { Z_LVAL_P(tmp)++; snprintf(nc, sizeof(nc), "%08ld", Z_LVAL_P(tmp)); } else { add_assoc_long(digest, "nc", 1); strcpy(nc, "00000001"); } PHP_MD5Init(&md5ctx); PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(login), Z_STRLEN_P(login)); PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "realm", sizeof("realm")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL && Z_TYPE_P(password) == IS_STRING) { PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(password), Z_STRLEN_P(password)); } PHP_MD5Final(hash, &md5ctx); make_digest(HA1, hash); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "algorithm", sizeof("algorithm")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING && Z_STRLEN_P(tmp) == sizeof("md5-sess")-1 && stricmp(Z_STRVAL_P(tmp), "md5-sess") == 0) { PHP_MD5Init(&md5ctx); PHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32); PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8); PHP_MD5Final(hash, &md5ctx); make_digest(HA1, hash); } PHP_MD5Init(&md5ctx); PHP_MD5Update(&md5ctx, (unsigned char*)"POST:", sizeof("POST:")-1); if (phpurl->path) { PHP_MD5Update(&md5ctx, (unsigned char*)phpurl->path, strlen(phpurl->path)); } else { PHP_MD5Update(&md5ctx, (unsigned char*)"/", 1); } if (phpurl->query) { PHP_MD5Update(&md5ctx, (unsigned char*)"?", 1); PHP_MD5Update(&md5ctx, (unsigned char*)phpurl->query, strlen(phpurl->query)); } /* TODO: Support for qop="auth-int" */ /* if (zend_hash_find(Z_ARRVAL_PP(digest), "qop", sizeof("qop"), (void **)&tmp) == SUCCESS && Z_TYPE_PP(tmp) == IS_STRING && Z_STRLEN_PP(tmp) == sizeof("auth-int")-1 && stricmp(Z_STRVAL_PP(tmp), "auth-int") == 0) { PHP_MD5Update(&md5ctx, ":", 1); PHP_MD5Update(&md5ctx, HEntity, HASHHEXLEN); } */ PHP_MD5Final(hash, &md5ctx); make_digest(HA2, hash); PHP_MD5Init(&md5ctx); PHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32); PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "qop", sizeof("qop")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { PHP_MD5Update(&md5ctx, (unsigned char*)nc, 8); PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8); PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); /* TODO: Support for qop="auth-int" */ PHP_MD5Update(&md5ctx, (unsigned char*)"auth", sizeof("auth")-1); PHP_MD5Update(&md5ctx, (unsigned char*)":", 1); } PHP_MD5Update(&md5ctx, (unsigned char*)HA2, 32); PHP_MD5Final(hash, &md5ctx); make_digest(response, hash); smart_str_append_const(&soap_headers, "Authorization: Digest username=\""); smart_str_appendl(&soap_headers, Z_STRVAL_P(login), Z_STRLEN_P(login)); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "realm", sizeof("realm")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { smart_str_append_const(&soap_headers, "\", realm=\""); smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { smart_str_append_const(&soap_headers, "\", nonce=\""); smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } smart_str_append_const(&soap_headers, "\", uri=\""); if (phpurl->path) { smart_str_appends(&soap_headers, phpurl->path); } else { smart_str_appendc(&soap_headers, '/'); } if (phpurl->query) { smart_str_appendc(&soap_headers, '?'); smart_str_appends(&soap_headers, phpurl->query); } if (phpurl->fragment) { smart_str_appendc(&soap_headers, '#'); smart_str_appends(&soap_headers, phpurl->fragment); } if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "qop", sizeof("qop")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { /* TODO: Support for qop="auth-int" */ smart_str_append_const(&soap_headers, "\", qop=\"auth"); smart_str_append_const(&soap_headers, "\", nc=\""); smart_str_appendl(&soap_headers, nc, 8); smart_str_append_const(&soap_headers, "\", cnonce=\""); smart_str_appendl(&soap_headers, cnonce, 8); } smart_str_append_const(&soap_headers, "\", response=\""); smart_str_appendl(&soap_headers, response, 32); if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "opaque", sizeof("opaque")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { smart_str_append_const(&soap_headers, "\", opaque=\""); smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "algorithm", sizeof("algorithm")-1)) != NULL && Z_TYPE_P(tmp) == IS_STRING) { smart_str_append_const(&soap_headers, "\", algorithm=\""); smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } smart_str_append_const(&soap_headers, "\"\r\n"); } } else { zend_string *buf; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_P(login), Z_STRLEN_P(login)); smart_str_appendc(&auth, ':'); if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL && Z_TYPE_P(password) == IS_STRING) { smart_str_appendl(&auth, Z_STRVAL_P(password), Z_STRLEN_P(password)); } smart_str_0(&auth); buf = php_base64_encode((unsigned char*)ZSTR_VAL(auth.s), ZSTR_LEN(auth.s)); smart_str_append_const(&soap_headers, "Authorization: Basic "); smart_str_appendl(&soap_headers, (char*)ZSTR_VAL(buf), ZSTR_LEN(buf)); smart_str_append_const(&soap_headers, "\r\n"); zend_string_release(buf); smart_str_free(&auth); } } /* Proxy HTTP Authentication */ if (use_proxy && !use_ssl) { has_proxy_authorization = proxy_authentication(this_ptr, &soap_headers); } /* Send cookies along with request */ if ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1)) != NULL && Z_TYPE_P(cookies) == IS_ARRAY) { zval *data; zend_string *key; int i, n; has_cookies = 1; n = zend_hash_num_elements(Z_ARRVAL_P(cookies)); if (n > 0) { zend_hash_internal_pointer_reset(Z_ARRVAL_P(cookies)); smart_str_append_const(&soap_headers, "Cookie: "); for (i = 0; i < n; i++) { zend_ulong numindx; int res = zend_hash_get_current_key(Z_ARRVAL_P(cookies), &key, &numindx); data = zend_hash_get_current_data(Z_ARRVAL_P(cookies)); if (res == HASH_KEY_IS_STRING && Z_TYPE_P(data) == IS_ARRAY) { zval *value; if ((value = zend_hash_index_find(Z_ARRVAL_P(data), 0)) != NULL && Z_TYPE_P(value) == IS_STRING) { zval *tmp; if (((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 1)) == NULL || strncmp(phpurl->path?phpurl->path:"/",Z_STRVAL_P(tmp),Z_STRLEN_P(tmp)) == 0) && ((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 2)) == NULL || in_domain(phpurl->host,Z_STRVAL_P(tmp))) && (use_ssl || (tmp = zend_hash_index_find(Z_ARRVAL_P(data), 3)) == NULL)) { smart_str_append(&soap_headers, key); smart_str_appendc(&soap_headers, '='); smart_str_append(&soap_headers, Z_STR_P(value)); smart_str_appendc(&soap_headers, ';'); } } } zend_hash_move_forward(Z_ARRVAL_P(cookies)); } smart_str_append_const(&soap_headers, "\r\n"); } } http_context_headers(context, has_authorization, has_proxy_authorization, has_cookies, &soap_headers); smart_str_append_const(&soap_headers, "\r\n"); smart_str_0(&soap_headers); if ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "trace", sizeof("trace")-1)) != NULL && (Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) { add_property_stringl(this_ptr, "__last_request_headers", ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s)); } smart_str_appendl(&soap_headers, request->val, request->len); smart_str_0(&soap_headers); err = php_stream_write(stream, ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s)); if (err != ZSTR_LEN(soap_headers.s)) { if (request != buf) { zend_string_release(request); } php_stream_close(stream); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); add_soap_fault(this_ptr, "HTTP", "Failed Sending HTTP SOAP request", NULL, NULL); smart_str_free(&soap_headers_z); return FALSE; } smart_str_free(&soap_headers); } else { add_soap_fault(this_ptr, "HTTP", "Failed to create stream??", NULL, NULL); smart_str_free(&soap_headers_z); return FALSE; } if (!return_value) { php_stream_close(stream); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); smart_str_free(&soap_headers_z); return TRUE; } do { http_headers = get_http_headers(stream); if (!http_headers) { if (request != buf) { zend_string_release(request); } php_stream_close(stream); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); add_soap_fault(this_ptr, "HTTP", "Error Fetching http headers", NULL, NULL); smart_str_free(&soap_headers_z); return FALSE; } if ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "trace", sizeof("trace")-1)) != NULL && (Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) { add_property_str(this_ptr, "__last_response_headers", zend_string_copy(http_headers)); } /* Check to see what HTTP status was sent */ http_1_1 = 0; http_status = 0; http_version = get_http_header_value(ZSTR_VAL(http_headers), "HTTP/"); if (http_version) { char *tmp; if (!strncmp(http_version,"1.1", 3)) { http_1_1 = 1; } tmp = strstr(http_version," "); if (tmp != NULL) { tmp++; http_status = atoi(tmp); } tmp = strstr(tmp," "); if (tmp != NULL) { tmp++; if (http_msg) { efree(http_msg); } http_msg = estrdup(tmp); } efree(http_version); /* Try and get headers again */ if (http_status == 100) { zend_string_release(http_headers); } } } while (http_status == 100); /* Grab and send back every cookie */ /* Not going to worry about Path: because we shouldn't be changing urls so path dont matter too much */ cookie_itt = strstr(ZSTR_VAL(http_headers), "Set-Cookie: "); while (cookie_itt) { char *cookie; char *eqpos, *sempos; zval *cookies; if ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1)) == NULL || Z_TYPE_P(cookies) != IS_ARRAY) { zval tmp_cookies; array_init(&tmp_cookies); cookies = zend_hash_str_update(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1, &tmp_cookies); } cookie = get_http_header_value(cookie_itt,"Set-Cookie: "); eqpos = strstr(cookie, "="); sempos = strstr(cookie, ";"); if (eqpos != NULL && (sempos == NULL || sempos > eqpos)) { smart_str name = {0}; int cookie_len; zval zcookie; if (sempos != NULL) { cookie_len = sempos-(eqpos+1); } else { cookie_len = strlen(cookie)-(eqpos-cookie)-1; } smart_str_appendl(&name, cookie, eqpos - cookie); smart_str_0(&name); array_init(&zcookie); add_index_stringl(&zcookie, 0, eqpos + 1, cookie_len); if (sempos != NULL) { char *options = cookie + cookie_len+1; while (*options) { while (*options == ' ') {options++;} sempos = strstr(options, ";"); if (strstr(options,"path=") == options) { eqpos = options + sizeof("path=")-1; add_index_stringl(&zcookie, 1, eqpos, sempos?(sempos-eqpos):strlen(eqpos)); } else if (strstr(options,"domain=") == options) { eqpos = options + sizeof("domain=")-1; add_index_stringl(&zcookie, 2, eqpos, sempos?(sempos-eqpos):strlen(eqpos)); } else if (strstr(options,"secure") == options) { add_index_bool(&zcookie, 3, 1); } if (sempos != NULL) { options = sempos+1; } else { break; } } } if (!zend_hash_index_exists(Z_ARRVAL(zcookie), 1)) { char *t = phpurl->path?phpurl->path:"/"; char *c = strrchr(t, '/'); if (c) { add_index_stringl(&zcookie, 1, t, c-t); } } if (!zend_hash_index_exists(Z_ARRVAL(zcookie), 2)) { add_index_string(&zcookie, 2, phpurl->host); } zend_symtable_update(Z_ARRVAL_P(cookies), name.s, &zcookie); smart_str_free(&name); } cookie_itt = strstr(cookie_itt + sizeof("Set-Cookie: "), "Set-Cookie: "); efree(cookie); } /* See if the server requested a close */ if (http_1_1) { http_close = FALSE; if (use_proxy && !use_ssl) { connection = get_http_header_value(ZSTR_VAL(http_headers), "Proxy-Connection: "); if (connection) { if (strncasecmp(connection, "close", sizeof("close")-1) == 0) { http_close = TRUE; } efree(connection); } } if (http_close == FALSE) { connection = get_http_header_value(ZSTR_VAL(http_headers), "Connection: "); if (connection) { if (strncasecmp(connection, "close", sizeof("close")-1) == 0) { http_close = TRUE; } efree(connection); } } } else { http_close = TRUE; if (use_proxy && !use_ssl) { connection = get_http_header_value(ZSTR_VAL(http_headers), "Proxy-Connection: "); if (connection) { if (strncasecmp(connection, "Keep-Alive", sizeof("Keep-Alive")-1) == 0) { http_close = FALSE; } efree(connection); } } if (http_close == TRUE) { connection = get_http_header_value(ZSTR_VAL(http_headers), "Connection: "); if (connection) { if (strncasecmp(connection, "Keep-Alive", sizeof("Keep-Alive")-1) == 0) { http_close = FALSE; } efree(connection); } } } http_body = get_http_body(stream, http_close, ZSTR_VAL(http_headers)); if (!http_body) { if (request != buf) { zend_string_release(request); } php_stream_close(stream); zend_string_release(http_headers); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); add_soap_fault(this_ptr, "HTTP", "Error Fetching http body, No Content-Length, connection closed or chunked data", NULL, NULL); if (http_msg) { efree(http_msg); } smart_str_free(&soap_headers_z); return FALSE; } if (request != buf) { zend_string_release(request); } if (http_close) { php_stream_close(stream); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); stream = NULL; } /* Process HTTP status codes */ if (http_status >= 300 && http_status < 400) { char *loc; if ((loc = get_http_header_value(ZSTR_VAL(http_headers), "Location: ")) != NULL) { php_url *new_url = php_url_parse(loc); if (new_url != NULL) { zend_string_release(http_headers); zend_string_release(http_body); efree(loc); if (new_url->scheme == NULL && new_url->path != NULL) { new_url->scheme = phpurl->scheme ? estrdup(phpurl->scheme) : NULL; new_url->host = phpurl->host ? estrdup(phpurl->host) : NULL; new_url->port = phpurl->port; if (new_url->path && new_url->path[0] != '/') { if (phpurl->path) { char *t = phpurl->path; char *p = strrchr(t, '/'); if (p) { char *s = emalloc((p - t) + strlen(new_url->path) + 2); strncpy(s, t, (p - t) + 1); s[(p - t) + 1] = 0; strcat(s, new_url->path); efree(new_url->path); new_url->path = s; } } else { char *s = emalloc(strlen(new_url->path) + 2); s[0] = '/'; s[1] = 0; strcat(s, new_url->path); efree(new_url->path); new_url->path = s; } } } phpurl = new_url; if (--redirect_max < 1) { add_soap_fault(this_ptr, "HTTP", "Redirection limit reached, aborting", NULL, NULL); smart_str_free(&soap_headers_z); return FALSE; } goto try_again; } } } else if (http_status == 401) { /* Digest authentication */ zval *digest, *login, *password; char *auth = get_http_header_value(ZSTR_VAL(http_headers), "WWW-Authenticate: "); if (auth && strstr(auth, "Digest") == auth && ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) == NULL || Z_TYPE_P(digest) != IS_ARRAY) && (login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login")-1)) != NULL && Z_TYPE_P(login) == IS_STRING && (password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL && Z_TYPE_P(password) == IS_STRING) { char *s; zval digest; ZVAL_UNDEF(&digest); s = auth + sizeof("Digest")-1; while (*s != '\0') { char *name, *val; while (*s == ' ') ++s; name = s; while (*s != '\0' && *s != '=') ++s; if (*s == '=') { *s = '\0'; ++s; if (*s == '"') { ++s; val = s; while (*s != '\0' && *s != '"') ++s; } else { val = s; while (*s != '\0' && *s != ' ' && *s != ',') ++s; } if (*s != '\0') { if (*s != ',') { *s = '\0'; ++s; while (*s != '\0' && *s != ',') ++s; if (*s != '\0') ++s; } else { *s = '\0'; ++s; } } if (Z_TYPE(digest) == IS_UNDEF) { array_init(&digest); } add_assoc_string(&digest, name, val); } } if (Z_TYPE(digest) != IS_UNDEF) { php_url *new_url = emalloc(sizeof(php_url)); Z_DELREF(digest); add_property_zval_ex(this_ptr, "_digest", sizeof("_digest")-1, &digest); *new_url = *phpurl; if (phpurl->scheme) phpurl->scheme = estrdup(phpurl->scheme); if (phpurl->user) phpurl->user = estrdup(phpurl->user); if (phpurl->pass) phpurl->pass = estrdup(phpurl->pass); if (phpurl->host) phpurl->host = estrdup(phpurl->host); if (phpurl->path) phpurl->path = estrdup(phpurl->path); if (phpurl->query) phpurl->query = estrdup(phpurl->query); if (phpurl->fragment) phpurl->fragment = estrdup(phpurl->fragment); phpurl = new_url; efree(auth); zend_string_release(http_headers); zend_string_release(http_body); goto try_again; } } if (auth) efree(auth); } smart_str_free(&soap_headers_z); /* Check and see if the server even sent a xml document */ content_type = get_http_header_value(ZSTR_VAL(http_headers), "Content-Type: "); if (content_type) { char *pos = NULL; int cmplen; pos = strstr(content_type,";"); if (pos != NULL) { cmplen = pos - content_type; } else { cmplen = strlen(content_type); } if (strncmp(content_type, "text/xml", cmplen) == 0 || strncmp(content_type, "application/soap+xml", cmplen) == 0) { content_type_xml = 1; /* if (strncmp(http_body, "<?xml", 5)) { zval *err; MAKE_STD_ZVAL(err); ZVAL_STRINGL(err, http_body, http_body_size, 1); add_soap_fault(this_ptr, "HTTP", "Didn't receive an xml document", NULL, err); efree(content_type); zend_string_release(http_headers); efree(http_body); return FALSE; } */ } efree(content_type); } /* Decompress response */ content_encoding = get_http_header_value(ZSTR_VAL(http_headers), "Content-Encoding: "); if (content_encoding) { zval func; zval retval; zval params[1]; if ((strcmp(content_encoding,"gzip") == 0 || strcmp(content_encoding,"x-gzip") == 0) && zend_hash_str_exists(EG(function_table), "gzinflate", sizeof("gzinflate")-1)) { ZVAL_STRING(&func, "gzinflate"); ZVAL_STRINGL(&params[0], http_body->val+10, http_body->len-10); } else if (strcmp(content_encoding,"deflate") == 0 && zend_hash_str_exists(EG(function_table), "gzuncompress", sizeof("gzuncompress")-1)) { ZVAL_STRING(&func, "gzuncompress"); ZVAL_STR_COPY(&params[0], http_body); } else { efree(content_encoding); zend_string_release(http_headers); zend_string_release(http_body); if (http_msg) { efree(http_msg); } add_soap_fault(this_ptr, "HTTP", "Unknown Content-Encoding", NULL, NULL); return FALSE; } if (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, 1, params) == SUCCESS && Z_TYPE(retval) == IS_STRING) { zval_ptr_dtor(&params[0]); zval_ptr_dtor(&func); zend_string_release(http_body); ZVAL_COPY_VALUE(return_value, &retval); } else { zval_ptr_dtor(&params[0]); zval_ptr_dtor(&func); efree(content_encoding); zend_string_release(http_headers); zend_string_release(http_body); add_soap_fault(this_ptr, "HTTP", "Can't uncompress compressed response", NULL, NULL); if (http_msg) { efree(http_msg); } return FALSE; } efree(content_encoding); } else { ZVAL_STR(return_value, http_body); } zend_string_release(http_headers); if (http_status >= 400) { int error = 0; if (Z_STRLEN_P(return_value) == 0) { error = 1; } else if (Z_STRLEN_P(return_value) > 0) { if (!content_type_xml) { char *s = Z_STRVAL_P(return_value); while (*s != '\0' && *s < ' ') { s++; } if (strncmp(s, "<?xml", 5)) { error = 1; } } } if (error) { zval_ptr_dtor(return_value); ZVAL_UNDEF(return_value); add_soap_fault(this_ptr, "HTTP", http_msg, NULL, NULL); efree(http_msg); return FALSE; } } if (http_msg) { efree(http_msg); } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71610: Type Confusion Vulnerability - SOAP / make_http_soap_request()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct ip6t_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, AF_INET6, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'netfilter: x_tables: introduce and use xt_copy_counters_from_user The three variants use same copy&pasted code, condense this into a helper and use that. Make sure info.name is 0-terminated. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap, int destroy, struct nlmsghdr *nlh, u32 portid) { struct in_ifaddr *promote = NULL; struct in_ifaddr *ifa, *ifa1 = *ifap; struct in_ifaddr *last_prim = in_dev->ifa_list; struct in_ifaddr *prev_prom = NULL; int do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev); ASSERT_RTNL(); /* 1. Deleting primary ifaddr forces deletion all secondaries * unless alias promotion is set **/ if (!(ifa1->ifa_flags & IFA_F_SECONDARY)) { struct in_ifaddr **ifap1 = &ifa1->ifa_next; while ((ifa = *ifap1) != NULL) { if (!(ifa->ifa_flags & IFA_F_SECONDARY) && ifa1->ifa_scope <= ifa->ifa_scope) last_prim = ifa; if (!(ifa->ifa_flags & IFA_F_SECONDARY) || ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) { ifap1 = &ifa->ifa_next; prev_prom = ifa; continue; } if (!do_promote) { inet_hash_remove(ifa); *ifap1 = ifa->ifa_next; rtmsg_ifa(RTM_DELADDR, ifa, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa); inet_free_ifa(ifa); } else { promote = ifa; break; } } } /* On promotion all secondaries from subnet are changing * the primary IP, we must remove all their routes silently * and later to add them back with new prefsrc. Do this * while all addresses are on the device list. */ for (ifa = promote; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask == ifa->ifa_mask && inet_ifa_match(ifa1->ifa_address, ifa)) fib_del_ifaddr(ifa, ifa1); } /* 2. Unlink it */ *ifap = ifa1->ifa_next; inet_hash_remove(ifa1); /* 3. Announce address deletion */ /* Send message first, then call notifier. At first sight, FIB update triggered by notifier will refer to already deleted ifaddr, that could confuse netlink listeners. It is not true: look, gated sees that route deleted and if it still thinks that ifaddr is valid, it will try to restore deleted routes... Grr. So that, this order is correct. */ rtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1); if (promote) { struct in_ifaddr *next_sec = promote->ifa_next; if (prev_prom) { prev_prom->ifa_next = promote->ifa_next; promote->ifa_next = last_prim->ifa_next; last_prim->ifa_next = promote; } promote->ifa_flags &= ~IFA_F_SECONDARY; rtmsg_ifa(RTM_NEWADDR, promote, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_UP, promote); for (ifa = next_sec; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) continue; fib_add_ifaddr(ifa); } } if (destroy) inet_free_ifa(ifa1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <solar@openwall.com> Signed-off-by: David S. Miller <davem@davemloft.net> Tested-by: Cyrill Gorcunov <gorcunov@openvz.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbfl_buffer_converter_new2( const mbfl_encoding *from, const mbfl_encoding *to, int buf_initsz) { mbfl_buffer_converter *convd; /* allocate */ convd = (mbfl_buffer_converter*)mbfl_malloc(sizeof (mbfl_buffer_converter)); if (convd == NULL) { return NULL; } /* initialize */ convd->from = from; convd->to = to; /* create convert filter */ convd->filter1 = NULL; convd->filter2 = NULL; if (mbfl_convert_filter_get_vtbl(convd->from->no_encoding, convd->to->no_encoding) != NULL) { convd->filter1 = mbfl_convert_filter_new(convd->from->no_encoding, convd->to->no_encoding, mbfl_memory_device_output, NULL, &convd->device); } else { convd->filter2 = mbfl_convert_filter_new(mbfl_no_encoding_wchar, convd->to->no_encoding, mbfl_memory_device_output, NULL, &convd->device); if (convd->filter2 != NULL) { convd->filter1 = mbfl_convert_filter_new(convd->from->no_encoding, mbfl_no_encoding_wchar, (int (*)(int, void*))convd->filter2->filter_function, (int (*)(void*))convd->filter2->filter_flush, convd->filter2); if (convd->filter1 == NULL) { mbfl_convert_filter_delete(convd->filter2); } } } if (convd->filter1 == NULL) { return NULL; } mbfl_memory_device_init(&convd->device, buf_initsz, buf_initsz/4); return convd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, offsetGet) { char *fname, *error; size_t fname_len; zval zfname; phar_entry_info *entry; zend_string *sfname; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } /* security is 0 here so that we can get a better error message than "entry doesn't exist" */ if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:""); } else { if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } if (entry->is_temp_dir) { efree(entry->filename); efree(entry); } sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname); ZVAL_NEW_STR(&zfname, sfname); spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname); zval_ptr_dtor(&zfname); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; int zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname); } return; } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void ext4_truncate_failed_write(struct inode *inode) { truncate_inode_pages(inode->i_mapping, inode->i_size); ext4_truncate(inode); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; handle_t *handle; struct ext4_ext_path *path; struct ext4_extent *extent; ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0; unsigned int credits, ee_len; int ret = 0, depth, split_flag = 0; loff_t ioffset; /* * We need to test this early because xfstests assumes that an * insert range of (0, 1) will return EOPNOTSUPP if the file * system does not support insert range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Insert range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EOPNOTSUPP; trace_ext4_insert_range(inode, offset, len); offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb); len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down to align start offset to page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } /* Check for wrap through zero */ if (inode->i_size + len > inode->i_sb->s_maxbytes) { ret = -EFBIG; goto out_mutex; } /* Offset should be less than i_size */ if (offset >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * Prevent page faults from reinstantiating pages we have released from * page cache. */ down_write(&EXT4_I(inode)->i_mmap_sem); truncate_pagecache(inode, ioffset); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_mmap; } /* Expand file to avoid data loss if there is error while shifting */ inode->i_size += len; EXT4_I(inode)->i_disksize += len; inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ret = ext4_mark_inode_dirty(handle, inode); if (ret) goto out_stop; down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); path = ext4_find_extent(inode, offset_lblk, NULL, 0); if (IS_ERR(path)) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } depth = ext_depth(inode); extent = path[depth].p_ext; if (extent) { ee_start_lblk = le32_to_cpu(extent->ee_block); ee_len = ext4_ext_get_actual_len(extent); /* * If offset_lblk is not the starting block of extent, split * the extent @offset_lblk */ if ((offset_lblk > ee_start_lblk) && (offset_lblk < (ee_start_lblk + ee_len))) { if (ext4_ext_is_unwritten(extent)) split_flag = EXT4_EXT_MARK_UNWRIT1 | EXT4_EXT_MARK_UNWRIT2; ret = ext4_split_extent_at(handle, inode, &path, offset_lblk, split_flag, EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_METADATA_NOFAIL); } ext4_ext_drop_refs(path); kfree(path); if (ret < 0) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } } ret = ext4_es_remove_extent(inode, offset_lblk, EXT_MAX_BLOCKS - offset_lblk); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } /* * if offset_lblk lies in a hole which is at start of file, use * ee_start_lblk to shift extents */ ret = ext4_ext_shift_extents(inode, handle, ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk, len_lblk, SHIFT_RIGHT); up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); out_stop: ext4_journal_stop(handle); out_mmap: up_write(&EXT4_I(inode)->i_mmap_sem); ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between buffered IO and collapse / insert range Current code implementing FALLOC_FL_COLLAPSE_RANGE and FALLOC_FL_INSERT_RANGE is prone to races with buffered writes and page faults. If buffered write or write via mmap manages to squeeze between filemap_write_and_wait_range() and truncate_pagecache() in the fallocate implementations, the written data is simply discarded by truncate_pagecache() although it should have been shifted. Fix the problem by moving filemap_write_and_wait_range() call inside i_mutex and i_mmap_sem. That way we are protected against races with both buffered writes and page faults. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: srtp_protect(srtp_ctx_t *ctx, void *rtp_hdr, int *pkt_octet_len) { srtp_hdr_t *hdr = (srtp_hdr_t *)rtp_hdr; uint32_t *enc_start; /* pointer to start of encrypted portion */ uint32_t *auth_start; /* pointer to start of auth. portion */ int enc_octet_len = 0; /* number of octets in encrypted portion */ xtd_seq_num_t est; /* estimated xtd_seq_num_t of *hdr */ int delta; /* delta of local pkt idx and that in hdr */ uint8_t *auth_tag = NULL; /* location of auth_tag within packet */ err_status_t status; int tag_len; srtp_stream_ctx_t *stream; int prefix_len; debug_print(mod_srtp, "function srtp_protect", NULL); /* we assume the hdr is 32-bit aligned to start */ /* Verify RTP header */ status = srtp_validate_rtp_header(rtp_hdr, pkt_octet_len); if (status) return status; /* check the packet length - it must at least contain a full header */ if (*pkt_octet_len < octets_in_rtp_header) return err_status_bad_param; /* * look up ssrc in srtp_stream list, and process the packet with * the appropriate stream. if we haven't seen this stream before, * there's a template key for this srtp_session, and the cipher * supports key-sharing, then we assume that a new stream using * that key has just started up */ stream = srtp_get_stream(ctx, hdr->ssrc); if (stream == NULL) { if (ctx->stream_template != NULL) { srtp_stream_ctx_t *new_stream; /* allocate and initialize a new stream */ status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream); if (status) return status; /* add new stream to the head of the stream_list */ new_stream->next = ctx->stream_list; ctx->stream_list = new_stream; /* set direction to outbound */ new_stream->direction = dir_srtp_sender; /* set stream (the pointer used in this function) */ stream = new_stream; } else { /* no template stream, so we return an error */ return err_status_no_ctx; } } /* * verify that stream is for sending traffic - this check will * detect SSRC collisions, since a stream that appears in both * srtp_protect() and srtp_unprotect() will fail this test in one of * those functions. */ if (stream->direction != dir_srtp_sender) { if (stream->direction == dir_unknown) { stream->direction = dir_srtp_sender; } else { srtp_handle_event(ctx, stream, event_ssrc_collision); } } /* * Check if this is an AEAD stream (GCM mode). If so, then dispatch * the request to our AEAD handler. */ if (stream->rtp_cipher->algorithm == AES_128_GCM || stream->rtp_cipher->algorithm == AES_256_GCM) { return srtp_protect_aead(ctx, stream, rtp_hdr, (unsigned int*)pkt_octet_len); } /* * update the key usage limit, and check it to make sure that we * didn't just hit either the soft limit or the hard limit, and call * the event handler if we hit either. */ switch(key_limit_update(stream->limit)) { case key_event_normal: break; case key_event_soft_limit: srtp_handle_event(ctx, stream, event_key_soft_limit); break; case key_event_hard_limit: srtp_handle_event(ctx, stream, event_key_hard_limit); return err_status_key_expired; default: break; } /* get tag length from stream */ tag_len = auth_get_tag_length(stream->rtp_auth); /* * find starting point for encryption and length of data to be * encrypted - the encrypted portion starts after the rtp header * extension, if present; otherwise, it starts after the last csrc, * if any are present * * if we're not providing confidentiality, set enc_start to NULL */ if (stream->rtp_services & sec_serv_conf) { enc_start = (uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc; if (hdr->x == 1) { srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t *)enc_start; enc_start += (ntohs(xtn_hdr->length) + 1); } if (!((uint8_t*)enc_start < (uint8_t*)hdr + *pkt_octet_len)) return err_status_parse_err; enc_octet_len = (int)(*pkt_octet_len - ((uint8_t*)enc_start - (uint8_t*)hdr)); if (enc_octet_len < 0) return err_status_parse_err; } else { enc_start = NULL; } /* * if we're providing authentication, set the auth_start and auth_tag * pointers to the proper locations; otherwise, set auth_start to NULL * to indicate that no authentication is needed */ if (stream->rtp_services & sec_serv_auth) { auth_start = (uint32_t *)hdr; auth_tag = (uint8_t *)hdr + *pkt_octet_len; } else { auth_start = NULL; auth_tag = NULL; } /* * estimate the packet index using the start of the replay window * and the sequence number from the header */ delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq)); status = rdbx_check(&stream->rtp_rdbx, delta); if (status) { if (status != err_status_replay_fail || !stream->allow_repeat_tx) return status; /* we've been asked to reuse an index */ } else rdbx_add_index(&stream->rtp_rdbx, delta); #ifdef NO_64BIT_MATH debug_print2(mod_srtp, "estimated packet index: %08x%08x", high32(est),low32(est)); #else debug_print(mod_srtp, "estimated packet index: %016llx", est); #endif /* * if we're using rindael counter mode, set nonce and seq */ if (stream->rtp_cipher->type->id == AES_ICM || stream->rtp_cipher->type->id == AES_256_ICM) { v128_t iv; iv.v32[0] = 0; iv.v32[1] = hdr->ssrc; #ifdef NO_64BIT_MATH iv.v64[1] = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16), low32(est) << 16)); #else iv.v64[1] = be64_to_cpu(est << 16); #endif status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt); } else { v128_t iv; /* otherwise, set the index to est */ #ifdef NO_64BIT_MATH iv.v32[0] = 0; iv.v32[1] = 0; #else iv.v64[0] = 0; #endif iv.v64[1] = be64_to_cpu(est); status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt); } if (status) return err_status_cipher_fail; /* shift est, put into network byte order */ #ifdef NO_64BIT_MATH est = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16), low32(est) << 16)); #else est = be64_to_cpu(est << 16); #endif /* * if we're authenticating using a universal hash, put the keystream * prefix into the authentication tag */ if (auth_start) { prefix_len = auth_get_prefix_length(stream->rtp_auth); if (prefix_len) { status = cipher_output(stream->rtp_cipher, auth_tag, prefix_len); if (status) return err_status_cipher_fail; debug_print(mod_srtp, "keystream prefix: %s", octet_string_hex_string(auth_tag, prefix_len)); } } /* if we're encrypting, exor keystream into the message */ if (enc_start) { status = cipher_encrypt(stream->rtp_cipher, (uint8_t *)enc_start, (unsigned int*)&enc_octet_len); if (status) return err_status_cipher_fail; } /* * if we're authenticating, run authentication function and put result * into the auth_tag */ if (auth_start) { /* initialize auth func context */ status = auth_start(stream->rtp_auth); if (status) return status; /* run auth func over packet */ status = auth_update(stream->rtp_auth, (uint8_t *)auth_start, *pkt_octet_len); if (status) return status; /* run auth func over ROC, put result into auth_tag */ debug_print(mod_srtp, "estimated packet index: %016llx", est); status = auth_compute(stream->rtp_auth, (uint8_t *)&est, 4, auth_tag); debug_print(mod_srtp, "srtp auth tag: %s", octet_string_hex_string(auth_tag, tag_len)); if (status) return err_status_auth_fail; } if (auth_tag) { /* increase the packet length by the length of the auth tag */ *pkt_octet_len += tag_len; } return err_status_ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Allow zero payload packets to pass bounds check.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long restore_tm_sigcontexts(struct pt_regs *regs, struct sigcontext __user *sc, struct sigcontext __user *tm_sc) { #ifdef CONFIG_ALTIVEC elf_vrreg_t __user *v_regs, *tm_v_regs; #endif unsigned long err = 0; unsigned long msr; #ifdef CONFIG_VSX int i; #endif /* copy the GPRs */ err |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr)); err |= __copy_from_user(&current->thread.ckpt_regs, sc->gp_regs, sizeof(regs->gpr)); /* * TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP. * TEXASR was set by the signal delivery reclaim, as was TFIAR. * Users doing anything abhorrent like thread-switching w/ signals for * TM-Suspended code will have to back TEXASR/TFIAR up themselves. * For the case of getting a signal and simply returning from it, * we don't need to re-copy them here. */ err |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]); err |= __get_user(current->thread.tm_tfhar, &sc->gp_regs[PT_NIP]); /* get MSR separately, transfer the LE bit if doing signal return */ err |= __get_user(msr, &sc->gp_regs[PT_MSR]); /* pull in MSR TM from user context */ regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr & MSR_TS_MASK); /* pull in MSR LE from user context */ regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE); /* The following non-GPR non-FPR non-VR state is also checkpointed: */ err |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]); err |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]); err |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]); err |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]); err |= __get_user(current->thread.ckpt_regs.ctr, &sc->gp_regs[PT_CTR]); err |= __get_user(current->thread.ckpt_regs.link, &sc->gp_regs[PT_LNK]); err |= __get_user(current->thread.ckpt_regs.xer, &sc->gp_regs[PT_XER]); err |= __get_user(current->thread.ckpt_regs.ccr, &sc->gp_regs[PT_CCR]); /* These regs are not checkpointed; they can go in 'regs'. */ err |= __get_user(regs->trap, &sc->gp_regs[PT_TRAP]); err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]); err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]); err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]); /* * Do this before updating the thread state in * current->thread.fpr/vr. That way, if we get preempted * and another task grabs the FPU/Altivec, it won't be * tempted to save the current CPU state into the thread_struct * and corrupt what we are writing there. */ discard_lazy_cpu_state(); /* * Force reload of FP/VEC. * This has to be done before copying stuff into current->thread.fpr/vr * for the reasons explained in the previous comment. */ regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX); #ifdef CONFIG_ALTIVEC err |= __get_user(v_regs, &sc->v_regs); err |= __get_user(tm_v_regs, &tm_sc->v_regs); if (err) return err; if (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128))) return -EFAULT; if (tm_v_regs && !access_ok(VERIFY_READ, tm_v_regs, 34 * sizeof(vector128))) return -EFAULT; /* Copy 33 vec registers (vr0..31 and vscr) from the stack */ if (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) { err |= __copy_from_user(&current->thread.vr_state, v_regs, 33 * sizeof(vector128)); err |= __copy_from_user(&current->thread.transact_vr, tm_v_regs, 33 * sizeof(vector128)); } else if (current->thread.used_vr) { memset(&current->thread.vr_state, 0, 33 * sizeof(vector128)); memset(&current->thread.transact_vr, 0, 33 * sizeof(vector128)); } /* Always get VRSAVE back */ if (v_regs != NULL && tm_v_regs != NULL) { err |= __get_user(current->thread.vrsave, (u32 __user *)&v_regs[33]); err |= __get_user(current->thread.transact_vrsave, (u32 __user *)&tm_v_regs[33]); } else { current->thread.vrsave = 0; current->thread.transact_vrsave = 0; } if (cpu_has_feature(CPU_FTR_ALTIVEC)) mtspr(SPRN_VRSAVE, current->thread.vrsave); #endif /* CONFIG_ALTIVEC */ /* restore floating point */ err |= copy_fpr_from_user(current, &sc->fp_regs); err |= copy_transact_fpr_from_user(current, &tm_sc->fp_regs); #ifdef CONFIG_VSX /* * Get additional VSX data. Update v_regs to point after the * VMX data. Copy VSX low doubleword from userspace to local * buffer for formatting, then into the taskstruct. */ if (v_regs && ((msr & MSR_VSX) != 0)) { v_regs += ELF_NVRREG; tm_v_regs += ELF_NVRREG; err |= copy_vsx_from_user(current, v_regs); err |= copy_transact_vsx_from_user(current, tm_v_regs); } else { for (i = 0; i < 32 ; i++) { current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0; current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0; } } #endif tm_enable(); /* Make sure the transaction is marked as failed */ current->thread.tm_texasr |= TEXASR_FS; /* This loads the checkpointed FP/VEC state, if used */ tm_recheckpoint(&current->thread, msr); /* This loads the speculative FP/VEC state, if used */ if (msr & MSR_FP) { do_load_up_transact_fpu(&current->thread); regs->msr |= (MSR_FP | current->thread.fpexc_mode); } #ifdef CONFIG_ALTIVEC if (msr & MSR_VEC) { do_load_up_transact_altivec(&current->thread); regs->msr |= MSR_VEC; } #endif return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-284', 'CWE-369'], 'message': 'powerpc/tm: Block signal return setting invalid MSR state Currently we allow both the MSR T and S bits to be set by userspace on a signal return. Unfortunately this is a reserved configuration and will cause a TM Bad Thing exception if attempted (via rfid). This patch checks for this case in both the 32 and 64 bit signals code. If both T and S are set, we mark the context as invalid. Found using a syscall fuzzer. Fixes: 2b0a576d15e0 ("powerpc: Add new transactional memory state to the signal context") Cc: stable@vger.kernel.org # v3.9+ Signed-off-by: Michael Neuling <mikey@neuling.org> Signed-off-by: Michael Ellerman <mpe@ellerman.id.au>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static pfunc check_literal(struct jv_parser* p) { if (p->tokenpos == 0) return 0; const char* pattern = 0; int plen; jv v; switch (p->tokenbuf[0]) { case 't': pattern = "true"; plen = 4; v = jv_true(); break; case 'f': pattern = "false"; plen = 5; v = jv_false(); break; case 'n': pattern = "null"; plen = 4; v = jv_null(); break; } if (pattern) { if (p->tokenpos != plen) return "Invalid literal"; for (int i=0; i<plen; i++) if (p->tokenbuf[i] != pattern[i]) return "Invalid literal"; TRY(value(p, v)); } else { // FIXME: better parser p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid char* end = 0; double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end); if (end == 0 || *end != 0) return "Invalid numeric literal"; TRY(value(p, jv_number(d))); } p->tokenpos = 0; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Heap buffer overflow in tokenadd() (fix #105) This was an off-by one: the NUL terminator byte was not allocated on resize. This was triggered by JSON-encoded numbers longer than 256 bytes.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BigInt inverse_mod(const BigInt& n, const BigInt& mod) { if(mod.is_zero()) throw BigInt::DivideByZero(); if(mod.is_negative() || n.is_negative()) throw Invalid_Argument("inverse_mod: arguments must be non-negative"); if(n.is_zero() || (n.is_even() && mod.is_even())) return 0; BigInt x = mod, y = n, u = mod, v = n; BigInt A = 1, B = 0, C = 0, D = 1; while(u.is_nonzero()) { size_t zero_bits = low_zero_bits(u); u >>= zero_bits; for(size_t i = 0; i != zero_bits; ++i) { if(A.is_odd() || B.is_odd()) { A += y; B -= x; } A >>= 1; B >>= 1; } zero_bits = low_zero_bits(v); v >>= zero_bits; for(size_t i = 0; i != zero_bits; ++i) { if(C.is_odd() || D.is_odd()) { C += y; D -= x; } C >>= 1; D >>= 1; } if(u >= v) { u -= v; A -= C; B -= D; } else { v -= u; C -= A; D -= B; } } if(v != 1) return 0; while(D.is_negative()) D += mod; while(D >= mod) D -= mod; return D; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fixes for CVE-2015-7827 and CVE-2016-2849'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(bcsqrt) { char *left; int left_len; long scale_param = 0; bc_num result; int scale = BCG(bc_precision), argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "s|l", &left, &left_len, &scale_param) == FAILURE) { return; } if (argc == 2) { scale = (int) ((int)scale_param < 0) ? 0 : scale_param; } bc_init_num(&result TSRMLS_CC); php_str2num(&result, left TSRMLS_CC); if (bc_sqrt (&result, scale TSRMLS_CC) != 0) { if (result->n_scale > scale) { result->n_scale = scale; } Z_STRVAL_P(return_value) = bc_num2str(result); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Square root of negative number"); } bc_free_num(&result); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition We can not modify result since it can be copy of _zero_ or _one_, etc. and "copy" in bcmath is just bumping the refcount. Conflicts: main/php_version.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=NULL; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; #ifdef EXIF_DEBUG char *dump_data; int dump_free; #endif /* EXIF_DEBUG */ /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached"); return FALSE; } ImageInfo->ifd_nesting_level++; tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components); return FALSE; } byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format]; if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC)); return FALSE; } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; /* dir_entry is ImageInfo->file.list[sn].data+2+i*12 offset_base is ImageInfo->file.list[sn].data-dir_offset dir_entry - offset_base is dir_offset+2+i*12 */ if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* It is important to check for IMAGE_FILETYPE_TIFF * JPEG does not use absolute pointers instead its pointers are * relative to the start of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength); } return FALSE; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = safe_emalloc(byte_count, 1, 0); outside = value_ptr; } else { /* In most cases we only access a small range so * it is faster to use a static buffer there * BUT it offers also the possibility to have * pointers read without the need to free them * explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = php_stream_tell(ImageInfo->infile); php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET); fgot = php_stream_tell(ImageInfo->infile); if (fgot!=offset_val) { EFREE_IF(outside); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val); return FALSE; } fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count); php_stream_seek(ImageInfo->infile, fpos, SEEK_SET); if (fgot<byte_count) { EFREE_IF(outside); EXIF_ERRLOG_FILEEOF(ImageInfo) return FALSE; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; #ifdef EXIF_DEBUG dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data); if (dump_free) { efree(dump_data); } #endif if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ ImageInfo->CopyrightPhotographer = estrdup(value_ptr); ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1); spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { ImageInfo->Copyright = estrndup(value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC); break; case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD"); } break; case TAG_MAKE: ImageInfo->make = estrndup(value_ptr, byte_count); break; case TAG_MODEL: ImageInfo->model = estrndup(value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF"); #endif ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS"); #endif ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY"); #endif ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer"); return FALSE; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index)); #endif } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC); EFREE_IF(outside); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72094 - Out of bounds heap read access in exif header processing'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(xml_parse_into_struct) { xml_parser *parser; zval *pind, **xdata, **info = NULL; char *data; int data_len, ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsZ|Z", &pind, &data, &data_len, &xdata, &info) == FAILURE) { return; } if (info) { zval_dtor(*info); array_init(*info); } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); zval_dtor(*xdata); array_init(*xdata); parser->data = *xdata; if (info) { parser->info = *info; } parser->level = 0; parser->ltags = safe_emalloc(XML_MAXLEVEL, sizeof(char *), 0); XML_SetDefaultHandler(parser->parser, _xml_defaultHandler); XML_SetElementHandler(parser->parser, _xml_startElementHandler, _xml_endElementHandler); XML_SetCharacterDataHandler(parser->parser, _xml_characterDataHandler); parser->isparsing = 1; ret = XML_Parse(parser->parser, data, data_len, 1); parser->isparsing = 0; RETVAL_LONG(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); return; } } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix bug #71735: Double-free in SplDoublyLinkedList::offsetSet'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void *bpf_any_get(void *raw, enum bpf_type type) { switch (type) { case BPF_TYPE_PROG: atomic_inc(&((struct bpf_prog *)raw)->aux->refcnt); break; case BPF_TYPE_MAP: bpf_map_inc(raw, true); break; default: WARN_ON_ONCE(1); break; } return raw; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Alexei Starovoitov <ast@kernel.org> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: polarssl_connect_step1(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; bool sni = TRUE; /* default is SNI enabled */ int ret = -1; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif void *old_session = NULL; char errorbuf[128]; errorbuf[0]=0; /* PolarSSL only supports SSLv3 and TLSv1 */ if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) { failf(data, "PolarSSL does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3) sni = FALSE; /* SSLv3 has no SNI */ #ifdef THREADING_SUPPORT entropy_init_mutex(&entropy); if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy, NULL, 0)) != 0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #else entropy_init(&connssl->entropy); if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy, NULL, 0)) != 0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #endif /* THREADING_SUPPORT */ /* Load the trusted CA */ memset(&connssl->cacert, 0, sizeof(x509_crt)); if(data->set.str[STRING_SSL_CAFILE]) { ret = x509_crt_parse_file(&connssl->cacert, data->set.str[STRING_SSL_CAFILE]); if(ret<0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading ca cert file %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_SSL_CAFILE], -ret, errorbuf); if(data->set.ssl.verifypeer) return CURLE_SSL_CACERT_BADFILE; } } if(data->set.str[STRING_SSL_CAPATH]) { ret = x509_crt_parse_path(&connssl->cacert, data->set.str[STRING_SSL_CAPATH]); if(ret<0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading ca cert path %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_SSL_CAPATH], -ret, errorbuf); if(data->set.ssl.verifypeer) return CURLE_SSL_CACERT_BADFILE; } } /* Load the client certificate */ memset(&connssl->clicert, 0, sizeof(x509_crt)); if(data->set.str[STRING_CERT]) { ret = x509_crt_parse_file(&connssl->clicert, data->set.str[STRING_CERT]); if(ret) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading client cert file %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_CERT], -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the client private key */ if(data->set.str[STRING_KEY]) { pk_context pk; pk_init(&pk); ret = pk_parse_keyfile(&pk, data->set.str[STRING_KEY], data->set.str[STRING_KEY_PASSWD]); if(ret == 0 && !pk_can_do(&pk, POLARSSL_PK_RSA)) ret = POLARSSL_ERR_PK_TYPE_MISMATCH; if(ret == 0) rsa_copy(&connssl->rsa, pk_rsa(pk)); else rsa_free(&connssl->rsa); pk_free(&pk); if(ret) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading private key %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_KEY], -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the CRL */ memset(&connssl->crl, 0, sizeof(x509_crl)); if(data->set.str[STRING_SSL_CRLFILE]) { ret = x509_crl_parse_file(&connssl->crl, data->set.str[STRING_SSL_CRLFILE]); if(ret) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading CRL file %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_SSL_CRLFILE], -ret, errorbuf); return CURLE_SSL_CRL_BADFILE; } } infof(data, "PolarSSL: Connecting to %s:%d\n", conn->host.name, conn->remote_port); if(ssl_init(&connssl->ssl)) { failf(data, "PolarSSL: ssl_init failed"); return CURLE_SSL_CONNECT_ERROR; } switch(data->set.ssl.version) { default: case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1); break; case CURL_SSLVERSION_SSLv3: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0); infof(data, "PolarSSL: Forced min. SSL Version to be SSLv3\n"); break; case CURL_SSLVERSION_TLSv1_0: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1); infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.0\n"); break; case CURL_SSLVERSION_TLSv1_1: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_2); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_2); infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.1\n"); break; case CURL_SSLVERSION_TLSv1_2: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3); infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.2\n"); break; } ssl_set_endpoint(&connssl->ssl, SSL_IS_CLIENT); ssl_set_authmode(&connssl->ssl, SSL_VERIFY_OPTIONAL); ssl_set_rng(&connssl->ssl, ctr_drbg_random, &connssl->ctr_drbg); ssl_set_bio(&connssl->ssl, net_recv, &conn->sock[sockindex], net_send, &conn->sock[sockindex]); ssl_set_ciphersuites(&connssl->ssl, ssl_list_ciphersuites()); if(!Curl_ssl_getsessionid(conn, &old_session, NULL)) { ret = ssl_set_session(&connssl->ssl, old_session); if(ret) { failf(data, "ssl_set_session returned -0x%x", -ret); return CURLE_SSL_CONNECT_ERROR; } infof(data, "PolarSSL re-using session\n"); } ssl_set_ca_chain(&connssl->ssl, &connssl->cacert, &connssl->crl, conn->host.name); ssl_set_own_cert_rsa(&connssl->ssl, &connssl->clicert, &connssl->rsa); if(!Curl_inet_pton(AF_INET, conn->host.name, &addr) && #ifdef ENABLE_IPV6 !Curl_inet_pton(AF_INET6, conn->host.name, &addr) && #endif sni && ssl_set_hostname(&connssl->ssl, conn->host.name)) { infof(data, "WARNING: failed to configure " "server name indication (SNI) TLS extension\n"); } #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { static const char* protocols[3]; int cur = 0; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID; infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif protocols[cur++] = ALPN_HTTP_1_1; infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); protocols[cur] = NULL; ssl_set_alpn_protocols(&connssl->ssl, protocols); } #endif #ifdef POLARSSL_DEBUG ssl_set_dbg(&connssl->ssl, polarssl_debug, data); #endif connssl->connecting_state = ssl_connect_2; return CURLE_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mbedtls/polarssl: set "hostname" unconditionally ...as otherwise the TLS libs will skip the CN/SAN check and just allow connection to any server. curl previously skipped this function when SNI wasn't used or when connecting to an IP address specified host. CVE-2016-3739 Bug: https://curl.haxx.se/docs/adv_20160518A.html Reported-by: Moti Avrahami'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit, rightLimit; int i; leftLimit = (-1); if (border < 0) { /* Refuse to fill to a non-solid border */ return; } for (i = x; (i >= 0); i--) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); leftLimit = i; } if (leftLimit == (-1)) { return; } /* Seek right */ rightLimit = x; for (i = (x + 1); (i < im->sx); i++) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info) { const char *errmsg; char errstr[129] = ""; if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; switch (error) { case XML_ERR_INVALID_HEX_CHARREF: errmsg = "CharRef: invalid hexadecimal value"; break; case XML_ERR_INVALID_DEC_CHARREF: errmsg = "CharRef: invalid decimal value"; break; case XML_ERR_INVALID_CHARREF: errmsg = "CharRef: invalid value"; break; case XML_ERR_INTERNAL_ERROR: errmsg = "internal error"; break; case XML_ERR_PEREF_AT_EOF: errmsg = "PEReference at end of document"; break; case XML_ERR_PEREF_IN_PROLOG: errmsg = "PEReference in prolog"; break; case XML_ERR_PEREF_IN_EPILOG: errmsg = "PEReference in epilog"; break; case XML_ERR_PEREF_NO_NAME: errmsg = "PEReference: no name"; break; case XML_ERR_PEREF_SEMICOL_MISSING: errmsg = "PEReference: expecting ';'"; break; case XML_ERR_ENTITY_LOOP: errmsg = "Detected an entity reference loop"; break; case XML_ERR_ENTITY_NOT_STARTED: errmsg = "EntityValue: \" or ' expected"; break; case XML_ERR_ENTITY_PE_INTERNAL: errmsg = "PEReferences forbidden in internal subset"; break; case XML_ERR_ENTITY_NOT_FINISHED: errmsg = "EntityValue: \" or ' expected"; break; case XML_ERR_ATTRIBUTE_NOT_STARTED: errmsg = "AttValue: \" or ' expected"; break; case XML_ERR_LT_IN_ATTRIBUTE: errmsg = "Unescaped '<' not allowed in attributes values"; break; case XML_ERR_LITERAL_NOT_STARTED: errmsg = "SystemLiteral \" or ' expected"; break; case XML_ERR_LITERAL_NOT_FINISHED: errmsg = "Unfinished System or Public ID \" or ' expected"; break; case XML_ERR_MISPLACED_CDATA_END: errmsg = "Sequence ']]>' not allowed in content"; break; case XML_ERR_URI_REQUIRED: errmsg = "SYSTEM or PUBLIC, the URI is missing"; break; case XML_ERR_PUBID_REQUIRED: errmsg = "PUBLIC, the Public Identifier is missing"; break; case XML_ERR_HYPHEN_IN_COMMENT: errmsg = "Comment must not contain '--' (double-hyphen)"; break; case XML_ERR_PI_NOT_STARTED: errmsg = "xmlParsePI : no target name"; break; case XML_ERR_RESERVED_XML_NAME: errmsg = "Invalid PI name"; break; case XML_ERR_NOTATION_NOT_STARTED: errmsg = "NOTATION: Name expected here"; break; case XML_ERR_NOTATION_NOT_FINISHED: errmsg = "'>' required to close NOTATION declaration"; break; case XML_ERR_VALUE_REQUIRED: errmsg = "Entity value required"; break; case XML_ERR_URI_FRAGMENT: errmsg = "Fragment not allowed"; break; case XML_ERR_ATTLIST_NOT_STARTED: errmsg = "'(' required to start ATTLIST enumeration"; break; case XML_ERR_NMTOKEN_REQUIRED: errmsg = "NmToken expected in ATTLIST enumeration"; break; case XML_ERR_ATTLIST_NOT_FINISHED: errmsg = "')' required to finish ATTLIST enumeration"; break; case XML_ERR_MIXED_NOT_STARTED: errmsg = "MixedContentDecl : '|' or ')*' expected"; break; case XML_ERR_PCDATA_REQUIRED: errmsg = "MixedContentDecl : '#PCDATA' expected"; break; case XML_ERR_ELEMCONTENT_NOT_STARTED: errmsg = "ContentDecl : Name or '(' expected"; break; case XML_ERR_ELEMCONTENT_NOT_FINISHED: errmsg = "ContentDecl : ',' '|' or ')' expected"; break; case XML_ERR_PEREF_IN_INT_SUBSET: errmsg = "PEReference: forbidden within markup decl in internal subset"; break; case XML_ERR_GT_REQUIRED: errmsg = "expected '>'"; break; case XML_ERR_CONDSEC_INVALID: errmsg = "XML conditional section '[' expected"; break; case XML_ERR_EXT_SUBSET_NOT_FINISHED: errmsg = "Content error in the external subset"; break; case XML_ERR_CONDSEC_INVALID_KEYWORD: errmsg = "conditional section INCLUDE or IGNORE keyword expected"; break; case XML_ERR_CONDSEC_NOT_FINISHED: errmsg = "XML conditional section not closed"; break; case XML_ERR_XMLDECL_NOT_STARTED: errmsg = "Text declaration '<?xml' required"; break; case XML_ERR_XMLDECL_NOT_FINISHED: errmsg = "parsing XML declaration: '?>' expected"; break; case XML_ERR_EXT_ENTITY_STANDALONE: errmsg = "external parsed entities cannot be standalone"; break; case XML_ERR_ENTITYREF_SEMICOL_MISSING: errmsg = "EntityRef: expecting ';'"; break; case XML_ERR_DOCTYPE_NOT_FINISHED: errmsg = "DOCTYPE improperly terminated"; break; case XML_ERR_LTSLASH_REQUIRED: errmsg = "EndTag: '</' not found"; break; case XML_ERR_EQUAL_REQUIRED: errmsg = "expected '='"; break; case XML_ERR_STRING_NOT_CLOSED: errmsg = "String not closed expecting \" or '"; break; case XML_ERR_STRING_NOT_STARTED: errmsg = "String not started expecting ' or \""; break; case XML_ERR_ENCODING_NAME: errmsg = "Invalid XML encoding name"; break; case XML_ERR_STANDALONE_VALUE: errmsg = "standalone accepts only 'yes' or 'no'"; break; case XML_ERR_DOCUMENT_EMPTY: errmsg = "Document is empty"; break; case XML_ERR_DOCUMENT_END: errmsg = "Extra content at the end of the document"; break; case XML_ERR_NOT_WELL_BALANCED: errmsg = "chunk is not well balanced"; break; case XML_ERR_EXTRA_CONTENT: errmsg = "extra content at the end of well balanced chunk"; break; case XML_ERR_VERSION_MISSING: errmsg = "Malformed declaration expecting version"; break; case XML_ERR_NAME_TOO_LONG: errmsg = "Name too long use XML_PARSE_HUGE option"; break; #if 0 case: errmsg = ""; break; #endif default: errmsg = "Unregistered error message"; } if (info == NULL) snprintf(errstr, 128, "%s\n", errmsg); else snprintf(errstr, 128, "%s: %%s\n", errmsg); if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, info, NULL, NULL, 0, 0, &errstr[0], info); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlSchemaFormatNodeForError(xmlChar ** msg, xmlSchemaAbstractCtxtPtr actxt, xmlNodePtr node) { xmlChar *str = NULL; *msg = NULL; if ((node != NULL) && (node->type != XML_ELEMENT_NODE) && (node->type != XML_ATTRIBUTE_NODE)) { /* * Don't try to format other nodes than element and * attribute nodes. * Play save and return an empty string. */ *msg = xmlStrdup(BAD_CAST ""); return(*msg); } if (node != NULL) { /* * Work on tree nodes. */ if (node->type == XML_ATTRIBUTE_NODE) { xmlNodePtr elem = node->parent; *msg = xmlStrdup(BAD_CAST "Element '"); if (elem->ns != NULL) *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, elem->ns->href, elem->name)); else *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, NULL, elem->name)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "', "); *msg = xmlStrcat(*msg, BAD_CAST "attribute '"); } else { *msg = xmlStrdup(BAD_CAST "Element '"); } if (node->ns != NULL) *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, node->ns->href, node->name)); else *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, NULL, node->name)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "': "); } else if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) actxt; /* * Work on node infos. */ if (vctxt->inode->nodeType == XML_ATTRIBUTE_NODE) { xmlSchemaNodeInfoPtr ielem = vctxt->elemInfos[vctxt->depth]; *msg = xmlStrdup(BAD_CAST "Element '"); *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, ielem->nsName, ielem->localName)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "', "); *msg = xmlStrcat(*msg, BAD_CAST "attribute '"); } else { *msg = xmlStrdup(BAD_CAST "Element '"); } *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, vctxt->inode->nsName, vctxt->inode->localName)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "': "); } else if (actxt->type == XML_SCHEMA_CTXT_PARSER) { /* * Hmm, no node while parsing? * Return an empty string, in case NULL will break something. */ *msg = xmlStrdup(BAD_CAST ""); } else { TODO return (NULL); } /* * VAL TODO: The output of the given schema component is currently * disabled. */ #if 0 if ((type != NULL) && (xmlSchemaIsGlobalItem(type))) { *msg = xmlStrcat(*msg, BAD_CAST " ["); *msg = xmlStrcat(*msg, xmlSchemaFormatItemForReport(&str, NULL, type, NULL, 0)); FREE_AND_NULL(str) *msg = xmlStrcat(*msg, BAD_CAST "]"); } #endif return (*msg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; size_t buffer_size = 0; size_t nbchars = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix inappropriate fetch of entities content For https://bugzilla.gnome.org/show_bug.cgi?id=761430 libfuzzer regression testing exposed another case where the parser would fetch content of an external entity while not in validating mode. Plug that hole'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk, struct x25_facilities *new, struct x25_dte_facilities *dte) { struct x25_sock *x25 = x25_sk(sk); struct x25_facilities *ours = &x25->facilities; struct x25_facilities theirs; int len; memset(&theirs, 0, sizeof(theirs)); memcpy(new, ours, sizeof(*new)); len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask); if (len < 0) return len; /* * They want reverse charging, we won't accept it. */ if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) { SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n"); return -1; } new->reverse = theirs.reverse; if (theirs.throughput) { int theirs_in = theirs.throughput & 0x0f; int theirs_out = theirs.throughput & 0xf0; int ours_in = ours->throughput & 0x0f; int ours_out = ours->throughput & 0xf0; if (!ours_in || theirs_in < ours_in) { SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n"); new->throughput = (new->throughput & 0xf0) | theirs_in; } if (!ours_out || theirs_out < ours_out) { SOCK_DEBUG(sk, "X.25: outbound throughput negotiated\n"); new->throughput = (new->throughput & 0x0f) | theirs_out; } } if (theirs.pacsize_in && theirs.pacsize_out) { if (theirs.pacsize_in < ours->pacsize_in) { SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n"); new->pacsize_in = theirs.pacsize_in; } if (theirs.pacsize_out < ours->pacsize_out) { SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n"); new->pacsize_out = theirs.pacsize_out; } } if (theirs.winsize_in && theirs.winsize_out) { if (theirs.winsize_in < ours->winsize_in) { SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n"); new->winsize_in = theirs.winsize_in; } if (theirs.winsize_out < ours->winsize_out) { SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n"); new->winsize_out = theirs.winsize_out; } } return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'net: fix a kernel infoleak in x25 module Stack object "dte_facilities" is allocated in x25_rx_call_request(), which is supposed to be initialized in x25_negotiate_facilities. However, 5 fields (8 bytes in total) are not initialized. This object is then copied to userland via copy_to_user, thus infoleak occurs. Signed-off-by: Kangjie Lu <kjlu@gatech.edu> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int add_array_entry(const char* loc_name, zval* hash_arr, char* key_name TSRMLS_DC) { char* key_value = NULL; char* cur_key_name = NULL; char* token = NULL; char* last_ptr = NULL; int result = 0; int cur_result = 0; int cnt = 0; if( strcmp(key_name , LOC_PRIVATE_TAG)==0 ){ key_value = get_private_subtags( loc_name ); result = 1; } else { key_value = get_icu_value_internal( loc_name , key_name , &result,1 ); } if( (strcmp(key_name , LOC_PRIVATE_TAG)==0) || ( strcmp(key_name , LOC_VARIANT_TAG)==0) ){ if( result > 0 && key_value){ /* Tokenize on the "_" or "-" */ token = php_strtok_r( key_value , DELIMITER ,&last_ptr); if( cur_key_name ){ efree( cur_key_name); } cur_key_name = (char*)ecalloc( 25, 25); sprintf( cur_key_name , "%s%d", key_name , cnt++); add_assoc_string( hash_arr, cur_key_name , token ,TRUE ); /* tokenize on the "_" or "-" and stop at singleton if any */ while( (token = php_strtok_r(NULL , DELIMITER , &last_ptr)) && (strlen(token)>1) ){ sprintf( cur_key_name , "%s%d", key_name , cnt++); add_assoc_string( hash_arr, cur_key_name , token , TRUE ); } /* if( strcmp(key_name, LOC_PRIVATE_TAG) == 0 ){ } */ } } else { if( result == 1 ){ add_assoc_string( hash_arr, key_name , key_value , TRUE ); cur_result = 1; } } if( cur_key_name ){ efree( cur_key_name); } /*if( key_name != LOC_PRIVATE_TAG && key_value){*/ if( key_value){ efree(key_value); } return cur_result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name) { zval** ele_value = NULL; if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if(Z_TYPE_PP(ele_value)!= IS_STRING ){ /* element value is not a string */ return FAILURE; } if(strcmp(key_name, LOC_LANG_TAG) != 0 && strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) { /* not lang or grandfathered tag */ smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); } smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } return LOC_NOT_FOUND; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter) { double width_d; double scale_f_d = 1.0; const double filter_width_d = DEFAULT_BOX_RADIUS; int windows_size; unsigned int u; LineContribType *res; if (scale_d < 1.0) { width_d = filter_width_d / scale_d; scale_f_d = scale_d; } else { width_d= filter_width_d; } windows_size = 2 * (int)ceil(width_d) + 1; res = _gdContributionsAlloc(line_size, windows_size); for (u = 0; u < line_size; u++) { const double dCenter = (double)u / scale_d; /* get the significant edge points affecting the pixel */ register int iLeft = MAX(0, (int)floor (dCenter - width_d)); int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1); double dTotalWeight = 0.0; int iSrc; res->ContribRow[u].Left = iLeft; res->ContribRow[u].Right = iRight; /* Cut edge points to fit in filter window in case of spill-off */ if (iRight - iLeft + 1 > windows_size) { if (iLeft < ((int)src_size - 1 / 2)) { iLeft++; } else { iRight--; } } for (iSrc = iLeft; iSrc <= iRight; iSrc++) { dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); } if (dTotalWeight < 0.0) { _gdContributionsFree(res); return NULL; } if (dTotalWeight > 0.0) { for (iSrc = iLeft; iSrc <= iRight; iSrc++) { res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight; } } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed memory overrun bug in gdImageScaleTwoPass _gdContributionsCalc would compute a window size and then adjust the left and right positions of the window to make a window within that size. However, it was storing the values in the struct *before* it made the adjustment. This change fixes that.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'</s>