text
stringlengths
478
227k
<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: ambsdtar_selfcheck( application_argument_t *argument) { if (argument->dle.disk) { char *qdisk = quote_string(argument->dle.disk); fprintf(stdout, "OK disk %s\n", qdisk); amfree(qdisk); } printf("OK ambsdtar version %s\n", VERSION); ambsdtar_build_exinclude(&argument->dle, 1, NULL, NULL, NULL, NULL); printf("OK ambsdtar\n"); if (bsdtar_path) { if (check_file(bsdtar_path, X_OK)) { if (check_exec_for_suid(bsdtar_path, TRUE)) { char *bsdtar_version; GPtrArray *argv_ptr = g_ptr_array_new(); g_ptr_array_add(argv_ptr, bsdtar_path); g_ptr_array_add(argv_ptr, "--version"); g_ptr_array_add(argv_ptr, NULL); bsdtar_version = get_first_line(argv_ptr); if (bsdtar_version) { char *tv, *bv; for (tv = bsdtar_version; *tv && !g_ascii_isdigit(*tv); tv++); for (bv = tv; *bv && *bv != ' '; bv++); if (*bv) *bv = '\0'; printf("OK ambsdtar bsdtar-version %s\n", tv); } else { printf(_("ERROR [Can't get %s version]\n"), bsdtar_path); } g_ptr_array_free(argv_ptr, TRUE); amfree(bsdtar_version); } } } else { printf(_("ERROR [BSDTAR program not available]\n")); } set_root_privs(1); if (state_dir && strlen(state_dir) == 0) state_dir = NULL; if (state_dir) { check_dir(state_dir, R_OK|W_OK); } else { printf(_("ERROR [No STATE-DIR]\n")); } if (bsdtar_directory) { check_dir(bsdtar_directory, R_OK); } else if (argument->dle.device) { check_dir(argument->dle.device, R_OK); } if (argument->calcsize) { char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL); check_exec_for_suid(calcsize, TRUE); check_file(calcsize, X_OK); check_suid(calcsize); amfree(calcsize); } set_root_privs(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c, application-src/amstar.c: Filter option from COMMAND-OPTIONS * common-src/ammessage.c: Add message. git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'</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: ambsdtar_build_argv( application_argument_t *argument, char *timestamps, char **file_exclude, char **file_include, int command) { int nb_exclude = 0; int nb_include = 0; char *dirname; char tmppath[PATH_MAX]; GPtrArray *argv_ptr = g_ptr_array_new(); GSList *copt; ambsdtar_build_exinclude(&argument->dle, 1, &nb_exclude, file_exclude, &nb_include, file_include); if (bsdtar_directory) { dirname = bsdtar_directory; } else { dirname = argument->dle.device; } g_ptr_array_add(argv_ptr, g_strdup(bsdtar_path)); g_ptr_array_add(argv_ptr, g_strdup("--create")); g_ptr_array_add(argv_ptr, g_strdup("--file")); if (command == CMD_ESTIMATE) { g_ptr_array_add(argv_ptr, g_strdup("/dev/null")); } else { g_ptr_array_add(argv_ptr, g_strdup("-")); } g_ptr_array_add(argv_ptr, g_strdup("--directory")); canonicalize_pathname(dirname, tmppath); g_ptr_array_add(argv_ptr, g_strdup(tmppath)); if (timestamps) { g_ptr_array_add(argv_ptr, g_strdup("--newer")); g_ptr_array_add(argv_ptr, g_strdup(timestamps)); } if (bsdtar_onefilesystem) g_ptr_array_add(argv_ptr, g_strdup("--one-file-system")); if (argument->tar_blocksize) { g_ptr_array_add(argv_ptr, g_strdup("--block-size")); g_ptr_array_add(argv_ptr, g_strdup(argument->tar_blocksize)); } g_ptr_array_add(argv_ptr, g_strdup("--totals")); for (copt = argument->command_options; copt != NULL; copt = copt->next) { g_ptr_array_add(argv_ptr, g_strdup((char *)copt->data)); } if (*file_exclude) { g_ptr_array_add(argv_ptr, g_strdup("--exclude-from")); g_ptr_array_add(argv_ptr, g_strdup(*file_exclude)); } if (*file_include) { g_ptr_array_add(argv_ptr, g_strdup("--files-from")); g_ptr_array_add(argv_ptr, g_strdup(*file_include)); } else { g_ptr_array_add(argv_ptr, g_strdup(".")); } g_ptr_array_add(argv_ptr, NULL); return(argv_ptr); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</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: ambsdtar_backup( application_argument_t *argument) { int dumpin; char *cmd = NULL; char *qdisk; char *timestamps; int mesgf = 3; int indexf = 4; int outf; int data_out; int index_out; int index_err; char *errmsg = NULL; amwait_t wait_status; GPtrArray *argv_ptr; pid_t tarpid; pid_t indexpid = 0; time_t tt; char *file_exclude; char *file_include; char new_timestamps[64]; char *option; mesgstream = fdopen(mesgf, "w"); if (!mesgstream) { error(_("error mesgstream(%d): %s\n"), mesgf, strerror(errno)); } if (!bsdtar_path) { error(_("BSDTAR-PATH not defined")); } if (!check_exec_for_suid(bsdtar_path, FALSE)) { error("'%s' binary is not secure", bsdtar_path); } if ((option = validate_command_options(argument))) { fprintf(stdout, "? Invalid '%s' COMMAND-OPTIONS\n", option); error("Invalid '%s' COMMAND-OPTIONS", option); } if (!state_dir) { error(_("STATE-DIR not defined")); } if (!argument->level) { fprintf(mesgstream, "? No level argument\n"); error(_("No level argument")); } if (!argument->dle.disk) { fprintf(mesgstream, "? No disk argument\n"); error(_("No disk argument")); } if (!argument->dle.device) { fprintf(mesgstream, "? No device argument\n"); error(_("No device argument")); } qdisk = quote_string(argument->dle.disk); tt = time(NULL); ctime_r(&tt, new_timestamps); new_timestamps[strlen(new_timestamps)-1] = '\0'; timestamps = ambsdtar_get_timestamps(argument, GPOINTER_TO_INT(argument->level->data), mesgstream, CMD_BACKUP); cmd = g_strdup(bsdtar_path); argv_ptr = ambsdtar_build_argv(argument, timestamps, &file_exclude, &file_include, CMD_BACKUP); if (argument->dle.create_index) { tarpid = pipespawnv(cmd, STDIN_PIPE|STDOUT_PIPE|STDERR_PIPE, 1, &dumpin, &data_out, &outf, (char **)argv_ptr->pdata); g_ptr_array_free_full(argv_ptr); argv_ptr = g_ptr_array_new(); g_ptr_array_add(argv_ptr, g_strdup(bsdtar_path)); g_ptr_array_add(argv_ptr, g_strdup("tf")); g_ptr_array_add(argv_ptr, g_strdup("-")); g_ptr_array_add(argv_ptr, NULL); indexpid = pipespawnv(cmd, STDIN_PIPE|STDOUT_PIPE|STDERR_PIPE, 1, &index_in, &index_out, &index_err, (char **)argv_ptr->pdata); g_ptr_array_free_full(argv_ptr); aclose(dumpin); indexstream = fdopen(indexf, "w"); if (!indexstream) { error(_("error indexstream(%d): %s\n"), indexf, strerror(errno)); } read_fd(data_out , "data out" , &read_data_out); read_fd(outf , "data err" , &read_text); read_fd(index_out, "index out", &read_text); read_fd(index_err, "index_err", &read_text); } else { tarpid = pipespawnv(cmd, STDIN_PIPE|STDERR_PIPE, 1, &dumpin, &dataf, &outf, (char **)argv_ptr->pdata); g_ptr_array_free_full(argv_ptr); aclose(dumpin); aclose(dataf); read_fd(outf, "data err", &read_text); } event_loop(0); waitpid(tarpid, &wait_status, 0); if (WIFSIGNALED(wait_status)) { errmsg = g_strdup_printf(_("%s terminated with signal %d: see %s"), cmd, WTERMSIG(wait_status), dbfn()); exit_status = 1; } else if (WIFEXITED(wait_status)) { if (exit_value[WEXITSTATUS(wait_status)] == 1) { errmsg = g_strdup_printf(_("%s exited with status %d: see %s"), cmd, WEXITSTATUS(wait_status), dbfn()); exit_status = 1; } else { /* Normal exit */ } } else { errmsg = g_strdup_printf(_("%s got bad exit: see %s"), cmd, dbfn()); exit_status = 1; } if (argument->dle.create_index) { waitpid(indexpid, &wait_status, 0); if (WIFSIGNALED(wait_status)) { errmsg = g_strdup_printf(_("'%s index' terminated with signal %d: see %s"), cmd, WTERMSIG(wait_status), dbfn()); exit_status = 1; } else if (WIFEXITED(wait_status)) { if (exit_value[WEXITSTATUS(wait_status)] == 1) { errmsg = g_strdup_printf(_("'%s index' exited with status %d: see %s"), cmd, WEXITSTATUS(wait_status), dbfn()); exit_status = 1; } else { /* Normal exit */ } } else { errmsg = g_strdup_printf(_("'%s index' got bad exit: see %s"), cmd, dbfn()); exit_status = 1; } } g_debug(_("after %s %s wait"), cmd, qdisk); g_debug(_("ambsdtar: %s: pid %ld"), cmd, (long)tarpid); if (errmsg) { g_debug("%s", errmsg); g_fprintf(mesgstream, "sendbackup: error [%s]\n", errmsg); exit_status = 1; } else if (argument->dle.record) { ambsdtar_set_timestamps(argument, GPOINTER_TO_INT(argument->level->data), new_timestamps, mesgstream); } g_debug("sendbackup: size %lld", (long long)dump_size); fprintf(mesgstream, "sendbackup: size %lld\n", (long long)dump_size); g_debug("sendbackup: end"); fprintf(mesgstream, "sendbackup: end\n"); if (argument->dle.create_index) fclose(indexstream); fclose(mesgstream); if (argument->verbose == 0) { if (file_exclude) unlink(file_exclude); if (file_include) unlink(file_include); } amfree(file_exclude); amfree(file_include); amfree(timestamps); amfree(qdisk); amfree(cmd); amfree(errmsg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</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 EmbFile::save2(FILE *f) { int c; m_objStr.streamReset(); while ((c = m_objStr.streamGetChar()) != EOF) { fputc(c, f); } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-670'], 'message': 'Check for stream before calling stream methods when saving an embedded file. Closes #659'</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: read_file(gchar* filepath) { FILE * f; size_t length; gchar *ret = NULL; f = fopen(filepath, "rb"); if (f) { fseek(f, 0, SEEK_END); length = (size_t)ftell(f); fseek(f, 0, SEEK_SET); /* We can't use MALLOC since it isn't thread safe */ ret = MALLOC(length + 1); if (ret) { if (fread(ret, length, 1, f) != 1) { log_message(LOG_INFO, "Failed to read all of %s", filepath); } ret[length] = '\0'; } else log_message(LOG_INFO, "Unable to read Dbus file %s", filepath); fclose(f); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <quentin@armitage.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: open_log_file(const char *name, const char *prog, const char *namespace, const char *instance) { char *file_name; if (log_file) { fclose(log_file); log_file = NULL; } if (!name) return; file_name = make_file_name(name, prog, namespace, instance); log_file = fopen(file_name, "a"); if (log_file) { int n = fileno(log_file); fcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD)); fcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL)); } FREE(file_name); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <quentin@armitage.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: modprobe_ipvs(void) { char *argv[] = { "/sbin/modprobe", "-s", "--", "ip_vs", NULL }; int child; int status; int rc; char *modprobe = get_modprobe(); struct sigaction act, old_act; if (modprobe) argv[0] = modprobe; act.sa_handler = SIG_DFL; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction ( SIGCHLD, &act, &old_act); if (log_file_name) flush_log_file(); if (!(child = fork())) { execv(argv[0], argv); exit(1); } rc = waitpid(child, &status, 0); sigaction ( SIGCHLD, &old_act, NULL); if (rc < 0) { log_message(LOG_INFO, "IPVS: waitpid error (%s)" , strerror(errno)); } if (modprobe) FREE(modprobe); if (!WIFEXITED(status) || WEXITSTATUS(status)) { return true; } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default If a non privileged user creates /tmp/keepalived.log and has it open for read (e.g. tail -f), then even though keepalived will change the owner to root and remove all read/write permissions from non owners, the application which already has the file open will be able to read the added log entries. Accordingly, opening a file in append mode is disabled by default, and only enabled if --enable-smtp-alert-debug or --enable-log-file (which are debugging options and unset by default) are enabled. This should further alleviate security concerns related to CVE-2018-19046. Signed-off-by: Quentin Armitage <quentin@armitage.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: FILE *fopen_safe(const char *path, const char *mode) { int fd; FILE *file; int flags = O_NOFOLLOW | O_CREAT; int sav_errno; if (mode[0] == 'r') return fopen(path, mode); if ((mode[0] != 'a' && mode[0] != 'w') || (mode[1] && (mode[1] != '+' || mode[2]))) { errno = EINVAL; return NULL; } if (mode[0] == 'w') flags |= O_TRUNC; else flags |= O_APPEND; if (mode[1]) flags |= O_RDWR; else flags |= O_WRONLY; fd = open(path, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (fd == -1) return NULL; /* Change file ownership to root */ if (fchown(fd, 0, 0)) { sav_errno = errno; log_message(LOG_INFO, "Unable to change file ownership of %s- errno %d (%m)", path, errno); close(fd); errno = sav_errno; return NULL; } /* Set file mode to rw------- */ if (fchmod(fd, S_IRUSR | S_IWUSR)) { sav_errno = errno; log_message(LOG_INFO, "Unable to change file permission of %s - errno %d (%m)", path, errno); close(fd); errno = sav_errno; return NULL; } file = fdopen (fd, "w"); if (!file) { sav_errno = errno; log_message(LOG_INFO, "fdopen(\"%s\") failed - errno %d (%m)", path, errno); close(fd); errno = sav_errno; return NULL; } return file; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default If a non privileged user creates /tmp/keepalived.log and has it open for read (e.g. tail -f), then even though keepalived will change the owner to root and remove all read/write permissions from non owners, the application which already has the file open will be able to read the added log entries. Accordingly, opening a file in append mode is disabled by default, and only enabled if --enable-smtp-alert-debug or --enable-log-file (which are debugging options and unset by default) are enabled. This should further alleviate security concerns related to CVE-2018-19046. Signed-off-by: Quentin Armitage <quentin@armitage.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: aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt) { BUF_UNION ubuf ; int subformat, samplerate ; ubuf.scbuf [0] = 0 ; /* The COMM chunk has an int aligned to an odd word boundary. Some ** procesors are not able to deal with this (ie bus fault) so we have ** to take special care. */ psf_binheader_readf (psf, "E242b", &(comm_fmt->numChannels), &(comm_fmt->numSampleFrames), &(comm_fmt->sampleSize), &(comm_fmt->sampleRate), SIGNED_SIZEOF (comm_fmt->sampleRate)) ; if (comm_fmt->size > 0x10000 && (comm_fmt->size & 0xffff) == 0) { psf_log_printf (psf, " COMM : %d (0x%x) *** should be ", comm_fmt->size, comm_fmt->size) ; comm_fmt->size = ENDSWAP_32 (comm_fmt->size) ; psf_log_printf (psf, "%d (0x%x)\n", comm_fmt->size, comm_fmt->size) ; } else psf_log_printf (psf, " COMM : %d\n", comm_fmt->size) ; if (comm_fmt->size == SIZEOF_AIFF_COMM) comm_fmt->encoding = NONE_MARKER ; else if (comm_fmt->size == SIZEOF_AIFC_COMM_MIN) psf_binheader_readf (psf, "Em", &(comm_fmt->encoding)) ; else if (comm_fmt->size >= SIZEOF_AIFC_COMM) { uint8_t encoding_len ; unsigned read_len ; psf_binheader_readf (psf, "Em1", &(comm_fmt->encoding), &encoding_len) ; comm_fmt->size = SF_MIN (sizeof (ubuf.scbuf), make_size_t (comm_fmt->size)) ; memset (ubuf.scbuf, 0, comm_fmt->size) ; read_len = comm_fmt->size - SIZEOF_AIFC_COMM + 1 ; psf_binheader_readf (psf, "b", ubuf.scbuf, read_len) ; ubuf.scbuf [read_len + 1] = 0 ; } ; samplerate = tenbytefloat2int (comm_fmt->sampleRate) ; psf_log_printf (psf, " Sample Rate : %d\n", samplerate) ; psf_log_printf (psf, " Frames : %u%s\n", comm_fmt->numSampleFrames, (comm_fmt->numSampleFrames == 0 && psf->filelength > 104) ? " (Should not be 0)" : "") ; if (comm_fmt->numChannels < 1 || comm_fmt->numChannels >= SF_MAX_CHANNELS) { psf_log_printf (psf, " Channels : %d (should be >= 1 and < %d)\n", comm_fmt->numChannels, SF_MAX_CHANNELS) ; return SFE_CHANNEL_COUNT_BAD ; } ; psf_log_printf (psf, " Channels : %d\n", comm_fmt->numChannels) ; /* Found some broken 'fl32' files with comm.samplesize == 16. Fix it here. */ if ((comm_fmt->encoding == fl32_MARKER || comm_fmt->encoding == FL32_MARKER) && comm_fmt->sampleSize != 32) { psf_log_printf (psf, " Sample Size : %d (should be 32)\n", comm_fmt->sampleSize) ; comm_fmt->sampleSize = 32 ; } else if ((comm_fmt->encoding == fl64_MARKER || comm_fmt->encoding == FL64_MARKER) && comm_fmt->sampleSize != 64) { psf_log_printf (psf, " Sample Size : %d (should be 64)\n", comm_fmt->sampleSize) ; comm_fmt->sampleSize = 64 ; } else psf_log_printf (psf, " Sample Size : %d\n", comm_fmt->sampleSize) ; subformat = s_bitwidth_to_subformat (comm_fmt->sampleSize) ; psf->sf.samplerate = samplerate ; psf->sf.frames = comm_fmt->numSampleFrames ; psf->sf.channels = comm_fmt->numChannels ; psf->bytewidth = BITWIDTH2BYTES (comm_fmt->sampleSize) ; psf->endian = SF_ENDIAN_BIG ; switch (comm_fmt->encoding) { case NONE_MARKER : psf->sf.format = (SF_FORMAT_AIFF | subformat) ; break ; case twos_MARKER : case in24_MARKER : case in32_MARKER : psf->sf.format = (SF_ENDIAN_BIG | SF_FORMAT_AIFF | subformat) ; break ; case sowt_MARKER : case ni24_MARKER : case ni32_MARKER : psf->endian = SF_ENDIAN_LITTLE ; psf->sf.format = (SF_ENDIAN_LITTLE | SF_FORMAT_AIFF | subformat) ; break ; case fl32_MARKER : case FL32_MARKER : psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_FLOAT) ; break ; case ulaw_MARKER : case ULAW_MARKER : psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ULAW) ; break ; case alaw_MARKER : case ALAW_MARKER : psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_ALAW) ; break ; case fl64_MARKER : case FL64_MARKER : psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_DOUBLE) ; break ; case raw_MARKER : psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_PCM_U8) ; break ; case DWVW_MARKER : psf->sf.format = SF_FORMAT_AIFF ; switch (comm_fmt->sampleSize) { case 12 : psf->sf.format |= SF_FORMAT_DWVW_12 ; break ; case 16 : psf->sf.format |= SF_FORMAT_DWVW_16 ; break ; case 24 : psf->sf.format |= SF_FORMAT_DWVW_24 ; break ; default : psf->sf.format |= SF_FORMAT_DWVW_N ; break ; } ; break ; case GSM_MARKER : psf->sf.format = SF_FORMAT_AIFF ; psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_GSM610) ; break ; case ima4_MARKER : psf->endian = SF_ENDIAN_BIG ; psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_IMA_ADPCM) ; break ; default : psf_log_printf (psf, "AIFC : Unimplemented format : %M\n", comm_fmt->encoding) ; return SFE_UNIMPLEMENTED ; } ; if (! ubuf.scbuf [0]) psf_log_printf (psf, " Encoding : %M\n", comm_fmt->encoding) ; else psf_log_printf (psf, " Encoding : %M => %s\n", comm_fmt->encoding, ubuf.scbuf) ; return 0 ; } /* aiff_read_comm_chunk */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix max channel count bug The code was allowing files to be written with a channel count of exactly `SF_MAX_CHANNELS` but was failing to read some file formats with the same channel count.'</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_MINIT_FUNCTION(com_dotnet) { zend_class_entry ce, *tmp; php_com_wrapper_minit(INIT_FUNC_ARGS_PASSTHRU); php_com_persist_minit(INIT_FUNC_ARGS_PASSTHRU); INIT_CLASS_ENTRY(ce, "com_exception", NULL); php_com_exception_class_entry = zend_register_internal_class_ex(&ce, zend_ce_exception); php_com_exception_class_entry->ce_flags |= ZEND_ACC_FINAL; /* php_com_exception_class_entry->constructor->common.fn_flags |= ZEND_ACC_PROTECTED; */ INIT_CLASS_ENTRY(ce, "com_safearray_proxy", NULL); php_com_saproxy_class_entry = zend_register_internal_class(&ce); php_com_saproxy_class_entry->ce_flags |= ZEND_ACC_FINAL; /* php_com_saproxy_class_entry->constructor->common.fn_flags |= ZEND_ACC_PROTECTED; */ php_com_saproxy_class_entry->get_iterator = php_com_saproxy_iter_get; INIT_CLASS_ENTRY(ce, "variant", NULL); ce.create_object = php_com_object_new; php_com_variant_class_entry = zend_register_internal_class(&ce); php_com_variant_class_entry->get_iterator = php_com_iter_get; INIT_CLASS_ENTRY(ce, "com", NULL); ce.create_object = php_com_object_new; tmp = zend_register_internal_class_ex(&ce, php_com_variant_class_entry); tmp->get_iterator = php_com_iter_get; zend_ts_hash_init(&php_com_typelibraries, 0, NULL, php_com_typelibrary_dtor, 1); #if HAVE_MSCOREE_H INIT_CLASS_ENTRY(ce, "dotnet", NULL); ce.create_object = php_com_object_new; tmp = zend_register_internal_class_ex(&ce, php_com_variant_class_entry); tmp->get_iterator = php_com_iter_get; #endif REGISTER_INI_ENTRIES(); #define COM_CONST(x) REGISTER_LONG_CONSTANT(#x, x, CONST_CS|CONST_PERSISTENT) #define COM_ERR_CONST(x) { \ zend_long __tmp; \ ULongToIntPtr(x, &__tmp); \ REGISTER_LONG_CONSTANT(#x, __tmp, CONST_CS|CONST_PERSISTENT); \ } COM_CONST(CLSCTX_INPROC_SERVER); COM_CONST(CLSCTX_INPROC_HANDLER); COM_CONST(CLSCTX_LOCAL_SERVER); COM_CONST(CLSCTX_REMOTE_SERVER); COM_CONST(CLSCTX_SERVER); COM_CONST(CLSCTX_ALL); #if 0 COM_CONST(DISPATCH_METHOD); COM_CONST(DISPATCH_PROPERTYGET); COM_CONST(DISPATCH_PROPERTYPUT); #endif COM_CONST(VT_NULL); COM_CONST(VT_EMPTY); COM_CONST(VT_UI1); COM_CONST(VT_I1); COM_CONST(VT_UI2); COM_CONST(VT_I2); COM_CONST(VT_UI4); COM_CONST(VT_I4); COM_CONST(VT_R4); COM_CONST(VT_R8); COM_CONST(VT_BOOL); COM_CONST(VT_ERROR); COM_CONST(VT_CY); COM_CONST(VT_DATE); COM_CONST(VT_BSTR); COM_CONST(VT_DECIMAL); COM_CONST(VT_UNKNOWN); COM_CONST(VT_DISPATCH); COM_CONST(VT_VARIANT); COM_CONST(VT_INT); COM_CONST(VT_UINT); COM_CONST(VT_ARRAY); COM_CONST(VT_BYREF); COM_CONST(CP_ACP); COM_CONST(CP_MACCP); COM_CONST(CP_OEMCP); COM_CONST(CP_UTF7); COM_CONST(CP_UTF8); COM_CONST(CP_SYMBOL); COM_CONST(CP_THREAD_ACP); COM_CONST(VARCMP_LT); COM_CONST(VARCMP_EQ); COM_CONST(VARCMP_GT); COM_CONST(VARCMP_NULL); COM_CONST(NORM_IGNORECASE); COM_CONST(NORM_IGNORENONSPACE); COM_CONST(NORM_IGNORESYMBOLS); COM_CONST(NORM_IGNOREWIDTH); COM_CONST(NORM_IGNOREKANATYPE); #ifdef NORM_IGNOREKASHIDA COM_CONST(NORM_IGNOREKASHIDA); #endif COM_ERR_CONST(DISP_E_DIVBYZERO); COM_ERR_CONST(DISP_E_OVERFLOW); COM_ERR_CONST(DISP_E_BADINDEX); COM_ERR_CONST(MK_E_UNAVAILABLE); #if SIZEOF_ZEND_LONG == 8 COM_CONST(VT_UI8); COM_CONST(VT_I8); #endif return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-502'], 'message': 'Fix #77177: Serializing or unserializing COM objects crashes Firstly, we avoid returning NULL from the get_property handler, but instead return an empty HashTable, which already prevents the crashes. Secondly, since (de-)serialization obviously makes no sense for COM, DOTNET and VARIANT objects (at least with the current implementation), we prohibit it right away.'</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* set_iovec_field(struct iovec *iovec, size_t *n_iovec, const char *field, const char *value) { char *x; x = strappend(field, value); if (x) iovec[(*n_iovec)++] = IOVEC_MAKE_STRING(x); return x; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'journald: do not store the iovec entry for process commandline on stack This fixes a crash where we would read the commandline, whose length is under control of the sending program, and then crash when trying to create a stack allocation for it. CVE-2018-16864 https://bugzilla.redhat.com/show_bug.cgi?id=1653855 The message actually doesn't get written to disk, because journal_file_append_entry() returns -E2BIG.'</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(void) { test_syslog_parse_identifier("pidu[111]: xxx", "pidu", "111", 11); test_syslog_parse_identifier("pidu: xxx", "pidu", NULL, 6); test_syslog_parse_identifier("pidu xxx", NULL, NULL, 0); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'journal: fix syslog_parse_identifier() Fixes #9829.'</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: build_gs_font(i_ctx_t *i_ctx_p, os_ptr op, gs_font ** ppfont, font_type ftype, gs_memory_type_ptr_t pstype, const build_proc_refs * pbuild, build_font_options_t options) { ref kname; /* t_string */ ref *pftype; ref *pencoding = 0; bool bitmapwidths; int exactsize, inbetweensize, transformedchar; int wmode; int code; gs_font *pfont; ref *pfid; ref *aop = dict_access_ref(op); bool cpsi_mode = gs_currentcpsimode(imemory); get_font_name(imemory, &kname, op - 1); if (dict_find_string(op, "FontType", &pftype) <= 0 || !r_has_type(pftype, t_integer) || pftype->value.intval != (int)ftype ) return_error(gs_error_invalidfont); if (dict_find_string(op, "Encoding", &pencoding) <= 0) { if (!(options & bf_Encoding_optional)) return_error(gs_error_invalidfont); pencoding = 0; } else { if (!r_is_array(pencoding)) return_error(gs_error_invalidfont); } if (pencoding) { /* observed Adobe behavior */ int count = r_size(pencoding); int type = ftype ? t_name : t_integer; bool fixit = false; while (count--) { ref r; if ((code = array_get(imemory, pencoding, count, &r)) < 0 || !(r_has_type(&r, type) || r_has_type(&r, t_null))) { if (!cpsi_mode && ftype == ft_user_defined) { if (code < 0 || r_has_type(&r, t_null)) { return_error(gs_error_typecheck); } fixit = true; break; } else { return_error(gs_error_typecheck); } } } /* For at least Type 3 fonts, Adobe Distiller will "fix" an Encoding array, as in, for example * Bug 692681 where the arrays contain integers rather than names. Once the font is instantiated * the integers have been converted to names. * It is preferable to to this manipulation here, rather than in Postscript, because we are less * restricted by read-only attributes and VM save levels. */ if (fixit) { ref penc; uint size = 0; char buf[32], *bptr; avm_space curglob = ialloc_space(idmemory); avm_space useglob = r_is_local(pencoding) ? avm_local : avm_global; ialloc_set_space(idmemory, useglob); count = r_size(pencoding); if ((code = ialloc_ref_array(&penc, (r_type_attrs(pencoding) & a_readonly), count, "build_gs_font")) < 0) return code; while (count--) { ref r; if (array_get(imemory, pencoding, count, &r) < 0){ return_error(gs_error_typecheck); } /* For type 3, we know the Encoding entries must be names */ if (r_has_type(&r, t_name)){ ref_assign(&(penc.value.refs[count]), &r); } else { if ((code = obj_cvs(imemory, &r, (byte *)buf, 32, &size, (const byte **)(&bptr))) < 0) { return(code); } if ((code = name_ref(imemory, (const byte *)bptr, size, &r, true)) < 0) return code; ref_assign(&(penc.value.refs[count]), &r); } } if ((code = dict_put_string(osp, "Encoding", &penc, NULL)) < 0) return code; ialloc_set_space(idmemory, curglob); } } if ((code = dict_int_param(op, "WMode", 0, 1, 0, &wmode)) < 0 || (code = dict_bool_param(op, "BitmapWidths", false, &bitmapwidths)) < 0 || (code = dict_int_param(op, "ExactSize", 0, 2, fbit_use_bitmaps, &exactsize)) < 0 || (code = dict_int_param(op, "InBetweenSize", 0, 2, fbit_use_outlines, &inbetweensize)) < 0 || (code = dict_int_param(op, "TransformedChar", 0, 2, fbit_use_outlines, &transformedchar)) < 0 ) return code; code = dict_find_string(op, "FID", &pfid); if (code > 0 && r_has_type(pfid, t_fontID)) { /* silently ignore invalid FID per CET 13-05.ps */ /* * If this font has a FID entry already, it might be a scaled font * made by makefont or scalefont; in a Level 2 environment, it might * be an existing font being registered under a second name, or a * re-encoded font (which was invalid in Level 1, but dvips did it * anyway). */ pfont = r_ptr(pfid, gs_font); /* * If the following condition is false this is a re-encoded font, * or some other questionable situation in which the FID * was preserved. Pretend the FID wasn't there. */ if (obj_eq(pfont->memory, pfont_dict(pfont), op)) { if (pfont->base == pfont) { /* original font */ if (!level2_enabled) return_error(gs_error_invalidfont); *ppfont = pfont; return 1; } else { /* This was made by makefont or scalefont. */ /* Just insert the new name. */ gs_matrix mat; ref fname; /* t_string */ code = sub_font_params(imemory, op, &mat, NULL, &fname); if (code < 0) return code; code = 1; copy_font_name(&pfont->font_name, &fname); goto set_name; } } } /* This is a new font. */ if (!r_has_attr(aop, a_write)) return_error(gs_error_invalidaccess); { ref encoding; /* * Since add_FID may resize the dictionary and cause * pencoding to become invalid, save the Encoding. */ if (pencoding) { encoding = *pencoding; pencoding = &encoding; } code = build_gs_sub_font(i_ctx_p, op, &pfont, ftype, pstype, pbuild, pencoding, op); if (code < 0) return code; } pfont->BitmapWidths = bitmapwidths; pfont->ExactSize = (fbit_type)exactsize; pfont->InBetweenSize = (fbit_type)inbetweensize; pfont->TransformedChar = (fbit_type)transformedchar; pfont->WMode = wmode; pfont->procs.font_info = zfont_info; code = 0; set_name: copy_font_name(&pfont->key_name, &kname); *ppfont = pfont; return code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking These were 'probably' safe anyway, since they mostly treat the objects as integers without checking, which at least can't result in a crash. Nevertheless, we ought to check. The return from comparedictkeys could be wrong if one of the keys had a value which was not an array, it could incorrectly decide the two were in fact the same.'</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: zimage3x(i_ctx_t *i_ctx_p) { os_ptr op = osp; gs_image3x_t image; ref *pDataDict; image_params ip_data; int num_components = gs_color_space_num_components(gs_currentcolorspace(igs)); int ignored; int code; check_type(*op, t_dictionary); check_dict_read(*op); memset(&image, 0, sizeof(gs_image3x_t)); gs_image3x_t_init(&image, NULL); if (dict_find_string(op, "DataDict", &pDataDict) <= 0) return_error(gs_error_rangecheck); if ((code = pixel_image_params(i_ctx_p, pDataDict, (gs_pixel_image_t *)&image, &ip_data, 16, false, gs_currentcolorspace(igs))) < 0 || (code = dict_int_param(pDataDict, "ImageType", 1, 1, 0, &ignored)) < 0 ) return code; /* * We have to process the masks in the reverse order, because they * insert their DataSource before the one(s) for the DataDict. */ if ((code = mask_dict_param(imemory, op, &ip_data, "ShapeMaskDict", num_components, &image.Shape)) < 0 || (code = mask_dict_param(imemory, op, &ip_data, "OpacityMaskDict", num_components, &image.Opacity)) < 0 ) return code; return zimage_setup(i_ctx_p, (gs_pixel_image_t *)&image, &ip_data.DataSource[0], image.CombineWithColor, 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking These were 'probably' safe anyway, since they mostly treat the objects as integers without checking, which at least can't result in a crash. Nevertheless, we ought to check. The return from comparedictkeys could be wrong if one of the keys had a value which was not an array, it could incorrectly decide the two were in fact the same.'</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 setindexedspace(i_ctx_t * i_ctx_p, ref *r, int *stage, int *cont, int CIESubst) { ref *pproc = &istate->colorspace[0].procs.special.index_proc; int code = 0; uint edepth = ref_stack_count(&e_stack); ref_colorspace cspace_old; ref hival, lookup; gs_color_space *pcs; gs_color_space *pcs_base; gs_color_space_index base_type; if (i_ctx_p->language_level < 2) return_error(gs_error_undefined); *cont = 0; if (*stage == 1) { *stage = 0; return 0; } cspace_old = istate->colorspace[0]; pcs_base = gs_currentcolorspace(igs); base_type = gs_color_space_get_index(pcs_base); code = array_get(imemory, r, 3, &lookup); if (code < 0) return code; code = array_get(imemory, r, 2, &hival); if (code < 0) return code; if (r_has_type(&lookup, t_string)) { int num_values = (hival.value.intval + 1) * cs_num_components(pcs_base); byte *data_tmp; check_read(lookup); /* * The PDF and PS specifications state that the lookup table must have * the exact number of of data bytes needed. However we have found * PDF files from Amyuni with extra data bytes. Acrobat 6.0 accepts * these files without complaint, so we ignore the extra data. */ if (r_size(&lookup) < num_values) return_error(gs_error_rangecheck); /* If we have a named color profile and the base space is DeviceN or Separation use a different set of procedures to ensure the named color remapping code is used */ if (igs->icc_manager->device_named != NULL && (base_type == gs_color_space_index_Separation || base_type == gs_color_space_index_DeviceN)) pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed_Named); else pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed); if (!pcs) { return_error(gs_error_VMerror); } pcs->base_space = pcs_base; rc_increment_cs(pcs_base); data_tmp = (byte *) (pcs->params.indexed.lookup.table.data = ialloc_string (lookup.tas.rsize, "setindexedspace")); if (!data_tmp) { rc_decrement(pcs, "setindexedspace"); return_error(gs_error_VMerror); } memcpy(data_tmp, lookup.value.const_bytes, lookup.tas.rsize); pcs->params.indexed.lookup.table.size = num_values; pcs->params.indexed.use_proc = 0; make_null(pproc); } else { gs_indexed_map *map; /* * We have to call zcs_begin_map before moving the parameters, * since if the color space is a DeviceN or Separation space, * the memmove will overwrite its parameters. */ code = zcs_begin_map(i_ctx_p, &map, &lookup, (hival.value.intval + 1), pcs_base, indexed_cont); if (code < 0) return code; if (igs->icc_manager->device_named != NULL && (base_type == gs_color_space_index_Separation || base_type == gs_color_space_index_DeviceN)) pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed_Named); else pcs = gs_cspace_alloc(imemory, &gs_color_space_type_Indexed); pcs->base_space = pcs_base; rc_increment_cs(pcs_base); pcs->params.indexed.use_proc = 1; *pproc = lookup; map->proc.lookup_index = lookup_indexed_map; pcs->params.indexed.lookup.map = map; } pcs->params.indexed.hival = hival.value.intval; pcs->params.indexed.n_comps = cs_num_components(pcs_base); code = gs_setcolorspace(igs, pcs); /* release reference from construction */ rc_decrement_only_cs(pcs, "setindexedspace"); if (code < 0) { istate->colorspace[0] = cspace_old; ref_stack_pop_to(&e_stack, edepth); return code; } *stage = 0; if (ref_stack_count(&e_stack) == edepth) { return 0; } else { *cont = 1; *stage = 1; return o_push_estack; /* installation will load the caches */ } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - check the Implementation of a Pattern before use Bug #700141 "Type confusion in setpattern" As the bug thread says, we were not checking that the Implementation of a pattern dictionary was a structure type, leading to a crash when we tried to treat it as one. Here we make the st_pattern1_instance and st_pattern2_instance structures public definitions and in zsetcolor we check the object stored under the Implementation key in the supplied dictionary to see if its a t_struct or t_astruct type, and if it is that its a st_pattern1_instance or st_pattern2_instance structure. If either check fails we throw a typecheck error. We need to make the st_pattern1_instance and st_pattern2_instance definitions public as they are defined in the graphics library and we need to check in the interpreter.'</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 crypto_report_one(struct crypto_alg *alg, struct crypto_user_alg *ualg, struct sk_buff *skb) { strlcpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name)); strlcpy(ualg->cru_driver_name, alg->cra_driver_name, sizeof(ualg->cru_driver_name)); strlcpy(ualg->cru_module_name, module_name(alg->cra_module), sizeof(ualg->cru_module_name)); ualg->cru_type = 0; ualg->cru_mask = 0; ualg->cru_flags = alg->cra_flags; ualg->cru_refcnt = refcount_read(&alg->cra_refcnt); if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority)) goto nla_put_failure; if (alg->cra_flags & CRYPTO_ALG_LARVAL) { struct crypto_report_larval rl; strlcpy(rl.type, "larval", sizeof(rl.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL, sizeof(struct crypto_report_larval), &rl)) goto nla_put_failure; goto out; } if (alg->cra_type && alg->cra_type->report) { if (alg->cra_type->report(skb, alg)) goto nla_put_failure; goto out; } switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) { case CRYPTO_ALG_TYPE_CIPHER: if (crypto_report_cipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_COMPRESS: if (crypto_report_comp(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_ACOMPRESS: if (crypto_report_acomp(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_AKCIPHER: if (crypto_report_akcipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_KPP: if (crypto_report_kpp(skb, alg)) goto nla_put_failure; break; } out: return 0; nla_put_failure: return -EMSGSIZE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'crypto: user - fix leaking uninitialized memory to userspace All bytes of the NETLINK_CRYPTO report structures must be initialized, since they are copied to userspace. The change from strncpy() to strlcpy() broke this. As a minimal fix, change it back. Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion") Cc: <stable@vger.kernel.org> # v4.12+ Signed-off-by: Eric Biggers <ebiggers@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.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: sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos) { int mxsize, cmd_size, k; int input_size, blocking; unsigned char opcode; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; struct sg_header old_hdr; sg_io_hdr_t *hp; unsigned char cmnd[SG_MAX_CDB_SIZE]; if (unlikely(uaccess_kernel())) return -EINVAL; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_write: count=%d\n", (int) count)); if (atomic_read(&sdp->detaching)) return -ENODEV; if (!((filp->f_flags & O_NONBLOCK) || scsi_block_when_processing_errors(sdp->device))) return -ENXIO; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; /* protects following copy_from_user()s + get_user()s */ if (count < SZ_SG_HEADER) return -EIO; if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER)) return -EFAULT; blocking = !(filp->f_flags & O_NONBLOCK); if (old_hdr.reply_len < 0) return sg_new_write(sfp, filp, buf, count, blocking, 0, 0, NULL); if (count < (SZ_SG_HEADER + 6)) return -EIO; /* The minimum scsi command length is 6 bytes. */ if (!(srp = sg_add_request(sfp))) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp, "sg_write: queue full\n")); return -EDOM; } buf += SZ_SG_HEADER; __get_user(opcode, buf); mutex_lock(&sfp->f_mutex); if (sfp->next_cmd_len > 0) { cmd_size = sfp->next_cmd_len; sfp->next_cmd_len = 0; /* reset so only this write() effected */ } else { cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */ if ((opcode >= 0xc0) && old_hdr.twelve_byte) cmd_size = 12; } mutex_unlock(&sfp->f_mutex); SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp, "sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size)); /* Determine buffer size. */ input_size = count - cmd_size; mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len; mxsize -= SZ_SG_HEADER; input_size -= SZ_SG_HEADER; if (input_size < 0) { sg_remove_request(sfp, srp); return -EIO; /* User did not pass enough bytes for this command. */ } hp = &srp->header; hp->interface_id = '\0'; /* indicator of old interface tunnelled */ hp->cmd_len = (unsigned char) cmd_size; hp->iovec_count = 0; hp->mx_sb_len = 0; if (input_size > 0) hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ? SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV; else hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE; hp->dxfer_len = mxsize; if ((hp->dxfer_direction == SG_DXFER_TO_DEV) || (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV)) hp->dxferp = (char __user *)buf + cmd_size; else hp->dxferp = NULL; hp->sbp = NULL; hp->timeout = old_hdr.reply_len; /* structure abuse ... */ hp->flags = input_size; /* structure abuse ... */ hp->pack_id = old_hdr.pack_id; hp->usr_ptr = NULL; if (__copy_from_user(cmnd, buf, cmd_size)) return -EFAULT; /* * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV, * but is is possible that the app intended SG_DXFER_TO_DEV, because there * is a non-zero input_size, so emit a warning. */ if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) { printk_ratelimited(KERN_WARNING "sg_write: data in/out %d/%d bytes " "for SCSI command 0x%x-- guessing " "data in;\n program %s not setting " "count and/or reply_len properly\n", old_hdr.reply_len - (int)SZ_SG_HEADER, input_size, (unsigned int) cmnd[0], current->comm); } k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking); return (k < 0) ? k : count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-732'], 'message': 'scsi: sg: mitigate read/write abuse As Al Viro noted in commit 128394eff343 ("sg_write()/bsg_write() is not fit to be called under KERNEL_DS"), sg improperly accesses userspace memory outside the provided buffer, permitting kernel memory corruption via splice(). But it doesn't just do it on ->write(), also on ->read(). As a band-aid, make sure that the ->read() and ->write() handlers can not be called in weird contexts (kernel context or credentials different from file opener), like for ib_safe_file_access(). If someone needs to use these interfaces from different security contexts, a new interface should be written that goes through the ->ioctl() handler. I've mostly copypasted ib_safe_file_access() over as sg_safe_file_access() because I couldn't find a good common header - please tell me if you know a better way. [mkp: s/_safe_/_check_/] Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: <stable@vger.kernel.org> Signed-off-by: Jann Horn <jannh@google.com> Acked-by: Douglas Gilbert <dgilbert@interlog.com> Signed-off-by: Martin K. Petersen <martin.petersen@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: rfbTightExtensionClientClose(rfbClientPtr cl, void* data) { if(data != NULL) free(data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'tightvnc-filetransfer: wait for download thread end in CloseUndoneFileDownload() ...and use it when deregistering the file transfer extension. Closes #242'</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: rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort) { rfbProtocolVersionMsg pv; int major,minor; char tmphost[250]; #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort); if (client->sock == -1) #endif { unsigned int host; if (!StringToIPAddr(repeaterHost, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost); return FALSE; } client->sock = ConnectClientToTcpAddr(host, repeaterPort); } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC repeater\n"); return FALSE; } if (!SetNonBlocking(client->sock)) return FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg] = 0; /* UltraVNC repeater always report version 000.000 to identify itself */ if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) { rfbClientLog("Not a valid VNC repeater (%s)\n",pv); return FALSE; } rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor); snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort); if (!WriteToRFBServer(client, tmphost, sizeof(tmphost))) return FALSE; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-665'], 'message': 'When connecting to a repeater, only send initialised string Closes #253'</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 CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c=0; c < 16; c+=2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) + (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Secunia 81800#1: samsumg_load_raw Secunia 81800#2: find_green Secunia 81800#3: rollei_load_raw remove_trailing_spaces: isspace() does not works right with signed non-latin chars Secunia 81800#5/6: nikon_coolscan_load_raw Secunia 81800#4: rollei_load_raw'</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: http_loop (struct url *u, struct url *original_url, char **newloc, char **local_file, const char *referer, int *dt, struct url *proxy, struct iri *iri) { int count; bool got_head = false; /* used for time-stamping and filename detection */ bool time_came_from_head = false; bool got_name = false; char *tms; const char *tmrate; uerr_t err, ret = TRYLIMEXC; time_t tmr = -1; /* remote time-stamp */ struct http_stat hstat; /* HTTP status */ struct_stat st; bool send_head_first = true; bool force_full_retrieve = false; /* If we are writing to a WARC file: always retrieve the whole file. */ if (opt.warc_filename != NULL) force_full_retrieve = true; /* Assert that no value for *LOCAL_FILE was passed. */ assert (local_file == NULL || *local_file == NULL); /* Set LOCAL_FILE parameter. */ if (local_file && opt.output_document) *local_file = HYPHENP (opt.output_document) ? NULL : xstrdup (opt.output_document); /* Reset NEWLOC parameter. */ *newloc = NULL; /* This used to be done in main, but it's a better idea to do it here so that we don't go through the hoops if we're just using FTP or whatever. */ if (opt.cookies) load_cookies (); /* Warn on (likely bogus) wildcard usage in HTTP. */ if (opt.ftp_glob && has_wildcards_p (u->path)) logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n")); /* Setup hstat struct. */ xzero (hstat); hstat.referer = referer; if (opt.output_document) { hstat.local_file = xstrdup (opt.output_document); got_name = true; } else if (!opt.content_disposition) { hstat.local_file = url_file_name (opt.trustservernames ? u : original_url, NULL); got_name = true; } if (got_name && file_exists_p (hstat.local_file) && opt.noclobber && !opt.output_document) { /* If opt.noclobber is turned on and file already exists, do not retrieve the file. But if the output_document was given, then this test was already done and the file didn't exist. Hence the !opt.output_document */ get_file_flags (hstat.local_file, dt); ret = RETROK; goto exit; } /* Reset the counter. */ count = 0; /* Reset the document type. */ *dt = 0; /* Skip preliminary HEAD request if we're not in spider mode. */ if (!opt.spider) send_head_first = false; /* Send preliminary HEAD request if --content-disposition and -c are used together. */ if (opt.content_disposition && opt.always_rest) send_head_first = true; #ifdef HAVE_METALINK if (opt.metalink_over_http) { *dt |= METALINK_METADATA; send_head_first = true; } #endif if (opt.timestamping) { /* Use conditional get request if requested * and if timestamp is known at this moment. */ if (opt.if_modified_since && !send_head_first && got_name && file_exists_p (hstat.local_file)) { *dt |= IF_MODIFIED_SINCE; { uerr_t timestamp_err = set_file_timestamp (&hstat); if (timestamp_err != RETROK) return timestamp_err; } } /* Send preliminary HEAD request if -N is given and we have existing * destination file or content disposition is enabled. */ else if (opt.content_disposition || file_exists_p (hstat.local_file)) send_head_first = true; } /* THE loop */ do { /* Increment the pass counter. */ ++count; sleep_between_retrievals (count); /* Get the current time string. */ tms = datetime_str (time (NULL)); if (opt.spider && !got_head) logprintf (LOG_VERBOSE, _("Spider mode enabled. Check if remote file exists.\n")); /* Print fetch message, if opt.verbose. */ if (opt.verbose) { char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); if (count > 1) { char tmp[256]; sprintf (tmp, _("(try:%2d)"), count); logprintf (LOG_NOTQUIET, "--%s-- %s %s\n", tms, tmp, hurl); } else { logprintf (LOG_NOTQUIET, "--%s-- %s\n", tms, hurl); } #ifdef WINDOWS ws_changetitle (hurl); #endif xfree (hurl); } /* Default document type is empty. However, if spider mode is on or time-stamping is employed, HEAD_ONLY commands is encoded within *dt. */ if (send_head_first && !got_head) *dt |= HEAD_ONLY; else *dt &= ~HEAD_ONLY; /* Decide whether or not to restart. */ if (force_full_retrieve) hstat.restval = hstat.len; else if (opt.start_pos >= 0) hstat.restval = opt.start_pos; else if (opt.always_rest && got_name && stat (hstat.local_file, &st) == 0 && S_ISREG (st.st_mode)) /* When -c is used, continue from on-disk size. (Can't use hstat.len even if count>1 because we don't want a failed first attempt to clobber existing data.) */ hstat.restval = st.st_size; else if (count > 1) /* otherwise, continue where the previous try left off */ hstat.restval = hstat.len; else hstat.restval = 0; /* Decide whether to send the no-cache directive. We send it in two cases: a) we're using a proxy, and we're past our first retrieval. Some proxies are notorious for caching incomplete data, so we require a fresh get. b) caching is explicitly inhibited. */ if ((proxy && count > 1) /* a */ || !opt.allow_cache) /* b */ *dt |= SEND_NOCACHE; else *dt &= ~SEND_NOCACHE; /* Try fetching the document, or at least its head. */ err = gethttp (u, &hstat, dt, proxy, iri, count); /* Time? */ tms = datetime_str (time (NULL)); /* Get the new location (with or without the redirection). */ if (hstat.newloc) *newloc = xstrdup (hstat.newloc); switch (err) { case HERR: case HEOF: case CONSOCKERR: case CONERROR: case READERR: case WRITEFAILED: case RANGEERR: case FOPEN_EXCL_ERR: case GATEWAYTIMEOUT: /* Non-fatal errors continue executing the loop, which will bring them to "while" statement at the end, to judge whether the number of tries was exceeded. */ printwhat (count, opt.ntry); continue; case FWRITEERR: case FOPENERR: /* Another fatal error. */ logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Cannot write to %s (%s).\n"), quote (hstat.local_file), strerror (errno)); case HOSTERR: case CONIMPOSSIBLE: case PROXERR: case SSLINITFAILED: case CONTNOTSUPPORTED: case VERIFCERTERR: case FILEBADFILE: case UNKNOWNATTR: /* Fatal errors just return from the function. */ ret = err; goto exit; case ATTRMISSING: /* A missing attribute in a Header is a fatal Protocol error. */ logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Required attribute missing from Header received.\n")); ret = err; goto exit; case AUTHFAILED: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Username/Password Authentication Failed.\n")); ret = err; goto exit; case WARC_ERR: /* A fatal WARC error. */ logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Cannot write to WARC file.\n")); ret = err; goto exit; case WARC_TMP_FOPENERR: case WARC_TMP_FWRITEERR: /* A fatal WARC error. */ logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Cannot write to temporary WARC file.\n")); ret = err; goto exit; case CONSSLERR: /* Another fatal error. */ logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n")); ret = err; goto exit; case UNLINKERR: /* Another fatal error. */ logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Cannot unlink %s (%s).\n"), quote (hstat.local_file), strerror (errno)); ret = err; goto exit; case NEWLOCATION: case NEWLOCATION_KEEP_POST: /* Return the new location to the caller. */ if (!*newloc) { logprintf (LOG_NOTQUIET, _("ERROR: Redirection (%d) without location.\n"), hstat.statcode); ret = WRONGCODE; } else { ret = err; } goto exit; case RETRUNNEEDED: /* The file was already fully retrieved. */ ret = RETROK; goto exit; case RETRFINISHED: /* Deal with you later. */ break; #ifdef HAVE_METALINK case RETR_WITH_METALINK: { if (hstat.metalink == NULL) { logputs (LOG_NOTQUIET, _("Could not find Metalink data in HTTP response. " "Downloading file using HTTP GET.\n")); *dt &= ~METALINK_METADATA; *dt &= ~HEAD_ONLY; got_head = true; continue; } logputs (LOG_VERBOSE, _("Metalink headers found. " "Switching to Metalink mode.\n")); ret = retrieve_from_metalink (hstat.metalink); goto exit; } break; #endif default: /* All possibilities should have been exhausted. */ abort (); } if (!(*dt & RETROKF)) { char *hurl = NULL; if (!opt.verbose) { /* #### Ugly ugly ugly! */ hurl = url_string (u, URL_AUTH_HIDE_PASSWD); logprintf (LOG_NONVERBOSE, "%s:\n", hurl); } /* Fall back to GET if HEAD fails with a 500 or 501 error code. */ if (*dt & HEAD_ONLY && (hstat.statcode == 500 || hstat.statcode == 501)) { got_head = true; continue; } /* Maybe we should always keep track of broken links, not just in * spider mode. * Don't log error if it was UTF-8 encoded because we will try * once unencoded. */ else if (opt.spider && !iri->utf8_encode) { /* #### Again: ugly ugly ugly! */ if (!hurl) hurl = url_string (u, URL_AUTH_HIDE_PASSWD); nonexisting_url (hurl); logprintf (LOG_NOTQUIET, _("\ Remote file does not exist -- broken link!!!\n")); } else { logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, hstat.statcode, quotearg_style (escape_quoting_style, hstat.error)); } logputs (LOG_VERBOSE, "\n"); ret = WRONGCODE; xfree (hurl); goto exit; } /* Did we get the time-stamp? */ if (!got_head || (opt.spider && !opt.recursive)) { got_head = true; /* no more time-stamping */ if (opt.timestamping && !hstat.remote_time) { logputs (LOG_NOTQUIET, _("\ Last-modified header missing -- time-stamps turned off.\n")); } else if (hstat.remote_time) { /* Convert the date-string into struct tm. */ tmr = http_atotm (hstat.remote_time); if (tmr == (time_t) (-1)) logputs (LOG_VERBOSE, _("\ Last-modified header invalid -- time-stamp ignored.\n")); if (*dt & HEAD_ONLY) time_came_from_head = true; } if (send_head_first) { /* The time-stamping section. */ if (opt.timestamping) { if (hstat.orig_file_name) /* Perform the following checks only if the file we're supposed to download already exists. */ { if (hstat.remote_time && tmr != (time_t) (-1)) { /* Now time-stamping can be used validly. Time-stamping means that if the sizes of the local and remote file match, and local file is newer than the remote file, it will not be retrieved. Otherwise, the normal download procedure is resumed. */ if (hstat.orig_file_tstamp >= tmr) { if (hstat.contlen == -1 || hstat.orig_file_size == hstat.contlen) { logprintf (LOG_VERBOSE, _("\ Server file no newer than local file %s -- not retrieving.\n\n"), quote (hstat.orig_file_name)); ret = RETROK; goto exit; } else { logprintf (LOG_VERBOSE, _("\ The sizes do not match (local %s) -- retrieving.\n"), number_to_static_string (hstat.orig_file_size)); } } else { force_full_retrieve = true; logputs (LOG_VERBOSE, _("Remote file is newer, retrieving.\n")); } logputs (LOG_VERBOSE, "\n"); } } /* free_hstat (&hstat); */ hstat.timestamp_checked = true; } if (opt.spider) { bool finished = true; if (opt.recursive) { if (*dt & TEXTHTML) { logputs (LOG_VERBOSE, _("\ Remote file exists and could contain links to other resources -- retrieving.\n\n")); finished = false; } else { logprintf (LOG_VERBOSE, _("\ Remote file exists but does not contain any link -- not retrieving.\n\n")); ret = RETROK; /* RETRUNNEEDED is not for caller. */ } } else { if (*dt & TEXTHTML) { logprintf (LOG_VERBOSE, _("\ Remote file exists and could contain further links,\n\ but recursion is disabled -- not retrieving.\n\n")); } else { logprintf (LOG_VERBOSE, _("\ Remote file exists.\n\n")); } ret = RETROK; /* RETRUNNEEDED is not for caller. */ } if (finished) { logprintf (LOG_NONVERBOSE, _("%s URL: %s %2d %s\n"), tms, u->url, hstat.statcode, hstat.message ? quotearg_style (escape_quoting_style, hstat.message) : ""); goto exit; } } got_name = true; *dt &= ~HEAD_ONLY; count = 0; /* the retrieve count for HEAD is reset */ xfree (hstat.message); xfree (hstat.error); continue; } /* send_head_first */ } /* !got_head */ if (opt.useservertimestamps && (tmr != (time_t) (-1)) && ((hstat.len == hstat.contlen) || ((hstat.res == 0) && (hstat.contlen == -1)))) { const char *fl = NULL; set_local_file (&fl, hstat.local_file); if (fl) { time_t newtmr = -1; /* Reparse time header, in case it's changed. */ if (time_came_from_head && hstat.remote_time && hstat.remote_time[0]) { newtmr = http_atotm (hstat.remote_time); if (newtmr != (time_t)-1) tmr = newtmr; } touch (fl, tmr); } } /* End of time-stamping section. */ tmrate = retr_rate (hstat.rd_size, hstat.dltime); total_download_time += hstat.dltime; if (hstat.len == hstat.contlen) { if (*dt & RETROKF || opt.content_on_error) { bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document)); logprintf (LOG_VERBOSE, write_to_stdout ? _("%s (%s) - written to stdout %s[%s/%s]\n\n") : _("%s (%s) - %s saved [%s/%s]\n\n"), tms, tmrate, write_to_stdout ? "" : quote (hstat.local_file), number_to_static_string (hstat.len), number_to_static_string (hstat.contlen)); logprintf (LOG_NONVERBOSE, "%s URL:%s [%s/%s] -> \"%s\" [%d]\n", tms, u->url, number_to_static_string (hstat.len), number_to_static_string (hstat.contlen), hstat.local_file, count); } ++numurls; total_downloaded_bytes += hstat.rd_size; /* Remember that we downloaded the file for later ".orig" code. */ if (*dt & ADDED_HTML_EXTENSION) downloaded_file (FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, hstat.local_file); else downloaded_file (FILE_DOWNLOADED_NORMALLY, hstat.local_file); ret = RETROK; goto exit; } else if (hstat.res == 0) /* No read error */ { if (hstat.contlen == -1) /* We don't know how much we were supposed to get, so assume we succeeded. */ { if (*dt & RETROKF || opt.content_on_error) { bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document)); logprintf (LOG_VERBOSE, write_to_stdout ? _("%s (%s) - written to stdout %s[%s]\n\n") : _("%s (%s) - %s saved [%s]\n\n"), tms, tmrate, write_to_stdout ? "" : quote (hstat.local_file), number_to_static_string (hstat.len)); logprintf (LOG_NONVERBOSE, "%s URL:%s [%s] -> \"%s\" [%d]\n", tms, u->url, number_to_static_string (hstat.len), hstat.local_file, count); } ++numurls; total_downloaded_bytes += hstat.rd_size; /* Remember that we downloaded the file for later ".orig" code. */ if (*dt & ADDED_HTML_EXTENSION) downloaded_file (FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, hstat.local_file); else downloaded_file (FILE_DOWNLOADED_NORMALLY, hstat.local_file); ret = RETROK; goto exit; } else if (hstat.len < hstat.contlen) /* meaning we lost the connection too soon */ { logprintf (LOG_VERBOSE, _("%s (%s) - Connection closed at byte %s. "), tms, tmrate, number_to_static_string (hstat.len)); printwhat (count, opt.ntry); continue; } else if (hstat.len != hstat.restval) /* Getting here would mean reading more data than requested with content-length, which we never do. */ abort (); else { /* Getting here probably means that the content-length was * _less_ than the original, local size. We should probably * truncate or re-read, or something. FIXME */ ret = RETROK; goto exit; } } else /* from now on hstat.res can only be -1 */ { if (hstat.contlen == -1) { logprintf (LOG_VERBOSE, _("%s (%s) - Read error at byte %s (%s)."), tms, tmrate, number_to_static_string (hstat.len), hstat.rderrmsg); printwhat (count, opt.ntry); continue; } else /* hstat.res == -1 and contlen is given */ { logprintf (LOG_VERBOSE, _("%s (%s) - Read error at byte %s/%s (%s). "), tms, tmrate, number_to_static_string (hstat.len), number_to_static_string (hstat.contlen), hstat.rderrmsg); printwhat (count, opt.ntry); continue; } } /* not reached */ } while (!opt.ntry || (count < opt.ntry)); exit: if ((ret == RETROK || opt.content_on_error) && local_file) { xfree (*local_file); *local_file = xstrdup (hstat.local_file); } free_hstat (&hstat); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Keep fetched URLs in POSIX extended attributes * configure.ac: Check for xattr availability * src/Makefile.am: Add xattr.c * src/ftp.c: Include xattr.h. (getftp): Set attributes if enabled. * src/http.c: Include xattr.h. (gethttp): Add parameter 'original_url', set attributes if enabled. (http_loop): Add 'original_url' to call of gethttp(). * src/init.c: Add new option --xattr. * src/main.c: Add new option --xattr, add description to help text. * src/options.h: Add new config member 'enable_xattr'. * src/xatrr.c: New file. * src/xattr.h: New file. These attributes provide a lightweight method of later determining where a file was downloaded from. This patch changes: * autoconf detects whether extended attributes are available and enables the code if they are. * The new flags --xattr and --no-xattr control whether xattr is enabled. * The new command "xattr = (on|off)" can be used in ~/.wgetrc or /etc/wgetrc * The original and redirected URLs are recorded as shown below. * This works for both single fetches and recursive mode. The attributes that are set are: user.xdg.origin.url: The URL that the content was fetched from. user.xdg.referrer.url: The URL that was originally requested. Here is an example, where http://archive.org redirects to https://archive.org: $ wget --xattr http://archive.org ... $ getfattr -d index.html user.xdg.origin.url="https://archive.org/" user.xdg.referrer.url="http://archive.org/" These attributes were chosen based on those stored by Google Chrome https://bugs.chromium.org/p/chromium/issues/detail?id=45903 and curl https://github.com/curl/curl/blob/master/src/tool_xattr.c'</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: main (int argc, char **argv) { int last_argc = -1; gpg_error_t err; int rc; parsed_uri_t uri; uri_tuple_t r; http_t hd; int c; unsigned int my_http_flags = 0; int no_out = 0; int tls_dbg = 0; int no_crl = 0; const char *cafile = NULL; http_session_t session = NULL; unsigned int timeout = 0; gpgrt_init (); log_set_prefix (PGM, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID); if (argc) { argc--; argv++; } while (argc && last_argc != argc ) { last_argc = argc; if (!strcmp (*argv, "--")) { argc--; argv++; break; } else if (!strcmp (*argv, "--help")) { fputs ("usage: " PGM " URL\n" "Options:\n" " --verbose print timings etc.\n" " --debug flyswatter\n" " --tls-debug N use TLS debug level N\n" " --cacert FNAME expect CA certificate in file FNAME\n" " --timeout MS timeout for connect in MS\n" " --no-verify do not verify the certificate\n" " --force-tls use HTTP_FLAG_FORCE_TLS\n" " --force-tor use HTTP_FLAG_FORCE_TOR\n" " --no-out do not print the content\n" " --no-crl do not consuilt a CRL\n", stdout); exit (0); } else if (!strcmp (*argv, "--verbose")) { verbose++; argc--; argv++; } else if (!strcmp (*argv, "--debug")) { verbose += 2; debug++; argc--; argv++; } else if (!strcmp (*argv, "--tls-debug")) { argc--; argv++; if (argc) { tls_dbg = atoi (*argv); argc--; argv++; } } else if (!strcmp (*argv, "--cacert")) { argc--; argv++; if (argc) { cafile = *argv; argc--; argv++; } } else if (!strcmp (*argv, "--timeout")) { argc--; argv++; if (argc) { timeout = strtoul (*argv, NULL, 10); argc--; argv++; } } else if (!strcmp (*argv, "--no-verify")) { no_verify = 1; argc--; argv++; } else if (!strcmp (*argv, "--force-tls")) { my_http_flags |= HTTP_FLAG_FORCE_TLS; argc--; argv++; } else if (!strcmp (*argv, "--force-tor")) { my_http_flags |= HTTP_FLAG_FORCE_TOR; argc--; argv++; } else if (!strcmp (*argv, "--no-out")) { no_out = 1; argc--; argv++; } else if (!strcmp (*argv, "--no-crl")) { no_crl = 1; argc--; argv++; } else if (!strncmp (*argv, "--", 2)) { fprintf (stderr, PGM ": unknown option '%s'\n", *argv); exit (1); } } if (argc != 1) { fprintf (stderr, PGM ": no or too many URLS given\n"); exit (1); } if (!cafile) cafile = prepend_srcdir ("tls-ca.pem"); if (verbose) my_http_flags |= HTTP_FLAG_LOG_RESP; if (verbose || debug) http_set_verbose (verbose, debug); /* http.c makes use of the assuan socket wrapper. */ assuan_sock_init (); if ((my_http_flags & HTTP_FLAG_FORCE_TOR)) { enable_dns_tormode (1); if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1)) { log_error ("error enabling Tor mode: %s\n", strerror (errno)); log_info ("(is your Libassuan recent enough?)\n"); } } #if HTTP_USE_NTBTLS log_info ("new session.\n"); err = http_session_new (&session, NULL, ((no_crl? HTTP_FLAG_NO_CRL : 0) | HTTP_FLAG_TRUST_DEF), my_http_tls_verify_cb, NULL); if (err) log_error ("http_session_new failed: %s\n", gpg_strerror (err)); ntbtls_set_debug (tls_dbg, NULL, NULL); #elif HTTP_USE_GNUTLS rc = gnutls_global_init (); if (rc) log_error ("gnutls_global_init failed: %s\n", gnutls_strerror (rc)); http_register_tls_callback (verify_callback); http_register_tls_ca (cafile); err = http_session_new (&session, NULL, ((no_crl? HTTP_FLAG_NO_CRL : 0) | HTTP_FLAG_TRUST_DEF), NULL, NULL); if (err) log_error ("http_session_new failed: %s\n", gpg_strerror (err)); /* rc = gnutls_dh_params_init(&dh_params); */ /* if (rc) */ /* log_error ("gnutls_dh_params_init failed: %s\n", gnutls_strerror (rc)); */ /* read_dh_params ("dh_param.pem"); */ /* rc = gnutls_certificate_set_x509_trust_file */ /* (certcred, "ca.pem", GNUTLS_X509_FMT_PEM); */ /* if (rc) */ /* log_error ("gnutls_certificate_set_x509_trust_file failed: %s\n", */ /* gnutls_strerror (rc)); */ /* gnutls_certificate_set_dh_params (certcred, dh_params); */ gnutls_global_set_log_function (my_gnutls_log); if (tls_dbg) gnutls_global_set_log_level (tls_dbg); #else (void)err; (void)tls_dbg; (void)no_crl; #endif /*HTTP_USE_GNUTLS*/ rc = http_parse_uri (&uri, *argv, 1); if (rc) { log_error ("'%s': %s\n", *argv, gpg_strerror (rc)); return 1; } printf ("Scheme: %s\n", uri->scheme); if (uri->opaque) printf ("Value : %s\n", uri->path); else { printf ("Auth : %s\n", uri->auth? uri->auth:"[none]"); printf ("Host : %s\n", uri->host); printf ("Port : %u\n", uri->port); printf ("Path : %s\n", uri->path); for (r = uri->params; r; r = r->next) { printf ("Params: %s", r->name); if (!r->no_value) { printf ("=%s", r->value); if (strlen (r->value) != r->valuelen) printf (" [real length=%d]", (int) r->valuelen); } putchar ('\n'); } for (r = uri->query; r; r = r->next) { printf ("Query : %s", r->name); if (!r->no_value) { printf ("=%s", r->value); if (strlen (r->value) != r->valuelen) printf (" [real length=%d]", (int) r->valuelen); } putchar ('\n'); } printf ("Flags :%s%s%s%s\n", uri->is_http? " http":"", uri->opaque? " opaque":"", uri->v6lit? " v6lit":"", uri->onion? " onion":""); printf ("TLS : %s\n", uri->use_tls? "yes": (my_http_flags&HTTP_FLAG_FORCE_TLS)? "forced" : "no"); printf ("Tor : %s\n", (my_http_flags&HTTP_FLAG_FORCE_TOR)? "yes" : "no"); } fflush (stdout); http_release_parsed_uri (uri); uri = NULL; if (session) http_session_set_timeout (session, timeout); rc = http_open_document (&hd, *argv, NULL, my_http_flags, NULL, session, NULL, NULL); if (rc) { log_error ("can't get '%s': %s\n", *argv, gpg_strerror (rc)); return 1; } log_info ("open_http_document succeeded; status=%u\n", http_get_status_code (hd)); { const char **names; int i; names = http_get_header_names (hd); if (!names) log_fatal ("http_get_header_names failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); for (i = 0; names[i]; i++) printf ("HDR: %s: %s\n", names[i], http_get_header (hd, names[i])); xfree (names); } fflush (stdout); switch (http_get_status_code (hd)) { case 200: case 400: case 401: case 403: case 404: { unsigned long count = 0; while ((c = es_getc (http_get_read_ptr (hd))) != EOF) { count++; if (!no_out) putchar (c); } log_info ("Received bytes: %lu\n", count); } break; case 301: case 302: case 307: log_info ("Redirected to: %s\n", http_get_header (hd, "Location")); break; } http_close (hd, 0); http_session_release (session); #ifdef HTTP_USE_GNUTLS gnutls_global_deinit (); #endif /*HTTP_USE_GNUTLS*/ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-352'], 'message': 'dirmngr: Avoid possible CSRF attacks via http redirects. * dirmngr/http.h (parsed_uri_s): Add fields off_host and off_path. (http_redir_info_t): New. * dirmngr/http.c (do_parse_uri): Set new fields. (same_host_p): New. (http_prepare_redirect): New. * dirmngr/t-http-basic.c: New test. * dirmngr/ks-engine-hkp.c (send_request): Use http_prepare_redirect instead of the open code. * dirmngr/ks-engine-http.c (ks_http_fetch): Ditto. -- With this change a http query will not follow a redirect unless the Location header gives the same host. If the host is different only the host and port is taken from the Location header and the original path and query parts are kept. Signed-off-by: Werner Koch <wk@gnupg.org> (cherry picked from commit fa1b1eaa4241ff3f0634c8bdf8591cbc7c464144)'</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: _Unpickler_MemoPut(UnpicklerObject *self, Py_ssize_t idx, PyObject *value) { PyObject *old_item; if (idx >= self->memo_size) { if (_Unpickler_ResizeMemoList(self, idx * 2) < 0) return -1; assert(idx < self->memo_size); } Py_INCREF(value); old_item = self->memo[idx]; self->memo[idx] = value; if (old_item != NULL) { Py_DECREF(old_item); } else { self->memo_len++; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'</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 Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if (bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { if ((MagickSizeType) length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835', 'CWE-369'], 'message': 'Prevent infinite loop'</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 PDFDoc::setup(const GooString *ownerPassword, const GooString *userPassword) { pdfdocLocker(); if (str->getLength() <= 0) { error(errSyntaxError, -1, "Document stream is empty"); return false; } str->setPos(0, -1); if (str->getPos() < 0) { error(errSyntaxError, -1, "Document base stream is not seekable"); return false; } str->reset(); // check footer // Adobe does not seem to enforce %%EOF, so we do the same // if (!checkFooter()) return false; // check header checkHeader(); bool wasReconstructed = false; // read xref table xref = new XRef(str, getStartXRef(), getMainXRefEntriesOffset(), &wasReconstructed); if (!xref->isOk()) { if (wasReconstructed) { delete xref; startXRefPos = -1; xref = new XRef(str, getStartXRef(true), getMainXRefEntriesOffset(true), &wasReconstructed); } if (!xref->isOk()) { error(errSyntaxError, -1, "Couldn't read xref table"); errCode = xref->getErrorCode(); return false; } } // check for encryption if (!checkEncryption(ownerPassword, userPassword)) { errCode = errEncrypted; return false; } // read catalog catalog = new Catalog(this); if (catalog && !catalog->isOk()) { if (!wasReconstructed) { // try one more time to construct the Catalog, maybe the problem is damaged XRef delete catalog; delete xref; xref = new XRef(str, 0, 0, nullptr, true); catalog = new Catalog(this); } if (catalog && !catalog->isOk()) { error(errSyntaxError, -1, "Couldn't read page catalog"); errCode = errBadCatalog; return false; } } // Extract PDF Subtype information extractPDFSubtype(); // done return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'PDFDoc::setup: Fix return value At that point xref can have gone wrong since extractPDFSubtype() can have caused a reconstruct that broke stuff so instead of unconditionally returning true, return xref->isOk() Fixes #706'</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 i2c_ddc_rx(I2CSlave *i2c) { I2CDDCState *s = I2CDDC(i2c); int value; value = s->edid_blob[s->reg]; s->reg++; return value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'i2c-ddc: fix oob read Suggested-by: Michael Hanselmann <public@hansmi.ch> Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Reviewed-by: Michael Hanselmann <public@hansmi.ch> Reviewed-by: Philippe Mathieu-Daudé <philmd@redhat.com> Message-id: 20190108102301.1957-1-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: static int bus_socket_make_message(sd_bus *bus, size_t size) { sd_bus_message *t; void *b; int r; assert(bus); assert(bus->rbuffer_size >= size); assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO)); r = bus_rqueue_make_room(bus); if (r < 0) return r; if (bus->rbuffer_size > size) { b = memdup((const uint8_t*) bus->rbuffer + size, bus->rbuffer_size - size); if (!b) return -ENOMEM; } else b = NULL; r = bus_message_from_malloc(bus, bus->rbuffer, size, bus->fds, bus->n_fds, NULL, &t); if (r < 0) { free(b); return r; } bus->rbuffer = b; bus->rbuffer_size -= size; bus->fds = NULL; bus->n_fds = 0; bus->rqueue[bus->rqueue_size++] = t; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'sd-bus: if we receive an invalid dbus message, ignore and proceeed dbus-daemon might have a slightly different idea of what a valid msg is than us (for example regarding valid msg and field sizes). Let's hence try to proceed if we can and thus drop messages rather than fail the connection if we fail to validate a message. Hopefully the differences in what is considered valid are not visible for real-life usecases, but are specific to exploit attempts only.'</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 eb_copy_relocations(const struct i915_execbuffer *eb) { const unsigned int count = eb->buffer_count; unsigned int i; int err; for (i = 0; i < count; i++) { const unsigned int nreloc = eb->exec[i].relocation_count; struct drm_i915_gem_relocation_entry __user *urelocs; struct drm_i915_gem_relocation_entry *relocs; unsigned long size; unsigned long copied; if (nreloc == 0) continue; err = check_relocations(&eb->exec[i]); if (err) goto err; urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr); size = nreloc * sizeof(*relocs); relocs = kvmalloc_array(size, 1, GFP_KERNEL); if (!relocs) { err = -ENOMEM; goto err; } /* copy_from_user is limited to < 4GiB */ copied = 0; do { unsigned int len = min_t(u64, BIT_ULL(31), size - copied); if (__copy_from_user((char *)relocs + copied, (char __user *)urelocs + copied, len)) { end_user: user_access_end(); kvfree(relocs); err = -EFAULT; goto err; } copied += len; } while (copied < size); /* * As we do not update the known relocation offsets after * relocating (due to the complexities in lock handling), * we need to mark them as invalid now so that we force the * relocation processing next time. Just in case the target * object is evicted and then rebound into its old * presumed_offset before the next execbuffer - if that * happened we would make the mistake of assuming that the * relocations were valid. */ user_access_begin(); for (copied = 0; copied < nreloc; copied++) unsafe_put_user(-1, &urelocs[copied].presumed_offset, end_user); user_access_end(); eb->exec[i].relocs_ptr = (uintptr_t)relocs; } return 0; err: while (i--) { struct drm_i915_gem_relocation_entry *relocs = u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr); if (eb->exec[i].relocation_count) kvfree(relocs); } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()' Originally, the rule used to be that you'd have to do access_ok() separately, and then user_access_begin() before actually doing the direct (optimized) user access. But experience has shown that people then decide not to do access_ok() at all, and instead rely on it being implied by other operations or similar. Which makes it very hard to verify that the access has actually been range-checked. If you use the unsafe direct user accesses, hardware features (either SMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged Access Never - on ARM) do force you to use user_access_begin(). But nothing really forces the range check. By putting the range check into user_access_begin(), we actually force people to do the right thing (tm), and the range check vill be visible near the actual accesses. We have way too long a history of people trying to avoid them. 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 hid_debug_events_open(struct inode *inode, struct file *file) { int err = 0; struct hid_debug_list *list; unsigned long flags; if (!(list = kzalloc(sizeof(struct hid_debug_list), GFP_KERNEL))) { err = -ENOMEM; goto out; } if (!(list->hid_debug_buf = kzalloc(HID_DEBUG_BUFSIZE, GFP_KERNEL))) { err = -ENOMEM; kfree(list); goto out; } list->hdev = (struct hid_device *) inode->i_private; file->private_data = list; mutex_init(&list->read_mutex); spin_lock_irqsave(&list->hdev->debug_list_lock, flags); list_add_tail(&list->node, &list->hdev->debug_list); spin_unlock_irqrestore(&list->hdev->debug_list_lock, flags); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'HID: debug: fix the ring buffer implementation Ring buffer implementation in hid_debug_event() and hid_debug_events_read() is strange allowing lost or corrupted data. After commit 717adfdaf147 ("HID: debug: check length before copy_to_user()") it is possible to enter an infinite loop in hid_debug_events_read() by providing 0 as count, this locks up a system. Fix this by rewriting the ring buffer implementation with kfifo and simplify the code. This fixes CVE-2019-3819. v2: fix an execution logic and add a comment v3: use __set_current_state() instead of set_current_state() Link: https://bugzilla.redhat.com/show_bug.cgi?id=1669187 Cc: stable@vger.kernel.org # v4.18+ Fixes: cd667ce24796 ("HID: use debugfs for events/reports dumping") Fixes: 717adfdaf147 ("HID: debug: check length before copy_to_user()") Signed-off-by: Vladis Dronov <vdronov@redhat.com> Reviewed-by: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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: ber_parse_header(STREAM s, int tagval, int *length) { int tag, len; if (tagval > 0xff) { in_uint16_be(s, tag); } else { in_uint8(s, tag); } if (tag != tagval) { error("expected tag %d, got %d\n", tagval, tag); return False; } in_uint8(s, len); if (len & 0x80) { len &= ~0x80; *length = 0; while (len--) next_be(s, *length); } else *length = len; return s_check(s); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</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: rdpsnddbg_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = (char *) xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, rdpsnddbg_line_handler, NULL); xfree(buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182'</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 UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 left; UINT32 runlength = 1; UINT32 planeSize = 0; left = originalSize; /** * We quit the loop if the running compressed size is larger than the original. * In such cases data will be sent uncompressed. */ while (left > 4 && planeSize < originalSize - 4) { if (left > 5 && *in == *(in + 1)) { runlength++; } else if (runlength == 1) { *out++ = *in; planeSize++; } else if (runlength < 256) { *out++ = *in; *out++ = *in; *out++ = runlength - 2; runlength = 1; planeSize += 3; } else { *out++ = *in; *out++ = *in; *out++ = 0xFF; *out++ = (runlength & 0x000000FF); *out++ = (runlength & 0x0000FF00) >> 8; *out++ = (runlength & 0x00FF0000) >> 16; *out++ = (runlength & 0xFF000000) >> 24; runlength = 1; planeSize += 7; } in++; left--; } if (planeSize < originalSize - 4) CopyMemory(out, in, 4); planeSize += 4; return planeSize; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.'</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 ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies.'</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: BGD_DECLARE(void) gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { gdImagePtr pim = 0, tim = im; int interlace, BitsPerPixel; interlace = im->interlace; if(im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if(!pim) { return; } tim = pim; } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFEncode( out, tim->sx, tim->sy, interlace, 0, tim->transparent, BitsPerPixel, tim->red, tim->green, tim->blue, tim); if(pim) { /* Destroy palette based temporary image. */ gdImageDestroy( pim); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #492: Potential double-free in gdImage*Ptr() Whenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we must not call `gdDPExtractData()`; otherwise a double-free would happen. Since `gdImage*Ctx()` are void functions, and we can't change that for BC reasons, we're introducing static helpers which are used internally. We're adding a regression test for `gdImageJpegPtr()`, but not for `gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to trigger failure of the respective `gdImage*Ctx()` calls. This potential security issue has been reported by Solmaz Salimi (aka. Rooney).'</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 * gdImageWBMPPtr (gdImagePtr im, int *size, int fg) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); gdImageWBMPCtx(im, fg, out); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here.'</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 ldb_wildcard_compare(struct ldb_context *ldb, const struct ldb_parse_tree *tree, const struct ldb_val value, bool *matched) { const struct ldb_schema_attribute *a; struct ldb_val val; struct ldb_val cnk; struct ldb_val *chunk; uint8_t *save_p = NULL; unsigned int c = 0; a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr); if (!a) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } if (tree->u.substring.chunks == NULL) { *matched = false; return LDB_SUCCESS; } if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } save_p = val.data; cnk.data = NULL; if ( ! tree->u.substring.start_with_wildcard ) { chunk = tree->u.substring.chunks[c]; if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */ if (cnk.length > val.length) { goto mismatch; } /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch; val.length -= cnk.length; val.data += cnk.length; c++; talloc_free(cnk.data); cnk.data = NULL; } while (tree->u.substring.chunks[c]) { uint8_t *p; chunk = tree->u.substring.chunks[c]; if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } /* * Values might be binary blobs. Don't use string * search, but memory search instead. */ p = memmem((const void *)val.data,val.length, (const void *)cnk.data, cnk.length); if (p == NULL) goto mismatch; /* * At this point we know cnk.length <= val.length as * otherwise there could be no match */ if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) { uint8_t *g; uint8_t *end = val.data + val.length; do { /* greedy */ /* * haystack is a valid pointer in val * because the memmem() can only * succeed if the needle (cnk.length) * is <= haystacklen * * p will be a pointer at least * cnk.length from the end of haystack */ uint8_t *haystack = p + cnk.length; size_t haystacklen = end - (haystack); g = memmem(haystack, haystacklen, (const uint8_t *)cnk.data, cnk.length); if (g) { p = g; } } while(g); } val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length; val.data = (uint8_t *)(p + cnk.length); c++; talloc_free(cnk.data); cnk.data = NULL; } /* last chunk may not have reached end of string */ if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch; talloc_free(save_p); *matched = true; return LDB_SUCCESS; mismatch: *matched = false; talloc_free(save_p); talloc_free(cnk.data); return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: wildcard_match check tree operation Check the operation type of the passed parse tree, and return LDB_INAPPROPRIATE_MATCH if the operation is not LDB_OP_SUBSTRING. A query of "attribute=*" gets parsed as LDB_OP_PRESENT, checking the operation and failing ldb_wildcard_match should help prevent confusion writing tests. BUG: https://bugzilla.samba.org/show_bug.cgi?id=13773 Signed-off-by: Gary Lockyer <gary@catalyst.net.nz> Reviewed-by: Andrew Bartlett <abartlet@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 struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem; int err; elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; err = copy_verifier_state(&elem->st, cur); if (err) goto err; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose(env, "BPF program is too complex\n"); goto err; } return &elem->st; err: free_verifier_state(env->cur_state, true); env->cur_state = NULL; /* pop all elements and return */ while (!pop_stack(env, NULL, NULL)); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Alexei Starovoitov <ast@kernel.org> Signed-off-by: Alexei Starovoitov <ast@kernel.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 Image *ReadSIXELImage(const ImageInfo *image_info,ExceptionInfo *exception) { char *sixel_buffer; Image *image; MagickBooleanType status; register char *p; register ssize_t x; register Quantum *q; size_t length; ssize_t i, j, y; unsigned char *sixel_pixels, *sixel_palette; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SIXEL file. */ length=MagickPathExtent; sixel_buffer=(char *) AcquireQuantumMemory((size_t) length+MagickPathExtent, sizeof(*sixel_buffer)); p=sixel_buffer; if (sixel_buffer != (char *) NULL) while (ReadBlobString(image,p) != (char *) NULL) { if ((*p == '#') && ((p == sixel_buffer) || (*(p-1) == '\n'))) continue; if ((*p == '}') && (*(p+1) == ';')) break; p+=strlen(p); if ((size_t) (p-sixel_buffer+MagickPathExtent+1) < length) continue; length<<=1; sixel_buffer=(char *) ResizeQuantumMemory(sixel_buffer,length+ MagickPathExtent+1,sizeof(*sixel_buffer)); if (sixel_buffer == (char *) NULL) break; p=sixel_buffer+strlen(sixel_buffer); } if (sixel_buffer == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); sixel_buffer[length]='\0'; /* Decode SIXEL */ if (sixel_decode(image,(unsigned char *) sixel_buffer,&sixel_pixels,&image->columns,&image->rows,&sixel_palette,&image->colors,exception) == MagickFalse) { sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer); ThrowReaderException(CorruptImageError,"CorruptImage"); } sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer); image->depth=24; image->storage_class=PseudoClass; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); return(DestroyImageList(image)); } if (AcquireImageColormap(image,image->colors, exception) == MagickFalse) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i = 0; i < (ssize_t) image->colors; ++i) { image->colormap[i].red = ScaleCharToQuantum(sixel_palette[i * 4 + 0]); image->colormap[i].green = ScaleCharToQuantum(sixel_palette[i * 4 + 1]); image->colormap[i].blue = ScaleCharToQuantum(sixel_palette[i * 4 + 2]); } j=0; if (image_info->ping == MagickFalse) { /* Read image pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { j=(ssize_t) sixel_pixels[y * image->columns + x]; SetPixelIndex(image,j,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (y < (ssize_t) image->rows) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); ThrowReaderException(CorruptImageError,"NotEnoughPixelData"); } } /* Relinquish resources. */ sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1452'</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: empe_app_smime_parse (EMailParserExtension *extension, EMailParser *parser, CamelMimePart *part, GString *part_id, GCancellable *cancellable, GQueue *out_mail_parts) { CamelCipherContext *context; CamelMimePart *opart; CamelCipherValidity *valid; CamelContentType *ct; GError *local_error = NULL; ct = camel_mime_part_get_content_type (part); if (camel_content_type_is (ct, "application", "pkcs7-signature") || camel_content_type_is (ct, "application", "xpkcs7-signature") || camel_content_type_is (ct, "application", "x-pkcs7-signature")) { return TRUE; } context = camel_smime_context_new (e_mail_parser_get_session (parser)); opart = camel_mime_part_new (); valid = camel_cipher_context_decrypt_sync ( context, part, opart, cancellable, &local_error); e_mail_part_preserve_charset_in_content_type (part, opart); if (local_error != NULL) { e_mail_parser_error ( parser, out_mail_parts, _("Could not parse S/MIME message: %s"), local_error->message); g_error_free (local_error); } else { GQueue work_queue = G_QUEUE_INIT; GList *head, *link; gint len = part_id->len; g_string_append (part_id, ".encrypted-smime"); e_mail_parser_parse_part ( parser, opart, part_id, cancellable, &work_queue); g_string_truncate (part_id, len); head = g_queue_peek_head_link (&work_queue); /* Update validity flags of all the involved subp-arts */ for (link = head; link != NULL; link = g_list_next (link)) { EMailPart *mail_part = link->data; e_mail_part_update_validity ( mail_part, valid, E_MAIL_PART_VALIDITY_ENCRYPTED | E_MAIL_PART_VALIDITY_SMIME); } e_queue_transfer (&work_queue, out_mail_parts); /* Add a widget with details about the encryption, but only * when the encrypted isn't itself secured, in that case it * has created the button itself. */ if (!e_mail_part_is_secured (opart)) { EMailPart *mail_part; g_string_append (part_id, ".encrypted-smime.button"); e_mail_parser_parse_part_as ( parser, part, part_id, "application/vnd.evolution.secure-button", cancellable, &work_queue); mail_part = g_queue_peek_head (&work_queue); if (mail_part != NULL) e_mail_part_update_validity ( mail_part, valid, E_MAIL_PART_VALIDITY_ENCRYPTED | E_MAIL_PART_VALIDITY_SMIME); e_queue_transfer (&work_queue, out_mail_parts); g_string_truncate (part_id, len); } camel_cipher_validity_free (valid); } g_object_unref (opart); g_object_unref (context); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-347'], 'message': 'eds-I#3 - [GPG] Mails that are not encrypted look encrypted Related to https://gitlab.gnome.org/GNOME/evolution-data-server/issues/3'</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: ews_config_lookup_worker_run (EConfigLookupWorker *lookup_worker, EConfigLookup *config_lookup, const ENamedParameters *params, ENamedParameters **out_restart_params, GCancellable *cancellable, GError **error) { CamelEwsSettings *ews_settings = NULL; ESource *source; const gchar *email_address; const gchar *password; const gchar *extension_name; g_return_if_fail (E_IS_EWS_CONFIG_LOOKUP (lookup_worker)); g_return_if_fail (E_IS_CONFIG_LOOKUP (config_lookup)); g_return_if_fail (params != NULL); email_address = e_named_parameters_get (params, E_CONFIG_LOOKUP_PARAM_EMAIL_ADDRESS); if (!email_address || !*email_address) return; if (!e_named_parameters_exists (params, E_CONFIG_LOOKUP_PARAM_PASSWORD)) { g_set_error (error, E_CONFIG_LOOKUP_WORKER_ERROR, E_CONFIG_LOOKUP_WORKER_ERROR_REQUIRES_PASSWORD, _("Requires user password to continue")); return; } ews_settings = g_object_new (CAMEL_TYPE_EWS_SETTINGS, NULL); camel_ews_settings_set_email (ews_settings, email_address); extension_name = e_source_camel_get_extension_name ("ews"); source = e_config_lookup_get_source (config_lookup, E_CONFIG_LOOKUP_SOURCE_COLLECTION); if (source && e_source_has_extension (source, extension_name)) { ESourceCamel *camel_extension; CamelSettings *settings; camel_extension = e_source_get_extension (source, extension_name); settings = e_source_camel_get_settings (camel_extension); /* Copy only the host url */ if (CAMEL_IS_EWS_SETTINGS (settings)) camel_ews_settings_set_hosturl (ews_settings, camel_ews_settings_get_hosturl (CAMEL_EWS_SETTINGS (settings))); } password = e_named_parameters_get (params, E_CONFIG_LOOKUP_PARAM_PASSWORD); if (password) { const gchar *servers; if (e_ews_autodiscover_ws_url_sync (source, ews_settings, email_address, password, cancellable, NULL)) { ews_config_lookup_worker_result_from_settings (lookup_worker, config_lookup, email_address, ews_settings, params); } servers = e_named_parameters_get (params, E_CONFIG_LOOKUP_PARAM_SERVERS); if (servers && *servers) { gchar **servers_strv; gint ii; servers_strv = g_strsplit (servers, ";", 0); for (ii = 0; servers_strv && servers_strv[ii] && !g_cancellable_is_cancelled (cancellable); ii++) { const gchar *server = servers_strv[ii]; gchar *tmp = NULL; if (*server && !strstr (server, "://")) { tmp = g_strconcat ("https://", server, "/EWS/Exchange.asmx", NULL); server = tmp; } camel_ews_settings_set_hosturl (ews_settings, server); if (e_ews_autodiscover_ws_url_sync (source, ews_settings, email_address, password, cancellable, NULL)) { ews_config_lookup_worker_result_from_settings (lookup_worker, config_lookup, email_address, ews_settings, params); } g_free (tmp); } g_strfreev (servers_strv); } if (out_restart_params) *out_restart_params = e_named_parameters_new_clone (params); } g_clear_object (&ews_settings); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</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: ews_connection_finalize (GObject *object) { EEwsConnectionPrivate *priv; priv = E_EWS_CONNECTION_GET_PRIVATE (object); g_free (priv->uri); g_free (priv->password); g_free (priv->email); g_free (priv->hash_key); g_free (priv->impersonate_user); g_clear_object (&priv->bearer_auth); g_mutex_clear (&priv->property_lock); g_rec_mutex_clear (&priv->queue_lock); g_mutex_clear (&priv->notification_lock); /* Chain up to parent's finalize() method. */ G_OBJECT_CLASS (e_ews_connection_parent_class)->finalize (object); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</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: ews_authenticate_sync (CamelService *service, const gchar *mechanism, GCancellable *cancellable, GError **error) { CamelAuthenticationResult result; CamelEwsStore *ews_store; CamelSettings *settings; CamelEwsSettings *ews_settings; EEwsConnection *connection; ESource *source; GSList *folders_created = NULL; GSList *folders_updated = NULL; GSList *folders_deleted = NULL; GSList *folder_ids = NULL; GSList *created_folder_ids = NULL; gboolean includes_last_folder = FALSE; gboolean initial_setup = FALSE; const gchar *password; gchar *hosturl; gchar *old_sync_state = NULL, *new_sync_state = NULL; GError *local_error = NULL; ews_store = CAMEL_EWS_STORE (service); password = camel_service_get_password (service); settings = camel_service_ref_settings (service); ews_settings = CAMEL_EWS_SETTINGS (settings); hosturl = camel_ews_settings_dup_hosturl (ews_settings); source = camel_ews_utils_ref_corresponding_source (service, cancellable); connection = e_ews_connection_new (source, hosturl, ews_settings); e_ews_connection_set_password (connection, password); g_clear_object (&source); g_free (hosturl); g_object_unref (settings); e_binding_bind_property ( service, "proxy-resolver", connection, "proxy-resolver", G_BINDING_SYNC_CREATE); /* XXX We need to run some operation that requires authentication * but does not change any server-side state, so we can check * the error status and determine if our password is valid. * David suggested e_ews_connection_sync_folder_hierarchy(), * since we have to do that eventually anyway. */ /*use old sync_state from summary*/ old_sync_state = camel_ews_store_summary_get_string_val (ews_store->summary, "sync_state", NULL); if (!old_sync_state) { initial_setup = TRUE; } else { gchar *folder_id; folder_id = camel_ews_store_summary_get_folder_id_from_folder_type (ews_store->summary, CAMEL_FOLDER_TYPE_INBOX); if (!folder_id || !*folder_id) initial_setup = TRUE; g_free (folder_id); if (!initial_setup) { folder_id = camel_ews_store_summary_get_folder_id_from_folder_type (ews_store->summary, CAMEL_FOLDER_TYPE_DRAFTS); if (!folder_id || !*folder_id) initial_setup = TRUE; g_free (folder_id); } } e_ews_connection_sync_folder_hierarchy_sync (connection, EWS_PRIORITY_MEDIUM, old_sync_state, &new_sync_state, &includes_last_folder, &folders_created, &folders_updated, &folders_deleted, cancellable, &local_error); g_free (old_sync_state); old_sync_state = NULL; if (g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_UNAVAILABLE)) { local_error->domain = CAMEL_SERVICE_ERROR; local_error->code = CAMEL_SERVICE_ERROR_UNAVAILABLE; } if (!initial_setup && g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_INVALIDSYNCSTATEDATA)) { g_clear_error (&local_error); ews_store_forget_all_folders (ews_store); camel_ews_store_summary_store_string_val (ews_store->summary, "sync_state", ""); camel_ews_store_summary_clear (ews_store->summary); initial_setup = TRUE; e_ews_connection_sync_folder_hierarchy_sync (connection, EWS_PRIORITY_MEDIUM, NULL, &new_sync_state, &includes_last_folder, &folders_created, &folders_updated, &folders_deleted, cancellable, &local_error); } if (local_error == NULL) { GSList *foreign_fids, *ff; g_mutex_lock (&ews_store->priv->connection_lock); ews_store_unset_connection_locked (ews_store); ews_store->priv->connection = g_object_ref (connection); g_signal_connect (ews_store->priv->connection, "password-will-expire", G_CALLBACK (camel_ews_store_password_will_expire_cb), ews_store); g_mutex_unlock (&ews_store->priv->connection_lock); /* This consumes all allocated result data. */ ews_update_folder_hierarchy ( ews_store, new_sync_state, includes_last_folder, folders_created, folders_deleted, folders_updated, &created_folder_ids); /* Also update folder structures of foreign folders, those which are subscribed with subfolders */ foreign_fids = camel_ews_store_summary_get_foreign_folders (ews_store->summary, NULL); for (ff = foreign_fids; ff != NULL; ff = ff->next) { const gchar *fid = ff->data; if (camel_ews_store_summary_get_foreign_subfolders (ews_store->summary, fid, NULL)) { camel_ews_store_update_foreign_subfolders (ews_store, fid); } } g_slist_free_full (foreign_fids, g_free); } else { g_mutex_lock (&ews_store->priv->connection_lock); ews_store_unset_connection_locked (ews_store); g_mutex_unlock (&ews_store->priv->connection_lock); g_free (new_sync_state); /* Make sure we're not leaking anything. */ g_warn_if_fail (folders_created == NULL); g_warn_if_fail (folders_updated == NULL); g_warn_if_fail (folders_deleted == NULL); } /*get folders using distinguished id by GetFolder operation and set system flags to folders, only for first time*/ if (!local_error && initial_setup && connection) { ews_initial_setup_with_connection_sync (CAMEL_STORE (ews_store), NULL, connection, cancellable, NULL); } /* postpone notification of new folders to time when also folder flags are known, thus the view in evolution sows Inbox with an Inbox icon. */ for (folder_ids = created_folder_ids; folder_ids; folder_ids = folder_ids->next) { CamelFolderInfo *fi; fi = camel_ews_utils_build_folder_info (ews_store, folder_ids->data); camel_store_folder_created (CAMEL_STORE (ews_store), fi); camel_subscribable_folder_subscribed (CAMEL_SUBSCRIBABLE (ews_store), fi); camel_folder_info_free (fi); } g_slist_free_full (created_folder_ids, g_free); if (local_error == NULL) { result = CAMEL_AUTHENTICATION_ACCEPTED; } else if (g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_AUTHENTICATION_FAILED)) { g_clear_error (&local_error); result = CAMEL_AUTHENTICATION_REJECTED; } else { g_propagate_error (error, local_error); result = CAMEL_AUTHENTICATION_ERROR; } g_object_unref (connection); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</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: keyfetch_done(isc_task_t *task, isc_event_t *event) { isc_result_t result, eresult; dns_fetchevent_t *devent; dns_keyfetch_t *kfetch; dns_zone_t *zone; isc_mem_t *mctx = NULL; dns_keytable_t *secroots = NULL; dns_dbversion_t *ver = NULL; dns_diff_t diff; bool alldone = false; bool commit = false; dns_name_t *keyname; dns_rdata_t sigrr = DNS_RDATA_INIT; dns_rdata_t dnskeyrr = DNS_RDATA_INIT; dns_rdata_t keydatarr = DNS_RDATA_INIT; dns_rdata_rrsig_t sig; dns_rdata_dnskey_t dnskey; dns_rdata_keydata_t keydata; bool initializing; char namebuf[DNS_NAME_FORMATSIZE]; unsigned char key_buf[4096]; isc_buffer_t keyb; dst_key_t *dstkey; isc_stdtime_t now; int pending = 0; bool secure = false, initial = false; bool free_needed; UNUSED(task); INSIST(event != NULL && event->ev_type == DNS_EVENT_FETCHDONE); INSIST(event->ev_arg != NULL); kfetch = event->ev_arg; zone = kfetch->zone; isc_mem_attach(zone->mctx, &mctx); keyname = dns_fixedname_name(&kfetch->name); devent = (dns_fetchevent_t *) event; eresult = devent->result; /* Free resources which are not of interest */ if (devent->node != NULL) { dns_db_detachnode(devent->db, &devent->node); } if (devent->db != NULL) { dns_db_detach(&devent->db); } isc_event_free(&event); dns_resolver_destroyfetch(&kfetch->fetch); LOCK_ZONE(zone); if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING) || zone->view == NULL) { goto cleanup; } isc_stdtime_get(&now); dns_name_format(keyname, namebuf, sizeof(namebuf)); result = dns_view_getsecroots(zone->view, &secroots); INSIST(result == ISC_R_SUCCESS); dns_diff_init(mctx, &diff); CHECK(dns_db_newversion(kfetch->db, &ver)); zone->refreshkeycount--; alldone = (zone->refreshkeycount == 0); if (alldone) { DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESHING); } dnssec_log(zone, ISC_LOG_DEBUG(3), "Returned from key fetch in keyfetch_done() for '%s': %s", namebuf, dns_result_totext(eresult)); /* Fetch failed */ if (eresult != ISC_R_SUCCESS || !dns_rdataset_isassociated(&kfetch->dnskeyset)) { dnssec_log(zone, ISC_LOG_WARNING, "Unable to fetch DNSKEY set '%s': %s", namebuf, dns_result_totext(eresult)); CHECK(minimal_update(kfetch, ver, &diff)); goto done; } /* No RRSIGs found */ if (!dns_rdataset_isassociated(&kfetch->dnskeysigset)) { dnssec_log(zone, ISC_LOG_WARNING, "No DNSKEY RRSIGs found for '%s': %s", namebuf, dns_result_totext(eresult)); CHECK(minimal_update(kfetch, ver, &diff)); goto done; } /* * Clear any cached trust level, as we need to run validation * over again; trusted keys might have changed. */ kfetch->dnskeyset.trust = kfetch->dnskeysigset.trust = dns_trust_none; /* * Validate the dnskeyset against the current trusted keys. */ for (result = dns_rdataset_first(&kfetch->dnskeysigset); result == ISC_R_SUCCESS; result = dns_rdataset_next(&kfetch->dnskeysigset)) { dns_keynode_t *keynode = NULL; dns_rdata_reset(&sigrr); dns_rdataset_current(&kfetch->dnskeysigset, &sigrr); result = dns_rdata_tostruct(&sigrr, &sig, NULL); RUNTIME_CHECK(result == ISC_R_SUCCESS); result = dns_keytable_find(secroots, keyname, &keynode); while (result == ISC_R_SUCCESS) { dns_keynode_t *nextnode = NULL; dns_fixedname_t fixed; dns_fixedname_init(&fixed); dstkey = dns_keynode_key(keynode); if (dstkey == NULL) { /* fail_secure() was called */ break; } if (dst_key_alg(dstkey) == sig.algorithm && dst_key_id(dstkey) == sig.keyid) { result = dns_dnssec_verify(keyname, &kfetch->dnskeyset, dstkey, false, 0, zone->view->mctx, &sigrr, dns_fixedname_name( &fixed)); dnssec_log(zone, ISC_LOG_DEBUG(3), "Verifying DNSKEY set for zone " "'%s' using key %d/%d: %s", namebuf, sig.keyid, sig.algorithm, dns_result_totext(result)); if (result == ISC_R_SUCCESS) { kfetch->dnskeyset.trust = dns_trust_secure; kfetch->dnskeysigset.trust = dns_trust_secure; secure = true; initial = dns_keynode_initial(keynode); dns_keynode_trust(keynode); break; } } result = dns_keytable_nextkeynode(secroots, keynode, &nextnode); dns_keytable_detachkeynode(secroots, &keynode); keynode = nextnode; } if (keynode != NULL) { dns_keytable_detachkeynode(secroots, &keynode); } if (secure) { break; } } /* * If we were not able to verify the answer using the current * trusted keys then all we can do is look at any revoked keys. */ if (!secure) { dnssec_log(zone, ISC_LOG_INFO, "DNSKEY set for zone '%s' could not be verified " "with current keys", namebuf); } /* * First scan keydataset to find keys that are not in dnskeyset * - Missing keys which are not scheduled for removal, * log a warning * - Missing keys which are scheduled for removal and * the remove hold-down timer has completed should * be removed from the key zone * - Missing keys whose acceptance timers have not yet * completed, log a warning and reset the acceptance * timer to 30 days in the future * - All keys not being removed have their refresh timers * updated */ initializing = true; for (result = dns_rdataset_first(&kfetch->keydataset); result == ISC_R_SUCCESS; result = dns_rdataset_next(&kfetch->keydataset)) { dns_keytag_t keytag; dns_rdata_reset(&keydatarr); dns_rdataset_current(&kfetch->keydataset, &keydatarr); result = dns_rdata_tostruct(&keydatarr, &keydata, NULL); RUNTIME_CHECK(result == ISC_R_SUCCESS); dns_keydata_todnskey(&keydata, &dnskey, NULL); result = compute_tag(keyname, &dnskey, mctx, &keytag); RUNTIME_CHECK(result == ISC_R_SUCCESS); /* * If any keydata record has a nonzero add holddown, then * there was a pre-existing trust anchor for this domain; * that means we are *not* initializing it and shouldn't * automatically trust all the keys we find at the zone apex. */ initializing = initializing && (keydata.addhd == 0); if (! matchkey(&kfetch->dnskeyset, &keydatarr)) { bool deletekey = false; if (!secure) { if (keydata.removehd != 0 && keydata.removehd <= now) { deletekey = true; } } else if (keydata.addhd == 0) { deletekey = true; } else if (keydata.addhd > now) { dnssec_log(zone, ISC_LOG_INFO, "Pending key %d for zone %s " "unexpectedly missing " "restarting 30-day acceptance " "timer", keytag, namebuf); if (keydata.addhd < now + dns_zone_mkey_month) { keydata.addhd = now + dns_zone_mkey_month; } keydata.refresh = refresh_time(kfetch, false); } else if (keydata.removehd == 0) { dnssec_log(zone, ISC_LOG_INFO, "Active key %d for zone %s " "unexpectedly missing", keytag, namebuf); keydata.refresh = now + dns_zone_mkey_hour; } else if (keydata.removehd <= now) { deletekey = true; dnssec_log(zone, ISC_LOG_INFO, "Revoked key %d for zone %s " "missing: deleting from " "managed keys database", keytag, namebuf); } else { keydata.refresh = refresh_time(kfetch, false); } if (secure || deletekey) { /* Delete old version */ CHECK(update_one_rr(kfetch->db, ver, &diff, DNS_DIFFOP_DEL, keyname, 0, &keydatarr)); } if (!secure || deletekey) { continue; } dns_rdata_reset(&keydatarr); isc_buffer_init(&keyb, key_buf, sizeof(key_buf)); dns_rdata_fromstruct(&keydatarr, zone->rdclass, dns_rdatatype_keydata, &keydata, &keyb); /* Insert updated version */ CHECK(update_one_rr(kfetch->db, ver, &diff, DNS_DIFFOP_ADD, keyname, 0, &keydatarr)); set_refreshkeytimer(zone, &keydata, now, false); } } /* * Next scan dnskeyset: * - If new keys are found (i.e., lacking a match in keydataset) * add them to the key zone and set the acceptance timer * to 30 days in the future (or to immediately if we've * determined that we're initializing the zone for the * first time) * - Previously-known keys that have been revoked * must be scheduled for removal from the key zone (or, * if they hadn't been accepted as trust anchors yet * anyway, removed at once) * - Previously-known unrevoked keys whose acceptance timers * have completed are promoted to trust anchors * - All keys not being removed have their refresh * timers updated */ for (result = dns_rdataset_first(&kfetch->dnskeyset); result == ISC_R_SUCCESS; result = dns_rdataset_next(&kfetch->dnskeyset)) { bool revoked = false; bool newkey = false; bool updatekey = false; bool deletekey = false; bool trustkey = false; dns_keytag_t keytag; dns_rdata_reset(&dnskeyrr); dns_rdataset_current(&kfetch->dnskeyset, &dnskeyrr); result = dns_rdata_tostruct(&dnskeyrr, &dnskey, NULL); RUNTIME_CHECK(result == ISC_R_SUCCESS); /* Skip ZSK's */ if ((dnskey.flags & DNS_KEYFLAG_KSK) == 0) { continue; } result = compute_tag(keyname, &dnskey, mctx, &keytag); RUNTIME_CHECK(result == ISC_R_SUCCESS); revoked = ((dnskey.flags & DNS_KEYFLAG_REVOKE) != 0); if (matchkey(&kfetch->keydataset, &dnskeyrr)) { dns_rdata_reset(&keydatarr); dns_rdataset_current(&kfetch->keydataset, &keydatarr); result = dns_rdata_tostruct(&keydatarr, &keydata, NULL); RUNTIME_CHECK(result == ISC_R_SUCCESS); if (revoked && revocable(kfetch, &keydata)) { if (keydata.addhd > now) { /* * Key wasn't trusted yet, and now * it's been revoked? Just remove it */ deletekey = true; dnssec_log(zone, ISC_LOG_INFO, "Pending key %d for " "zone %s is now revoked: " "deleting from the " "managed keys database", keytag, namebuf); } else if (keydata.removehd == 0) { /* * Remove key from secroots. */ dns_view_untrust(zone->view, keyname, &dnskey, mctx); /* If initializing, delete now */ if (keydata.addhd == 0) { deletekey = true; } else { keydata.removehd = now + dns_zone_mkey_month; keydata.flags |= DNS_KEYFLAG_REVOKE; } dnssec_log(zone, ISC_LOG_INFO, "Trusted key %d for " "zone %s is now revoked", keytag, namebuf); } else if (keydata.removehd < now) { /* Scheduled for removal */ deletekey = true; dnssec_log(zone, ISC_LOG_INFO, "Revoked key %d for " "zone %s removal timer " "complete: deleting from " "the managed keys database", keytag, namebuf); } } else if (revoked && keydata.removehd == 0) { dnssec_log(zone, ISC_LOG_WARNING, "Active key %d for zone " "%s is revoked but " "did not self-sign; " "ignoring", keytag, namebuf); continue; } else if (secure) { if (keydata.removehd != 0) { /* * Key isn't revoked--but it * seems it used to be. * Remove it now and add it * back as if it were a fresh key, * with a 30-day acceptance timer. */ deletekey = true; newkey = true; keydata.removehd = 0; keydata.addhd = now + dns_zone_mkey_month; dnssec_log(zone, ISC_LOG_INFO, "Revoked key %d for " "zone %s has returned: " "starting 30-day " "acceptance timer", keytag, namebuf); } else if (keydata.addhd > now) { pending++; } else if (keydata.addhd == 0) { keydata.addhd = now; } if (keydata.addhd <= now) { trustkey = true; dnssec_log(zone, ISC_LOG_INFO, "Key %d for zone %s " "is now trusted (%s)", keytag, namebuf, initial ? "initializing key " "verified" : "acceptance timer " "complete"); } } else if (keydata.addhd > now) { /* * Not secure, and key is pending: * reset the acceptance timer */ pending++; keydata.addhd = now + dns_zone_mkey_month; dnssec_log(zone, ISC_LOG_INFO, "Pending key %d " "for zone %s was " "not validated: restarting " "30-day acceptance timer", keytag, namebuf); } if (!deletekey && !newkey) { updatekey = true; } } else if (secure) { /* * Key wasn't in the key zone but it's * revoked now anyway, so just skip it */ if (revoked) { continue; } /* Key wasn't in the key zone: add it */ newkey = true; if (initializing) { dnssec_log(zone, ISC_LOG_WARNING, "Initializing automatic trust " "anchor management for zone '%s'; " "DNSKEY ID %d is now trusted, " "waiving the normal 30-day " "waiting period.", namebuf, keytag); trustkey = true; } else { dnssec_log(zone, ISC_LOG_INFO, "New key %d observed " "for zone '%s': " "starting 30-day " "acceptance timer", keytag, namebuf); } } else { /* * No previously known key, and the key is not * secure, so skip it. */ continue; } /* Delete old version */ if (deletekey || !newkey) { CHECK(update_one_rr(kfetch->db, ver, &diff, DNS_DIFFOP_DEL, keyname, 0, &keydatarr)); } if (updatekey) { /* Set refresh timer */ keydata.refresh = refresh_time(kfetch, false); dns_rdata_reset(&keydatarr); isc_buffer_init(&keyb, key_buf, sizeof(key_buf)); dns_rdata_fromstruct(&keydatarr, zone->rdclass, dns_rdatatype_keydata, &keydata, &keyb); /* Insert updated version */ CHECK(update_one_rr(kfetch->db, ver, &diff, DNS_DIFFOP_ADD, keyname, 0, &keydatarr)); } else if (newkey) { /* Convert DNSKEY to KEYDATA */ result = dns_rdata_tostruct(&dnskeyrr, &dnskey, NULL); RUNTIME_CHECK(result == ISC_R_SUCCESS); dns_keydata_fromdnskey(&keydata, &dnskey, 0, 0, 0, NULL); keydata.addhd = initializing ? now : now + dns_zone_mkey_month; keydata.refresh = refresh_time(kfetch, false); dns_rdata_reset(&keydatarr); isc_buffer_init(&keyb, key_buf, sizeof(key_buf)); dns_rdata_fromstruct(&keydatarr, zone->rdclass, dns_rdatatype_keydata, &keydata, &keyb); /* Insert into key zone */ CHECK(update_one_rr(kfetch->db, ver, &diff, DNS_DIFFOP_ADD, keyname, 0, &keydatarr)); } if (trustkey) { /* Trust this key. */ result = dns_rdata_tostruct(&dnskeyrr, &dnskey, NULL); RUNTIME_CHECK(result == ISC_R_SUCCESS); trust_key(zone, keyname, &dnskey, false, mctx); } if (secure && !deletekey) { INSIST(newkey || updatekey); set_refreshkeytimer(zone, &keydata, now, false); } } /* * RFC5011 says, "A trust point that has all of its trust anchors * revoked is considered deleted and is treated as if the trust * point was never configured." But if someone revoked their * active key before the standby was trusted, that would mean the * zone would suddenly be nonsecured. We avoid this by checking to * see if there's pending keydata. If so, we put a null key in * the security roots; then all queries to the zone will fail. */ if (pending != 0) { fail_secure(zone, keyname); } done: if (!ISC_LIST_EMPTY(diff.tuples)) { /* Write changes to journal file. */ CHECK(update_soa_serial(kfetch->db, ver, &diff, mctx, zone->updatemethod)); CHECK(zone_journal(zone, &diff, NULL, "keyfetch_done")); commit = true; DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED); zone_needdump(zone, 30); } else if (result == ISC_R_NOMORE) { /* * If "updatekey" was true for all keys found in the DNSKEY * response and the previous update of those keys happened * during the same second (only possible if a key refresh was * externally triggered), it may happen that all relevant * update_one_rr() calls will return ISC_R_SUCCESS, but * diff.tuples will remain empty. Reset result to * ISC_R_SUCCESS to prevent a bogus warning from being logged. */ result = ISC_R_SUCCESS; } failure: if (result != ISC_R_SUCCESS) { dnssec_log(zone, ISC_LOG_ERROR, "error during managed-keys processing (%s): " "DNSSEC validation may be at risk", isc_result_totext(result)); } dns_diff_clear(&diff); if (ver != NULL) { dns_db_closeversion(kfetch->db, &ver, commit); } cleanup: dns_db_detach(&kfetch->db); INSIST(zone->irefs > 0); zone->irefs--; kfetch->zone = NULL; if (dns_rdataset_isassociated(&kfetch->keydataset)) { dns_rdataset_disassociate(&kfetch->keydataset); } if (dns_rdataset_isassociated(&kfetch->dnskeyset)) { dns_rdataset_disassociate(&kfetch->dnskeyset); } if (dns_rdataset_isassociated(&kfetch->dnskeysigset)) { dns_rdataset_disassociate(&kfetch->dnskeysigset); } dns_name_free(keyname, mctx); isc_mem_put(mctx, kfetch, sizeof(dns_keyfetch_t)); isc_mem_detach(&mctx); if (secroots != NULL) { dns_keytable_detach(&secroots); } free_needed = exit_check(zone); UNLOCK_ZONE(zone); if (free_needed) { zone_free(zone); } INSIST(ver == NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'Update keyfetch_done compute_tag check If in keyfetch_done the compute_tag fails (because for example the algorithm is not supported), don't crash, but instead ignore the key.'</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 update_blocked_averages(int cpu) { struct rq *rq = cpu_rq(cpu); struct cfs_rq *cfs_rq = &rq->cfs; const struct sched_class *curr_class; struct rq_flags rf; rq_lock_irqsave(rq, &rf); update_rq_clock(rq); update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq); curr_class = rq->curr->sched_class; update_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class); update_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class); update_irq_load_avg(rq, 0); #ifdef CONFIG_NO_HZ_COMMON rq->last_blocked_load_update_tick = jiffies; if (!cfs_rq_has_blocked(cfs_rq) && !others_have_blocked(rq)) rq->has_blocked_load = 0; #endif rq_unlock_irqrestore(rq, &rf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <xiexiuqi@huawei.com> Analyzed-by: Vincent Guittot <vincent.guittot@linaro.org> Reported-by: Zhipeng Xie <xiezhipeng1@huawei.com> Reported-by: Sargun Dhillon <sargun@sargun.me> Reported-by: Xie XiuQi <xiexiuqi@huawei.com> Tested-by: Zhipeng Xie <xiezhipeng1@huawei.com> Tested-by: Sargun Dhillon <sargun@sargun.me> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Vincent Guittot <vincent.guittot@linaro.org> Cc: <stable@vger.kernel.org> # v4.13+ Cc: Bin Li <huawei.libin@huawei.com> Cc: Mike Galbraith <efault@gmx.de> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Tejun Heo <tj@kernel.org> Cc: Thomas Gleixner <tglx@linutronix.de> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/1545879866-27809-1-git-send-email-xiexiuqi@huawei.com Signed-off-by: Ingo Molnar <mingo@kernel.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: set_vterm_palette(VTerm *vterm, long_u *rgb) { int index = 0; VTermState *state = vterm_obtain_state(vterm); for (; index < 16; index++) { VTermColor color; color.red = (unsigned)(rgb[index] >> 16); color.green = (unsigned)(rgb[index] >> 8) & 255; color.blue = (unsigned)rgb[index] & 255; vterm_state_set_palette_color(state, index, &color); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window Problem: Crash when out of memory while opening a terminal window. Solution: Handle out-of-memory more gracefully.'</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 png_print_chunk(unsigned type, unsigned char* data, unsigned size) { char tag[5]; unsigned i; be_uint32_write(tag, type); tag[4] = 0; cout << tag << setw(8) << size; switch (type) { case ADV_MNG_CN_MHDR : cout << " width:" << be_uint32_read(data+0) << " height:" << be_uint32_read(data+4) << " frequency:" << be_uint32_read(data+8); cout << " simplicity:" << be_uint32_read(data+24); cout << "(bit"; for(i=0;i<32;++i) { if (be_uint32_read(data+24) & (1 << i)) { cout << "," << i; } } cout << ")"; break; case ADV_MNG_CN_DHDR : cout << " id:" << be_uint16_read(data+0); switch (data[2]) { case 0 : cout << " img:unspecified"; break; case 1 : cout << " img:png"; break; case 2 : cout << " img:jng"; break; default: cout << " img:?"; break; } switch (data[3]) { case 0 : cout << " delta:entire_replacement"; break; case 1 : cout << " delta:block_addition"; break; case 2 : cout << " delta:block_alpha_addition"; break; case 3 : cout << " delta:block_color_addition"; break; case 4 : cout << " delta:block_replacement"; break; case 5 : cout << " delta:block_alpha_replacement"; break; case 6 : cout << " delta:block_color_replacement"; break; case 7 : cout << " delta:no_change"; break; default: cout << " delta:?"; break; } if (size >= 12) { cout << " width:" << be_uint32_read(data + 4) << " height:" << be_uint32_read(data + 8); } if (size >= 20) { cout << " x:" << (int)be_uint32_read(data + 12) << " y:" << (int)be_uint32_read(data + 16); } break; case ADV_MNG_CN_FRAM : if (size >= 1) { cout << " mode:" << (unsigned)data[0]; } if (size > 1) { i = 1; while (i < size && data[i]!=0) ++i; cout << " len:" << i-1; if (size >= i+2) { cout << " delay_mode:" << (unsigned)data[i+1]; } if (size >= i+3) { cout << " timeout:" << (unsigned)data[i+2]; } if (size >= i+4) { cout << " clip:" << (unsigned)data[i+3]; } if (size >= i+5) { cout << " syncid:" << (unsigned)data[i+4]; } if (size >= i+9) { cout << " tick:" << be_uint32_read(data+i+5); } if (size >= i+13) { cout << " timeout:" << be_uint32_read(data+i+9); } if (size >= i+14) { cout << " dt:" << (unsigned)data[i+10]; } if (size >= i+15) { cout << " ..."; } } break; case ADV_MNG_CN_DEFI : cout << " id:" << be_uint16_read(data+0); if (size >= 3) { switch (data[2]) { case 0 : cout << " visible:yes"; break; case 1 : cout << " visible:no"; break; default : cout << " visible:?"; break; } } if (size >= 4) { switch (data[3]) { case 0 : cout << " concrete:abstract"; break; case 1 : cout << " concrete:concrete"; break; default : cout << " concrete:?"; break; } } if (size >= 12) { cout << " x:" << (int)be_uint32_read(data + 4) << " y:" << (int)be_uint32_read(data + 8); } if (size >= 28) { cout << " left:" << be_uint32_read(data + 12) << " right:" << be_uint32_read(data + 16) << " top:" << be_uint32_read(data + 20) << " bottom:" << be_uint32_read(data + 24); } break; case ADV_MNG_CN_MOVE : cout << " id_from:" << be_uint16_read(data+0) << " id_to:" << be_uint16_read(data+2); switch (data[4]) { case 0 : cout << " type:replace"; break; case 1 : cout << " type:add"; break; default : cout << " type:?"; break; } cout << " x:" << (int)be_uint32_read(data + 5) << " y:" << (int)be_uint32_read(data + 9); break; case ADV_MNG_CN_PPLT : switch (data[0]) { case 0 : cout << " type:replacement_rgb"; break; case 1 : cout << " type:delta_rgb"; break; case 2 : cout << " type:replacement_alpha"; break; case 3 : cout << " type:delta_alpha"; break; case 4 : cout << " type:replacement_rgba"; break; case 5 : cout << " type:delta_rgba"; break; default : cout << " type:?"; break; } i = 1; while (i<size) { unsigned ssize; cout << " " << (unsigned)data[i] << ":" << (unsigned)data[i+1]; if (data[0] == 0 || data[1] == 1) ssize = 3; else if (data[0] == 2 || data[1] == 3) ssize = 1; else ssize = 4; i += 2 + (data[i+1] - data[i] + 1) * ssize; } break; case ADV_PNG_CN_IHDR : cout << " width:" << be_uint32_read(data) << " height:" << be_uint32_read(data + 4); cout << " depth:" << (unsigned)data[8]; cout << " color_type:" << (unsigned)data[9]; cout << " compression:" << (unsigned)data[10]; cout << " filter:" << (unsigned)data[11]; cout << " interlace:" << (unsigned)data[12]; break; } cout << endl; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix a buffer overflow caused by invalid chunks'</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: xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error) { xml_element* xReturn = NULL; char buf[100] = ""; static STRUCT_XML_ELEM_INPUT_OPTIONS default_opts = {encoding_utf_8}; if(!options) { options = &default_opts; } if(in_buf) { XML_Parser parser; xml_elem_data mydata = {0}; parser = XML_ParserCreate(NULL); mydata.root = xml_elem_new(); mydata.current = mydata.root; mydata.input_options = options; mydata.needs_enc_conversion = options->encoding && strcmp(options->encoding, encoding_utf_8); XML_SetElementHandler(parser, (XML_StartElementHandler)_xmlrpc_startElement, (XML_EndElementHandler)_xmlrpc_endElement); XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)_xmlrpc_charHandler); /* pass the xml_elem_data struct along */ XML_SetUserData(parser, (void*)&mydata); if(!len) { len = strlen(in_buf); } /* parse the XML */ if(XML_Parse(parser, in_buf, len, 1) == 0) { enum XML_Error err_code = XML_GetErrorCode(parser); int line_num = XML_GetCurrentLineNumber(parser); int col_num = XML_GetCurrentColumnNumber(parser); long byte_idx = XML_GetCurrentByteIndex(parser); int byte_total = XML_GetCurrentByteCount(parser); const char * error_str = XML_ErrorString(err_code); if(byte_idx >= 0) { snprintf(buf, sizeof(buf), "\n\tdata beginning %ld before byte index: %s\n", byte_idx > 10 ? 10 : byte_idx, in_buf + (byte_idx > 10 ? byte_idx - 10 : byte_idx)); } fprintf(stderr, "expat reports error code %i\n" "\tdescription: %s\n" "\tline: %i\n" "\tcolumn: %i\n" "\tbyte index: %ld\n" "\ttotal bytes: %i\n%s ", err_code, error_str, line_num, col_num, byte_idx, byte_total, buf); /* error condition */ if(error) { error->parser_code = (long)err_code; error->line = line_num; error->column = col_num; error->byte_index = byte_idx; error->parser_error = error_str; } } else { xReturn = (xml_element*)Q_Head(&mydata.root->children); xReturn->parent = NULL; } XML_ParserFree(parser); xml_elem_free_non_recurse(mydata.root); } return xReturn; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'MFH: Fixed bug #46746 (xmlrpc_decode_request outputs non-suppressable error when given bad data).'</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(mb_split) { char *arg_pattern; size_t arg_pattern_len; php_mb_regex_t *re; OnigRegion *regs = NULL; char *string; OnigUChar *pos, *chunk_pos; size_t string_len; int err; size_t n; zend_long count = -1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|l", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) { RETURN_FALSE; } if (count > 0) { count--; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax))) == NULL) { RETURN_FALSE; } array_init(return_value); chunk_pos = pos = (OnigUChar *)string; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while (count != 0 && (size_t)(pos - (OnigUChar *)string) < string_len) { size_t beg, end; err = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0); if (err < 0) { break; } beg = regs->beg[0], end = regs->end[0]; /* add it to the array */ if ((size_t)(pos - (OnigUChar *)string) < end) { if (beg < string_len && beg >= (size_t)(chunk_pos - (OnigUChar *)string)) { add_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos)); --count; } else { err = -2; break; } /* point at our new starting point */ chunk_pos = pos = (OnigUChar *)string + end; } else { pos++; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL, E_WARNING, "mbregex search failure in mbsplit(): %s", err_str); zend_array_destroy(Z_ARR_P(return_value)); RETURN_FALSE; } /* otherwise we just have one last element to add to the array */ n = ((OnigUChar *)(string + string_len) - chunk_pos); if (n > 0) { add_next_index_stringl(return_value, (char *)chunk_pos, n); } else { add_next_index_stringl(return_value, "", 0); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #77367: Negative size parameter in mb_split When adding the last element to the result value of `mb_split`, the `chunk_pos` may point beyond the end of the string, in which case the unsigned `n` would underflow. Therefore, we check whether this is the case in the first place, and only calculate `n` otherwise. Since `n` is no longer used outside the block, we move its declaration inside.'</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: Output8bitPixel ( IN OUT EFI_IMAGE_INPUT *Image, IN UINT8 *Data, IN EFI_HII_IMAGE_PALETTE_INFO *PaletteInfo ) { UINT16 Xpos; UINT16 Ypos; UINTN OffsetY; EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BitMapPtr; EFI_GRAPHICS_OUTPUT_BLT_PIXEL PaletteValue[256]; EFI_HII_IMAGE_PALETTE_INFO *Palette; UINTN PaletteSize; UINT16 PaletteNum; UINT8 Byte; ASSERT (Image != NULL && Data != NULL && PaletteInfo != NULL); BitMapPtr = Image->Bitmap; // // The bitmap should allocate each color index starting from 0. // PaletteSize = 0; CopyMem (&PaletteSize, PaletteInfo, sizeof (UINT16)); PaletteSize += sizeof (UINT16); Palette = AllocateZeroPool (PaletteSize); ASSERT (Palette != NULL); if (Palette == NULL) { return; } CopyMem (Palette, PaletteInfo, PaletteSize); PaletteNum = (UINT16)(Palette->PaletteSize / sizeof (EFI_HII_RGB_PIXEL)); ZeroMem (PaletteValue, sizeof (PaletteValue)); CopyRgbToGopPixel (PaletteValue, Palette->PaletteValue, PaletteNum); FreePool (Palette); // // Convert the pixel from 8 bits to corresponding color. // for (Ypos = 0; Ypos < Image->Height; Ypos++) { OffsetY = BITMAP_LEN_8_BIT ((UINT32) Image->Width, Ypos); // // All bits are meaningful since the bitmap is 8 bits per pixel. // for (Xpos = 0; Xpos < Image->Width; Xpos++) { Byte = *(Data + OffsetY + Xpos); BitMapPtr[OffsetY + Xpos] = PaletteValue[Byte]; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/HiiImage: Fix stack overflow when corrupted BMP is parsed (CVE-2018-12181) REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1135 For 4bit BMP, there are only 2^4 = 16 colors in the palette. But when a corrupted BMP contains more than 16 colors in the palette, today's implementation wrongly copies all colors to the local PaletteValue[16] array which causes stack overflow. The similar issue also exists in the logic to handle 8bit BMP. The patch fixes the issue by only copies the first 16 or 256 colors in the palette depending on the BMP type. Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Ray Ni <ray.ni@intel.com> Cc: Liming Gao <liming.gao@intel.com> Cc: Jiewen Yao <jiewen.yao@intel.com> Reviewed-by: Jian J Wang <jian.j.wang@intel.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: channel_x11_req(LIBSSH2_CHANNEL *channel, int single_connection, const char *auth_proto, const char *auth_cookie, int screen_number) { LIBSSH2_SESSION *session = channel->session; unsigned char *s; static const unsigned char reply_codes[3] = { SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 }; size_t proto_len = auth_proto ? strlen(auth_proto) : (sizeof("MIT-MAGIC-COOKIE-1") - 1); size_t cookie_len = auth_cookie ? strlen(auth_cookie) : LIBSSH2_X11_RANDOM_COOKIE_LEN; int rc; if(channel->reqX11_state == libssh2_NB_state_idle) { /* 30 = packet_type(1) + channel(4) + x11_req_len(4) + "x11-req"(7) + * want_reply(1) + single_cnx(1) + proto_len(4) + cookie_len(4) + * screen_num(4) */ channel->reqX11_packet_len = proto_len + cookie_len + 30; /* Zero the whole thing out */ memset(&channel->reqX11_packet_requirev_state, 0, sizeof(channel->reqX11_packet_requirev_state)); _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Requesting x11-req for channel %lu/%lu: single=%d " "proto=%s cookie=%s screen=%d", channel->local.id, channel->remote.id, single_connection, auth_proto ? auth_proto : "MIT-MAGIC-COOKIE-1", auth_cookie ? auth_cookie : "<random>", screen_number); s = channel->reqX11_packet = LIBSSH2_ALLOC(session, channel->reqX11_packet_len); if(!channel->reqX11_packet) { return _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for pty-request"); } *(s++) = SSH_MSG_CHANNEL_REQUEST; _libssh2_store_u32(&s, channel->remote.id); _libssh2_store_str(&s, "x11-req", sizeof("x11-req") - 1); *(s++) = 0x01; /* want_reply */ *(s++) = single_connection ? 0x01 : 0x00; _libssh2_store_str(&s, auth_proto ? auth_proto : "MIT-MAGIC-COOKIE-1", proto_len); _libssh2_store_u32(&s, cookie_len); if(auth_cookie) { memcpy(s, auth_cookie, cookie_len); } else { int i; /* note: the extra +1 below is necessary since the sprintf() loop will always write 3 bytes so the last one will write the trailing zero at the LIBSSH2_X11_RANDOM_COOKIE_LEN/2 border */ unsigned char buffer[(LIBSSH2_X11_RANDOM_COOKIE_LEN / 2) + 1]; _libssh2_random(buffer, LIBSSH2_X11_RANDOM_COOKIE_LEN / 2); for(i = 0; i < (LIBSSH2_X11_RANDOM_COOKIE_LEN / 2); i++) { snprintf((char *)&s[i*2], 3, "%02X%c", buffer[i], '\0'); } } s += cookie_len; _libssh2_store_u32(&s, screen_number); channel->reqX11_state = libssh2_NB_state_created; } if(channel->reqX11_state == libssh2_NB_state_created) { rc = _libssh2_transport_send(session, channel->reqX11_packet, channel->reqX11_packet_len, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, rc, "Would block sending X11-req packet"); return rc; } if(rc) { LIBSSH2_FREE(session, channel->reqX11_packet); channel->reqX11_packet = NULL; channel->reqX11_state = libssh2_NB_state_idle; return _libssh2_error(session, rc, "Unable to send x11-req packet"); } LIBSSH2_FREE(session, channel->reqX11_packet); channel->reqX11_packet = NULL; _libssh2_htonu32(channel->reqX11_local_channel, channel->local.id); channel->reqX11_state = libssh2_NB_state_sent; } if(channel->reqX11_state == libssh2_NB_state_sent) { size_t data_len; unsigned char *data; unsigned char code; rc = _libssh2_packet_requirev(session, reply_codes, &data, &data_len, 1, channel->reqX11_local_channel, 4, &channel->reqX11_packet_requirev_state); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { channel->reqX11_state = libssh2_NB_state_idle; return _libssh2_error(session, rc, "waiting for x11-req response packet"); } code = data[0]; LIBSSH2_FREE(session, data); channel->reqX11_state = libssh2_NB_state_idle; if(code == SSH_MSG_CHANNEL_SUCCESS) return 0; } return _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED, "Unable to complete request for channel x11-req"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315) * Bounds checks Fixes for CVEs https://www.libssh2.org/CVE-2019-3863.html https://www.libssh2.org/CVE-2019-3856.html * Packet length bounds check CVE https://www.libssh2.org/CVE-2019-3855.html * Response length check CVE https://www.libssh2.org/CVE-2019-3859.html * Bounds check CVE https://www.libssh2.org/CVE-2019-3857.html * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html and additional data validation * Check bounds before reading into buffers * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html * declare SIZE_MAX and UINT_MAX if needed'</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: hostkey_method_ssh_rsa_init(LIBSSH2_SESSION * session, const unsigned char *hostkey_data, size_t hostkey_data_len, void **abstract) { libssh2_rsa_ctx *rsactx; const unsigned char *s, *e, *n; unsigned long len, e_len, n_len; int ret; (void) hostkey_data_len; if(*abstract) { hostkey_method_ssh_rsa_dtor(session, abstract); *abstract = NULL; } s = hostkey_data; len = _libssh2_ntohu32(s); s += 4; if(len != 7 || strncmp((char *) s, "ssh-rsa", 7) != 0) { return -1; } s += 7; e_len = _libssh2_ntohu32(s); s += 4; e = s; s += e_len; n_len = _libssh2_ntohu32(s); s += 4; n = s; ret = _libssh2_rsa_new(&rsactx, e, e_len, n, n_len, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0); if(ret) { return -1; } *abstract = rsactx; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315) * Bounds checks Fixes for CVEs https://www.libssh2.org/CVE-2019-3863.html https://www.libssh2.org/CVE-2019-3856.html * Packet length bounds check CVE https://www.libssh2.org/CVE-2019-3855.html * Response length check CVE https://www.libssh2.org/CVE-2019-3859.html * Bounds check CVE https://www.libssh2.org/CVE-2019-3857.html * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html and additional data validation * Check bounds before reading into buffers * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html * declare SIZE_MAX and UINT_MAX if needed'</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 *userauth_list(LIBSSH2_SESSION *session, const char *username, unsigned int username_len) { static const unsigned char reply_codes[3] = { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, 0 }; /* packet_type(1) + username_len(4) + service_len(4) + service(14)"ssh-connection" + method_len(4) = 27 */ unsigned long methods_len; unsigned char *s; int rc; if(session->userauth_list_state == libssh2_NB_state_idle) { /* Zero the whole thing out */ memset(&session->userauth_list_packet_requirev_state, 0, sizeof(session->userauth_list_packet_requirev_state)); session->userauth_list_data_len = username_len + 27; s = session->userauth_list_data = LIBSSH2_ALLOC(session, session->userauth_list_data_len); if(!session->userauth_list_data) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for userauth_list"); return NULL; } *(s++) = SSH_MSG_USERAUTH_REQUEST; _libssh2_store_str(&s, username, username_len); _libssh2_store_str(&s, "ssh-connection", 14); _libssh2_store_u32(&s, 4); /* send "none" separately */ session->userauth_list_state = libssh2_NB_state_created; } if(session->userauth_list_state == libssh2_NB_state_created) { rc = _libssh2_transport_send(session, session->userauth_list_data, session->userauth_list_data_len, (unsigned char *)"none", 4); if(rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block requesting userauth list"); return NULL; } /* now free the packet that was sent */ LIBSSH2_FREE(session, session->userauth_list_data); session->userauth_list_data = NULL; if(rc) { _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND, "Unable to send userauth-none request"); session->userauth_list_state = libssh2_NB_state_idle; return NULL; } session->userauth_list_state = libssh2_NB_state_sent; } if(session->userauth_list_state == libssh2_NB_state_sent) { rc = _libssh2_packet_requirev(session, reply_codes, &session->userauth_list_data, &session->userauth_list_data_len, 0, NULL, 0, &session->userauth_list_packet_requirev_state); if(rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block requesting userauth list"); return NULL; } else if(rc) { _libssh2_error(session, rc, "Failed getting response"); session->userauth_list_state = libssh2_NB_state_idle; return NULL; } if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_SUCCESS) { /* Wow, who'dve thought... */ _libssh2_error(session, LIBSSH2_ERROR_NONE, "No error"); LIBSSH2_FREE(session, session->userauth_list_data); session->userauth_list_data = NULL; session->state |= LIBSSH2_STATE_AUTHENTICATED; session->userauth_list_state = libssh2_NB_state_idle; return NULL; } methods_len = _libssh2_ntohu32(session->userauth_list_data + 1); /* Do note that the memory areas overlap! */ memmove(session->userauth_list_data, session->userauth_list_data + 5, methods_len); session->userauth_list_data[methods_len] = '\0'; _libssh2_debug(session, LIBSSH2_TRACE_AUTH, "Permitted auth methods: %s", session->userauth_list_data); } session->userauth_list_state = libssh2_NB_state_idle; return (char *) session->userauth_list_data; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315) * Bounds checks Fixes for CVEs https://www.libssh2.org/CVE-2019-3863.html https://www.libssh2.org/CVE-2019-3856.html * Packet length bounds check CVE https://www.libssh2.org/CVE-2019-3855.html * Response length check CVE https://www.libssh2.org/CVE-2019-3859.html * Bounds check CVE https://www.libssh2.org/CVE-2019-3857.html * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html and additional data validation * Check bounds before reading into buffers * Bounds checking CVE https://www.libssh2.org/CVE-2019-3859.html * declare SIZE_MAX and UINT_MAX if needed'</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 MagickBooleanType DecodeImage(Image *image,unsigned char *luma, unsigned char *chroma1,unsigned char *chroma2) { #define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL) #define PCDGetBits(n) \ { \ sum=(sum << n) & 0xffffffff; \ bits-=n; \ while (bits <= 24) \ { \ if (p >= (buffer+0x800)) \ { \ count=ReadBlob(image,0x800,buffer); \ p=buffer; \ } \ sum|=((unsigned int) (*p) << (24-bits)); \ bits+=8; \ p++; \ } \ } typedef struct PCDTable { unsigned int length, sequence; MagickStatusType mask; unsigned char key; } PCDTable; PCDTable *pcd_table[3]; register ssize_t i, j; register PCDTable *r; register unsigned char *p, *q; size_t bits, length, plane, pcd_length[3], row, sum; ssize_t count, quantum; unsigned char *buffer; /* Initialize Huffman tables. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(luma != (unsigned char *) NULL); assert(chroma1 != (unsigned char *) NULL); assert(chroma2 != (unsigned char *) NULL); buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); sum=0; bits=32; p=buffer+0x800; for (i=0; i < 3; i++) { pcd_table[i]=(PCDTable *) NULL; pcd_length[i]=0; } for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) { PCDGetBits(8); length=(sum & 0xff)+1; pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length, sizeof(*pcd_table[i])); if (pcd_table[i] == (PCDTable *) NULL) { buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } r=pcd_table[i]; for (j=0; j < (ssize_t) length; j++) { PCDGetBits(8); r->length=(unsigned int) (sum & 0xff)+1; if (r->length > 16) { buffer=(unsigned char *) RelinquishMagickMemory(buffer); return(MagickFalse); } PCDGetBits(16); r->sequence=(unsigned int) (sum & 0xffff) << 16; PCDGetBits(8); r->key=(unsigned char) (sum & 0xff); r->mask=(~((1U << (32-r->length))-1)); r++; } pcd_length[i]=(size_t) length; } /* Search for Sync byte. */ for (i=0; i < 1; i++) PCDGetBits(16); for (i=0; i < 1; i++) PCDGetBits(16); while ((sum & 0x00fff000UL) != 0x00fff000UL) PCDGetBits(8); while (IsSync(sum) == 0) PCDGetBits(1); /* Recover the Huffman encoded luminance and chrominance deltas. */ count=0; length=0; plane=0; row=0; q=luma; for ( ; ; ) { if (IsSync(sum) != 0) { /* Determine plane and row number. */ PCDGetBits(16); row=((sum >> 9) & 0x1fff); if (row == image->rows) break; PCDGetBits(8); plane=sum >> 30; PCDGetBits(16); switch (plane) { case 0: { q=luma+row*image->columns; count=(ssize_t) image->columns; break; } case 2: { q=chroma1+(row >> 1)*image->columns; count=(ssize_t) (image->columns >> 1); plane--; break; } case 3: { q=chroma2+(row >> 1)*image->columns; count=(ssize_t) (image->columns >> 1); plane--; break; } default: { for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); } } length=pcd_length[plane]; continue; } /* Decode luminance or chrominance deltas. */ r=pcd_table[plane]; for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++) r++; if ((row > image->rows) || (r == (PCDTable *) NULL)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename); while ((sum & 0x00fff000) != 0x00fff000) PCDGetBits(8); while (IsSync(sum) == 0) PCDGetBits(1); continue; } if (r->key < 128) quantum=(ssize_t) (*q)+r->key; else quantum=(ssize_t) (*q)+r->key-256; *q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum); q++; PCDGetBits(r->length); count--; } /* Relinquish resources. */ for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); buffer=(unsigned char *) RelinquishMagickMemory(buffer); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1450'</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: g_socket_client_enumerator_callback (GObject *object, GAsyncResult *result, gpointer user_data) { GSocketClientAsyncConnectData *data = user_data; GSocketAddress *address = NULL; GSocket *socket; ConnectionAttempt *attempt; GError *error = NULL; if (g_task_return_error_if_cancelled (data->task)) { g_object_unref (data->task); return; } address = g_socket_address_enumerator_next_finish (data->enumerator, result, &error); if (address == NULL) { if (data->connection_attempts) return; g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, NULL); if (!error) { if (data->last_error) { error = data->last_error; data->last_error = NULL; } else { g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_FAILED, _("Unknown error on connect")); } } g_task_return_error (data->task, error); g_object_unref (data->task); return; } g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVED, data->connectable, NULL); if (G_IS_PROXY_ADDRESS (address) && data->client->priv->enable_proxy) data->proxy_addr = g_object_ref (G_PROXY_ADDRESS (address)); g_clear_error (&data->last_error); socket = create_socket (data->client, address, &data->last_error); if (socket == NULL) { g_object_unref (address); enumerator_next_async (data); return; } attempt = connection_attempt_new (); attempt->data = data; attempt->socket = socket; attempt->address = address; attempt->cancellable = g_cancellable_new (); attempt->connection = (GIOStream *)g_socket_connection_factory_create_connection (socket); attempt->timeout_source = g_timeout_source_new (HAPPY_EYEBALLS_CONNECTION_ATTEMPT_TIMEOUT_MS); g_source_set_callback (attempt->timeout_source, on_connection_attempt_timeout, attempt, NULL); g_source_attach (attempt->timeout_source, g_main_context_get_thread_default ()); data->connection_attempts = g_slist_append (data->connection_attempts, attempt); if (g_task_get_cancellable (data->task)) g_cancellable_connect (g_task_get_cancellable (data->task), G_CALLBACK (on_connection_cancelled), g_object_ref (attempt->cancellable), g_object_unref); g_socket_connection_set_cached_remote_address ((GSocketConnection *)attempt->connection, address); g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTING, data->connectable, attempt->connection); g_socket_connection_connect_async (G_SOCKET_CONNECTION (attempt->connection), address, attempt->cancellable, g_socket_client_connected_callback, connection_attempt_ref (attempt)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals This ensures the parent GTask is kept alive as long as an enumeration is running and trying to connect. Closes #1646 Closes #1649'</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_scan_thumbnail(image_info_type *ImageInfo) { uchar c, *data = (uchar*)ImageInfo->Thumbnail.data; int n, marker; size_t length=2, pos=0; jpeg_sof_info sof_info; if (!data) { return FALSE; /* nothing to do here */ } if (memcmp(data, "\xFF\xD8\xFF", 3)) { if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Thumbnail is not a JPEG image"); } return FALSE; } for (;;) { pos += length; if (pos>=ImageInfo->Thumbnail.size) return FALSE; c = data[pos++]; if (pos>=ImageInfo->Thumbnail.size) return FALSE; if (c != 0xFF) { return FALSE; } n = 8; while ((c = data[pos++]) == 0xFF && n--) { if (pos+3>=ImageInfo->Thumbnail.size) return FALSE; /* +3 = pos++ of next check when reaching marker + 2 bytes for length */ } if (c == 0xFF) return FALSE; marker = c; length = php_jpg_get16(data+pos); if (pos+length>=ImageInfo->Thumbnail.size) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process section(x%02X=%s) @ x%04X + x%04X", marker, exif_get_markername(marker), pos, length); #endif switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: /* handle SOFn block */ exif_process_SOFn(data+pos, marker, &sof_info); ImageInfo->Thumbnail.height = sof_info.height; ImageInfo->Thumbnail.width = sof_info.width; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size: %d * %d", sof_info.width, sof_info.height); #endif return TRUE; case M_SOS: case M_EOI: exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail"); return FALSE; break; default: /* just skip */ break; } } exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail"); return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77540 - Invalid Read on exif_process_SOFn'</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 PDFDoc::markObject (Object* obj, XRef *xRef, XRef *countRef, unsigned int numOffset, int oldRefNum, int newRefNum, std::set<Dict*> *alreadyMarkedDicts) { Array *array; switch (obj->getType()) { case objArray: array = obj->getArray(); for (int i=0; i<array->getLength(); i++) { Object obj1 = array->getNF(i).copy(); markObject(&obj1, xRef, countRef, numOffset, oldRefNum, newRefNum); } break; case objDict: markDictionnary (obj->getDict(), xRef, countRef, numOffset, oldRefNum, newRefNum, alreadyMarkedDicts); break; case objStream: { Stream *stream = obj->getStream(); markDictionnary (stream->getDict(), xRef, countRef, numOffset, oldRefNum, newRefNum, alreadyMarkedDicts); } break; case objRef: { if (obj->getRef().num + (int) numOffset >= xRef->getNumObjects() || xRef->getEntry(obj->getRef().num + numOffset)->type == xrefEntryFree) { if (getXRef()->getEntry(obj->getRef().num)->type == xrefEntryFree) { return; // already marked as free => should be replaced } xRef->add(obj->getRef().num + numOffset, obj->getRef().gen, 0, true); if (getXRef()->getEntry(obj->getRef().num)->type == xrefEntryCompressed) { xRef->getEntry(obj->getRef().num + numOffset)->type = xrefEntryCompressed; } } if (obj->getRef().num + (int) numOffset >= countRef->getNumObjects() || countRef->getEntry(obj->getRef().num + numOffset)->type == xrefEntryFree) { countRef->add(obj->getRef().num + numOffset, 1, 0, true); } else { XRefEntry *entry = countRef->getEntry(obj->getRef().num + numOffset); entry->gen++; if (entry->gen > 9) break; } Object obj1 = getXRef()->fetch(obj->getRef()); markObject(&obj1, xRef, countRef, numOffset, oldRefNum, newRefNum); } break; default: break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'pdfunite: Fix stack overflow on broken file Fixes issue #741'</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 *load_device_tree(const char *filename_path, int *sizep) { int dt_size; int dt_file_load_size; int ret; void *fdt = NULL; *sizep = 0; dt_size = get_image_size(filename_path); if (dt_size < 0) { error_report("Unable to get size of device tree file '%s'", filename_path); goto fail; } /* Expand to 2x size to give enough room for manipulation. */ dt_size += 10000; dt_size *= 2; /* First allocate space in qemu for device tree */ fdt = g_malloc0(dt_size); dt_file_load_size = load_image(filename_path, fdt); if (dt_file_load_size < 0) { error_report("Unable to open device tree file '%s'", filename_path); goto fail; } ret = fdt_open_into(fdt, fdt, dt_size); if (ret) { error_report("Unable to copy device tree in memory"); goto fail; } /* Check sanity of device tree */ if (fdt_check_header(fdt)) { error_report("Device tree file loaded into memory is invalid: %s", filename_path); goto fail; } *sizep = dt_size; return fdt; fail: g_free(fdt); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'device_tree.c: Don't use load_image() The load_image() function is deprecated, as it does not let the caller specify how large the buffer to read the file into is. Instead use load_image_size(). Signed-off-by: Peter Maydell <peter.maydell@linaro.org> Reviewed-by: Richard Henderson <richard.henderson@linaro.org> Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com> Reviewed-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Eric Blake <eblake@redhat.com> Message-id: 20181130151712.2312-9-peter.maydell@linaro.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: CpuMpPeimInit ( IN EFI_PEI_FILE_HANDLE FileHandle, IN CONST EFI_PEI_SERVICES **PeiServices ) { EFI_STATUS Status; EFI_VECTOR_HANDOFF_INFO *VectorInfo; EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi; // // Get Vector Hand-off Info PPI // VectorInfo = NULL; Status = PeiServicesLocatePpi ( &gEfiVectorHandoffInfoPpiGuid, 0, NULL, (VOID **)&VectorHandoffInfoPpi ); if (Status == EFI_SUCCESS) { VectorInfo = VectorHandoffInfoPpi->Info; } Status = InitializeCpuExceptionHandlers (VectorInfo); ASSERT_EFI_ERROR (Status); // // Wakeup APs to do initialization // Status = MpInitLibInitialize (); ASSERT_EFI_ERROR (Status); // // Update and publish CPU BIST information // CollectBistDataFromPpi (PeiServices); // // Install CPU MP PPI // Status = PeiServicesInstallPpi(&mPeiCpuMpPpiDesc); ASSERT_EFI_ERROR (Status); return Status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'UefiCpuPkg/CpuMpPei: support stack guard feature This feature is the same as Stack Guard enabled in driver CpuDxe but applies to PEI phase. Due to the specialty in PEI module dispatching, this driver is changed to do the actual initialization in notify callback of event gEfiPeiMemoryDiscoveredPpiGuid. This can let the stack guard apply to as most PEI drivers as possible. To let Stack Guard work, some simple page table management code are introduced to setup Guard page at base of stack for each processor. Cc: Eric Dong <eric.dong@intel.com> Cc: Laszlo Ersek <lersek@redhat.com> Cc: Ruiyu Ni <ruiyu.ni@intel.com> Cc: Jiewen Yao <jiewen.yao@intel.com> Cc: Star Zeng <star.zeng@intel.com> Cc: "Ware, Ryan R" <ryan.r.ware@intel.com> Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang <jian.j.wang@intel.com> Regression-tested-by: Laszlo Ersek <lersek@redhat.com> Reviewed-by: Eric Dong <eric.dong@intel.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 inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { int msr; struct page *page; unsigned long *msr_bitmap_l1; unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap; /* * pred_cmd & spec_ctrl are trying to verify two things: * * 1. L0 gave a permission to L1 to actually passthrough the MSR. This * ensures that we do not accidentally generate an L02 MSR bitmap * from the L12 MSR bitmap that is too permissive. * 2. That L1 or L2s have actually used the MSR. This avoids * unnecessarily merging of the bitmap if the MSR is unused. This * works properly because we only update the L01 MSR bitmap lazily. * So even if L0 should pass L1 these MSRs, the L01 bitmap is only * updated to reflect this when L1 (or its L2s) actually write to * the MSR. */ bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD); bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL); /* Nothing to do if the MSR bitmap is not in use. */ if (!cpu_has_vmx_msr_bitmap() || !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS)) return false; if (!nested_cpu_has_virt_x2apic_mode(vmcs12) && !pred_cmd && !spec_ctrl) return false; page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap); if (is_error_page(page)) return false; msr_bitmap_l1 = (unsigned long *)kmap(page); /* * To keep the control flow simple, pay eight 8-byte writes (sixteen * 4-byte writes on 32-bit systems) up front to enable intercepts for * the x2APIC MSR range and selectively disable them below. */ enable_x2apic_msr_intercepts(msr_bitmap_l0); if (nested_cpu_has_virt_x2apic_mode(vmcs12)) { if (nested_cpu_has_apic_reg_virt(vmcs12)) { /* * L0 need not intercept reads for MSRs between 0x800 * and 0x8ff, it just lets the processor take the value * from the virtual-APIC page; take those 256 bits * directly from the L1 bitmap. */ for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) { unsigned word = msr / BITS_PER_LONG; msr_bitmap_l0[word] = msr_bitmap_l1[word]; } } nested_vmx_disable_intercept_for_msr( msr_bitmap_l1, msr_bitmap_l0, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_W); if (nested_cpu_has_vid(vmcs12)) { nested_vmx_disable_intercept_for_msr( msr_bitmap_l1, msr_bitmap_l0, X2APIC_MSR(APIC_EOI), MSR_TYPE_W); nested_vmx_disable_intercept_for_msr( msr_bitmap_l1, msr_bitmap_l0, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W); } } if (spec_ctrl) nested_vmx_disable_intercept_for_msr( msr_bitmap_l1, msr_bitmap_l0, MSR_IA32_SPEC_CTRL, MSR_TYPE_R | MSR_TYPE_W); if (pred_cmd) nested_vmx_disable_intercept_for_msr( msr_bitmap_l1, msr_bitmap_l0, MSR_IA32_PRED_CMD, MSR_TYPE_W); kunmap(page); kvm_release_page_clean(page); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-863'], 'message': 'KVM: x86: nVMX: fix x2APIC VTPR read intercept Referring to the "VIRTUALIZING MSR-BASED APIC ACCESSES" chapter of the SDM, when "virtualize x2APIC mode" is 1 and "APIC-register virtualization" is 0, a RDMSR of 808H should return the VTPR from the virtual APIC page. However, for nested, KVM currently fails to disable the read intercept for this MSR. This means that a RDMSR exit takes precedence over "virtualize x2APIC mode", and KVM passes through L1's TPR to L2, instead of sourcing the value from L2's virtual APIC page. This patch fixes the issue by disabling the read intercept, in VMCS02, for the VTPR when "APIC-register virtualization" is 0. The issue described above and fix prescribed here, were verified with a related patch in kvm-unit-tests titled "Test VMX's virtualize x2APIC mode w/ nested". Signed-off-by: Marc Orr <marcorr@google.com> Reviewed-by: Jim Mattson <jmattson@google.com> Fixes: c992384bde84f ("KVM: vmx: speed up MSR bitmap merge") Signed-off-by: Paolo Bonzini <pbonzini@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 inline void iocb_put(struct aio_kiocb *iocb) { if (refcount_read(&iocb->ki_refcnt) == 0 || refcount_dec_and_test(&iocb->ki_refcnt)) { percpu_ref_put(&iocb->ki_ctx->reqs); kmem_cache_free(kiocb_cachep, iocb); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit() Al Viro root-caused a race where the IOCB_CMD_POLL handling of fget/fput() could cause us to access the file pointer after it had already been freed: "In more details - normally IOCB_CMD_POLL handling looks so: 1) io_submit(2) allocates aio_kiocb instance and passes it to aio_poll() 2) aio_poll() resolves the descriptor to struct file by req->file = fget(iocb->aio_fildes) 3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that aio_kiocb to 2 (bumps by 1, that is). 4) aio_poll() calls vfs_poll(). After sanity checks (basically, "poll_wait() had been called and only once") it locks the queue. That's what the extra reference to iocb had been for - we know we can safely access it. 5) With queue locked, we check if ->woken has already been set to true (by aio_poll_wake()) and, if it had been, we unlock the queue, drop a reference to aio_kiocb and bugger off - at that point it's a responsibility to aio_poll_wake() and the stuff called/scheduled by it. That code will drop the reference to file in req->file, along with the other reference to our aio_kiocb. 6) otherwise, we see whether we need to wait. If we do, we unlock the queue, drop one reference to aio_kiocb and go away - eventual wakeup (or cancel) will deal with the reference to file and with the other reference to aio_kiocb 7) otherwise we remove ourselves from waitqueue (still under the queue lock), so that wakeup won't get us. No async activity will be happening, so we can safely drop req->file and iocb ourselves. If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb won't get freed under us, so we can do all the checks and locking safely. And we don't touch ->file if we detect that case. However, vfs_poll() most certainly *does* touch the file it had been given. So wakeup coming while we are still in ->poll() might end up doing fput() on that file. That case is not too rare, and usually we are saved by the still present reference from descriptor table - that fput() is not the final one. But if another thread closes that descriptor right after our fget() and wakeup does happen before ->poll() returns, we are in trouble - final fput() done while we are in the middle of a method: Al also wrote a patch to take an extra reference to the file descriptor to fix this, but I instead suggested we just streamline the whole file pointer handling by submit_io() so that the generic aio submission code simply keeps the file pointer around until the aio has completed. Fixes: bfe4037e722e ("aio: implement IOCB_CMD_POLL") Acked-by: Al Viro <viro@zeniv.linux.org.uk> Reported-by: syzbot+503d4cc169fcec1cb18c@syzkaller.appspotmail.com 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: do_conversion (const char *tocode, const char *fromcode, char const *in_org, size_t inlen, char **out) { iconv_t cd; /* sXXXav : hummm hard to guess... */ size_t len, done, outlen; int invalid = 0, tooshort = 0; char *s, *in, *in_save; cd = iconv_open (tocode, fromcode); if (cd == (iconv_t)(-1)) { logprintf (LOG_VERBOSE, _("Conversion from %s to %s isn't supported\n"), quote (fromcode), quote (tocode)); *out = NULL; return false; } /* iconv() has to work on an unescaped string */ in_save = in = xstrndup (in_org, inlen); url_unescape_except_reserved (in); inlen = strlen(in); len = outlen = inlen * 2; *out = s = xmalloc (outlen + 1); done = 0; for (;;) { if (iconv (cd, (ICONV_CONST char **) &in, &inlen, out, &outlen) != (size_t)(-1) && iconv (cd, NULL, NULL, out, &outlen) != (size_t)(-1)) { *out = s; *(s + len - outlen - done) = '\0'; xfree(in_save); iconv_close(cd); IF_DEBUG { /* not not print out embedded passwords, in_org might be an URL */ if (!strchr(in_org, '@') && !strchr(*out, '@')) debug_logprintf ("converted '%s' (%s) -> '%s' (%s)\n", in_org, fromcode, *out, tocode); else debug_logprintf ("logging suppressed, strings may contain password\n"); } return true; } /* Incomplete or invalid multibyte sequence */ if (errno == EINVAL || errno == EILSEQ) { if (!invalid) logprintf (LOG_VERBOSE, _("Incomplete or invalid multibyte sequence encountered\n")); invalid++; **out = *in; in++; inlen--; (*out)++; outlen--; } else if (errno == E2BIG) /* Output buffer full */ { tooshort++; done = len; len = outlen = done + inlen * 2; s = xrealloc (s, outlen + 1); *out = s + done; } else /* Weird, we got an unspecified error */ { logprintf (LOG_VERBOSE, _("Unhandled errno %d\n"), errno); break; } } xfree(in_save); iconv_close(cd); IF_DEBUG { /* not not print out embedded passwords, in_org might be an URL */ if (!strchr(in_org, '@') && !strchr(*out, '@')) debug_logprintf ("converted '%s' (%s) -> '%s' (%s)\n", in_org, fromcode, *out, tocode); else debug_logprintf ("logging suppressed, strings may contain password\n"); } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix a buffer overflow vulnerability * src/iri.c(do_conversion): Reallocate the output buffer to a larger size if it is already full'</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: qb_log_blackbox_write_to_file(const char *filename) { ssize_t written_size = 0; struct qb_log_target *t; struct _blackbox_file_header header; int fd = open(filename, O_CREAT | O_RDWR | O_EXCL, 0700); if (fd < 0) { return -errno; } /* Write header, so we know this is a 'new' format blackbox */ header.word_size = QB_BLACKBOX_HEADER_WORDSIZE; header.read_pt = QB_BLACKBOX_HEADER_READPT; header.write_pt = QB_BLACKBOX_HEADER_WRITEPT; header.version = QB_BLACKBOX_HEADER_VERSION; header.hash = QB_BLACKBOX_HEADER_HASH; written_size = write(fd, &header, sizeof(header)); if (written_size < sizeof(header)) { close(fd); return written_size; } t = qb_log_target_get(QB_LOG_BLACKBOX); if (t->instance) { written_size += qb_rb_write_to_file(t->instance, fd); } else { written_size = -ENOENT; } close(fd); return written_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'ipc: fixes Use O_EXCL on IPC files'</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 CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep) { std::string idx = request::findValue(&req, "idx"); if (idx == "") { return; } std::vector<std::vector<std::string> > result; result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%s", idx.c_str()); if (result.empty()) return; reply::set_content(&rep, result[0][0].begin(), result[0][0].end()); std::string oname = "floorplan"; if (result[0][0].size() > 10) { if (result[0][0][0] == 'P') oname += ".png"; else if (result[0][0][0] == -1) oname += ".jpg"; else if (result[0][0][0] == 'B') oname += ".bmp"; else if (result[0][0][0] == 'G') oname += ".gif"; } reply::add_header_attachment(&rep, oname); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)'</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: brcmf_wowl_nd_results(struct brcmf_if *ifp, const struct brcmf_event_msg *e, void *data) { struct brcmf_cfg80211_info *cfg = ifp->drvr->config; struct wiphy *wiphy = cfg_to_wiphy(cfg); struct brcmf_pno_scanresults_le *pfn_result; struct brcmf_pno_net_info_le *netinfo; brcmf_dbg(SCAN, "Enter\n"); if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) { brcmf_dbg(SCAN, "Event data to small. Ignore\n"); return 0; } pfn_result = (struct brcmf_pno_scanresults_le *)data; if (e->event_code == BRCMF_E_PFN_NET_LOST) { brcmf_dbg(SCAN, "PFN NET LOST event. Ignore\n"); return 0; } if (le32_to_cpu(pfn_result->count) < 1) { bphy_err(wiphy, "Invalid result count, expected 1 (%d)\n", le32_to_cpu(pfn_result->count)); return -EINVAL; } netinfo = brcmf_get_netinfo_array(pfn_result); memcpy(cfg->wowl.nd->ssid.ssid, netinfo->SSID, netinfo->SSID_len); cfg->wowl.nd->ssid.ssid_len = netinfo->SSID_len; cfg->wowl.nd->n_channels = 1; cfg->wowl.nd->channels[0] = ieee80211_channel_to_frequency(netinfo->channel, netinfo->channel <= CH_MAX_2G_CHANNEL ? NL80211_BAND_2GHZ : NL80211_BAND_5GHZ); cfg->wowl.nd_info->n_matches = 1; cfg->wowl.nd_info->matches[0] = cfg->wowl.nd; /* Inform (the resume task) that the net detect information was recvd */ cfg->wowl.nd_data_completed = true; wake_up(&cfg->wowl.nd_data_wait); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'brcmfmac: assure SSID length from firmware is limited The SSID length as received from firmware should not exceed IEEE80211_MAX_SSID_LEN as that would result in heap overflow. Reviewed-by: Hante Meuleman <hante.meuleman@broadcom.com> Reviewed-by: Pieter-Paul Giesberts <pieter-paul.giesberts@broadcom.com> Reviewed-by: Franky Lin <franky.lin@broadcom.com> Signed-off-by: Arend van Spriel <arend.vanspriel@broadcom.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.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 exif_process_COM (image_info_type *image_info, char *value, size_t length) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'</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_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { size_t i; int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel; #ifdef KALLE_0 int offset_diff; #endif const maker_note_type *maker_note; char *dir_start; int data_len; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) { #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "No maker note data found. Detected maker: %s (length = %d)", ImageInfo->make, strlen(ImageInfo->make)); #endif /* unknown manufacturer, not an error, use it as a string */ return TRUE; } maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } if (value_len < 2 || maker_note->offset >= value_len - 1) { /* Do not go past the value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X offset 0x%04X", value_len, maker_note->offset); return FALSE; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; data_len = value_len; break; #ifdef KALLE_0 case MN_OFFSET_GUESS: if (maker_note->offset + 10 + 4 >= value_len) { /* Can not read dir_start+10 since it's beyond value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X", value_len); return FALSE; } offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif if (offset_diff < 0 || offset_diff >= value_len ) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data bad offset: 0x%04X length 0x%04X", offset_diff, value_len); return FALSE; } offset_base = value_ptr + offset_diff; data_len = value_len - offset_diff; break; #endif default: case MN_OFFSET_NORMAL: data_len = value_len; break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, data_len, displacement, section_index, 0, maker_note->tag_table)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77753 - Heap-buffer-overflow in php_ifd_get32s'</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 format8BIM(Image *ifile, Image *ofile) { char temp[MagickPathExtent]; unsigned int foundOSType; int ID, resCount, i, c; ssize_t count; unsigned char *PString, *str; resCount=0; foundOSType=0; /* found the OSType */ (void) foundOSType; c=ReadBlobByte(ifile); while (c != EOF) { if (c == '8') { unsigned char buffer[5]; buffer[0]=(unsigned char) c; for (i=1; i<4; i++) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); buffer[i] = (unsigned char) c; } buffer[4]=0; if (strcmp((const char *)buffer, "8BIM") == 0) foundOSType=1; else continue; } else { c=ReadBlobByte(ifile); continue; } /* We found the OSType (8BIM) and now grab the ID, PString, and Size fields. */ ID=ReadBlobMSBSignedShort(ifile); if (ID < 0) return(-1); { unsigned char plen; c=ReadBlobByte(ifile); if (c == EOF) return(-1); plen = (unsigned char) c; PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+ MagickPathExtent),sizeof(*PString)); if (PString == (unsigned char *) NULL) return 0; for (i=0; i<plen; i++) { c=ReadBlobByte(ifile); if (c == EOF) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } PString[i] = (unsigned char) c; } PString[ plen ] = 0; if ((plen & 0x01) == 0) { c=ReadBlobByte(ifile); if (c == EOF) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } } } count=(ssize_t) ReadBlobMSBSignedLong(ifile); if ((count < 0) || (count > GetBlobSize(ifile))) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } /* make a buffer to hold the data and snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str)); if (str == (unsigned char *) NULL) { PString=(unsigned char *) RelinquishMagickMemory(PString); return 0; } for (i=0; i < (ssize_t) count; i++) { c=ReadBlobByte(ifile); if (c == EOF) { str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } str[i]=(unsigned char) c; } /* we currently skip thumbnails, since it does not make * any sense preserving them in a real world application */ if (ID != THUMBNAIL_ID) { /* now finish up by formatting this binary data into * ASCII equivalent */ if (strlen((const char *)PString) > 0) (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID, PString); else (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID); (void) WriteBlobString(ofile,temp); if (ID == IPTC_ID) { formatString(ofile, "IPTC", 4); formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count); } else formatString(ofile, (char *)str, (ssize_t) count); } str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); resCount++; c=ReadBlobByte(ifile); } return resCount; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119', 'CWE-193'], 'message': '...'</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: find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma, *prev; addr &= PAGE_MASK; vma = find_vma_prev(mm, addr, &prev); if (vma && (vma->vm_start <= addr)) return vma; if (!prev || expand_stack(prev, addr)) return NULL; if (prev->vm_flags & VM_LOCKED) populate_vma_page_range(prev, addr, prev->vm_end, NULL); return prev; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/alpine.LSU.2.11.1707191716030.2055@eggly.anvils "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/20190325224949.11068-1-aarcange@redhat.com Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Reported-by: Jann Horn <jannh@google.com> Suggested-by: Oleg Nesterov <oleg@redhat.com> Acked-by: Peter Xu <peterx@redhat.com> Reviewed-by: Mike Rapoport <rppt@linux.ibm.com> Reviewed-by: Oleg Nesterov <oleg@redhat.com> Reviewed-by: Jann Horn <jannh@google.com> Acked-by: Jason Gunthorpe <jgg@mellanox.com> Acked-by: Michal Hocko <mhocko@suse.com> Cc: <stable@vger.kernel.org> 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 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) { size_t length; unsigned 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), 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(%d)", tag, exif_get_tagname(tag, tagname, -12, tag_table), 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)); 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), 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), 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, displacement+offset_val, SEEK_SET); fgot = php_stream_tell(ImageInfo->infile); if (fgot!=displacement+offset_val) { EFREE_IF(outside); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, displacement+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); 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), 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); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); 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); 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); 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); } 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", ImageInfo->CopyrightPhotographer, ImageInfo->CopyrightEditor); /* 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); 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); 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); 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)*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)*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); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); 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); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)) { 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: if (!exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement)) { EFREE_IF(outside); return FALSE; } 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)) { 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), tag, format, components, value_ptr, byte_count); EFREE_IF(outside); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77950 - Heap-buffer-overflow in _estrndup via exif_process_IFD_TAG I do not completely understand what is going on there, but I am pretty sure dir_entry <= offset_base if not a normal situation, so we better not to rely on such dir_entry.'</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 lookupName( Parse *pParse, /* The parsing context */ const char *zDb, /* Name of the database containing table, or NULL */ const char *zTab, /* Name of table containing column, or NULL */ const char *zCol, /* Name of the column. */ NameContext *pNC, /* The name context used to resolve the name */ Expr *pExpr /* Make this EXPR node point to the selected column */ ){ int i, j; /* Loop counters */ int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ int nSubquery = 0; /* How many levels of subquery */ sqlite3 *db = pParse->db; /* The database connection */ struct SrcList_item *pItem; /* Use for looping over pSrcList items */ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ Table *pTab = 0; /* Table hold the row */ Column *pCol; /* A column of pTab */ assert( pNC ); /* the name context cannot be NULL. */ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); /* Initialize the node to no-match */ pExpr->iTable = -1; ExprSetVVAProperty(pExpr, EP_NoReduce); /* Translate the schema name in zDb into a pointer to the corresponding ** schema. If not found, pSchema will remain NULL and nothing will match ** resulting in an appropriate error message toward the end of this routine */ if( zDb ){ testcase( pNC->ncFlags & NC_PartIdx ); testcase( pNC->ncFlags & NC_IsCheck ); if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ /* Silently ignore database qualifiers inside CHECK constraints and ** partial indices. Do not raise errors because that might break ** legacy and because it does not hurt anything to just ignore the ** database name. */ zDb = 0; }else{ for(i=0; i<db->nDb; i++){ assert( db->aDb[i].zDbSName ); if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ pSchema = db->aDb[i].pSchema; break; } } } } /* Start at the inner-most context and move outward until a match is found */ assert( pNC && cnt==0 ); do{ ExprList *pEList; SrcList *pSrcList = pNC->pSrcList; if( pSrcList ){ for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ pTab = pItem->pTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 ); if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ int hit = 0; pEList = pItem->pSelect->pEList; for(j=0; j<pEList->nExpr; j++){ if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ cnt++; cntTab = 2; pMatch = pItem; pExpr->iColumn = j; hit = 1; } } if( hit || zTab==0 ) continue; } if( zDb && pTab->pSchema!=pSchema ){ continue; } if( zTab ){ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; assert( zTabName!=0 ); if( sqlite3StrICmp(zTabName, zTab)!=0 ){ continue; } if( IN_RENAME_OBJECT && pItem->zAlias ){ sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); } } if( 0==(cntTab++) ){ pMatch = pItem; } for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ /* If there has been exactly one prior match and this match ** is for the right-hand table of a NATURAL JOIN or is in a ** USING clause, then skip this match. */ if( cnt==1 ){ if( pItem->fg.jointype & JT_NATURAL ) continue; if( nameInUsingClause(pItem->pUsing, zCol) ) continue; } cnt++; pMatch = pItem; /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; break; } } } if( pMatch ){ pExpr->iTable = pMatch->iCursor; pExpr->y.pTab = pMatch->pTab; /* RIGHT JOIN not (yet) supported */ assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ ExprSetProperty(pExpr, EP_CanBeNull); } pSchema = pExpr->y.pTab->pSchema; } } /* if( pSrcList ) */ #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference. Or ** maybe it is an excluded.* from an upsert. */ if( zDb==0 && zTab!=0 && cntTab==0 ){ pTab = 0; #ifndef SQLITE_OMIT_TRIGGER if( pParse->pTriggerTab!=0 ){ int op = pParse->eTriggerOp; assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ pExpr->iTable = 1; pTab = pParse->pTriggerTab; }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ pExpr->iTable = 0; pTab = pParse->pTriggerTab; } } #endif /* SQLITE_OMIT_TRIGGER */ #ifndef SQLITE_OMIT_UPSERT if( (pNC->ncFlags & NC_UUpsert)!=0 ){ Upsert *pUpsert = pNC->uNC.pUpsert; if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ pTab = pUpsert->pUpsertSrc->a[0].pTab; pExpr->iTable = 2; } } #endif /* SQLITE_OMIT_UPSERT */ if( pTab ){ int iCol; pSchema = pTab->pSchema; cntTab++; for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; } break; } } if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ /* IMP: R-51414-32910 */ iCol = -1; } if( iCol<pTab->nCol ){ cnt++; #ifndef SQLITE_OMIT_UPSERT if( pExpr->iTable==2 ){ testcase( iCol==(-1) ); if( IN_RENAME_OBJECT ){ pExpr->iColumn = iCol; pExpr->y.pTab = pTab; eNewExprOp = TK_COLUMN; }else{ pExpr->iTable = pNC->uNC.pUpsert->regData + iCol; eNewExprOp = TK_REGISTER; ExprSetProperty(pExpr, EP_Alias); } }else #endif /* SQLITE_OMIT_UPSERT */ { #ifndef SQLITE_OMIT_TRIGGER if( iCol<0 ){ pExpr->affinity = SQLITE_AFF_INTEGER; }else if( pExpr->iTable==0 ){ testcase( iCol==31 ); testcase( iCol==32 ); pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); }else{ testcase( iCol==31 ); testcase( iCol==32 ); pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); } pExpr->y.pTab = pTab; pExpr->iColumn = (i16)iCol; eNewExprOp = TK_TRIGGER; #endif /* SQLITE_OMIT_TRIGGER */ } } } } #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ /* ** Perhaps the name is a reference to the ROWID */ if( cnt==0 && cntTab==1 && pMatch && (pNC->ncFlags & NC_IdxExpr)==0 && sqlite3IsRowid(zCol) && VisibleRowid(pMatch->pTab) ){ cnt = 1; pExpr->iColumn = -1; pExpr->affinity = SQLITE_AFF_INTEGER; } /* ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z ** might refer to an result-set alias. This happens, for example, when ** we are resolving names in the WHERE clause of the following command: ** ** SELECT a+b AS x FROM table WHERE x<10; ** ** In cases like this, replace pExpr with a copy of the expression that ** forms the result set entry ("a+b" in the example) and return immediately. ** Note that the expression in the result set should have already been ** resolved by the time the WHERE clause is resolved. ** ** The ability to use an output result-set column in the WHERE, GROUP BY, ** or HAVING clauses, or as part of a larger expression in the ORDER BY ** clause is not standard SQL. This is a (goofy) SQLite extension, that ** is supported for backwards compatibility only. Hence, we issue a warning ** on sqlite3_log() whenever the capability is used. */ if( (pNC->ncFlags & NC_UEList)!=0 && cnt==0 && zTab==0 ){ pEList = pNC->uNC.pEList; assert( pEList!=0 ); for(j=0; j<pEList->nExpr; j++){ char *zAs = pEList->a[j].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ Expr *pOrig; assert( pExpr->pLeft==0 && pExpr->pRight==0 ); assert( pExpr->x.pList==0 ); assert( pExpr->x.pSelect==0 ); pOrig = pEList->a[j].pExpr; if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); return WRC_Abort; } if( sqlite3ExprVectorSize(pOrig)!=1 ){ sqlite3ErrorMsg(pParse, "row value misused"); return WRC_Abort; } resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); cnt = 1; pMatch = 0; assert( zTab==0 && zDb==0 ); if( IN_RENAME_OBJECT ){ sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); } goto lookupname_end; } } } /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ if( cnt ) break; pNC = pNC->pNext; nSubquery++; }while( pNC ); /* ** If X and Y are NULL (in other words if only the column name Z is ** supplied) and the value of Z is enclosed in double-quotes, then ** Z is a string literal if it doesn't match any column names. In that ** case, we need to return right away and not make any changes to ** pExpr. ** ** Because no reference was made to outer contexts, the pNC->nRef ** fields are not changed in any context. */ if( cnt==0 && zTab==0 ){ assert( pExpr->op==TK_ID ); if( ExprHasProperty(pExpr,EP_DblQuoted) ){ /* If a double-quoted identifier does not match any known column name, ** then treat it as a string. ** ** This hack was added in the early days of SQLite in a misguided attempt ** to be compatible with MySQL 3.x, which used double-quotes for strings. ** I now sorely regret putting in this hack. The effect of this hack is ** that misspelled identifier names are silently converted into strings ** rather than causing an error, to the frustration of countless ** programmers. To all those frustrated programmers, my apologies. ** ** Someday, I hope to get rid of this hack. Unfortunately there is ** a huge amount of legacy SQL that uses it. So for now, we just ** issue a warning. */ sqlite3_log(SQLITE_WARNING, "double-quoted string literal: \"%w\"", zCol); #ifdef SQLITE_ENABLE_NORMALIZE sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); #endif pExpr->op = TK_STRING; pExpr->y.pTab = 0; return WRC_Prune; } if( sqlite3ExprIdToTrueFalse(pExpr) ){ return WRC_Prune; } } /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if( cnt!=1 ){ const char *zErr; zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); } pParse->checkSchema = 1; pTopNC->nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the ** column number is greater than the number of bits in the bitmask ** then set the high-order bit of the bitmask. */ if( pExpr->iColumn>=0 && pMatch!=0 ){ int n = pExpr->iColumn; testcase( n==BMS-1 ); if( n>=BMS ){ n = BMS-1; } assert( pMatch->iCursor==pExpr->iTable ); pMatch->colUsed |= ((Bitmask)1)<<n; } /* Clean up and return */ sqlite3ExprDelete(db, pExpr->pLeft); pExpr->pLeft = 0; sqlite3ExprDelete(db, pExpr->pRight); pExpr->pRight = 0; pExpr->op = eNewExprOp; ExprSetProperty(pExpr, EP_Leaf); lookupname_end: if( cnt==1 ){ assert( pNC!=0 ); if( !ExprHasProperty(pExpr, EP_Alias) ){ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); } /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ for(;;){ assert( pTopNC!=0 ); pTopNC->nRef++; if( pTopNC==pNC ) break; pTopNC = pTopNC->pNext; } return WRC_Prune; } else { return WRC_Abort; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Prevent aliases of window functions expressions from being used as arguments to aggregate or other window functions. FossilOrigin-Name: 1e16d3e8fc60d39ca3899759ff15d355fdd7d3e23b325d8d2b0f954e11ce8dce'</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 try_smi_init(struct smi_info *new_smi) { int rv = 0; int i; char *init_name = NULL; pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type], addr_space_to_str[new_smi->io.addr_type], new_smi->io.addr_data, new_smi->io.slave_addr, new_smi->io.irq); switch (new_smi->io.si_type) { case SI_KCS: new_smi->handlers = &kcs_smi_handlers; break; case SI_SMIC: new_smi->handlers = &smic_smi_handlers; break; case SI_BT: new_smi->handlers = &bt_smi_handlers; break; default: /* No support for anything else yet. */ rv = -EIO; goto out_err; } new_smi->si_num = smi_num; /* Do this early so it's available for logs. */ if (!new_smi->io.dev) { init_name = kasprintf(GFP_KERNEL, "ipmi_si.%d", new_smi->si_num); /* * If we don't already have a device from something * else (like PCI), then register a new one. */ new_smi->pdev = platform_device_alloc("ipmi_si", new_smi->si_num); if (!new_smi->pdev) { pr_err("Unable to allocate platform device\n"); rv = -ENOMEM; goto out_err; } new_smi->io.dev = &new_smi->pdev->dev; new_smi->io.dev->driver = &ipmi_platform_driver.driver; /* Nulled by device_add() */ new_smi->io.dev->init_name = init_name; } /* Allocate the state machine's data and initialize it. */ new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL); if (!new_smi->si_sm) { rv = -ENOMEM; goto out_err; } new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm, &new_smi->io); /* Now that we know the I/O size, we can set up the I/O. */ rv = new_smi->io.io_setup(&new_smi->io); if (rv) { dev_err(new_smi->io.dev, "Could not set up I/O space\n"); goto out_err; } /* Do low-level detection first. */ if (new_smi->handlers->detect(new_smi->si_sm)) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "Interface detection failed\n"); rv = -ENODEV; goto out_err; } /* * Attempt a get device id command. If it fails, we probably * don't have a BMC here. */ rv = try_get_dev_id(new_smi); if (rv) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "There appears to be no BMC at this location\n"); goto out_err; } setup_oem_data_handler(new_smi); setup_xaction_handlers(new_smi); check_for_broken_irqs(new_smi); new_smi->waiting_msg = NULL; new_smi->curr_msg = NULL; atomic_set(&new_smi->req_events, 0); new_smi->run_to_completion = false; for (i = 0; i < SI_NUM_STATS; i++) atomic_set(&new_smi->stats[i], 0); new_smi->interrupt_disabled = true; atomic_set(&new_smi->need_watch, 0); rv = try_enable_event_buffer(new_smi); if (rv == 0) new_smi->has_event_buffer = true; /* * Start clearing the flags before we enable interrupts or the * timer to avoid racing with the timer. */ start_clear_flags(new_smi); /* * IRQ is defined to be set when non-zero. req_events will * cause a global flags check that will enable interrupts. */ if (new_smi->io.irq) { new_smi->interrupt_disabled = false; atomic_set(&new_smi->req_events, 1); } if (new_smi->pdev && !new_smi->pdev_registered) { rv = platform_device_add(new_smi->pdev); if (rv) { dev_err(new_smi->io.dev, "Unable to register system interface device: %d\n", rv); goto out_err; } new_smi->pdev_registered = true; } dev_set_drvdata(new_smi->io.dev, new_smi); rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group); if (rv) { dev_err(new_smi->io.dev, "Unable to add device attributes: error %d\n", rv); goto out_err; } new_smi->dev_group_added = true; rv = ipmi_register_smi(&handlers, new_smi, new_smi->io.dev, new_smi->io.slave_addr); if (rv) { dev_err(new_smi->io.dev, "Unable to register device: error %d\n", rv); goto out_err; } /* Don't increment till we know we have succeeded. */ smi_num++; dev_info(new_smi->io.dev, "IPMI %s interface initialized\n", si_to_str[new_smi->io.si_type]); WARN_ON(new_smi->io.dev->init_name != NULL); out_err: kfree(init_name); return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: stable@vger.kernel.org Reported-by: NuoHan Qiao <qiaonuohan@huawei.com> Suggested-by: Corey Minyard <cminyard@mvista.com> Signed-off-by: Yang Yingliang <yangyingliang@huawei.com> Signed-off-by: Corey Minyard <cminyard@mvista.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 intel_vgpu_mmap(struct mdev_device *mdev, struct vm_area_struct *vma) { unsigned int index; u64 virtaddr; unsigned long req_size, pgoff = 0; pgprot_t pg_prot; struct intel_vgpu *vgpu = mdev_get_drvdata(mdev); index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT); if (index >= VFIO_PCI_ROM_REGION_INDEX) return -EINVAL; if (vma->vm_end < vma->vm_start) return -EINVAL; if ((vma->vm_flags & VM_SHARED) == 0) return -EINVAL; if (index != VFIO_PCI_BAR2_REGION_INDEX) return -EINVAL; pg_prot = vma->vm_page_prot; virtaddr = vma->vm_start; req_size = vma->vm_end - vma->vm_start; pgoff = vgpu_aperture_pa_base(vgpu) >> PAGE_SHIFT; return remap_pfn_range(vma, virtaddr, pgoff, req_size, pg_prot); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'drm/i915/gvt: Fix mmap range check This is to fix missed mmap range check on vGPU bar2 region and only allow to map vGPU allocated GMADDR range, which means user space should support sparse mmap to get proper offset for mmap vGPU aperture. And this takes care of actual pgoff in mmap request as original code always does from beginning of vGPU aperture. Fixes: 659643f7d814 ("drm/i915/gvt/kvmgt: add vfio/mdev support to KVMGT") Cc: "Monroy, Rodrigo Axel" <rodrigo.axel.monroy@intel.com> Cc: "Orrala Contreras, Alfredo" <alfredo.orrala.contreras@intel.com> Cc: stable@vger.kernel.org # v4.10+ Reviewed-by: Hang Yuan <hang.yuan@intel.com> Signed-off-by: Zhenyu Wang <zhenyuw@linux.intel.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 JPXStream::init() { Object oLen, cspace, smaskInData; if (getDict()) { oLen = getDict()->lookup("Length"); cspace = getDict()->lookup("ColorSpace"); smaskInData = getDict()->lookup("SMaskInData"); } int bufSize = BUFFER_INITIAL_SIZE; if (oLen.isInt()) bufSize = oLen.getInt(); bool indexed = false; if (cspace.isArray() && cspace.arrayGetLength() > 0) { const Object cstype = cspace.arrayGet(0); if (cstype.isName("Indexed")) indexed = true; } priv->smaskInData = 0; if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt(); int length = 0; unsigned char *buf = str->toUnsignedChars(&length, bufSize); priv->init2(OPJ_CODEC_JP2, buf, length, indexed); gfree(buf); if (priv->image) { int numComps = (priv->image) ? priv->image->numcomps : 1; int alpha = 0; if (priv->image) { if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; } else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; } else if (numComps == 2) { numComps = 1; alpha = 1; } else if (numComps > 4) { numComps = 4; alpha = 1; } else { alpha = 0; } } priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h; priv->ncomps = priv->image->numcomps; if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--; for (int component = 0; component < priv->ncomps; component++) { if (priv->image->comps[component].data == nullptr) { close(); break; } unsigned char *cdata = (unsigned char *)priv->image->comps[component].data; int adjust = 0; int depth = priv->image->comps[component].prec; if (priv->image->comps[component].prec > 8) adjust = priv->image->comps[component].prec - 8; int sgndcorr = 0; if (priv->image->comps[component].sgnd) sgndcorr = 1 << (priv->image->comps[0].prec - 1); for (int i = 0; i < priv->npixels; i++) { int r = priv->image->comps[component].data[i]; *(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed); } } } else { priv->npixels = 0; } priv->counter = 0; priv->ccounter = 0; priv->inited = true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'JPEG2000Stream: fail gracefully if not all components have the same WxH I think this is just a mistake, or at least the only file we have with this scenario is a fuzzed one'</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: deliver_message(uschar *id, BOOL forced, BOOL give_up) { int i, rc; int final_yield = DELIVER_ATTEMPTED_NORMAL; time_t now = time(NULL); address_item *addr_last = NULL; uschar *filter_message = NULL; int process_recipients = RECIP_ACCEPT; open_db dbblock; open_db *dbm_file; extern int acl_where; uschar *info = queue_run_pid == (pid_t)0 ? string_sprintf("delivering %s", id) : string_sprintf("delivering %s (queue run pid %d)", id, queue_run_pid); /* If the D_process_info bit is on, set_process_info() will output debugging information. If not, we want to show this initial information if D_deliver or D_queue_run is set or in verbose mode. */ set_process_info("%s", info); if ( !(debug_selector & D_process_info) && (debug_selector & (D_deliver|D_queue_run|D_v)) ) debug_printf("%s\n", info); /* Ensure that we catch any subprocesses that are created. Although Exim sets SIG_DFL as its initial default, some routes through the code end up here with it set to SIG_IGN - cases where a non-synchronous delivery process has been forked, but no re-exec has been done. We use sigaction rather than plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a problem on AIX with this.) */ #ifdef SA_NOCLDWAIT { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGCHLD, &act, NULL); } #else signal(SIGCHLD, SIG_DFL); #endif /* Make the forcing flag available for routers and transports, set up the global message id field, and initialize the count for returned files and the message size. This use of strcpy() is OK because the length id is checked when it is obtained from a command line (the -M or -q options), and otherwise it is known to be a valid message id. */ Ustrcpy(message_id, id); f.deliver_force = forced; return_count = 0; message_size = 0; /* Initialize some flags */ update_spool = FALSE; remove_journal = TRUE; /* Set a known context for any ACLs we call via expansions */ acl_where = ACL_WHERE_DELIVERY; /* Reset the random number generator, so that if several delivery processes are started from a queue runner that has already used random numbers (for sorting), they don't all get the same sequence. */ random_seed = 0; /* Open and lock the message's data file. Exim locks on this one because the header file may get replaced as it is re-written during the delivery process. Any failures cause messages to be written to the log, except for missing files while queue running - another process probably completed delivery. As part of opening the data file, message_subdir gets set. */ if ((deliver_datafile = spool_open_datafile(id)) < 0) return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ /* The value of message_size at this point has been set to the data length, plus one for the blank line that notionally precedes the data. */ /* Now read the contents of the header file, which will set up the headers in store, and also the list of recipients and the tree of non-recipients and assorted flags. It updates message_size. If there is a reading or format error, give up; if the message has been around for sufficiently long, remove it. */ { uschar * spoolname = string_sprintf("%s-H", id); if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK) { if (errno == ERRNO_SPOOLFORMAT) { struct stat statbuf; if (Ustat(spool_fname(US"input", message_subdir, spoolname, US""), &statbuf) == 0) log_write(0, LOG_MAIN, "Format error in spool file %s: " "size=" OFF_T_FMT, spoolname, statbuf.st_size); else log_write(0, LOG_MAIN, "Format error in spool file %s", spoolname); } else log_write(0, LOG_MAIN, "Error reading spool file %s: %s", spoolname, strerror(errno)); /* If we managed to read the envelope data, received_time contains the time the message was received. Otherwise, we can calculate it from the message id. */ if (rc != spool_read_hdrerror) { received_time.tv_sec = received_time.tv_usec = 0; /*XXX subsec precision?*/ for (i = 0; i < 6; i++) received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0']; } /* If we've had this malformed message too long, sling it. */ if (now - received_time.tv_sec > keep_malformed) { Uunlink(spool_fname(US"msglog", message_subdir, id, US"")); Uunlink(spool_fname(US"input", message_subdir, id, US"-D")); Uunlink(spool_fname(US"input", message_subdir, id, US"-H")); Uunlink(spool_fname(US"input", message_subdir, id, US"-J")); log_write(0, LOG_MAIN, "Message removed because older than %s", readconf_printtime(keep_malformed)); } (void)close(deliver_datafile); deliver_datafile = -1; return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } } /* The spool header file has been read. Look to see if there is an existing journal file for this message. If there is, it means that a previous delivery attempt crashed (program or host) before it could update the spool header file. Read the list of delivered addresses from the journal and add them to the nonrecipients tree. Then update the spool file. We can leave the journal in existence, as it will get further successful deliveries added to it in this run, and it will be deleted if this function gets to its end successfully. Otherwise it might be needed again. */ { uschar * fname = spool_fname(US"input", message_subdir, id, US"-J"); FILE * jread; if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND #ifdef O_CLOEXEC | O_CLOEXEC #endif #ifdef O_NOFOLLOW | O_NOFOLLOW #endif , SPOOL_MODE)) >= 0 && lseek(journal_fd, 0, SEEK_SET) == 0 && (jread = fdopen(journal_fd, "rb")) ) { while (Ufgets(big_buffer, big_buffer_size, jread)) { int n = Ustrlen(big_buffer); big_buffer[n-1] = 0; tree_add_nonrecipient(big_buffer); DEBUG(D_deliver) debug_printf("Previously delivered address %s taken from " "journal file\n", big_buffer); } rewind(jread); if ((journal_fd = dup(fileno(jread))) < 0) journal_fd = fileno(jread); else (void) fclose(jread); /* Try to not leak the FILE resource */ /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } else if (errno != ENOENT) { log_write(0, LOG_MAIN|LOG_PANIC, "attempt to open journal for reading gave: " "%s", strerror(errno)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* A null recipients list indicates some kind of disaster. */ if (!recipients_list) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN, "Spool error: no recipients for %s", fname); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } } /* Handle a message that is frozen. There are a number of different things that can happen, but in the default situation, unless forced, no delivery is attempted. */ if (f.deliver_freeze) { #ifdef SUPPORT_MOVE_FROZEN_MESSAGES /* Moving to another directory removes the message from Exim's view. Other tools must be used to deal with it. Logging of this action happens in spool_move_message() and its subfunctions. */ if ( move_frozen_messages && spool_move_message(id, message_subdir, US"", US"F") ) return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ #endif /* For all frozen messages (bounces or not), timeout_frozen_after sets the maximum time to keep messages that are frozen. Thaw if we reach it, with a flag causing all recipients to be failed. The time is the age of the message, not the time since freezing. */ if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after) { log_write(0, LOG_MAIN, "cancelled by timeout_frozen_after"); process_recipients = RECIP_FAIL_TIMEOUT; } /* For bounce messages (and others with no sender), thaw if the error message ignore timer is exceeded. The message will be discarded if this delivery fails. */ else if (!*sender_address && message_age >= ignore_bounce_errors_after) log_write(0, LOG_MAIN, "Unfrozen by errmsg timer"); /* If this is a bounce message, or there's no auto thaw, or we haven't reached the auto thaw time yet, and this delivery is not forced by an admin user, do not attempt delivery of this message. Note that forced is set for continuing messages down the same channel, in order to skip load checking and ignore hold domains, but we don't want unfreezing in that case. */ else { if ( ( sender_address[0] == 0 || auto_thaw <= 0 || now <= deliver_frozen_at + auto_thaw ) && ( !forced || !f.deliver_force_thaw || !f.admin_user || continue_hostname ) ) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(L_skip_delivery, LOG_MAIN, "Message is frozen"); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* If delivery was forced (by an admin user), assume a manual thaw. Otherwise it's an auto thaw. */ if (forced) { f.deliver_manual_thaw = TRUE; log_write(0, LOG_MAIN, "Unfrozen by forced delivery"); } else log_write(0, LOG_MAIN, "Unfrozen by auto-thaw"); } /* We get here if any of the rules for unfreezing have triggered. */ f.deliver_freeze = FALSE; update_spool = TRUE; } /* Open the message log file if we are using them. This records details of deliveries, deferments, and failures for the benefit of the mail administrator. The log is not used by exim itself to track the progress of a message; that is done by rewriting the header spool file. */ if (message_logs) { uschar * fname = spool_fname(US"msglog", message_subdir, id, US""); uschar * error; int fd; if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't %s message log %s: %s", error, fname, strerror(errno)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* Make a C stream out of it. */ if (!(message_log = fdopen(fd, "a"))) { log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't fdopen message log %s: %s", fname, strerror(errno)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } } /* If asked to give up on a message, log who did it, and set the action for all the addresses. */ if (give_up) { struct passwd *pw = getpwuid(real_uid); log_write(0, LOG_MAIN, "cancelled by %s", pw ? US pw->pw_name : string_sprintf("uid %ld", (long int)real_uid)); process_recipients = RECIP_FAIL; } /* Otherwise, if there are too many Received: headers, fail all recipients. */ else if (received_count > received_headers_max) process_recipients = RECIP_FAIL_LOOP; /* Otherwise, if a system-wide, address-independent message filter is specified, run it now, except in the case when we are failing all recipients as a result of timeout_frozen_after. If the system filter yields "delivered", then ignore the true recipients of the message. Failure of the filter file is logged, and the delivery attempt fails. */ else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT) { int rc; int filtertype; ugid_block ugid; redirect_block redirect; if (system_filter_uid_set) { ugid.uid = system_filter_uid; ugid.gid = system_filter_gid; ugid.uid_set = ugid.gid_set = TRUE; } else { ugid.uid_set = ugid.gid_set = FALSE; } return_path = sender_address; f.enable_dollar_recipients = TRUE; /* Permit $recipients in system filter */ f.system_filtering = TRUE; /* Any error in the filter file causes a delivery to be abandoned. */ redirect.string = system_filter; redirect.isfile = TRUE; redirect.check_owner = redirect.check_group = FALSE; redirect.owners = NULL; redirect.owngroups = NULL; redirect.pw = NULL; redirect.modemask = 0; DEBUG(D_deliver|D_filter) debug_printf("running system filter\n"); rc = rda_interpret( &redirect, /* Where the data is */ RDO_DEFER | /* Turn on all the enabling options */ RDO_FAIL | /* Leave off all the disabling options */ RDO_FILTER | RDO_FREEZE | RDO_REALLOG | RDO_REWRITE, NULL, /* No :include: restriction (not used in filter) */ NULL, /* No sieve vacation directory (not sieve!) */ NULL, /* No sieve enotify mailto owner (not sieve!) */ NULL, /* No sieve user address (not sieve!) */ NULL, /* No sieve subaddress (not sieve!) */ &ugid, /* uid/gid data */ &addr_new, /* Where to hang generated addresses */ &filter_message, /* Where to put error message */ NULL, /* Don't skip syntax errors */ &filtertype, /* Will always be set to FILTER_EXIM for this call */ US"system filter"); /* For error messages */ DEBUG(D_deliver|D_filter) debug_printf("system filter returned %d\n", rc); if (rc == FF_ERROR || rc == FF_NONEXIST) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN|LOG_PANIC, "Error in system filter: %s", string_printing(filter_message)); return continue_closedown(); /* yields DELIVER_NOT_ATTEMPTED */ } /* Reset things. If the filter message is an empty string, which can happen for a filter "fail" or "freeze" command with no text, reset it to NULL. */ f.system_filtering = FALSE; f.enable_dollar_recipients = FALSE; if (filter_message && filter_message[0] == 0) filter_message = NULL; /* Save the values of the system filter variables so that user filters can use them. */ memcpy(filter_sn, filter_n, sizeof(filter_sn)); /* The filter can request that delivery of the original addresses be deferred. */ if (rc == FF_DEFER) { process_recipients = RECIP_DEFER; deliver_msglog("Delivery deferred by system filter\n"); log_write(0, LOG_MAIN, "Delivery deferred by system filter"); } /* The filter can request that a message be frozen, but this does not take place if the message has been manually thawed. In that case, we must unset "delivered", which is forced by the "freeze" command to make -bF work properly. */ else if (rc == FF_FREEZE && !f.deliver_manual_thaw) { f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); process_recipients = RECIP_DEFER; frozen_info = string_sprintf(" by the system filter%s%s", filter_message ? US": " : US"", filter_message ? filter_message : US""); } /* The filter can request that a message be failed. The error message may be quite long - it is sent back to the sender in the bounce - but we don't want to fill up the log with repetitions of it. If it starts with << then the text between << and >> is written to the log, with the rest left for the bounce message. */ else if (rc == FF_FAIL) { uschar *colon = US""; uschar *logmsg = US""; int loglen = 0; process_recipients = RECIP_FAIL_FILTER; if (filter_message) { uschar *logend; colon = US": "; if ( filter_message[0] == '<' && filter_message[1] == '<' && (logend = Ustrstr(filter_message, ">>")) ) { logmsg = filter_message + 2; loglen = logend - logmsg; filter_message = logend + 2; if (filter_message[0] == 0) filter_message = NULL; } else { logmsg = filter_message; loglen = Ustrlen(filter_message); } } log_write(0, LOG_MAIN, "cancelled by system filter%s%.*s", colon, loglen, logmsg); } /* Delivery can be restricted only to those recipients (if any) that the filter specified. */ else if (rc == FF_DELIVERED) { process_recipients = RECIP_IGNORE; if (addr_new) log_write(0, LOG_MAIN, "original recipients ignored (system filter)"); else log_write(0, LOG_MAIN, "=> discarded (system filter)"); } /* If any new addresses were created by the filter, fake up a "parent" for them. This is necessary for pipes, etc., which are expected to have parents, and it also gives some sensible logging for others. Allow pipes, files, and autoreplies, and run them as the filter uid if set, otherwise as the current uid. */ if (addr_new) { int uid = (system_filter_uid_set)? system_filter_uid : geteuid(); int gid = (system_filter_gid_set)? system_filter_gid : getegid(); /* The text "system-filter" is tested in transport_set_up_command() and in set_up_shell_command() in the pipe transport, to enable them to permit $recipients, so don't change it here without also changing it there. */ address_item *p = addr_new; address_item *parent = deliver_make_addr(US"system-filter", FALSE); parent->domain = string_copylc(qualify_domain_recipient); parent->local_part = US"system-filter"; /* As part of this loop, we arrange for addr_last to end up pointing at the final address. This is used if we go on to add addresses for the original recipients. */ while (p) { if (parent->child_count == USHRT_MAX) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "system filter generated more " "than %d delivery addresses", USHRT_MAX); parent->child_count++; p->parent = parent; if (testflag(p, af_pfr)) { uschar *tpname; uschar *type; p->uid = uid; p->gid = gid; setflag(p, af_uid_set); setflag(p, af_gid_set); setflag(p, af_allow_file); setflag(p, af_allow_pipe); setflag(p, af_allow_reply); /* Find the name of the system filter's appropriate pfr transport */ if (p->address[0] == '|') { type = US"pipe"; tpname = system_filter_pipe_transport; address_pipe = p->address; } else if (p->address[0] == '>') { type = US"reply"; tpname = system_filter_reply_transport; } else { if (p->address[Ustrlen(p->address)-1] == '/') { type = US"directory"; tpname = system_filter_directory_transport; } else { type = US"file"; tpname = system_filter_file_transport; } address_file = p->address; } /* Now find the actual transport, first expanding the name. We have set address_file or address_pipe above. */ if (tpname) { uschar *tmp = expand_string(tpname); address_file = address_pipe = NULL; if (!tmp) p->message = string_sprintf("failed to expand \"%s\" as a " "system filter transport name", tpname); tpname = tmp; } else p->message = string_sprintf("system_filter_%s_transport is unset", type); if (tpname) { transport_instance *tp; for (tp = transports; tp; tp = tp->next) if (Ustrcmp(tp->name, tpname) == 0) { p->transport = tp; break; } if (!tp) p->message = string_sprintf("failed to find \"%s\" transport " "for system filter delivery", tpname); } /* If we couldn't set up a transport, defer the delivery, putting the error on the panic log as well as the main log. */ if (!p->transport) { address_item *badp = p; p = p->next; if (!addr_last) addr_new = p; else addr_last->next = p; badp->local_part = badp->address; /* Needed for log line */ post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0); continue; } } /* End of pfr handling */ /* Either a non-pfr delivery, or we found a transport */ DEBUG(D_deliver|D_filter) debug_printf("system filter added %s\n", p->address); addr_last = p; p = p->next; } /* Loop through all addr_new addresses */ } } /* Scan the recipients list, and for every one that is not in the non- recipients tree, add an addr item to the chain of new addresses. If the pno value is non-negative, we must set the onetime parent from it. This which points to the relevant entry in the recipients list. This processing can be altered by the setting of the process_recipients variable, which is changed if recipients are to be ignored, failed, or deferred. This can happen as a result of system filter activity, or if the -Mg option is used to fail all of them. Duplicate addresses are handled later by a different tree structure; we can't just extend the non-recipients tree, because that will be re-written to the spool if the message is deferred, and in any case there are casing complications for local addresses. */ if (process_recipients != RECIP_IGNORE) for (i = 0; i < recipients_count; i++) if (!tree_search(tree_nonrecipients, recipients_list[i].address)) { recipient_item *r = recipients_list + i; address_item *new = deliver_make_addr(r->address, FALSE); new->prop.errors_address = r->errors_to; #ifdef SUPPORT_I18N if ((new->prop.utf8_msg = message_smtputf8)) { new->prop.utf8_downcvt = message_utf8_downconvert == 1; new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1; DEBUG(D_deliver) debug_printf("utf8, downconvert %s\n", new->prop.utf8_downcvt ? "yes" : new->prop.utf8_downcvt_maybe ? "ifneeded" : "no"); } #endif if (r->pno >= 0) new->onetime_parent = recipients_list[r->pno].address; /* If DSN support is enabled, set the dsn flags and the original receipt to be passed on to other DSN enabled MTAs */ new->dsn_flags = r->dsn_flags & rf_dsnflags; new->dsn_orcpt = r->orcpt; DEBUG(D_deliver) debug_printf("DSN: set orcpt: %s flags: %d\n", new->dsn_orcpt ? new->dsn_orcpt : US"", new->dsn_flags); switch (process_recipients) { /* RECIP_DEFER is set when a system filter freezes a message. */ case RECIP_DEFER: new->next = addr_defer; addr_defer = new; break; /* RECIP_FAIL_FILTER is set when a system filter has obeyed a "fail" command. */ case RECIP_FAIL_FILTER: new->message = filter_message ? filter_message : US"delivery cancelled"; setflag(new, af_pass_message); goto RECIP_QUEUE_FAILED; /* below */ /* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older than the value in timeout_frozen_after. Treat non-bounce messages similarly to -Mg; for bounce messages we just want to discard, so don't put the address on the failed list. The timeout has already been logged. */ case RECIP_FAIL_TIMEOUT: new->message = US"delivery cancelled; message timed out"; goto RECIP_QUEUE_FAILED; /* below */ /* RECIP_FAIL is set when -Mg has been used. */ case RECIP_FAIL: new->message = US"delivery cancelled by administrator"; /* Fall through */ /* Common code for the failure cases above. If this is not a bounce message, put the address on the failed list so that it is used to create a bounce. Otherwise do nothing - this just discards the address. The incident has already been logged. */ RECIP_QUEUE_FAILED: if (sender_address[0]) { new->next = addr_failed; addr_failed = new; } break; /* RECIP_FAIL_LOOP is set when there are too many Received: headers in the message. Process each address as a routing failure; if this is a bounce message, it will get frozen. */ case RECIP_FAIL_LOOP: new->message = US"Too many \"Received\" headers - suspected mail loop"; post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); break; /* Value should be RECIP_ACCEPT; take this as the safe default. */ default: if (!addr_new) addr_new = new; else addr_last->next = new; addr_last = new; break; } #ifndef DISABLE_EVENT if (process_recipients != RECIP_ACCEPT) { uschar * save_local = deliver_localpart; const uschar * save_domain = deliver_domain; deliver_localpart = expand_string( string_sprintf("${local_part:%s}", new->address)); deliver_domain = expand_string( string_sprintf("${domain:%s}", new->address)); (void) event_raise(event_action, US"msg:fail:internal", new->message); deliver_localpart = save_local; deliver_domain = save_domain; } #endif } DEBUG(D_deliver) { address_item *p; debug_printf("Delivery address list:\n"); for (p = addr_new; p; p = p->next) debug_printf(" %s %s\n", p->address, p->onetime_parent ? p->onetime_parent : US""); } /* Set up the buffers used for copying over the file when delivering. */ deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); /* Until there are no more new addresses, handle each one as follows: . If this is a generated address (indicated by the presence of a parent pointer) then check to see whether it is a pipe, file, or autoreply, and if so, handle it directly here. The router that produced the address will have set the allow flags into the address, and also set the uid/gid required. Having the routers generate new addresses and then checking them here at the outer level is tidier than making each router do the checking, and means that routers don't need access to the failed address queue. . Break up the address into local part and domain, and make lowercased versions of these strings. We also make unquoted versions of the local part. . Handle the percent hack for those domains for which it is valid. . For child addresses, determine if any of the parents have the same address. If so, generate a different string for previous delivery checking. Without this code, if the address spqr generates spqr via a forward or alias file, delivery of the generated spqr stops further attempts at the top level spqr, which is not what is wanted - it may have generated other addresses. . Check on the retry database to see if routing was previously deferred, but only if in a queue run. Addresses that are to be routed are put on the addr_route chain. Addresses that are to be deferred are put on the addr_defer chain. We do all the checking first, so as not to keep the retry database open any longer than necessary. . Now we run the addresses through the routers. A router may put the address on either the addr_local or the addr_remote chain for local or remote delivery, respectively, or put it on the addr_failed chain if it is undeliveable, or it may generate child addresses and put them on the addr_new chain, or it may defer an address. All the chain anchors are passed as arguments so that the routers can be called for verification purposes as well. . If new addresses have been generated by the routers, da capo. */ f.header_rewritten = FALSE; /* No headers rewritten yet */ while (addr_new) /* Loop until all addresses dealt with */ { address_item *addr, *parent; /* Failure to open the retry database is treated the same as if it does not exist. In both cases, dbm_file is NULL. */ if (!(dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE))) DEBUG(D_deliver|D_retry|D_route|D_hints_lookup) debug_printf("no retry data available\n"); /* Scan the current batch of new addresses, to handle pipes, files and autoreplies, and determine which others are ready for routing. */ while (addr_new) { int rc; uschar *p; tree_node *tnode; dbdata_retry *domain_retry_record; dbdata_retry *address_retry_record; addr = addr_new; addr_new = addr->next; DEBUG(D_deliver|D_retry|D_route) { debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); debug_printf("Considering: %s\n", addr->address); } /* Handle generated address that is a pipe or a file or an autoreply. */ if (testflag(addr, af_pfr)) { /* If an autoreply in a filter could not generate a syntactically valid address, give up forthwith. Set af_ignore_error so that we don't try to generate a bounce. */ if (testflag(addr, af_bad_reply)) { addr->basic_errno = ERRNO_BADADDRESS2; addr->local_part = addr->address; addr->message = US"filter autoreply generated syntactically invalid recipient"; addr->prop.ignore_error = TRUE; (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } /* If two different users specify delivery to the same pipe or file or autoreply, there should be two different deliveries, so build a unique string that incorporates the original address, and use this for duplicate testing and recording delivery, and also for retrying. */ addr->unique = string_sprintf("%s:%s", addr->address, addr->parent->unique + (testflag(addr->parent, af_homonym)? 3:0)); addr->address_retry_key = addr->domain_retry_key = string_sprintf("T:%s", addr->unique); /* If a filter file specifies two deliveries to the same pipe or file, we want to de-duplicate, but this is probably not wanted for two mail commands to the same address, where probably both should be delivered. So, we have to invent a different unique string in that case. Just keep piling '>' characters on the front. */ if (addr->address[0] == '>') { while (tree_search(tree_duplicates, addr->unique)) addr->unique = string_sprintf(">%s", addr->unique); } else if ((tnode = tree_search(tree_duplicates, addr->unique))) { DEBUG(D_deliver|D_route) debug_printf("%s is a duplicate address: discarded\n", addr->address); addr->dupof = tnode->data.ptr; addr->next = addr_duplicate; addr_duplicate = addr; continue; } DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique); /* Check for previous delivery */ if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: discarded\n", addr->address); child_done(addr, tod_stamp(tod_log)); continue; } /* Save for checking future duplicates */ tree_add_duplicate(addr->unique, addr); /* Set local part and domain */ addr->local_part = addr->address; addr->domain = addr->parent->domain; /* Ensure that the delivery is permitted. */ if (testflag(addr, af_file)) { if (!testflag(addr, af_allow_file)) { addr->basic_errno = ERRNO_FORBIDFILE; addr->message = US"delivery to file forbidden"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } } else if (addr->address[0] == '|') { if (!testflag(addr, af_allow_pipe)) { addr->basic_errno = ERRNO_FORBIDPIPE; addr->message = US"delivery to pipe forbidden"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } } else if (!testflag(addr, af_allow_reply)) { addr->basic_errno = ERRNO_FORBIDREPLY; addr->message = US"autoreply forbidden"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* with the next new address */ } /* If the errno field is already set to BADTRANSPORT, it indicates failure to expand a transport string, or find the associated transport, or an unset transport when one is required. Leave this test till now so that the forbid errors are given in preference. */ if (addr->basic_errno == ERRNO_BADTRANSPORT) { (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; } /* Treat /dev/null as a special case and abandon the delivery. This avoids having to specify a uid on the transport just for this case. Arrange for the transport name to be logged as "**bypassed**". */ if (Ustrcmp(addr->address, "/dev/null") == 0) { uschar *save = addr->transport->name; addr->transport->name = US"**bypassed**"; (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '='); addr->transport->name = save; continue; /* with the next new address */ } /* Pipe, file, or autoreply delivery is to go ahead as a normal local delivery. */ DEBUG(D_deliver|D_route) debug_printf("queued for %s transport\n", addr->transport->name); addr->next = addr_local; addr_local = addr; continue; /* with the next new address */ } /* Handle normal addresses. First, split up into local part and domain, handling the %-hack if necessary. There is the possibility of a defer from a lookup in percent_hack_domains. */ if ((rc = deliver_split_address(addr)) == DEFER) { addr->message = US"cannot check percent_hack_domains"; addr->basic_errno = ERRNO_LISTDEFER; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } /* Check to see if the domain is held. If so, proceed only if the delivery was forced by hand. */ deliver_domain = addr->domain; /* set $domain */ if ( !forced && hold_domains && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != FAIL ) { if (rc == DEFER) { addr->message = US"hold_domains lookup deferred"; addr->basic_errno = ERRNO_LISTDEFER; } else { addr->message = US"domain is held"; addr->basic_errno = ERRNO_HELD; } (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } /* Now we can check for duplicates and previously delivered addresses. In order to do this, we have to generate a "unique" value for each address, because there may be identical actual addresses in a line of descendents. The "unique" field is initialized to the same value as the "address" field, but gets changed here to cope with identically-named descendents. */ for (parent = addr->parent; parent; parent = parent->parent) if (strcmpic(addr->address, parent->address) == 0) break; /* If there's an ancestor with the same name, set the homonym flag. This influences how deliveries are recorded. Then add a prefix on the front of the unique address. We use \n\ where n starts at 0 and increases each time. It is unlikely to pass 9, but if it does, it may look odd but will still work. This means that siblings or cousins with the same names are treated as duplicates, which is what we want. */ if (parent) { setflag(addr, af_homonym); if (parent->unique[0] != '\\') addr->unique = string_sprintf("\\0\\%s", addr->address); else addr->unique = string_sprintf("\\%c\\%s", parent->unique[1] + 1, addr->address); } /* Ensure that the domain in the unique field is lower cased, because domains are always handled caselessly. */ p = Ustrrchr(addr->unique, '@'); while (*p != 0) { *p = tolower(*p); p++; } DEBUG(D_deliver|D_route) debug_printf("unique = %s\n", addr->unique); if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: discarded\n", addr->unique); child_done(addr, tod_stamp(tod_log)); continue; } /* Get the routing retry status, saving the two retry keys (with and without the local part) for subsequent use. If there is no retry record for the standard address routing retry key, we look for the same key with the sender attached, because this form is used by the smtp transport after a 4xx response to RCPT when address_retry_include_sender is true. */ addr->domain_retry_key = string_sprintf("R:%s", addr->domain); addr->address_retry_key = string_sprintf("R:%s@%s", addr->local_part, addr->domain); if (dbm_file) { domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key); if ( domain_retry_record && now - domain_retry_record->time_stamp > retry_data_expire ) domain_retry_record = NULL; /* Ignore if too old */ address_retry_record = dbfn_read(dbm_file, addr->address_retry_key); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire ) address_retry_record = NULL; /* Ignore if too old */ if (!address_retry_record) { uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key, sender_address); address_retry_record = dbfn_read(dbm_file, altkey); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire) address_retry_record = NULL; /* Ignore if too old */ } } else domain_retry_record = address_retry_record = NULL; DEBUG(D_deliver|D_retry) { if (!domain_retry_record) debug_printf("no domain retry record\n"); if (!address_retry_record) debug_printf("no address retry record\n"); } /* If we are sending a message down an existing SMTP connection, we must assume that the message which created the connection managed to route an address to that connection. We do not want to run the risk of taking a long time over routing here, because if we do, the server at the other end of the connection may time it out. This is especially true for messages with lots of addresses. For this kind of delivery, queue_running is not set, so we would normally route all addresses. We take a pragmatic approach and defer routing any addresses that have any kind of domain retry record. That is, we don't even look at their retry times. It doesn't matter if this doesn't work occasionally. This is all just an optimization, after all. The reason for not doing the same for address retries is that they normally arise from 4xx responses, not DNS timeouts. */ if (continue_hostname && domain_retry_record) { addr->message = US"reusing SMTP connection skips previous routing defer"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } /* If we are in a queue run, defer routing unless there is no retry data or we've passed the next retry time, or this message is forced. In other words, ignore retry data when not in a queue run. However, if the domain retry time has expired, always allow the routing attempt. If it fails again, the address will be failed. This ensures that each address is routed at least once, even after long-term routing failures. If there is an address retry, check that too; just wait for the next retry time. This helps with the case when the temporary error on the address was really message-specific rather than address specific, since it allows other messages through. We also wait for the next retry time if this is a message sent down an existing SMTP connection (even though that will be forced). Otherwise there will be far too many attempts for an address that gets a 4xx error. In fact, after such an error, we should not get here because, the host should not be remembered as one this message needs. However, there was a bug that used to cause this to happen, so it is best to be on the safe side. Even if we haven't reached the retry time in the hints, there is one more check to do, which is for the ultimate address timeout. We only do this check if there is an address retry record and there is not a domain retry record; this implies that previous attempts to handle the address had the retry_use_local_parts option turned on. We use this as an approximation for the destination being like a local delivery, for example delivery over LMTP to an IMAP message store. In this situation users are liable to bump into their quota and thereby have intermittently successful deliveries, which keep the retry record fresh, which can lead to us perpetually deferring messages. */ else if ( ( f.queue_running && !f.deliver_force || continue_hostname ) && ( ( domain_retry_record && now < domain_retry_record->next_try && !domain_retry_record->expired ) || ( address_retry_record && now < address_retry_record->next_try ) ) && ( domain_retry_record || !address_retry_record || !retry_ultimate_address_timeout(addr->address_retry_key, addr->domain, address_retry_record, now) ) ) { addr->message = US"retry time not reached"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } /* The domain is OK for routing. Remember if retry data exists so it can be cleaned up after a successful delivery. */ else { if (domain_retry_record || address_retry_record) setflag(addr, af_dr_retry_exists); addr->next = addr_route; addr_route = addr; DEBUG(D_deliver|D_route) debug_printf("%s: queued for routing\n", addr->address); } } /* The database is closed while routing is actually happening. Requests to update it are put on a chain and all processed together at the end. */ if (dbm_file) dbfn_close(dbm_file); /* If queue_domains is set, we don't even want to try routing addresses in those domains. During queue runs, queue_domains is forced to be unset. Optimize by skipping this pass through the addresses if nothing is set. */ if (!f.deliver_force && queue_domains) { address_item *okaddr = NULL; while (addr_route) { address_item *addr = addr_route; addr_route = addr->next; deliver_domain = addr->domain; /* set $domain */ if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != OK) if (rc == DEFER) { addr->basic_errno = ERRNO_LISTDEFER; addr->message = US"queue_domains lookup deferred"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } else { addr->next = okaddr; okaddr = addr; } else { addr->basic_errno = ERRNO_QUEUE_DOMAIN; addr->message = US"domain is in queue_domains"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } } addr_route = okaddr; } /* Now route those addresses that are not deferred. */ while (addr_route) { int rc; address_item *addr = addr_route; const uschar *old_domain = addr->domain; uschar *old_unique = addr->unique; addr_route = addr->next; addr->next = NULL; /* Just in case some router parameter refers to it. */ if (!(return_path = addr->prop.errors_address)) return_path = sender_address; /* If a router defers an address, add a retry item. Whether or not to use the local part in the key is a property of the router. */ if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new, &addr_succeed, v_none)) == DEFER) retry_add_item(addr, addr->router->retry_use_local_part ? string_sprintf("R:%s@%s", addr->local_part, addr->domain) : string_sprintf("R:%s", addr->domain), 0); /* Otherwise, if there is an existing retry record in the database, add retry items to delete both forms. We must also allow for the possibility of a routing retry that includes the sender address. Since the domain might have been rewritten (expanded to fully qualified) as a result of routing, ensure that the rewritten form is also deleted. */ else if (testflag(addr, af_dr_retry_exists)) { uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key, sender_address); retry_add_item(addr, altkey, rf_delete); retry_add_item(addr, addr->address_retry_key, rf_delete); retry_add_item(addr, addr->domain_retry_key, rf_delete); if (Ustrcmp(addr->domain, old_domain) != 0) retry_add_item(addr, string_sprintf("R:%s", old_domain), rf_delete); } /* DISCARD is given for :blackhole: and "seen finish". The event has been logged, but we need to ensure the address (and maybe parents) is marked done. */ if (rc == DISCARD) { address_done(addr, tod_stamp(tod_log)); continue; /* route next address */ } /* The address is finished with (failed or deferred). */ if (rc != OK) { (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; /* route next address */ } /* The address has been routed. If the router changed the domain, it will also have changed the unique address. We have to test whether this address has already been delivered, because it's the unique address that finally gets recorded. */ if ( addr->unique != old_unique && tree_search(tree_nonrecipients, addr->unique) != 0 ) { DEBUG(D_deliver|D_route) debug_printf("%s was previously delivered: " "discarded\n", addr->address); if (addr_remote == addr) addr_remote = addr->next; else if (addr_local == addr) addr_local = addr->next; } /* If the router has same_domain_copy_routing set, we are permitted to copy the routing for any other addresses with the same domain. This is an optimisation to save repeated DNS lookups for "standard" remote domain routing. The option is settable only on routers that generate host lists. We play it very safe, and do the optimization only if the address is routed to a remote transport, there are no header changes, and the domain was not modified by the router. */ if ( addr_remote == addr && addr->router->same_domain_copy_routing && !addr->prop.extra_headers && !addr->prop.remove_headers && old_domain == addr->domain ) { address_item **chain = &addr_route; while (*chain) { address_item *addr2 = *chain; if (Ustrcmp(addr2->domain, addr->domain) != 0) { chain = &(addr2->next); continue; } /* Found a suitable address; take it off the routing list and add it to the remote delivery list. */ *chain = addr2->next; addr2->next = addr_remote; addr_remote = addr2; /* Copy the routing data */ addr2->domain = addr->domain; addr2->router = addr->router; addr2->transport = addr->transport; addr2->host_list = addr->host_list; addr2->fallback_hosts = addr->fallback_hosts; addr2->prop.errors_address = addr->prop.errors_address; copyflag(addr2, addr, af_hide_child); copyflag(addr2, addr, af_local_host_removed); DEBUG(D_deliver|D_route) debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" "routing %s\n" "Routing for %s copied from %s\n", addr2->address, addr2->address, addr->address); } } } /* Continue with routing the next address. */ } /* Loop to process any child addresses that the routers created, and any rerouted addresses that got put back on the new chain. */ /* Debugging: show the results of the routing */ DEBUG(D_deliver|D_retry|D_route) { address_item *p; debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); debug_printf("After routing:\n Local deliveries:\n"); for (p = addr_local; p; p = p->next) debug_printf(" %s\n", p->address); debug_printf(" Remote deliveries:\n"); for (p = addr_remote; p; p = p->next) debug_printf(" %s\n", p->address); debug_printf(" Failed addresses:\n"); for (p = addr_failed; p; p = p->next) debug_printf(" %s\n", p->address); debug_printf(" Deferred addresses:\n"); for (p = addr_defer; p; p = p->next) debug_printf(" %s\n", p->address); } /* Free any resources that were cached during routing. */ search_tidyup(); route_tidyup(); /* These two variables are set only during routing, after check_local_user. Ensure they are not set in transports. */ local_user_gid = (gid_t)(-1); local_user_uid = (uid_t)(-1); /* Check for any duplicate addresses. This check is delayed until after routing, because the flexibility of the routing configuration means that identical addresses with different parentage may end up being redirected to different addresses. Checking for duplicates too early (as we previously used to) makes this kind of thing not work. */ do_duplicate_check(&addr_local); do_duplicate_check(&addr_remote); /* When acting as an MUA wrapper, we proceed only if all addresses route to a remote transport. The check that they all end up in one transaction happens in the do_remote_deliveries() function. */ if ( mua_wrapper && (addr_local || addr_failed || addr_defer) ) { address_item *addr; uschar *which, *colon, *msg; if (addr_local) { addr = addr_local; which = US"local"; } else if (addr_defer) { addr = addr_defer; which = US"deferred"; } else { addr = addr_failed; which = US"failed"; } while (addr->parent) addr = addr->parent; if (addr->message) { colon = US": "; msg = addr->message; } else colon = msg = US""; /* We don't need to log here for a forced failure as it will already have been logged. Defer will also have been logged, but as a defer, so we do need to do the failure logging. */ if (addr != addr_failed) log_write(0, LOG_MAIN, "** %s routing yielded a %s delivery", addr->address, which); /* Always write an error to the caller */ fprintf(stderr, "routing %s yielded a %s delivery%s%s\n", addr->address, which, colon, msg); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; /* So that we remove the message */ goto DELIVERY_TIDYUP; } /* If this is a run to continue deliveries to an external channel that is already set up, defer any local deliveries. */ if (continue_transport) { if (addr_defer) { address_item *addr = addr_defer; while (addr->next) addr = addr->next; addr->next = addr_local; } else addr_defer = addr_local; addr_local = NULL; } /* Because address rewriting can happen in the routers, we should not really do ANY deliveries until all addresses have been routed, so that all recipients of the message get the same headers. However, this is in practice not always possible, since sometimes remote addresses give DNS timeouts for days on end. The pragmatic approach is to deliver what we can now, saving any rewritten headers so that at least the next lot of recipients benefit from the rewriting that has already been done. If any headers have been rewritten during routing, update the spool file to remember them for all subsequent deliveries. This can be delayed till later if there is only address to be delivered - if it succeeds the spool write need not happen. */ if ( f.header_rewritten && ( addr_local && (addr_local->next || addr_remote) || addr_remote && addr_remote->next ) ) { /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); f.header_rewritten = FALSE; } /* If there are any deliveries to be and we do not already have the journal file, create it. This is used to record successful deliveries as soon as possible after each delivery is known to be complete. A file opened with O_APPEND is used so that several processes can run simultaneously. The journal is just insurance against crashes. When the spool file is ultimately updated at the end of processing, the journal is deleted. If a journal is found to exist at the start of delivery, the addresses listed therein are added to the non-recipients. */ if (addr_local || addr_remote) { if (journal_fd < 0) { uschar * fname = spool_fname(US"input", message_subdir, id, US"-J"); if ((journal_fd = Uopen(fname, #ifdef O_CLOEXEC O_CLOEXEC | #endif O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't open journal file %s: %s", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } /* Set the close-on-exec flag, make the file owned by Exim, and ensure that the mode is correct - the group setting doesn't always seem to get set automatically. */ if( fchown(journal_fd, exim_uid, exim_gid) || fchmod(journal_fd, SPOOL_MODE) #ifndef O_CLOEXEC || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC) #endif ) { int ret = Uunlink(fname); log_write(0, LOG_MAIN|LOG_PANIC, "Couldn't set perms on journal file %s: %s", fname, strerror(errno)); if(ret && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } } } else if (journal_fd >= 0) { close(journal_fd); journal_fd = -1; } /* Now we can get down to the business of actually doing deliveries. Local deliveries are done first, then remote ones. If ever the problems of how to handle fallback transports are figured out, this section can be put into a loop for handling fallbacks, though the uid switching will have to be revised. */ /* Precompile a regex that is used to recognize a parameter in response to an LHLO command, if is isn't already compiled. This may be used on both local and remote LMTP deliveries. */ if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA = regex_must_compile(US"\\n250[\\s\\-]IGNOREQUOTA(\\s|\\n|$)", FALSE, TRUE); /* Handle local deliveries */ if (addr_local) { DEBUG(D_deliver|D_transport) debug_printf(">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\n"); do_local_deliveries(); f.disable_logging = FALSE; } /* If queue_run_local is set, we do not want to attempt any remote deliveries, so just queue them all. */ if (f.queue_run_local) while (addr_remote) { address_item *addr = addr_remote; addr_remote = addr->next; addr->next = NULL; addr->basic_errno = ERRNO_LOCAL_ONLY; addr->message = US"remote deliveries suppressed"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0); } /* Handle remote deliveries */ if (addr_remote) { DEBUG(D_deliver|D_transport) debug_printf(">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\n"); /* Precompile some regex that are used to recognize parameters in response to an EHLO command, if they aren't already compiled. */ deliver_init(); /* Now sort the addresses if required, and do the deliveries. The yield of do_remote_deliveries is FALSE when mua_wrapper is set and all addresses cannot be delivered in one transaction. */ if (remote_sort_domains) sort_remote_deliveries(); if (!do_remote_deliveries(FALSE)) { log_write(0, LOG_MAIN, "** mua_wrapper is set but recipients cannot all " "be delivered in one transaction"); fprintf(stderr, "delivery to smarthost failed (configuration problem)\n"); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; /* So that we remove the message */ goto DELIVERY_TIDYUP; } /* See if any of the addresses that failed got put on the queue for delivery to their fallback hosts. We do it this way because often the same fallback host is used for many domains, so all can be sent in a single transaction (if appropriately configured). */ if (addr_fallback && !mua_wrapper) { DEBUG(D_deliver) debug_printf("Delivering to fallback hosts\n"); addr_remote = addr_fallback; addr_fallback = NULL; if (remote_sort_domains) sort_remote_deliveries(); do_remote_deliveries(TRUE); } f.disable_logging = FALSE; } /* All deliveries are now complete. Ignore SIGTERM during this tidying up phase, to minimize cases of half-done things. */ DEBUG(D_deliver) debug_printf(">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\n"); cancel_cutthrough_connection(TRUE, US"deliveries are done"); /* Root privilege is no longer needed */ exim_setugid(exim_uid, exim_gid, FALSE, US"post-delivery tidying"); set_process_info("tidying up after delivering %s", message_id); signal(SIGTERM, SIG_IGN); /* When we are acting as an MUA wrapper, the smtp transport will either have succeeded for all addresses, or failed them all in normal cases. However, there are some setup situations (e.g. when a named port does not exist) that cause an immediate exit with deferral of all addresses. Convert those into failures. We do not ever want to retry, nor do we want to send a bounce message. */ if (mua_wrapper) { if (addr_defer) { address_item *addr, *nextaddr; for (addr = addr_defer; addr; addr = nextaddr) { log_write(0, LOG_MAIN, "** %s mua_wrapper forced failure for deferred " "delivery", addr->address); nextaddr = addr->next; addr->next = addr_failed; addr_failed = addr; } addr_defer = NULL; } /* Now all should either have succeeded or failed. */ if (!addr_failed) final_yield = DELIVER_MUA_SUCCEEDED; else { host_item * host; uschar *s = addr_failed->user_message; if (!s) s = addr_failed->message; fprintf(stderr, "Delivery failed: "); if (addr_failed->basic_errno > 0) { fprintf(stderr, "%s", strerror(addr_failed->basic_errno)); if (s) fprintf(stderr, ": "); } if ((host = addr_failed->host_used)) fprintf(stderr, "H=%s [%s]: ", host->name, host->address); if (s) fprintf(stderr, "%s", CS s); else if (addr_failed->basic_errno <= 0) fprintf(stderr, "unknown error"); fprintf(stderr, "\n"); final_yield = DELIVER_MUA_FAILED; addr_failed = NULL; } } /* In a normal configuration, we now update the retry database. This is done in one fell swoop at the end in order not to keep opening and closing (and locking) the database. The code for handling retries is hived off into a separate module for convenience. We pass it the addresses of the various chains, because deferred addresses can get moved onto the failed chain if the retry cutoff time has expired for all alternative destinations. Bypass the updating of the database if the -N flag is set, which is a debugging thing that prevents actual delivery. */ else if (!f.dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed); /* Send DSN for successful messages if requested */ addr_senddsn = NULL; for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { /* af_ignore_error not honored here. it's not an error */ DEBUG(D_deliver) debug_printf("DSN: processing router : %s\n" "DSN: processing successful delivery address: %s\n" "DSN: Sender_address: %s\n" "DSN: orcpt: %s flags: %d\n" "DSN: envid: %s ret: %d\n" "DSN: Final recipient: %s\n" "DSN: Remote SMTP server supports DSN: %d\n", addr_dsntmp->router ? addr_dsntmp->router->name : US"(unknown)", addr_dsntmp->address, sender_address, addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US"NULL", addr_dsntmp->dsn_flags, dsn_envid ? dsn_envid : US"NULL", dsn_ret, addr_dsntmp->address, addr_dsntmp->dsn_aware ); /* send report if next hop not DSN aware or a router flagged "last DSN hop" and a report was requested */ if ( ( addr_dsntmp->dsn_aware != dsn_support_yes || addr_dsntmp->dsn_flags & rf_dsnlasthop ) && addr_dsntmp->dsn_flags & rf_dsnflags && addr_dsntmp->dsn_flags & rf_notify_success ) { /* copy and relink address_item and send report with all of them at once later */ address_item * addr_next = addr_senddsn; addr_senddsn = store_get(sizeof(address_item)); *addr_senddsn = *addr_dsntmp; addr_senddsn->next = addr_next; } else DEBUG(D_deliver) debug_printf("DSN: not sending DSN success message\n"); } if (addr_senddsn) { pid_t pid; int fd; /* create exim process to send message */ pid = child_open_exim(&fd); DEBUG(D_deliver) debug_printf("DSN: child_open_exim returns: %d\n", pid); if (pid < 0) /* Creation of child failed */ { log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Process %d (parent %d) failed to " "create child process to send failure message: %s", getpid(), getppid(), strerror(errno)); DEBUG(D_deliver) debug_printf("DSN: child_open_exim failed\n"); } else /* Creation of child succeeded */ { FILE *f = fdopen(fd, "wb"); /* header only as required by RFC. only failure DSN needs to honor RET=FULL */ uschar * bound; transport_ctx tctx = {{0}}; DEBUG(D_deliver) debug_printf("sending error message to: %s\n", sender_address); /* build unique id for MIME boundary */ bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand()); DEBUG(D_deliver) debug_printf("DSN: MIME boundary: %s\n", bound); if (errors_reply_to) fprintf(f, "Reply-To: %s\n", errors_reply_to); fprintf(f, "Auto-Submitted: auto-generated\n" "From: Mail Delivery System <Mailer-Daemon@%s>\n" "To: %s\n" "Subject: Delivery Status Notification\n" "Content-Type: multipart/report; report-type=delivery-status; boundary=%s\n" "MIME-Version: 1.0\n\n" "--%s\n" "Content-type: text/plain; charset=us-ascii\n\n" "This message was created automatically by mail delivery software.\n" " ----- The following addresses had successful delivery notifications -----\n", qualify_domain_sender, sender_address, bound, bound); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) fprintf(f, "<%s> (relayed %s)\n\n", addr_dsntmp->address, (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? "via non DSN router" : addr_dsntmp->dsn_aware == dsn_support_no ? "to non-DSN-aware mailer" : "via non \"Remote SMTP\" router" ); fprintf(f, "--%s\n" "Content-type: message/delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); if (dsn_envid) { /* must be decoded from xtext: see RFC 3461:6.3a */ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, "Original-Envelope-ID: %s\n", dsn_envid); else fprintf(f, "X-Original-Envelope-ID: error decoding xtext formatted ENVID\n"); } fputc('\n', f); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { if (addr_dsntmp->dsn_orcpt) fprintf(f,"Original-Recipient: %s\n", addr_dsntmp->dsn_orcpt); fprintf(f, "Action: delivered\n" "Final-Recipient: rfc822;%s\n" "Status: 2.0.0\n", addr_dsntmp->address); if (addr_dsntmp->host_used && addr_dsntmp->host_used->name) fprintf(f, "Remote-MTA: dns; %s\nDiagnostic-Code: smtp; 250 Ok\n\n", addr_dsntmp->host_used->name); else fprintf(f, "Diagnostic-Code: X-Exim; relayed via non %s router\n\n", (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? "DSN" : "SMTP"); } fprintf(f, "--%s\nContent-type: text/rfc822-headers\n\n", bound); fflush(f); transport_filter_argv = NULL; /* Just in case */ return_path = sender_address; /* In case not previously set */ /* Write the original email out */ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_write_message(&tctx, 0); fflush(f); fprintf(f,"\n--%s--\n", bound); fflush(f); fclose(f); rc = child_close(pid, 0); /* Waits for child to close, no timeout */ } } /* If any addresses failed, we must send a message to somebody, unless af_ignore_error is set, in which case no action is taken. It is possible for several messages to get sent if there are addresses with different requirements. */ while (addr_failed) { pid_t pid; int fd; uschar *logtod = tod_stamp(tod_log); address_item *addr; address_item *handled_addr = NULL; address_item **paddr; address_item *msgchain = NULL; address_item **pmsgchain = &msgchain; /* There are weird cases when logging is disabled in the transport. However, there may not be a transport (address failed by a router). */ f.disable_logging = FALSE; if (addr_failed->transport) f.disable_logging = addr_failed->transport->disable_logging; DEBUG(D_deliver) debug_printf("processing failed address %s\n", addr_failed->address); /* There are only two ways an address in a bounce message can get here: (1) When delivery was initially deferred, but has now timed out (in the call to retry_update() above). We can detect this by testing for af_retry_timedout. If the address does not have its own errors address, we arrange to ignore the error. (2) If delivery failures for bounce messages are being ignored. We can detect this by testing for af_ignore_error. This will also be set if a bounce message has been autothawed and the ignore_bounce_errors_after time has passed. It might also be set if a router was explicitly configured to ignore errors (errors_to = ""). If neither of these cases obtains, something has gone wrong. Log the incident, but then ignore the error. */ if (sender_address[0] == 0 && !addr_failed->prop.errors_address) { if ( !testflag(addr_failed, af_retry_timedout) && !addr_failed->prop.ignore_error) log_write(0, LOG_MAIN|LOG_PANIC, "internal error: bounce message " "failure is neither frozen nor ignored (it's been ignored)"); addr_failed->prop.ignore_error = TRUE; } /* If the first address on the list has af_ignore_error set, just remove it from the list, throw away any saved message file, log it, and mark the recipient done. */ if ( addr_failed->prop.ignore_error || ( addr_failed->dsn_flags & rf_dsnflags && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure ) ) { addr = addr_failed; addr_failed = addr->next; if (addr->return_filename) Uunlink(addr->return_filename); log_write(0, LOG_MAIN, "%s%s%s%s: error ignored", addr->address, !addr->parent ? US"" : US" <", !addr->parent ? US"" : addr->parent->address, !addr->parent ? US"" : US">"); address_done(addr, logtod); child_done(addr, logtod); /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } /* Otherwise, handle the sending of a message. Find the error address for the first address, then send a message that includes all failed addresses that have the same error address. Note the bounce_recipient is a global so that it can be accessed by $bounce_recipient while creating a customized error message. */ else { if (!(bounce_recipient = addr_failed->prop.errors_address)) bounce_recipient = sender_address; /* Make a subprocess to send a message */ if ((pid = child_open_exim(&fd)) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Process %d (parent %d) failed to " "create child process to send failure message: %s", getpid(), getppid(), strerror(errno)); /* Creation of child succeeded */ else { int ch, rc; int filecount = 0; int rcount = 0; uschar *bcc, *emf_text; FILE * fp = fdopen(fd, "wb"); FILE * emf = NULL; BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0; int max = (bounce_return_size_limit/DELIVER_IN_BUFFER_SIZE + 1) * DELIVER_IN_BUFFER_SIZE; uschar * bound; uschar *dsnlimitmsg; uschar *dsnnotifyhdr; int topt; DEBUG(D_deliver) debug_printf("sending error message to: %s\n", bounce_recipient); /* Scan the addresses for all that have the same errors address, removing them from the addr_failed chain, and putting them on msgchain. */ paddr = &addr_failed; for (addr = addr_failed; addr; addr = *paddr) if (Ustrcmp(bounce_recipient, addr->prop.errors_address ? addr->prop.errors_address : sender_address) == 0) { /* The same - dechain */ *paddr = addr->next; *pmsgchain = addr; addr->next = NULL; pmsgchain = &(addr->next); } else paddr = &addr->next; /* Not the same; skip */ /* Include X-Failed-Recipients: for automatic interpretation, but do not let any one header line get too long. We do this by starting a new header every 50 recipients. Omit any addresses for which the "hide_child" flag is set. */ for (addr = msgchain; addr; addr = addr->next) { if (testflag(addr, af_hide_child)) continue; if (rcount >= 50) { fprintf(fp, "\n"); rcount = 0; } fprintf(fp, "%s%s", rcount++ == 0 ? "X-Failed-Recipients: " : ",\n ", testflag(addr, af_pfr) && addr->parent ? string_printing(addr->parent->address) : string_printing(addr->address)); } if (rcount > 0) fprintf(fp, "\n"); /* Output the standard headers */ if (errors_reply_to) fprintf(fp, "Reply-To: %s\n", errors_reply_to); fprintf(fp, "Auto-Submitted: auto-replied\n"); moan_write_from(fp); fprintf(fp, "To: %s\n", bounce_recipient); /* generate boundary string and output MIME-Headers */ bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand()); fprintf(fp, "Content-Type: multipart/report;" " report-type=delivery-status; boundary=%s\n" "MIME-Version: 1.0\n", bound); /* Open a template file if one is provided. Log failure to open, but carry on - default texts will be used. */ if (bounce_message_file) if (!(emf = Ufopen(bounce_message_file, "rb"))) log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for error " "message texts: %s", bounce_message_file, strerror(errno)); /* Quietly copy to configured additional addresses if required. */ if ((bcc = moan_check_errorcopy(bounce_recipient))) fprintf(fp, "Bcc: %s\n", bcc); /* The texts for the message can be read from a template file; if there isn't one, or if it is too short, built-in texts are used. The first emf text is a Subject: and any other headers. */ if ((emf_text = next_emf(emf, US"header"))) fprintf(fp, "%s\n", emf_text); else fprintf(fp, "Subject: Mail delivery failed%s\n\n", to_sender? ": returning message to sender" : ""); /* output human readable part as text/plain section */ fprintf(fp, "--%s\n" "Content-type: text/plain; charset=us-ascii\n\n", bound); if ((emf_text = next_emf(emf, US"intro"))) fprintf(fp, "%s", CS emf_text); else { fprintf(fp, /* This message has been reworded several times. It seems to be confusing to somebody, however it is worded. I have retreated to the original, simple wording. */ "This message was created automatically by mail delivery software.\n"); if (bounce_message_text) fprintf(fp, "%s", CS bounce_message_text); if (to_sender) fprintf(fp, "\nA message that you sent could not be delivered to one or more of its\n" "recipients. This is a permanent error. The following address(es) failed:\n"); else fprintf(fp, "\nA message sent by\n\n <%s>\n\n" "could not be delivered to one or more of its recipients. The following\n" "address(es) failed:\n", sender_address); } fputc('\n', fp); /* Process the addresses, leaving them on the msgchain if they have a file name for a return message. (There has already been a check in post_process_one() for the existence of data in the message file.) A TRUE return from print_address_information() means that the address is not hidden. */ paddr = &msgchain; for (addr = msgchain; addr; addr = *paddr) { if (print_address_information(addr, fp, US" ", US"\n ", US"")) print_address_error(addr, fp, US""); /* End the final line for the address */ fputc('\n', fp); /* Leave on msgchain if there's a return file. */ if (addr->return_file >= 0) { paddr = &(addr->next); filecount++; } /* Else save so that we can tick off the recipient when the message is sent. */ else { *paddr = addr->next; addr->next = handled_addr; handled_addr = addr; } } fputc('\n', fp); /* Get the next text, whether we need it or not, so as to be positioned for the one after. */ emf_text = next_emf(emf, US"generated text"); /* If there were any file messages passed by the local transports, include them in the message. Then put the address on the handled chain. In the case of a batch of addresses that were all sent to the same transport, the return_file field in all of them will contain the same fd, and the return_filename field in the *last* one will be set (to the name of the file). */ if (msgchain) { address_item *nextaddr; if (emf_text) fprintf(fp, "%s", CS emf_text); else fprintf(fp, "The following text was generated during the delivery " "attempt%s:\n", (filecount > 1)? "s" : ""); for (addr = msgchain; addr; addr = nextaddr) { FILE *fm; address_item *topaddr = addr; /* List all the addresses that relate to this file */ fputc('\n', fp); while(addr) /* Insurance */ { print_address_information(addr, fp, US"------ ", US"\n ", US" ------\n"); if (addr->return_filename) break; addr = addr->next; } fputc('\n', fp); /* Now copy the file */ if (!(fm = Ufopen(addr->return_filename, "rb"))) fprintf(fp, " +++ Exim error... failed to open text file: %s\n", strerror(errno)); else { while ((ch = fgetc(fm)) != EOF) fputc(ch, fp); (void)fclose(fm); } Uunlink(addr->return_filename); /* Can now add to handled chain, first fishing off the next address on the msgchain. */ nextaddr = addr->next; addr->next = handled_addr; handled_addr = topaddr; } fputc('\n', fp); } /* output machine readable part */ #ifdef SUPPORT_I18N if (message_smtputf8) fprintf(fp, "--%s\n" "Content-type: message/global-delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); else #endif fprintf(fp, "--%s\n" "Content-type: message/delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); if (dsn_envid) { /* must be decoded from xtext: see RFC 3461:6.3a */ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(fp, "Original-Envelope-ID: %s\n", dsn_envid); else fprintf(fp, "X-Original-Envelope-ID: error decoding xtext formatted ENVID\n"); } fputc('\n', fp); for (addr = handled_addr; addr; addr = addr->next) { host_item * hu; fprintf(fp, "Action: failed\n" "Final-Recipient: rfc822;%s\n" "Status: 5.0.0\n", addr->address); if ((hu = addr->host_used) && hu->name) { fprintf(fp, "Remote-MTA: dns; %s\n", hu->name); #ifdef EXPERIMENTAL_DSN_INFO { const uschar * s; if (hu->address) { uschar * p = hu->port == 25 ? US"" : string_sprintf(":%d", hu->port); fprintf(fp, "Remote-MTA: X-ip; [%s]%s\n", hu->address, p); } if ((s = addr->smtp_greeting) && *s) fprintf(fp, "X-Remote-MTA-smtp-greeting: X-str; %s\n", s); if ((s = addr->helo_response) && *s) fprintf(fp, "X-Remote-MTA-helo-response: X-str; %s\n", s); if ((s = addr->message) && *s) fprintf(fp, "X-Exim-Diagnostic: X-str; %s\n", s); } #endif print_dsn_diagnostic_code(addr, fp); } fputc('\n', fp); } /* Now copy the message, trying to give an intelligible comment if it is too long for it all to be copied. The limit isn't strictly applied because of the buffering. There is, however, an option to suppress copying altogether. */ emf_text = next_emf(emf, US"copy"); /* add message body we ignore the intro text from template and add the text for bounce_return_size_limit at the end. bounce_return_message is ignored in case RET= is defined we honor these values otherwise bounce_return_body is honored. bounce_return_size_limit is always honored. */ fprintf(fp, "--%s\n", bound); dsnlimitmsg = US"X-Exim-DSN-Information: Due to administrative limits only headers are returned"; dsnnotifyhdr = NULL; topt = topt_add_return_path; /* RET=HDRS? top priority */ if (dsn_ret == dsn_ret_hdrs) topt |= topt_no_body; else { struct stat statbuf; /* no full body return at all? */ if (!bounce_return_body) { topt |= topt_no_body; /* add header if we overrule RET=FULL */ if (dsn_ret == dsn_ret_full) dsnnotifyhdr = dsnlimitmsg; } /* line length limited... return headers only if oversize */ /* size limited ... return headers only if limit reached */ else if ( max_received_linelength > bounce_return_linesize_limit || ( bounce_return_size_limit > 0 && fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max ) ) { topt |= topt_no_body; dsnnotifyhdr = dsnlimitmsg; } } #ifdef SUPPORT_I18N if (message_smtputf8) fputs(topt & topt_no_body ? "Content-type: message/global-headers\n\n" : "Content-type: message/global\n\n", fp); else #endif fputs(topt & topt_no_body ? "Content-type: text/rfc822-headers\n\n" : "Content-type: message/rfc822\n\n", fp); fflush(fp); transport_filter_argv = NULL; /* Just in case */ return_path = sender_address; /* In case not previously set */ { /* Dummy transport for headers add */ transport_ctx tctx = {{0}}; transport_instance tb = {0}; tctx.u.fd = fileno(fp); tctx.tblock = &tb; tctx.options = topt; tb.add_headers = dsnnotifyhdr; transport_write_message(&tctx, 0); } fflush(fp); /* we never add the final text. close the file */ if (emf) (void)fclose(emf); fprintf(fp, "\n--%s--\n", bound); /* Close the file, which should send an EOF to the child process that is receiving the message. Wait for it to finish. */ (void)fclose(fp); rc = child_close(pid, 0); /* Waits for child to close, no timeout */ /* In the test harness, let the child do it's thing first. */ if (f.running_in_test_harness) millisleep(500); /* If the process failed, there was some disaster in setting up the error message. Unless the message is very old, ensure that addr_defer is non-null, which will have the effect of leaving the message on the spool. The failed addresses will get tried again next time. However, we don't really want this to happen too often, so freeze the message unless there are some genuine deferred addresses to try. To do this we have to call spool_write_header() here, because with no genuine deferred addresses the normal code below doesn't get run. */ if (rc != 0) { uschar *s = US""; if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer) { addr_defer = (address_item *)(+1); f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); s = US" (frozen)"; } deliver_msglog("Process failed (%d) when writing error message " "to %s%s", rc, bounce_recipient, s); log_write(0, LOG_MAIN, "Process failed (%d) when writing error message " "to %s%s", rc, bounce_recipient, s); } /* The message succeeded. Ensure that the recipients that failed are now marked finished with on the spool and their parents updated. */ else { for (addr = handled_addr; addr; addr = addr->next) { address_done(addr, logtod); child_done(addr, logtod); } /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } } } } f.disable_logging = FALSE; /* In case left set */ /* Come here from the mua_wrapper case if routing goes wrong */ DELIVERY_TIDYUP: /* If there are now no deferred addresses, we are done. Preserve the message log if so configured, and we are using them. Otherwise, sling it. Then delete the message itself. */ if (!addr_defer) { uschar * fname; if (message_logs) { fname = spool_fname(US"msglog", message_subdir, id, US""); if (preserve_message_logs) { int rc; uschar * moname = spool_fname(US"msglog.OLD", US"", id, US""); if ((rc = Urename(fname, moname)) < 0) { (void)directory_make(spool_directory, spool_sname(US"msglog.OLD", US""), MSGLOG_DIRECTORY_MODE, TRUE); rc = Urename(fname, moname); } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to move %s to the " "msglog.OLD directory", fname); } else if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); } /* Remove the two message files. */ fname = spool_fname(US"input", message_subdir, id, US"-D"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); fname = spool_fname(US"input", message_subdir, id, US"-H"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); /* Log the end of this message, with queue time if requested. */ if (LOGGING(queue_time_overall)) log_write(0, LOG_MAIN, "Completed QT=%s", string_timesince(&received_time)); else log_write(0, LOG_MAIN, "Completed"); /* Unset deliver_freeze so that we won't try to move the spool files further down */ f.deliver_freeze = FALSE; #ifndef DISABLE_EVENT (void) event_raise(event_action, US"msg:complete", NULL); #endif } /* If there are deferred addresses, we are keeping this message because it is not yet completed. Lose any temporary files that were catching output from pipes for any of the deferred addresses, handle one-time aliases, and see if the message has been on the queue for so long that it is time to send a warning message to the sender, unless it is a mailer-daemon. If all deferred addresses have the same domain, we can set deliver_domain for the expansion of delay_warning_ condition - if any of them are pipes, files, or autoreplies, use the parent's domain. If all the deferred addresses have an error number that indicates "retry time not reached", skip sending the warning message, because it won't contain the reason for the delay. It will get sent at the next real delivery attempt. However, if at least one address has tried, we'd better include all of them in the message. If we can't make a process to send the message, don't worry. For mailing list expansions we want to send the warning message to the mailing list manager. We can't do a perfect job here, as some addresses may have different errors addresses, but if we take the errors address from each deferred address it will probably be right in most cases. If addr_defer == +1, it means there was a problem sending an error message for failed addresses, and there were no "real" deferred addresses. The value was set just to keep the message on the spool, so there is nothing to do here. */ else if (addr_defer != (address_item *)(+1)) { address_item *addr; uschar *recipients = US""; BOOL delivery_attempted = FALSE; deliver_domain = testflag(addr_defer, af_pfr) ? addr_defer->parent->domain : addr_defer->domain; for (addr = addr_defer; addr; addr = addr->next) { address_item *otaddr; if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE; if (deliver_domain) { const uschar *d = testflag(addr, af_pfr) ? addr->parent->domain : addr->domain; /* The domain may be unset for an address that has never been routed because the system filter froze the message. */ if (!d || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL; } if (addr->return_filename) Uunlink(addr->return_filename); /* Handle the case of one-time aliases. If any address in the ancestry of this one is flagged, ensure it is in the recipients list, suitably flagged, and that its parent is marked delivered. */ for (otaddr = addr; otaddr; otaddr = otaddr->parent) if (otaddr->onetime_parent) break; if (otaddr) { int i; int t = recipients_count; for (i = 0; i < recipients_count; i++) { uschar *r = recipients_list[i].address; if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i; if (Ustrcmp(otaddr->address, r) == 0) break; } /* Didn't find the address already in the list, and did find the ultimate parent's address in the list, and they really are different (i.e. not from an identity-redirect). After adding the recipient, update the errors address in the recipients list. */ if ( i >= recipients_count && t < recipients_count && Ustrcmp(otaddr->address, otaddr->parent->address) != 0) { DEBUG(D_deliver) debug_printf("one_time: adding %s in place of %s\n", otaddr->address, otaddr->parent->address); receive_add_recipient(otaddr->address, t); recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address; tree_add_nonrecipient(otaddr->parent->address); update_spool = TRUE; } } /* Except for error messages, ensure that either the errors address for this deferred address or, if there is none, the sender address, is on the list of recipients for a warning message. */ if (sender_address[0]) { uschar * s = addr->prop.errors_address; if (!s) s = sender_address; if (Ustrstr(recipients, s) == NULL) recipients = string_sprintf("%s%s%s", recipients, recipients[0] ? "," : "", s); } } /* Send a warning message if the conditions are right. If the condition check fails because of a lookup defer, there is nothing we can do. The warning is not sent. Another attempt will be made at the next delivery attempt (if it also defers). */ if ( !f.queue_2stage && delivery_attempted && ( ((addr_defer->dsn_flags & rf_dsnflags) == 0) || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay ) && delay_warning[1] > 0 && sender_address[0] != 0 && ( !delay_warning_condition || expand_check_condition(delay_warning_condition, US"delay_warning", US"option") ) ) { int count; int show_time; int queue_time = time(NULL) - received_time.tv_sec; /* When running in the test harness, there's an option that allows us to fudge this time so as to get repeatability of the tests. Take the first time off the list. In queue runs, the list pointer gets updated in the calling process. */ if (f.running_in_test_harness && fudged_queue_times[0] != 0) { int qt = readconf_readtime(fudged_queue_times, '/', FALSE); if (qt >= 0) { DEBUG(D_deliver) debug_printf("fudged queue_times = %s\n", fudged_queue_times); queue_time = qt; } } /* See how many warnings we should have sent by now */ for (count = 0; count < delay_warning[1]; count++) if (queue_time < delay_warning[count+2]) break; show_time = delay_warning[count+1]; if (count >= delay_warning[1]) { int extra; int last_gap = show_time; if (count > 1) last_gap -= delay_warning[count]; extra = (queue_time - delay_warning[count+1])/last_gap; show_time += last_gap * extra; count += extra; } DEBUG(D_deliver) { debug_printf("time on queue = %s\n", readconf_printtime(queue_time)); debug_printf("warning counts: required %d done %d\n", count, warning_count); } /* We have computed the number of warnings there should have been by now. If there haven't been enough, send one, and up the count to what it should have been. */ if (warning_count < count) { header_line *h; int fd; pid_t pid = child_open_exim(&fd); if (pid > 0) { uschar *wmf_text; FILE *wmf = NULL; FILE *f = fdopen(fd, "wb"); uschar * bound; transport_ctx tctx = {{0}}; if (warn_message_file) if (!(wmf = Ufopen(warn_message_file, "rb"))) log_write(0, LOG_MAIN|LOG_PANIC, "Failed to open %s for warning " "message texts: %s", warn_message_file, strerror(errno)); warnmsg_recipients = recipients; warnmsg_delay = queue_time < 120*60 ? string_sprintf("%d minutes", show_time/60) : string_sprintf("%d hours", show_time/3600); if (errors_reply_to) fprintf(f, "Reply-To: %s\n", errors_reply_to); fprintf(f, "Auto-Submitted: auto-replied\n"); moan_write_from(f); fprintf(f, "To: %s\n", recipients); /* generated boundary string and output MIME-Headers */ bound = string_sprintf(TIME_T_FMT "-eximdsn-%d", time(NULL), rand()); fprintf(f, "Content-Type: multipart/report;" " report-type=delivery-status; boundary=%s\n" "MIME-Version: 1.0\n", bound); if ((wmf_text = next_emf(wmf, US"header"))) fprintf(f, "%s\n", wmf_text); else fprintf(f, "Subject: Warning: message %s delayed %s\n\n", message_id, warnmsg_delay); /* output human readable part as text/plain section */ fprintf(f, "--%s\n" "Content-type: text/plain; charset=us-ascii\n\n", bound); if ((wmf_text = next_emf(wmf, US"intro"))) fprintf(f, "%s", CS wmf_text); else { fprintf(f, "This message was created automatically by mail delivery software.\n"); if (Ustrcmp(recipients, sender_address) == 0) fprintf(f, "A message that you sent has not yet been delivered to one or more of its\n" "recipients after more than "); else fprintf(f, "A message sent by\n\n <%s>\n\n" "has not yet been delivered to one or more of its recipients after more than \n", sender_address); fprintf(f, "%s on the queue on %s.\n\n" "The message identifier is: %s\n", warnmsg_delay, primary_hostname, message_id); for (h = header_list; h; h = h->next) if (strncmpic(h->text, US"Subject:", 8) == 0) fprintf(f, "The subject of the message is: %s", h->text + 9); else if (strncmpic(h->text, US"Date:", 5) == 0) fprintf(f, "The date of the message is: %s", h->text + 6); fputc('\n', f); fprintf(f, "The address%s to which the message has not yet been " "delivered %s:\n", !addr_defer->next ? "" : "es", !addr_defer->next ? "is": "are"); } /* List the addresses, with error information if allowed */ /* store addr_defer for machine readable part */ address_item *addr_dsndefer = addr_defer; fputc('\n', f); while (addr_defer) { address_item *addr = addr_defer; addr_defer = addr->next; if (print_address_information(addr, f, US" ", US"\n ", US"")) print_address_error(addr, f, US"Delay reason: "); fputc('\n', f); } fputc('\n', f); /* Final text */ if (wmf) { if ((wmf_text = next_emf(wmf, US"final"))) fprintf(f, "%s", CS wmf_text); (void)fclose(wmf); } else { fprintf(f, "No action is required on your part. Delivery attempts will continue for\n" "some time, and this warning may be repeated at intervals if the message\n" "remains undelivered. Eventually the mail delivery software will give up,\n" "and when that happens, the message will be returned to you.\n"); } /* output machine readable part */ fprintf(f, "\n--%s\n" "Content-type: message/delivery-status\n\n" "Reporting-MTA: dns; %s\n", bound, smtp_active_hostname); if (dsn_envid) { /* must be decoded from xtext: see RFC 3461:6.3a */ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f,"Original-Envelope-ID: %s\n", dsn_envid); else fprintf(f,"X-Original-Envelope-ID: error decoding xtext formatted ENVID\n"); } fputc('\n', f); for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next) { if (addr_dsndefer->dsn_orcpt) fprintf(f, "Original-Recipient: %s\n", addr_dsndefer->dsn_orcpt); fprintf(f, "Action: delayed\n" "Final-Recipient: rfc822;%s\n" "Status: 4.0.0\n", addr_dsndefer->address); if (addr_dsndefer->host_used && addr_dsndefer->host_used->name) { fprintf(f, "Remote-MTA: dns; %s\n", addr_dsndefer->host_used->name); print_dsn_diagnostic_code(addr_dsndefer, f); } fputc('\n', f); } fprintf(f, "--%s\n" "Content-type: text/rfc822-headers\n\n", bound); fflush(f); /* header only as required by RFC. only failure DSN needs to honor RET=FULL */ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_filter_argv = NULL; /* Just in case */ return_path = sender_address; /* In case not previously set */ /* Write the original email out */ transport_write_message(&tctx, 0); fflush(f); fprintf(f,"\n--%s--\n", bound); fflush(f); /* Close and wait for child process to complete, without a timeout. If there's an error, don't update the count. */ (void)fclose(f); if (child_close(pid, 0) == 0) { warning_count = count; update_spool = TRUE; /* Ensure spool rewritten */ } } } } /* Clear deliver_domain */ deliver_domain = NULL; /* If this was a first delivery attempt, unset the first time flag, and ensure that the spool gets updated. */ if (f.deliver_firsttime) { f.deliver_firsttime = FALSE; update_spool = TRUE; } /* If delivery was frozen and freeze_tell is set, generate an appropriate message, unless the message is a local error message (to avoid loops). Then log the freezing. If the text in "frozen_info" came from a system filter, it has been escaped into printing characters so as not to mess up log lines. For the "tell" message, we turn \n back into newline. Also, insert a newline near the start instead of the ": " string. */ if (f.deliver_freeze) { if (freeze_tell && freeze_tell[0] != 0 && !f.local_error_message) { uschar *s = string_copy(frozen_info); uschar *ss = Ustrstr(s, " by the system filter: "); if (ss != NULL) { ss[21] = '.'; ss[22] = '\n'; } ss = s; while (*ss != 0) { if (*ss == '\\' && ss[1] == 'n') { *ss++ = ' '; *ss++ = '\n'; } else ss++; } moan_tell_someone(freeze_tell, addr_defer, US"Message frozen", "Message %s has been frozen%s.\nThe sender is <%s>.\n", message_id, s, sender_address); } /* Log freezing just before we update the -H file, to minimize the chance of a race problem. */ deliver_msglog("*** Frozen%s\n", frozen_info); log_write(0, LOG_MAIN, "Frozen%s", frozen_info); } /* If there have been any updates to the non-recipients list, or other things that get written to the spool, we must now update the spool header file so that it has the right information for the next delivery attempt. If there was more than one address being delivered, the header_change update is done earlier, in case one succeeds and then something crashes. */ DEBUG(D_deliver) debug_printf("delivery deferred: update_spool=%d header_rewritten=%d\n", update_spool, f.header_rewritten); if (update_spool || f.header_rewritten) /* Panic-dies on error */ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } /* Finished with the message log. If the message is complete, it will have been unlinked or renamed above. */ if (message_logs) (void)fclose(message_log); /* Now we can close and remove the journal file. Its only purpose is to record successfully completed deliveries asap so that this information doesn't get lost if Exim (or the machine) crashes. Forgetting about a failed delivery is not serious, as trying it again is not harmful. The journal might not be open if all addresses were deferred at routing or directing. Nevertheless, we must remove it if it exists (may have been lying around from a crash during the previous delivery attempt). We don't remove the journal if a delivery subprocess failed to pass back delivery information; this is controlled by the remove_journal flag. When the journal is left, we also don't move the message off the main spool if frozen and the option is set. It should get moved at the next attempt, after the journal has been inspected. */ if (journal_fd >= 0) (void)close(journal_fd); if (remove_journal) { uschar * fname = spool_fname(US"input", message_subdir, id, US"-J"); if (Uunlink(fname) < 0 && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to unlink %s: %s", fname, strerror(errno)); /* Move the message off the spool if requested */ #ifdef SUPPORT_MOVE_FROZEN_MESSAGES if (f.deliver_freeze && move_frozen_messages) (void)spool_move_message(id, message_subdir, US"", US"F"); #endif } /* Closing the data file frees the lock; if the file has been unlinked it will go away. Otherwise the message becomes available for another process to try delivery. */ (void)close(deliver_datafile); deliver_datafile = -1; DEBUG(D_deliver) debug_printf("end delivery of %s\n", id); /* It is unlikely that there will be any cached resources, since they are released after routing, and in the delivery subprocesses. However, it's possible for an expansion for something afterwards (for example, expand_check_condition) to do a lookup. We must therefore be sure everything is released. */ search_tidyup(); acl_where = ACL_WHERE_UNKNOWN; return final_yield; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'Events: raise msg:fail:internal & msg:complete for -Mrm. Bug 2310'</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 tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <avekceeb@gmail.com> Cc: Jason Wang <jasowang@redhat.com> Cc: "Michael S. Tsirkin" <mst@redhat.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: static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) { int i; memset(cfg, 0, sizeof(cfg_t)); cfg->debug_file = stderr; for (i = 0; i < argc; i++) { if (strncmp(argv[i], "max_devices=", 12) == 0) sscanf(argv[i], "max_devices=%u", &cfg->max_devs); if (strcmp(argv[i], "manual") == 0) cfg->manual = 1; if (strcmp(argv[i], "debug") == 0) cfg->debug = 1; if (strcmp(argv[i], "nouserok") == 0) cfg->nouserok = 1; if (strcmp(argv[i], "openasuser") == 0) cfg->openasuser = 1; if (strcmp(argv[i], "alwaysok") == 0) cfg->alwaysok = 1; if (strcmp(argv[i], "interactive") == 0) cfg->interactive = 1; if (strcmp(argv[i], "cue") == 0) cfg->cue = 1; if (strcmp(argv[i], "nodetect") == 0) cfg->nodetect = 1; if (strncmp(argv[i], "authfile=", 9) == 0) cfg->auth_file = argv[i] + 9; if (strncmp(argv[i], "authpending_file=", 17) == 0) cfg->authpending_file = argv[i] + 17; if (strncmp(argv[i], "origin=", 7) == 0) cfg->origin = argv[i] + 7; if (strncmp(argv[i], "appid=", 6) == 0) cfg->appid = argv[i] + 6; if (strncmp(argv[i], "prompt=", 7) == 0) cfg->prompt = argv[i] + 7; if (strncmp (argv[i], "debug_file=", 11) == 0) { const char *filename = argv[i] + 11; if(strncmp (filename, "stdout", 6) == 0) { cfg->debug_file = stdout; } else if(strncmp (filename, "stderr", 6) == 0) { cfg->debug_file = stderr; } else if( strncmp (filename, "syslog", 6) == 0) { cfg->debug_file = (FILE *)-1; } else { struct stat st; FILE *file; if(lstat(filename, &st) == 0) { if(S_ISREG(st.st_mode)) { file = fopen(filename, "a"); if(file != NULL) { cfg->debug_file = file; } } } } } } if (cfg->debug) { D(cfg->debug_file, "called."); D(cfg->debug_file, "flags %d argc %d", flags, argc); for (i = 0; i < argc; i++) { D(cfg->debug_file, "argv[%d]=%s", i, argv[i]); } D(cfg->debug_file, "max_devices=%d", cfg->max_devs); D(cfg->debug_file, "debug=%d", cfg->debug); D(cfg->debug_file, "interactive=%d", cfg->interactive); D(cfg->debug_file, "cue=%d", cfg->cue); D(cfg->debug_file, "nodetect=%d", cfg->nodetect); D(cfg->debug_file, "manual=%d", cfg->manual); D(cfg->debug_file, "nouserok=%d", cfg->nouserok); D(cfg->debug_file, "openasuser=%d", cfg->openasuser); D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok); D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)"); D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)"); D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)"); D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)"); D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Do not leak file descriptor when doing exec When opening a custom debug file, the descriptor would stay open when calling exec and leak to the child process. Make sure all files are opened with close-on-exec. This fixes CVE-2019-12210. Thanks to Matthias Gerstner of the SUSE Security Team for reporting the issue.'</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: openscript( char_u *name, int directly) /* when TRUE execute directly */ { if (curscript + 1 == NSCRIPT) { emsg(_(e_nesting)); return; } #ifdef FEAT_EVAL if (ignore_script) /* Not reading from script, also don't open one. Warning message? */ return; #endif if (scriptin[curscript] != NULL) /* already reading script */ ++curscript; /* use NameBuff for expanded name */ expand_env(name, NameBuff, MAXPATHL); if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL) { semsg(_(e_notopen), name); if (curscript) --curscript; return; } if (save_typebuf() == FAIL) return; /* * Execute the commands from the file right now when using ":source!" * after ":global" or ":argdo" or in a loop. Also when another command * follows. This means the display won't be updated. Don't do this * always, "make test" would fail. */ if (directly) { oparg_T oa; int oldcurscript; int save_State = State; int save_restart_edit = restart_edit; int save_insertmode = p_im; int save_finish_op = finish_op; int save_msg_scroll = msg_scroll; State = NORMAL; msg_scroll = FALSE; /* no msg scrolling in Normal mode */ restart_edit = 0; /* don't go to Insert mode */ p_im = FALSE; /* don't use 'insertmode' */ clear_oparg(&oa); finish_op = FALSE; oldcurscript = curscript; do { update_topline_cursor(); // update cursor position and topline normal_cmd(&oa, FALSE); // execute one command vpeekc(); // check for end of file } while (scriptin[oldcurscript] != NULL); State = save_State; msg_scroll = save_msg_scroll; restart_edit = save_restart_edit; p_im = save_insertmode; finish_op = save_finish_op; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.1365: source command doesn't check for the sandbox Problem: Source command doesn't check for the sandbox. (Armin Razmjou) Solution: Check for the sandbox when sourcing a file.'</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 hash__init_new_context(struct mm_struct *mm) { int index; index = hash__alloc_context_id(); if (index < 0) return index; /* * The old code would re-promote on fork, we don't do that when using * slices as it could cause problem promoting slices that have been * forced down to 4K. * * For book3s we have MMU_NO_CONTEXT set to be ~0. Hence check * explicitly against context.id == 0. This ensures that we properly * initialize context slice details for newly allocated mm's (which will * have id == 0) and don't alter context slice inherited via fork (which * will have id != 0). * * We should not be calling init_new_context() on init_mm. Hence a * check against 0 is OK. */ if (mm->context.id == 0) slice_init_new_context_exec(mm); subpage_prot_init_new_context(mm); pkey_mm_init(mm); return index; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'powerpc/mm/64s/hash: Reallocate context ids on fork When using the Hash Page Table (HPT) MMU, userspace memory mappings are managed at two levels. Firstly in the Linux page tables, much like other architectures, and secondly in the SLB (Segment Lookaside Buffer) and HPT. It's the SLB and HPT that are actually used by the hardware to do translations. As part of the series adding support for 4PB user virtual address space using the hash MMU, we added support for allocating multiple "context ids" per process, one for each 512TB chunk of address space. These are tracked in an array called extended_id in the mm_context_t of a process that has done a mapping above 512TB. If such a process forks (ie. clone(2) without CLONE_VM set) it's mm is copied, including the mm_context_t, and then init_new_context() is called to reinitialise parts of the mm_context_t as appropriate to separate the address spaces of the two processes. The key step in ensuring the two processes have separate address spaces is to allocate a new context id for the process, this is done at the beginning of hash__init_new_context(). If we didn't allocate a new context id then the two processes would share mappings as far as the SLB and HPT are concerned, even though their Linux page tables would be separate. For mappings above 512TB, which use the extended_id array, we neglected to allocate new context ids on fork, meaning the parent and child use the same ids and therefore share those mappings even though they're supposed to be separate. This can lead to the parent seeing writes done by the child, which is essentially memory corruption. There is an additional exposure which is that if the child process exits, all its context ids are freed, including the context ids that are still in use by the parent for mappings above 512TB. One or more of those ids can then be reallocated to a third process, that process can then read/write to the parent's mappings above 512TB. Additionally if the freed id is used for the third process's primary context id, then the parent is able to read/write to the third process's mappings *below* 512TB. All of these are fundamental failures to enforce separation between processes. The only mitigating factor is that the bug only occurs if a process creates mappings above 512TB, and most applications still do not create such mappings. Only machines using the hash page table MMU are affected, eg. PowerPC 970 (G5), PA6T, Power5/6/7/8/9. By default Power9 bare metal machines (powernv) use the Radix MMU and are not affected, unless the machine has been explicitly booted in HPT mode (using disable_radix on the kernel command line). KVM guests on Power9 may be affected if the host or guest is configured to use the HPT MMU. LPARs under PowerVM on Power9 are affected as they always use the HPT MMU. Kernels built with PAGE_SIZE=4K are not affected. The fix is relatively simple, we need to reallocate context ids for all extended mappings on fork. Fixes: f384796c40dc ("powerpc/mm: Add support for handling > 512TB address in SLB miss") Cc: stable@vger.kernel.org # v4.17+ 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: int hllSparseToDense(robj *o) { sds sparse = o->ptr, dense; struct hllhdr *hdr, *oldhdr = (struct hllhdr*)sparse; int idx = 0, runlen, regval; uint8_t *p = (uint8_t*)sparse, *end = p+sdslen(sparse); /* If the representation is already the right one return ASAP. */ hdr = (struct hllhdr*) sparse; if (hdr->encoding == HLL_DENSE) return C_OK; /* Create a string of the right size filled with zero bytes. * Note that the cached cardinality is set to 0 as a side effect * that is exactly the cardinality of an empty HLL. */ dense = sdsnewlen(NULL,HLL_DENSE_SIZE); hdr = (struct hllhdr*) dense; *hdr = *oldhdr; /* This will copy the magic and cached cardinality. */ hdr->encoding = HLL_DENSE; /* Now read the sparse representation and set non-zero registers * accordingly. */ p += HLL_HDR_SIZE; while(p < end) { if (HLL_SPARSE_IS_ZERO(p)) { runlen = HLL_SPARSE_ZERO_LEN(p); idx += runlen; p++; } else if (HLL_SPARSE_IS_XZERO(p)) { runlen = HLL_SPARSE_XZERO_LEN(p); idx += runlen; p += 2; } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); while(runlen--) { HLL_DENSE_SET_REGISTER(hdr->registers,idx,regval); idx++; } p++; } } /* If the sparse representation was valid, we expect to find idx * set to HLL_REGISTERS. */ if (idx != HLL_REGISTERS) { sdsfree(dense); return C_ERR; } /* Free the old representation and set the new one. */ sdsfree(o->ptr); o->ptr = dense; return C_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix hyperloglog corruption'</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 nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'nfc: Ensure presence of required attributes in the deactivate_target handler Check that the NFC_ATTR_TARGET_INDEX attributes (in addition to NFC_ATTR_DEVICE_INDEX) are provided by the netlink client prior to accessing them. This prevents potential unhandled NULL pointer dereference exceptions which can be triggered by malicious user-mode programs, if they omit one or both of these attributes. Signed-off-by: Young Xiao <92siuyang@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 am_handle_repost(request_rec *r) { am_mod_cfg_rec *mod_cfg; const char *query; const char *enctype; char *charset; char *psf_id; char *cp; char *psf_filename; char *post_data; const char *post_form; char *output; char *return_url; const char *(*post_mkform)(request_rec *, const char *); if (am_cookie_get(r) == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Repost query without a session"); return HTTP_FORBIDDEN; } mod_cfg = am_get_mod_cfg(r->server); if (!mod_cfg->post_dir) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Repost query without MellonPostDirectory."); return HTTP_NOT_FOUND; } query = r->parsed_uri.query; enctype = am_extract_query_parameter(r->pool, query, "enctype"); if (enctype == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: missing enctype"); return HTTP_BAD_REQUEST; } if (strcmp(enctype, "urlencoded") == 0) { enctype = "application/x-www-form-urlencoded"; post_mkform = am_post_mkform_urlencoded; } else if (strcmp(enctype, "multipart") == 0) { enctype = "multipart/form-data"; post_mkform = am_post_mkform_multipart; } else { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid enctype \"%s\".", enctype); return HTTP_BAD_REQUEST; } charset = am_extract_query_parameter(r->pool, query, "charset"); if (charset != NULL) { if (am_urldecode(charset) != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid charset \"%s\"", charset); return HTTP_BAD_REQUEST; } /* Check that charset is sane */ for (cp = charset; *cp; cp++) { if (!apr_isalnum(*cp) && (*cp != '-') && (*cp != '_')) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid charset \"%s\"", charset); return HTTP_BAD_REQUEST; } } } psf_id = am_extract_query_parameter(r->pool, query, "id"); if (psf_id == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: missing id"); return HTTP_BAD_REQUEST; } /* Check that Id is sane */ for (cp = psf_id; *cp; cp++) { if (!apr_isalnum(*cp)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: invalid id \"%s\"", psf_id); return HTTP_BAD_REQUEST; } } return_url = am_extract_query_parameter(r->pool, query, "ReturnTo"); if (return_url == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid or missing query ReturnTo parameter."); return HTTP_BAD_REQUEST; } if (am_urldecode(return_url) != OK) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: return"); return HTTP_BAD_REQUEST; } psf_filename = apr_psprintf(r->pool, "%s/%s", mod_cfg->post_dir, psf_id); post_data = am_getfile(r->pool, r->server, psf_filename); if (post_data == NULL) { /* Unable to load repost data. Just redirect us instead. */ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "Bad repost query: cannot find \"%s\"", psf_filename); apr_table_setn(r->headers_out, "Location", return_url); return HTTP_SEE_OTHER; } if ((post_form = (*post_mkform)(r, post_data)) == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "am_post_mkform() failed"); return HTTP_INTERNAL_SERVER_ERROR; } if (charset != NULL) { ap_set_content_type(r, apr_psprintf(r->pool, "text/html; charset=\"%s\"", charset)); charset = apr_psprintf(r->pool, " accept-charset=\"%s\"", charset); } else { ap_set_content_type(r, "text/html"); charset = (char *)""; } output = apr_psprintf(r->pool, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" "<html>\n" " <head>\n" " <title>SAML rePOST request</title>\n" " </head>\n" " <body onload=\"document.getElementById('form').submit();\">\n" " <noscript>\n" " Your browser does not support Javascript, \n" " you must click the button below to proceed.\n" " </noscript>\n" " <form id=\"form\" method=\"POST\" action=\"%s\" enctype=\"%s\"%s>\n%s" " <noscript>\n" " <input type=\"submit\">\n" " </noscript>\n" " </form>\n" " </body>\n" "</html>\n", am_htmlencode(r, return_url), enctype, charset, post_form); ap_rputs(output, r); return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Add MellonRedirectDomains option. Limit the domains that we will redirect to after login / logout to a set of trusted domains. By default we only allow redirects to the current domain. This change breaks backwards compatibility with any site that relies on redirects to separate domains. Fixes #35'</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 Image *ReadAAIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; size_t height, length, width; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read AAI Dune image. */ width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((width == 0UL) || (height == 0UL)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Convert AAI raster image to pixel packets. */ image->columns=width; image->rows=height; image->depth=8; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } pixels=(unsigned char *) AcquireQuantumMemory(image->columns, 4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) 4*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); if (*p == 254) *p=255; SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (q->opacity != OpaqueOpacity) image->matte=MagickTrue; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if ((width != 0UL) && (height != 0UL)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((width != 0UL) && (height != 0UL)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</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 Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; Quantum blue, green, red; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; size_t bits_per_pixel, height, length, width; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PIX image. */ width=ReadBlobMSBShort(image); height=ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); /* x-offset */ (void) ReadBlobMSBShort(image); /* y-offset */ bits_per_pixel=ReadBlobMSBShort(image); if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) && (bits_per_pixel != 24))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Initialize image structure. */ image->columns=width; image->rows=height; if (bits_per_pixel == 8) if (AcquireImageColormap(image,256) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Convert PIX raster image to pixel packets. */ red=(Quantum) 0; green=(Quantum) 0; blue=(Quantum) 0; index=(IndexPacket) 0; length=0; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if (length == 0) { int c; c=ReadBlobByte(image); if ((c == 0) || (c == EOF)) break; length=(size_t) c; if (bits_per_pixel == 8) index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); else { blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } } if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,index); SetPixelBlue(q,blue); SetPixelGreen(q,green); SetPixelRed(q,red); length--; q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); bits_per_pixel=ReadBlobMSBShort(image); status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) || (bits_per_pixel == 24)) ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (status != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</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 Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SGI raster header. */ (void) memset(&iris_info,0,sizeof(iris_info)); iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.dimension=ReadBlobMSBShort(image); if ((iris_info.dimension == 0) || (iris_info.dimension > 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); if ((size_t) count != sizeof(iris_info.name)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.name[sizeof(iris_info.name)-1]='\0'; if (*iris_info.name != '\0') (void) SetImageProperty(image,"label",iris_info.name); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); if ((size_t) count != sizeof(iris_info.filler)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=iris_info.columns; image->rows=iris_info.rows; image->matte=iris_info.depth == 4 ? MagickTrue : MagickFalse; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel, MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status != MagickFalse) status=ResetImagePixels(image,&image->exception); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(pixels,0,iris_info.columns*iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (count != (bytes_per_pixel*iris_info.columns)) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } if (y < (ssize_t) iris_info.rows) break; } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info != (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) { offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); packet_info=RelinquishVirtualMemory(packet_info); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } (void) ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (count != runlength[y+z*iris_info.rows]) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) { offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); packet_info=RelinquishVirtualMemory(packet_info); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } p+=(iris_info.columns*4*bytes_per_pixel); } if (y < (ssize_t) iris_info.rows) break; } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (count != runlength[y+z*iris_info.rows]) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) { offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); packet_info=RelinquishVirtualMemory(packet_info); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } if (z < (ssize_t) iris_info.depth) break; p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1))))); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3))))); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5))))); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7))))); p+=8; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); q->green=ScaleCharToQuantum(*(p+1)); q->blue=ScaleCharToQuantum(*(p+2)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*(p+3))); p+=4; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(indexes+x,quantum); p+=8; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,*p); p+=4; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</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: g_vfs_daemon_init (GVfsDaemon *daemon) { GError *error; gint max_threads = 1; /* TODO: handle max threads */ daemon->thread_pool = g_thread_pool_new (job_handler_callback, daemon, max_threads, FALSE, NULL); /* TODO: verify thread_pool != NULL in a nicer way */ g_assert (daemon->thread_pool != NULL); g_mutex_init (&daemon->lock); daemon->mount_counter = 0; daemon->jobs = NULL; daemon->registered_paths = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)registered_path_free); /* This is where we store active client connections so when a new filter is registered, * we re-register them on all active connections */ daemon->client_connections = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, NULL); daemon->conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL); g_assert (daemon->conn != NULL); daemon->daemon_skeleton = gvfs_dbus_daemon_skeleton_new (); g_signal_connect (daemon->daemon_skeleton, "handle-get-connection", G_CALLBACK (handle_get_connection), daemon); g_signal_connect (daemon->daemon_skeleton, "handle-cancel", G_CALLBACK (handle_cancel), daemon); g_signal_connect (daemon->daemon_skeleton, "handle-list-monitor-implementations", G_CALLBACK (handle_list_monitor_implementations), daemon); error = NULL; if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (daemon->daemon_skeleton), daemon->conn, G_VFS_DBUS_DAEMON_PATH, &error)) { g_warning ("Error exporting daemon interface: %s (%s, %d)\n", error->message, g_quark_to_string (error->domain), error->code); g_error_free (error); } daemon->mountable_skeleton = gvfs_dbus_mountable_skeleton_new (); g_signal_connect (daemon->mountable_skeleton, "handle-mount", G_CALLBACK (daemon_handle_mount), daemon); error = NULL; if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (daemon->mountable_skeleton), daemon->conn, G_VFS_DBUS_MOUNTABLE_PATH, &error)) { g_warning ("Error exporting mountable interface: %s (%s, %d)\n", error->message, g_quark_to_string (error->domain), error->code); g_error_free (error); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-276'], 'message': 'gvfsdaemon: Check that the connecting client is the same user Otherwise, an attacker who learns the abstract socket address from netstat(8) or similar could connect to it and issue D-Bus method calls. Signed-off-by: Simon McVittie <smcv@collabora.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 insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct *desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; desc = get_desc(sel); if (!desc) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc->type & BIT(3))) return -EINVAL; switch ((desc->l << 1) | desc->d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: stable@vger.kernel.org Signed-off-by: Jann Horn <jannh@google.com> 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: int hci_conn_check_link_mode(struct hci_conn *conn) { BT_DBG("hcon %p", conn); /* In Secure Connections Only mode, it is required that Secure * Connections is used and the link is encrypted with AES-CCM * using a P-256 authenticated combination key. */ if (hci_dev_test_flag(conn->hdev, HCI_SC_ONLY)) { if (!hci_conn_sc_enabled(conn) || !test_bit(HCI_CONN_AES_CCM, &conn->flags) || conn->key_type != HCI_LK_AUTH_COMBINATION_P256) return 0; } if (hci_conn_ssp_enabled(conn) && !test_bit(HCI_CONN_ENCRYPT, &conn->flags)) return 0; /* The minimum encryption key size needs to be enforced by the * host stack before establishing any L2CAP connections. The * specification in theory allows a minimum of 1, but to align * BR/EDR and LE transports, a minimum of 7 is chosen. */ if (conn->enc_key_size < HCI_MIN_ENC_KEY_SIZE) return 0; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'Bluetooth: Fix regression with minimum encryption key size alignment When trying to align the minimum encryption key size requirement for Bluetooth connections, it turns out doing this in a central location in the HCI connection handling code is not possible. Original Bluetooth version up to 2.0 used a security model where the L2CAP service would enforce authentication and encryption. Starting with Bluetooth 2.1 and Secure Simple Pairing that model has changed into that the connection initiator is responsible for providing an encrypted ACL link before any L2CAP communication can happen. Now connecting Bluetooth 2.1 or later devices with Bluetooth 2.0 and before devices are causing a regression. The encryption key size check needs to be moved out of the HCI connection handling into the L2CAP channel setup. To achieve this, the current check inside hci_conn_security() has been moved into l2cap_check_enc_key_size() helper function and then called from four decisions point inside L2CAP to cover all combinations of Secure Simple Pairing enabled devices and device using legacy pairing and legacy service security model. Fixes: d5bb334a8e17 ("Bluetooth: Align minimum encryption key size for LE and BR/EDR connections") Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203643 Signed-off-by: Marcel Holtmann <marcel@holtmann.org> Cc: stable@vger.kernel.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: void PngImage::readMetadata() { #ifdef DEBUG std::cerr << "Exiv2::PngImage::readMetadata: Reading PNG file " << io_->path() << std::endl; #endif if (io_->open() != 0) { throw Error(kerDataSourceOpenFailed, io_->path(), strError()); } IoCloser closer(*io_); if (!isPngType(*io_, true)) { throw Error(kerNotAnImage, "PNG"); } clearMetadata(); const long imgSize = (long) io_->size(); DataBuf cheaderBuf(8); // Chunk header: 4 bytes (data size) + 4 bytes (chunk type). while(!io_->eof()) { std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_); readChunk(cheaderBuf, *io_); // Read chunk header. // Decode chunk data length. uint32_t chunkLength = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian); long pos = io_->tell(); if (pos == -1 || chunkLength > uint32_t(0x7FFFFFFF) || static_cast<long>(chunkLength) > imgSize - pos) { throw Exiv2::Error(kerFailedToReadImageData); } std::string chunkType(reinterpret_cast<char *>(cheaderBuf.pData_) + 4, 4); #ifdef DEBUG std::cout << "Exiv2::PngImage::readMetadata: chunk type: " << chunkType << " length: " << chunkLength << std::endl; #endif /// \todo analyse remaining chunks of the standard // Perform a chunk triage for item that we need. if (chunkType == "IEND" || chunkType == "IHDR" || chunkType == "tEXt" || chunkType == "zTXt" || chunkType == "iTXt" || chunkType == "iCCP") { DataBuf chunkData(chunkLength); readChunk(chunkData, *io_); // Extract chunk data. if (chunkType == "IEND") { return; // Last chunk found: we stop parsing. } else if (chunkType == "IHDR" && chunkData.size_ >= 8) { PngChunk::decodeIHDRChunk(chunkData, &pixelWidth_, &pixelHeight_); } else if (chunkType == "tEXt") { PngChunk::decodeTXTChunk(this, chunkData, PngChunk::tEXt_Chunk); } else if (chunkType == "zTXt") { PngChunk::decodeTXTChunk(this, chunkData, PngChunk::zTXt_Chunk); } else if (chunkType == "iTXt") { PngChunk::decodeTXTChunk(this, chunkData, PngChunk::iTXt_Chunk); } else if (chunkType == "iCCP") { // The ICC profile name can vary from 1-79 characters. uint32_t iccOffset = 0; while (iccOffset < 80 && iccOffset < chunkLength) { if (chunkData.pData_[iccOffset++] == 0x00) { break; } } profileName_ = std::string(reinterpret_cast<char *>(chunkData.pData_), iccOffset-1); ++iccOffset; // +1 = 'compressed' flag zlibToDataBuf(chunkData.pData_ + iccOffset, chunkLength - iccOffset, iccProfile_); #ifdef DEBUG std::cout << "Exiv2::PngImage::readMetadata: profile name: " << profileName_ << std::endl; std::cout << "Exiv2::PngImage::readMetadata: iccProfile.size_ (uncompressed) : " << iccProfile_.size_ << std::endl; #endif } // Set chunkLength to 0 in case we have read a supported chunk type. Otherwise, we need to seek the // file to the next chunk position. chunkLength = 0; } // Move to the next chunk: chunk data size + 4 CRC bytes. #ifdef DEBUG std::cout << "Exiv2::PngImage::readMetadata: Seek to offset: " << chunkLength + 4 << std::endl; #endif io_->seek(chunkLength + 4 , BasicIo::cur); if (io_->error() || io_->eof()) { throw Error(kerFailedToReadImageData); } } } // PngImage::readMetadata ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Avoid negative integer overflow when `iccOffset > chunkLength`. This fixes #790.'</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 Exiv2::http(Exiv2::Dictionary& request,Exiv2::Dictionary& response,std::string& errors) { if ( !request.count("verb") ) request["verb" ] = "GET"; if ( !request.count("header") ) request["header" ] = "" ; if ( !request.count("version")) request["version"] = "1.0"; if ( !request.count("port") ) request["port" ] = "" ; std::string file; errors = ""; int result = 0; //////////////////////////////////// // Windows specific code #ifdef WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); #endif const char* servername = request["server" ].c_str(); const char* page = request["page" ].c_str(); const char* verb = request["verb" ].c_str(); const char* header = request["header" ].c_str(); const char* version = request["version"].c_str(); const char* port = request["port" ].c_str(); const char* servername_p = servername; const char* port_p = port ; std::string url = std::string("http://") + request["server"] + request["page"]; // parse and change server if using a proxy const char* PROXI = "HTTP_PROXY"; const char* proxi = "http_proxy"; const char* PROXY = getenv(PROXI); const char* proxy = getenv(proxi); bool bProx = PROXY || proxy; const char* prox = bProx ? (proxy?proxy:PROXY):""; Exiv2::Uri Proxy = Exiv2::Uri::Parse(prox); // find the dictionary of no_proxy servers const char* NO_PROXI = "NO_PROXY"; const char* no_proxi = "no_proxy"; const char* NO_PROXY = getenv(NO_PROXI); const char* no_proxy = getenv(no_proxi); bool bNoProxy = NO_PROXY||no_proxy; std::string no_prox = std::string(bNoProxy?(no_proxy?no_proxy:NO_PROXY):""); Exiv2::Dictionary noProxy= stringToDict(no_prox + ",localhost,127.0.0.1"); // if the server is on the no_proxy list ... ignore the proxy! if ( noProxy.count(servername) ) bProx = false; if ( bProx ) { servername_p = Proxy.Host.c_str(); port_p = Proxy.Port.c_str(); page = url.c_str(); std::string p(proxy?proxi:PROXI); // std::cerr << p << '=' << prox << " page = " << page << std::endl; } if ( !port [0] ) port = "80"; if ( !port_p[0] ) port_p = "80"; //////////////////////////////////// // open the socket int sockfd = (int) socket(AF_INET , SOCK_STREAM,IPPROTO_TCP) ; if ( sockfd < 0 ) return error(errors, "unable to create socket\n",NULL,NULL,0) ; // connect the socket to the server int server = -1 ; // fill in the address struct sockaddr_in serv_addr ; int serv_len = sizeof(serv_addr); memset((char *)&serv_addr,0,serv_len); serv_addr.sin_addr.s_addr = inet_addr(servername_p); serv_addr.sin_family = AF_INET ; serv_addr.sin_port = htons(atoi(port_p)); // convert unknown servername into IP address // http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6uafinet.htm if (serv_addr.sin_addr.s_addr == (unsigned long)INADDR_NONE) { struct hostent* host = gethostbyname(servername_p); if ( !host ) return error(errors, "no such host", servername_p); memcpy(&serv_addr.sin_addr,host->h_addr,sizeof(serv_addr.sin_addr)); } makeNonBlocking(sockfd) ; //////////////////////////////////// // and connect server = connect(sockfd, (const struct sockaddr *) &serv_addr, serv_len) ; if ( server == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK ) return error(errors,"error - unable to connect to server = %s port = %s wsa_error = %d",servername_p,port_p,WSAGetLastError()); char buffer[32*1024+1]; size_t buff_l= sizeof buffer - 1 ; //////////////////////////////////// // format the request int n = snprintf(buffer,buff_l,httpTemplate,verb,page,version,servername,header) ; buffer[n] = 0 ; response["requestheaders"]=std::string(buffer,n); //////////////////////////////////// // send the header (we'll have to wait for the connection by the non-blocking socket) while ( sleep_ >= 0 && send(sockfd,buffer,n,0) == SOCKET_ERROR /* && WSAGetLastError() == WSAENOTCONN */ ) { Sleep(snooze) ; sleep_ -= snooze ; } if ( sleep_ < 0 ) return error(errors,"error - timeout connecting to server = %s port = %s wsa_error = %d",servername,port,WSAGetLastError()); int end = 0 ; // write position in buffer bool bSearching = true ; // looking for headers in the response int status= 200 ; // assume happiness //////////////////////////////////// // read and process the response int err ; n=forgive(recv(sockfd,buffer,(int)buff_l,0),err) ; while ( n >= 0 && OK(status) ) { if ( n ) { end += n ; buffer[end] = 0 ; size_t body = 0 ; // start of body if ( bSearching ) { // search for the body for ( size_t b = 0 ; bSearching && b < lengthof(blankLines) ; b++ ) { if ( strstr(buffer,blankLines[b]) ) { bSearching = false ; body = (int) ( strstr(buffer,blankLines[b]) - buffer ) + strlen(blankLines[b]) ; status = atoi(strchr(buffer,' ')) ; } } // parse response headers char* h = buffer; char C = ':' ; char N = '\n'; int i = 0 ; // initial byte in buffer while(buffer[i] == N ) i++; h = strchr(h+i,N)+1; response[""]=std::string(buffer+i).substr(0,h-buffer-2); result = atoi(strchr(buffer,' ')); char* c = strchr(h,C); char* first_newline = strchr(h,N); while ( c && first_newline && c < first_newline && h < buffer+body ) { std::string key(h); std::string value(c+1); key = key.substr(0,c-h); value = value.substr(0,first_newline-c-1); response[key]=value; h = first_newline+1; c = strchr(h,C); first_newline = strchr(h,N); } } // if the bufffer's full and we're still searching - give up! // this handles the possibility that there are no headers if ( bSearching && buff_l-end < 10 ) { bSearching = false ; body = 0 ; } if ( !bSearching && OK(status) ) { flushBuffer(buffer,body,end,file); } } n=forgive(recv(sockfd,buffer+end,(int)(buff_l-end),0),err) ; if ( !n ) { Sleep(snooze) ; sleep_ -= snooze ; if ( sleep_ < 0 ) n = FINISH ; } } if ( n != FINISH || !OK(status) ) { snprintf(buffer,sizeof buffer,"wsa_error = %d,n = %d,sleep_ = %d status = %d" , WSAGetLastError() , n , sleep_ , status ) ; error(errors,buffer,NULL,NULL,0) ; } else if ( bSearching && OK(status) ) { if ( end ) { // we finished OK without finding headers, flush the buffer flushBuffer(buffer,0,end,file) ; } else { return error(errors,"error - no response from server = %s port = %s wsa_error = %d",servername,port,WSAGetLastError()); } } //////////////////////////////////// // close sockets closesocket(server) ; closesocket(sockfd) ; response["body"]=file; return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Avoid null pointer exception due to NULL return value from strchr. This fixes #793.'</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 opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; /* Avoids index out of bounds access with include*/ if (index >= pi->include_size) { opj_pi_emit_error(pi, "Invalid access to pi->include"); return OPJ_FALSE; } if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Revert "[MJ2] Avoid index out of bounds access to pi->include[]" This reverts commit c277159986c80142180fbe5efb256bbf3bdf3edc. The commit didn't compile. include_size is not defined in openmj2'</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: g_keyfile_settings_backend_keyfile_write (GKeyfileSettingsBackend *kfsb) { gchar *contents; gsize length; contents = g_key_file_to_data (kfsb->keyfile, &length, NULL); g_file_replace_contents (kfsb->file, contents, length, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL, NULL, NULL); compute_checksum (kfsb->digest, contents, length); g_free (contents); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-732'], 'message': 'keyfile settings: Use tighter permissions When creating directories, create them with 700 permissions, instead of 777. Closes: #1658'</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: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { ChannelType channel; const char *option; ImageInfo *mogrify_info; MagickStatusType status; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); channel=mogrify_info->channel; status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL); InheritException(exception,&(*images)->exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel",option+1) == 0) { if (*option == '+') { channel=DefaultChannels; break; } channel=(ChannelType) ParseChannelOption(argv[i+1]); break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImageChannel(image,channel,clut_image); clut_image=DestroyImage(clut_image); InheritException(exception,&image->exception); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images); combine_image=CombineImages(*images,channel,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { const char *option; double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedMetric; option=GetImageOption(image_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImageChannels(image,reconstruct_image, channel,metric,&distortion,exception); if (difference_image == (Image *) NULL) break; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { Image *mask_image, *composite_image, *image; RectangleInfo geometry; (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); composite_image=RemoveFirstImageFromList(images); if (composite_image == (Image *) NULL) { status=MagickFalse; break; } (void) TransformImage(&composite_image,(char *) NULL, composite_image->geometry); SetGeometry(composite_image,&geometry); (void) ParseAbsoluteGeometry(composite_image->geometry,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity, &geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image != (Image *) NULL) { if ((image->compose == DisplaceCompositeOp) || (image->compose == DistortCompositeOp)) { /* Merge Y displacement into X displacement image. */ (void) CompositeImage(composite_image,CopyGreenCompositeOp, mask_image,0,0); mask_image=DestroyImage(mask_image); } else { /* Set a blending mask for the composition. */ if (image->mask != (Image *) NULL) image->mask=DestroyImage(image->mask); image->mask=mask_image; (void) NegateImage(image->mask,MagickFalse); } } (void) CompositeImageChannel(image,channel,image->compose, composite_image,geometry.x,geometry.y); if (mask_image != (Image *) NULL) { image->mask=DestroyImage(image->mask); mask_image=image->mask; } composite_image=DestroyImage(composite_image); InheritException(exception,&image->exception); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images); deconstruct_image=DeconstructImages(*images,exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither=MagickFalse; break; } quantize_info->dither=MagickTrue; quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images); fx_image=FxImageChannel(*images,channel,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImageChannel(image,channel,hald_image); hald_image=DestroyImage(hald_image); InheritException(exception,&image->exception); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { p=DestroyImage(p); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; ImageLayerMethod method; (void) SyncImagesSettings(mogrify_info,*images); layers=(Image *) NULL; method=(ImageLayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImageLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); InheritException(exception,&(*images)->exception); (void) RemapImages(quantize_info,*images,(Image *) NULL); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL); InheritException(exception,&(*images)->exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MaxTextExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images); args=InterpretImageProperties(mogrify_info,*images,argv[i+1]); InheritException(exception,&(*images)->exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImageChannel(*images,channel, number_arguments >> 1,arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; break; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images); string=InterpretImageProperties(mogrify_info,*images,argv[i+1]); if (string == (char *) NULL) break; InheritException(exception,&(*images)->exception); (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *arguments; int next, status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MaxTextExtent-1)) token=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; arguments=argv[i+1]; token_info=AcquireTokenInfo(); status=Tokenizer(token_info,0,token,length,arguments,"","=", "\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (status == 0) { const char *argv; argv=(&(arguments[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&argv, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); InheritException(exception,&(*images)->exception); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MaxTextExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images); (void) FormatLocaleString(key,MaxTextExtent,"cache:%s",argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1623'</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 MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], format, magick[MaxTextExtent]; const char *value; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *pixels, *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ max_value=GetQuantumRange(image->depth); packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MaxTextExtent); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,&image->exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,&image->exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MaxTextExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MaxTextExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,&image->exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MaxTextExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent); if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent); break; } default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MaxTextExtent); break; } } if (image->matte != MagickFalse) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n", type); (void) WriteBlobString(image,buffer); } /* Convert to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)), ScaleQuantumToChar(GetPixelGreen(p)), ScaleQuantumToChar(GetPixelBlue(p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)), ScaleQuantumToShort(GetPixelGreen(p)), ScaleQuantumToShort(GetPixelBlue(p))); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)), ScaleQuantumToLong(GetPixelGreen(p)), ScaleQuantumToLong(GetPixelBlue(p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 32) pixel=ScaleQuantumToLong(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1612'</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 PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1586'</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: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1609'</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 MagickBooleanType WriteDPXImage(const ImageInfo *image_info, Image *image) { const char *value; const StringInfo *profile; DPXInfo dpx; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; GeometryInfo geometry_info; QuantumInfo *quantum_info; QuantumType quantum_type; register const PixelPacket *p; register ssize_t i; ssize_t count, horizontal_factor, vertical_factor, y; size_t channels, extent; time_t seconds; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); horizontal_factor=4; vertical_factor=4; if (image_info->sampling_factor != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(image_info->sampling_factor,&geometry_info); horizontal_factor=(ssize_t) geometry_info.rho; vertical_factor=(ssize_t) geometry_info.sigma; if ((flags & SigmaValue) == 0) vertical_factor=horizontal_factor; if ((horizontal_factor != 1) && (horizontal_factor != 2) && (horizontal_factor != 4) && (vertical_factor != 1) && (vertical_factor != 2) && (vertical_factor != 4)) ThrowWriterException(CorruptImageError,"UnexpectedSamplingFactor"); } if ((image->colorspace == YCbCrColorspace) && ((horizontal_factor == 2) || (vertical_factor == 2))) if ((image->columns % 2) != 0) image->columns++; status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Write file header. */ (void) memset(&dpx,0,sizeof(dpx)); offset=0; dpx.file.magic=0x53445058U; offset+=WriteBlobLong(image,dpx.file.magic); dpx.file.image_offset=0x2000U; profile=GetImageProfile(image,"dpx:user-data"); if (profile != (StringInfo *) NULL) { if (GetStringInfoLength(profile) > 1048576) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); dpx.file.image_offset+=(unsigned int) GetStringInfoLength(profile); dpx.file.image_offset=(((dpx.file.image_offset+0x2000-1)/0x2000)*0x2000); } offset+=WriteBlobLong(image,dpx.file.image_offset); (void) strncpy(dpx.file.version,"V2.0",sizeof(dpx.file.version)-1); offset+=WriteBlob(image,8,(unsigned char *) &dpx.file.version); channels=1; if (IsGrayImage(image,&image->exception) == MagickFalse) channels=3; if (image->matte != MagickFalse) channels++; dpx.file.file_size=(unsigned int) (channels*image->columns*image->rows+ dpx.file.image_offset); offset+=WriteBlobLong(image,dpx.file.file_size); dpx.file.ditto_key=1U; /* new frame */ offset+=WriteBlobLong(image,dpx.file.ditto_key); dpx.file.generic_size=0x00000680U; offset+=WriteBlobLong(image,dpx.file.generic_size); dpx.file.industry_size=0x00000180U; offset+=WriteBlobLong(image,dpx.file.industry_size); dpx.file.user_size=0; if (profile != (StringInfo *) NULL) { dpx.file.user_size+=(unsigned int) GetStringInfoLength(profile); dpx.file.user_size=(((dpx.file.user_size+0x2000-1)/0x2000)*0x2000); } offset+=WriteBlobLong(image,dpx.file.user_size); value=GetDPXProperty(image,"dpx:file.filename"); if (value != (const char *) NULL) (void) strncpy(dpx.file.filename,value,sizeof(dpx.file.filename)-1); offset+=WriteBlob(image,sizeof(dpx.file.filename),(unsigned char *) dpx.file.filename); seconds=time((time_t *) NULL); (void) FormatMagickTime(seconds,sizeof(dpx.file.timestamp), dpx.file.timestamp); offset+=WriteBlob(image,sizeof(dpx.file.timestamp),(unsigned char *) dpx.file.timestamp); (void) strncpy(dpx.file.creator,MagickAuthoritativeURL, sizeof(dpx.file.creator)-1); value=GetDPXProperty(image,"dpx:file.creator"); if (value != (const char *) NULL) (void) strncpy(dpx.file.creator,value,sizeof(dpx.file.creator)-1); offset+=WriteBlob(image,sizeof(dpx.file.creator),(unsigned char *) dpx.file.creator); value=GetDPXProperty(image,"dpx:file.project"); if (value != (const char *) NULL) (void) strncpy(dpx.file.project,value,sizeof(dpx.file.project)-1); offset+=WriteBlob(image,sizeof(dpx.file.project),(unsigned char *) dpx.file.project); value=GetDPXProperty(image,"dpx:file.copyright"); if (value != (const char *) NULL) (void) strncpy(dpx.file.copyright,value,sizeof(dpx.file.copyright)-1); offset+=WriteBlob(image,sizeof(dpx.file.copyright),(unsigned char *) dpx.file.copyright); dpx.file.encrypt_key=(~0U); offset+=WriteBlobLong(image,dpx.file.encrypt_key); offset+=WriteBlob(image,sizeof(dpx.file.reserve),(unsigned char *) dpx.file.reserve); /* Write image header. */ switch (image->orientation) { default: case TopLeftOrientation: dpx.image.orientation=0; break; case TopRightOrientation: dpx.image.orientation=1; break; case BottomLeftOrientation: dpx.image.orientation=2; break; case BottomRightOrientation: dpx.image.orientation=3; break; case LeftTopOrientation: dpx.image.orientation=4; break; case RightTopOrientation: dpx.image.orientation=5; break; case LeftBottomOrientation: dpx.image.orientation=6; break; case RightBottomOrientation: dpx.image.orientation=7; break; } offset+=WriteBlobShort(image,dpx.image.orientation); dpx.image.number_elements=1; offset+=WriteBlobShort(image,dpx.image.number_elements); if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); offset+=WriteBlobLong(image,(unsigned int) image->columns); offset+=WriteBlobLong(image,(unsigned int) image->rows); for (i=0; i < 8; i++) { dpx.image.image_element[i].data_sign=0U; offset+=WriteBlobLong(image,dpx.image.image_element[i].data_sign); dpx.image.image_element[i].low_data=0U; offset+=WriteBlobLong(image,dpx.image.image_element[i].low_data); dpx.image.image_element[i].low_quantity=0.0f; offset+=WriteBlobFloat(image,dpx.image.image_element[i].low_quantity); dpx.image.image_element[i].high_data=0U; offset+=WriteBlobLong(image,dpx.image.image_element[i].high_data); dpx.image.image_element[i].high_quantity=0.0f; offset+=WriteBlobFloat(image,dpx.image.image_element[i].high_quantity); dpx.image.image_element[i].descriptor=0; if (i == 0) switch (image->colorspace) { case Rec601YCbCrColorspace: case Rec709YCbCrColorspace: case YCbCrColorspace: { dpx.image.image_element[i].descriptor=CbYCr444ComponentType; if (image->matte != MagickFalse) dpx.image.image_element[i].descriptor=CbYCrA4444ComponentType; break; } default: { dpx.image.image_element[i].descriptor=RGBComponentType; if (image->matte != MagickFalse) dpx.image.image_element[i].descriptor=RGBAComponentType; if ((image_info->type != TrueColorType) && (image->matte == MagickFalse) && (SetImageGray(image,&image->exception) != MagickFalse)) dpx.image.image_element[i].descriptor=LumaComponentType; break; } } offset+=WriteBlobByte(image,dpx.image.image_element[i].descriptor); dpx.image.image_element[i].transfer_characteristic=0; if (image->colorspace == LogColorspace) dpx.image.image_element[0].transfer_characteristic= PrintingDensityColorimetric; offset+=WriteBlobByte(image, dpx.image.image_element[i].transfer_characteristic); dpx.image.image_element[i].colorimetric=0; offset+=WriteBlobByte(image,dpx.image.image_element[i].colorimetric); dpx.image.image_element[i].bit_size=0; if (i == 0) dpx.image.image_element[i].bit_size=(unsigned char) image->depth; offset+=WriteBlobByte(image,dpx.image.image_element[i].bit_size); dpx.image.image_element[i].packing=0; if ((image->depth == 10) || (image->depth == 12)) dpx.image.image_element[i].packing=1; offset+=WriteBlobShort(image,dpx.image.image_element[i].packing); dpx.image.image_element[i].encoding=0; offset+=WriteBlobShort(image,dpx.image.image_element[i].encoding); dpx.image.image_element[i].data_offset=0U; if (i == 0) dpx.image.image_element[i].data_offset=dpx.file.image_offset; offset+=WriteBlobLong(image,dpx.image.image_element[i].data_offset); dpx.image.image_element[i].end_of_line_padding=0U; offset+=WriteBlobLong(image,dpx.image.image_element[i].end_of_line_padding); offset+=WriteBlobLong(image, dpx.image.image_element[i].end_of_image_padding); offset+=WriteBlob(image,sizeof(dpx.image.image_element[i].description), (unsigned char *) dpx.image.image_element[i].description); } offset+=WriteBlob(image,sizeof(dpx.image.reserve),(unsigned char *) dpx.image.reserve); /* Write orientation header. */ if ((image->rows != image->magick_rows) || (image->columns != image->magick_columns)) { /* These properties are not valid if image size changed. */ (void) DeleteImageProperty(image,"dpx:orientation.x_offset"); (void) DeleteImageProperty(image,"dpx:orientation.y_offset"); (void) DeleteImageProperty(image,"dpx:orientation.x_center"); (void) DeleteImageProperty(image,"dpx:orientation.y_center"); (void) DeleteImageProperty(image,"dpx:orientation.x_size"); (void) DeleteImageProperty(image,"dpx:orientation.y_size"); } dpx.orientation.x_offset=0U; value=GetDPXProperty(image,"dpx:orientation.x_offset"); if (value != (const char *) NULL) dpx.orientation.x_offset=(unsigned int) StringToUnsignedLong(value); offset+=WriteBlobLong(image,dpx.orientation.x_offset); dpx.orientation.y_offset=0U; value=GetDPXProperty(image,"dpx:orientation.y_offset"); if (value != (const char *) NULL) dpx.orientation.y_offset=(unsigned int) StringToUnsignedLong(value); offset+=WriteBlobLong(image,dpx.orientation.y_offset); dpx.orientation.x_center=0.0f; value=GetDPXProperty(image,"dpx:orientation.x_center"); if (value != (const char *) NULL) dpx.orientation.x_center=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.orientation.x_center); dpx.orientation.y_center=0.0f; value=GetDPXProperty(image,"dpx:orientation.y_center"); if (value != (const char *) NULL) dpx.orientation.y_center=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.orientation.y_center); dpx.orientation.x_size=0U; value=GetDPXProperty(image,"dpx:orientation.x_size"); if (value != (const char *) NULL) dpx.orientation.x_size=(unsigned int) StringToUnsignedLong(value); offset+=WriteBlobLong(image,dpx.orientation.x_size); dpx.orientation.y_size=0U; value=GetDPXProperty(image,"dpx:orientation.y_size"); if (value != (const char *) NULL) dpx.orientation.y_size=(unsigned int) StringToUnsignedLong(value); offset+=WriteBlobLong(image,dpx.orientation.y_size); value=GetDPXProperty(image,"dpx:orientation.filename"); if (value != (const char *) NULL) (void) strncpy(dpx.orientation.filename,value, sizeof(dpx.orientation.filename)-1); offset+=WriteBlob(image,sizeof(dpx.orientation.filename),(unsigned char *) dpx.orientation.filename); offset+=WriteBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *) dpx.orientation.timestamp); value=GetDPXProperty(image,"dpx:orientation.device"); if (value != (const char *) NULL) (void) strncpy(dpx.orientation.device,value, sizeof(dpx.orientation.device)-1); offset+=WriteBlob(image,sizeof(dpx.orientation.device),(unsigned char *) dpx.orientation.device); value=GetDPXProperty(image,"dpx:orientation.serial"); if (value != (const char *) NULL) (void) strncpy(dpx.orientation.serial,value, sizeof(dpx.orientation.serial)-1); offset+=WriteBlob(image,sizeof(dpx.orientation.serial),(unsigned char *) dpx.orientation.serial); for (i=0; i < 4; i++) dpx.orientation.border[i]=0; value=GetDPXProperty(image,"dpx:orientation.border"); if (value != (const char *) NULL) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; dpx.orientation.border[0]=(unsigned short) (geometry_info.rho+0.5); dpx.orientation.border[1]=(unsigned short) (geometry_info.sigma+0.5); dpx.orientation.border[2]=(unsigned short) (geometry_info.xi+0.5); dpx.orientation.border[3]=(unsigned short) (geometry_info.psi+0.5); } for (i=0; i < 4; i++) offset+=WriteBlobShort(image,dpx.orientation.border[i]); for (i=0; i < 2; i++) dpx.orientation.aspect_ratio[i]=0U; value=GetDPXProperty(image,"dpx:orientation.aspect_ratio"); if (value != (const char *) NULL) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; dpx.orientation.aspect_ratio[0]=(unsigned int) (geometry_info.rho+0.5); dpx.orientation.aspect_ratio[1]=(unsigned int) (geometry_info.sigma+0.5); } for (i=0; i < 2; i++) offset+=WriteBlobLong(image,dpx.orientation.aspect_ratio[i]); offset+=WriteBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *) dpx.orientation.reserve); /* Write film header. */ (void) memset(dpx.film.id,0,sizeof(dpx.film.id)); value=GetDPXProperty(image,"dpx:film.id"); if (value != (const char *) NULL) (void) strncpy(dpx.film.id,value,sizeof(dpx.film.id)-1); offset+=WriteBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id); (void) memset(dpx.film.type,0,sizeof(dpx.film.type)); value=GetDPXProperty(image,"dpx:film.type"); if (value != (const char *) NULL) (void) strncpy(dpx.film.type,value,sizeof(dpx.film.type)-1); offset+=WriteBlob(image,sizeof(dpx.film.type),(unsigned char *) dpx.film.type); (void) memset(dpx.film.offset,0,sizeof(dpx.film.offset)); value=GetDPXProperty(image,"dpx:film.offset"); if (value != (const char *) NULL) (void) strncpy(dpx.film.offset,value,sizeof(dpx.film.offset)-1); offset+=WriteBlob(image,sizeof(dpx.film.offset),(unsigned char *) dpx.film.offset); (void) memset(dpx.film.prefix,0,sizeof(dpx.film.prefix)); value=GetDPXProperty(image,"dpx:film.prefix"); if (value != (const char *) NULL) (void) strncpy(dpx.film.prefix,value,sizeof(dpx.film.prefix)-1); offset+=WriteBlob(image,sizeof(dpx.film.prefix),(unsigned char *) dpx.film.prefix); (void) memset(dpx.film.count,0,sizeof(dpx.film.count)); value=GetDPXProperty(image,"dpx:film.count"); if (value != (const char *) NULL) (void) strncpy(dpx.film.count,value,sizeof(dpx.film.count)-1); offset+=WriteBlob(image,sizeof(dpx.film.count),(unsigned char *) dpx.film.count); (void) memset(dpx.film.format,0,sizeof(dpx.film.format)); value=GetDPXProperty(image,"dpx:film.format"); if (value != (const char *) NULL) (void) strncpy(dpx.film.format,value,sizeof(dpx.film.format)-1); offset+=WriteBlob(image,sizeof(dpx.film.format),(unsigned char *) dpx.film.format); dpx.film.frame_position=0U; value=GetDPXProperty(image,"dpx:film.frame_position"); if (value != (const char *) NULL) dpx.film.frame_position=(unsigned int) StringToUnsignedLong(value); offset+=WriteBlobLong(image,dpx.film.frame_position); dpx.film.sequence_extent=0U; value=GetDPXProperty(image,"dpx:film.sequence_extent"); if (value != (const char *) NULL) dpx.film.sequence_extent=(unsigned int) StringToUnsignedLong(value); offset+=WriteBlobLong(image,dpx.film.sequence_extent); dpx.film.held_count=0U; value=GetDPXProperty(image,"dpx:film.held_count"); if (value != (const char *) NULL) dpx.film.held_count=(unsigned int) StringToUnsignedLong(value); offset+=WriteBlobLong(image,dpx.film.held_count); dpx.film.frame_rate=0.0f; value=GetDPXProperty(image,"dpx:film.frame_rate"); if (value != (const char *) NULL) dpx.film.frame_rate=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.film.frame_rate); dpx.film.shutter_angle=0.0f; value=GetDPXProperty(image,"dpx:film.shutter_angle"); if (value != (const char *) NULL) dpx.film.shutter_angle=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.film.shutter_angle); (void) memset(dpx.film.frame_id,0,sizeof(dpx.film.frame_id)); value=GetDPXProperty(image,"dpx:film.frame_id"); if (value != (const char *) NULL) (void) strncpy(dpx.film.frame_id,value,sizeof(dpx.film.frame_id)-1); offset+=WriteBlob(image,sizeof(dpx.film.frame_id),(unsigned char *) dpx.film.frame_id); value=GetDPXProperty(image,"dpx:film.slate"); if (value != (const char *) NULL) (void) strncpy(dpx.film.slate,value,sizeof(dpx.film.slate)-1); offset+=WriteBlob(image,sizeof(dpx.film.slate),(unsigned char *) dpx.film.slate); offset+=WriteBlob(image,sizeof(dpx.film.reserve),(unsigned char *) dpx.film.reserve); /* Write television header. */ value=GetDPXProperty(image,"dpx:television.time.code"); if (value != (const char *) NULL) dpx.television.time_code=StringToTimeCode(value); offset+=WriteBlobLong(image,dpx.television.time_code); value=GetDPXProperty(image,"dpx:television.user.bits"); if (value != (const char *) NULL) dpx.television.user_bits=StringToTimeCode(value); offset+=WriteBlobLong(image,dpx.television.user_bits); value=GetDPXProperty(image,"dpx:television.interlace"); if (value != (const char *) NULL) dpx.television.interlace=(unsigned char) StringToLong(value); offset+=WriteBlobByte(image,dpx.television.interlace); value=GetDPXProperty(image,"dpx:television.field_number"); if (value != (const char *) NULL) dpx.television.field_number=(unsigned char) StringToLong(value); offset+=WriteBlobByte(image,dpx.television.field_number); dpx.television.video_signal=0; value=GetDPXProperty(image,"dpx:television.video_signal"); if (value != (const char *) NULL) dpx.television.video_signal=(unsigned char) StringToLong(value); offset+=WriteBlobByte(image,dpx.television.video_signal); dpx.television.padding=0; value=GetDPXProperty(image,"dpx:television.padding"); if (value != (const char *) NULL) dpx.television.padding=(unsigned char) StringToLong(value); offset+=WriteBlobByte(image,dpx.television.padding); dpx.television.horizontal_sample_rate=0.0f; value=GetDPXProperty(image,"dpx:television.horizontal_sample_rate"); if (value != (const char *) NULL) dpx.television.horizontal_sample_rate=StringToDouble(value, (char **) NULL); offset+=WriteBlobFloat(image,dpx.television.horizontal_sample_rate); dpx.television.vertical_sample_rate=0.0f; value=GetDPXProperty(image,"dpx:television.vertical_sample_rate"); if (value != (const char *) NULL) dpx.television.vertical_sample_rate=StringToDouble(value, (char **) NULL); offset+=WriteBlobFloat(image,dpx.television.vertical_sample_rate); dpx.television.frame_rate=0.0f; value=GetDPXProperty(image,"dpx:television.frame_rate"); if (value != (const char *) NULL) dpx.television.frame_rate=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.frame_rate); dpx.television.time_offset=0.0f; value=GetDPXProperty(image,"dpx:television.time_offset"); if (value != (const char *) NULL) dpx.television.time_offset=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.time_offset); dpx.television.gamma=0.0f; value=GetDPXProperty(image,"dpx:television.gamma"); if (value != (const char *) NULL) dpx.television.gamma=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.gamma); dpx.television.black_level=0.0f; value=GetDPXProperty(image,"dpx:television.black_level"); if (value != (const char *) NULL) dpx.television.black_level=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.black_level); dpx.television.black_gain=0.0f; value=GetDPXProperty(image,"dpx:television.black_gain"); if (value != (const char *) NULL) dpx.television.black_gain=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.black_gain); dpx.television.break_point=0.0f; value=GetDPXProperty(image,"dpx:television.break_point"); if (value != (const char *) NULL) dpx.television.break_point=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.break_point); dpx.television.white_level=0.0f; value=GetDPXProperty(image,"dpx:television.white_level"); if (value != (const char *) NULL) dpx.television.white_level=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.white_level); dpx.television.integration_times=0.0f; value=GetDPXProperty(image,"dpx:television.integration_times"); if (value != (const char *) NULL) dpx.television.integration_times=StringToDouble(value,(char **) NULL); offset+=WriteBlobFloat(image,dpx.television.integration_times); offset+=WriteBlob(image,sizeof(dpx.television.reserve),(unsigned char *) dpx.television.reserve); /* Write user header. */ value=GetDPXProperty(image,"dpx:user.id"); if (value != (const char *) NULL) (void) strncpy(dpx.user.id,value,sizeof(dpx.user.id)-1); offset+=WriteBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id); if (profile != (StringInfo *) NULL) offset+=WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); while (offset < (MagickOffsetType) dpx.image.image_element[0].data_offset) { count=WriteBlobByte(image,0x00); if (count != 1) { ThrowFileException(&image->exception,FileOpenError,"UnableToWriteFile", image->filename); break; } offset+=count; } /* Convert pixel packets to DPX raster image. */ quantum_info=AcquireQuantumInfo(image_info,image); SetQuantumQuantum(quantum_info,32); SetQuantumPack(quantum_info,dpx.image.image_element[0].packing == 0 ? MagickTrue : MagickFalse); quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; if (image->colorspace == YCbCrColorspace) { quantum_type=CbYCrQuantum; if (image->matte != MagickFalse) quantum_type=CbYCrAQuantum; if ((horizontal_factor == 2) || (vertical_factor == 2)) quantum_type=CbYCrYQuantum; } extent=GetBytesPerRow(image->columns,image->matte != MagickFalse ? 4UL : 3UL, image->depth,dpx.image.image_element[0].packing == 0 ? MagickFalse : MagickTrue); if ((image_info->type != TrueColorType) && (image->matte == MagickFalse) && (SetImageGray(image,&image->exception) != MagickFalse)) { quantum_type=GrayQuantum; extent=GetBytesPerRow(image->columns,1UL,image->depth, dpx.image.image_element[0].packing == 0 ? MagickFalse : MagickTrue); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { size_t length; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); if (y < (ssize_t) image->rows) ThrowWriterException(CorruptImageError,"UnableToWriteImageData"); (void) CloseBlob(image); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1517'</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 JPXStream::init() { Object oLen, cspace, smaskInData; if (getDict()) { oLen = getDict()->lookup("Length"); cspace = getDict()->lookup("ColorSpace"); smaskInData = getDict()->lookup("SMaskInData"); } int bufSize = BUFFER_INITIAL_SIZE; if (oLen.isInt()) bufSize = oLen.getInt(); bool indexed = false; if (cspace.isArray() && cspace.arrayGetLength() > 0) { const Object cstype = cspace.arrayGet(0); if (cstype.isName("Indexed")) indexed = true; } priv->smaskInData = 0; if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt(); int length = 0; unsigned char *buf = str->toUnsignedChars(&length, bufSize); priv->init2(OPJ_CODEC_JP2, buf, length, indexed); gfree(buf); if (priv->image) { int numComps = (priv->image) ? priv->image->numcomps : 1; int alpha = 0; if (priv->image) { if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; } else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; } else if (numComps == 2) { numComps = 1; alpha = 1; } else if (numComps > 4) { numComps = 4; alpha = 1; } else { alpha = 0; } } priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h; priv->ncomps = priv->image->numcomps; if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--; for (int component = 0; component < priv->ncomps; component++) { if (priv->image->comps[component].data == nullptr) { close(); break; } const int componentPixels = priv->image->comps[component].w * priv->image->comps[component].h; if (componentPixels != priv->npixels) { error(errSyntaxWarning, -1, "Component {0:d} has different WxH than component 0", component); close(); break; } unsigned char *cdata = (unsigned char *)priv->image->comps[component].data; int adjust = 0; int depth = priv->image->comps[component].prec; if (priv->image->comps[component].prec > 8) adjust = priv->image->comps[component].prec - 8; int sgndcorr = 0; if (priv->image->comps[component].sgnd) sgndcorr = 1 << (priv->image->comps[0].prec - 1); for (int i = 0; i < priv->npixels; i++) { int r = priv->image->comps[component].data[i]; *(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed); } } } else { priv->npixels = 0; } priv->counter = 0; priv->ccounter = 0; priv->inited = true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'JPXStream::init: ignore dict Length if clearly broken Fixes issue #805'</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 set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || /* check for zero in F_SECT_PER_TRACK */ (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'floppy: fix out-of-bounds read in copy_buffer This fixes a global out-of-bounds read access in the copy_buffer function of the floppy driver. The FDDEFPRM ioctl allows one to set the geometry of a disk. The sect and head fields (unsigned int) of the floppy_drive structure are used to compute the max_sector (int) in the make_raw_rw_request function. It is possible to overflow the max_sector. Next, max_sector is passed to the copy_buffer function and used in one of the memcpy calls. An unprivileged user could trigger the bug if the device is accessible, but requires a floppy disk to be inserted. The patch adds the check for the .sect * .head multiplication for not overflowing in the set_geometry function. The bug was found by syzkaller. Signed-off-by: Denis Efremov <efremov@ispras.ru> Tested-by: Willy Tarreau <w@1wt.eu> 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 void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { ipfix_template_record_t *ipfix_template_record; // a template flowset can contain multiple records ( templates ) while ( size_left ) { uint32_t id; // map next record. ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; id = ntohs(ipfix_template_record->TemplateID); // count = ntohs(ipfix_template_record->FieldCount); if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) { // withdraw all templates remove_all_translation_tables(exporter); ReInitExtensionMapList(fs); } else { remove_translation_table(fs, exporter, id); } DataPtr = DataPtr + 4; if ( size_left < 4 ) { // pading dbg_printf("Skip %u bytes padding\n", size_left); size_left = 0; } } } // End of Process_ipfix_template_withdraw ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix potential unsigned integer underflow'</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: asn1_get_oid( unsigned char **buffer, /* IO - Pointer in buffer */ unsigned char *bufend, /* I - End of buffer */ unsigned length, /* I - Length of value */ int *oid, /* I - OID buffer */ int oidsize) /* I - Size of OID buffer */ { unsigned char *valend; /* End of value */ int *oidptr, /* Current OID */ *oidend; /* End of OID buffer */ int number; /* OID number */ valend = *buffer + length; oidptr = oid; oidend = oid + oidsize - 1; if (valend > bufend) valend = bufend; number = asn1_get_packed(buffer, bufend); if (number < 80) { *oidptr++ = number / 40; number = number % 40; *oidptr++ = number; } else { *oidptr++ = 2; number -= 80; *oidptr++ = number; } while (*buffer < valend) { number = asn1_get_packed(buffer, bufend); if (oidptr < oidend) *oidptr++ = number; } *oidptr = -1; return ((int)(oidptr - oid)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues: - CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251) - Fixed IPP buffer overflow (rdar://50035411) - Fixed memory disclosure issue in the scheduler (rdar://51373853) - Fixed DoS issues in the scheduler (rdar://51373929)'</s>