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: static int handle_gid_request(enum request_types request_type, gid_t gid, const char *domain_name, struct berval **berval) { int ret; struct group grp; char *sid_str = NULL; enum sss_id_type id_type; size_t buf_len; char *buf = NULL; struct sss_nss_kv *kv_list = NULL; ret = get_buffer(&buf_len, &buf); if (ret != LDAP_SUCCESS) { return ret; } if (request_type == REQ_SIMPLE) { ret = sss_nss_getsidbyid(gid, &sid_str, &id_type); if (ret != 0 || id_type != SSS_ID_TYPE_GID) { if (ret == ENOENT) { ret = LDAP_NO_SUCH_OBJECT; } else { ret = LDAP_OPERATIONS_ERROR; } goto done; } ret = pack_ber_sid(sid_str, berval); } else { ret = getgrgid_r_wrapper(MAX_BUF, gid, &grp, &buf, &buf_len); if (ret != 0) { if (ret == ENOMEM || ret == ERANGE) { ret = LDAP_OPERATIONS_ERROR; } else { ret = LDAP_NO_SUCH_OBJECT; } goto done; } if (request_type == REQ_FULL_WITH_GROUPS) { ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type); if (ret != 0 || !(id_type == SSS_ID_TYPE_GID || id_type == SSS_ID_TYPE_BOTH)) { if (ret == ENOENT) { ret = LDAP_NO_SUCH_OBJECT; } else { ret = LDAP_OPERATIONS_ERROR; } goto done; } } ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP : RESP_GROUP_MEMBERS), domain_name, grp.gr_name, grp.gr_gid, grp.gr_mem, kv_list, berval); } done: sss_nss_free_kv(kv_list); free(sid_str); free(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable The get*_r_wrapper() calls expect a maximum buffer size to avoid memory shortage if too many threads try to allocate buffers e.g. for large groups. With this patch this size can be configured by setting ipaExtdomMaxNssBufSize in the plugin config object cn=ipa_extdom_extop,cn=plugins,cn=config. Related to https://fedorahosted.org/freeipa/ticket/4908 Reviewed-By: Alexander Bokovoy <abokovoy@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: xmlTextReaderSetup(xmlTextReaderPtr reader, xmlParserInputBufferPtr input, const char *URL, const char *encoding, int options) { if (reader == NULL) { if (input != NULL) xmlFreeParserInputBuffer(input); return (-1); } /* * we force the generation of compact text nodes on the reader * since usr applications should never modify the tree */ options |= XML_PARSE_COMPACT; reader->doc = NULL; reader->entNr = 0; reader->parserFlags = options; reader->validate = XML_TEXTREADER_NOT_VALIDATE; if ((input != NULL) && (reader->input != NULL) && (reader->allocs & XML_TEXTREADER_INPUT)) { xmlFreeParserInputBuffer(reader->input); reader->input = NULL; reader->allocs -= XML_TEXTREADER_INPUT; } if (input != NULL) { reader->input = input; reader->allocs |= XML_TEXTREADER_INPUT; } if (reader->buffer == NULL) reader->buffer = xmlBufCreateSize(100); if (reader->buffer == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlTextReaderSetup : malloc failed\n"); return (-1); } if (reader->sax == NULL) reader->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler)); if (reader->sax == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlTextReaderSetup : malloc failed\n"); return (-1); } xmlSAXVersion(reader->sax, 2); reader->startElement = reader->sax->startElement; reader->sax->startElement = xmlTextReaderStartElement; reader->endElement = reader->sax->endElement; reader->sax->endElement = xmlTextReaderEndElement; #ifdef LIBXML_SAX1_ENABLED if (reader->sax->initialized == XML_SAX2_MAGIC) { #endif /* LIBXML_SAX1_ENABLED */ reader->startElementNs = reader->sax->startElementNs; reader->sax->startElementNs = xmlTextReaderStartElementNs; reader->endElementNs = reader->sax->endElementNs; reader->sax->endElementNs = xmlTextReaderEndElementNs; #ifdef LIBXML_SAX1_ENABLED } else { reader->startElementNs = NULL; reader->endElementNs = NULL; } #endif /* LIBXML_SAX1_ENABLED */ reader->characters = reader->sax->characters; reader->sax->characters = xmlTextReaderCharacters; reader->sax->ignorableWhitespace = xmlTextReaderCharacters; reader->cdataBlock = reader->sax->cdataBlock; reader->sax->cdataBlock = xmlTextReaderCDataBlock; reader->mode = XML_TEXTREADER_MODE_INITIAL; reader->node = NULL; reader->curnode = NULL; if (input != NULL) { if (xmlBufUse(reader->input->buffer) < 4) { xmlParserInputBufferRead(input, 4); } if (reader->ctxt == NULL) { if (xmlBufUse(reader->input->buffer) >= 4) { reader->ctxt = xmlCreatePushParserCtxt(reader->sax, NULL, (const char *) xmlBufContent(reader->input->buffer), 4, URL); reader->base = 0; reader->cur = 4; } else { reader->ctxt = xmlCreatePushParserCtxt(reader->sax, NULL, NULL, 0, URL); reader->base = 0; reader->cur = 0; } } else { xmlParserInputPtr inputStream; xmlParserInputBufferPtr buf; xmlCharEncoding enc = XML_CHAR_ENCODING_NONE; xmlCtxtReset(reader->ctxt); buf = xmlAllocParserInputBuffer(enc); if (buf == NULL) return(-1); inputStream = xmlNewInputStream(reader->ctxt); if (inputStream == NULL) { xmlFreeParserInputBuffer(buf); return(-1); } if (URL == NULL) inputStream->filename = NULL; else inputStream->filename = (char *) xmlCanonicPath((const xmlChar *) URL); inputStream->buf = buf; xmlBufResetInput(buf->buffer, inputStream); inputPush(reader->ctxt, inputStream); reader->cur = 0; } if (reader->ctxt == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlTextReaderSetup : malloc failed\n"); return (-1); } } if (reader->dict != NULL) { if (reader->ctxt->dict != NULL) { if (reader->dict != reader->ctxt->dict) { xmlDictFree(reader->dict); reader->dict = reader->ctxt->dict; } } else { reader->ctxt->dict = reader->dict; } } else { if (reader->ctxt->dict == NULL) reader->ctxt->dict = xmlDictCreate(); reader->dict = reader->ctxt->dict; } reader->ctxt->_private = reader; reader->ctxt->linenumbers = 1; reader->ctxt->dictNames = 1; /* * use the parser dictionnary to allocate all elements and attributes names */ reader->ctxt->docdict = 1; reader->ctxt->parseMode = XML_PARSE_READER; #ifdef LIBXML_XINCLUDE_ENABLED if (reader->xincctxt != NULL) { xmlXIncludeFreeContext(reader->xincctxt); reader->xincctxt = NULL; } if (options & XML_PARSE_XINCLUDE) { reader->xinclude = 1; reader->xinclude_name = xmlDictLookup(reader->dict, XINCLUDE_NODE, -1); options -= XML_PARSE_XINCLUDE; } else reader->xinclude = 0; reader->in_xinclude = 0; #endif #ifdef LIBXML_PATTERN_ENABLED if (reader->patternTab == NULL) { reader->patternNr = 0; reader->patternMax = 0; } while (reader->patternNr > 0) { reader->patternNr--; if (reader->patternTab[reader->patternNr] != NULL) { xmlFreePattern(reader->patternTab[reader->patternNr]); reader->patternTab[reader->patternNr] = NULL; } } #endif if (options & XML_PARSE_DTDVALID) reader->validate = XML_TEXTREADER_VALIDATE_DTD; xmlCtxtUseOptions(reader->ctxt, options); if (encoding != NULL) { xmlCharEncodingHandlerPtr hdlr; hdlr = xmlFindCharEncodingHandler(encoding); if (hdlr != NULL) xmlSwitchToEncoding(reader->ctxt, hdlr); } if ((URL != NULL) && (reader->ctxt->input != NULL) && (reader->ctxt->input->filename == NULL)) reader->ctxt->input->filename = (char *) xmlStrdup((const xmlChar *) URL); reader->doc = NULL; return (0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory One of the operation on the reader could resolve entities leading to the classic expansion issue. Make sure the buffer used for xmlreader operation is bounded. Introduce a new allocation type for the buffers for this effect.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: stop reading hs_error.log from /tmp The file might contain anything and there is no way to verify its contents. Related: #1211835 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: do not override existing files by compat cores Implement all checks used in kernel's do_coredump() and require non-relative path if suid_dumpable is 2. Related: #1212818 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error) { problem_data_t *pd = problem_data_new(); GVariantIter *iter; g_variant_get(problem_info, "a{ss}", &iter); gchar *key, *value; while (g_variant_iter_loop(iter, "{ss}", &key, &value)) { problem_data_add_text_editable(pd, key, value); } if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL) { /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */ log_info("Adding UID %d to problem data", caller_uid); char buf[sizeof(uid_t) * 3 + 2]; snprintf(buf, sizeof(buf), "%d", caller_uid); problem_data_add_text_noteditable(pd, FILENAME_UID, buf); } /* At least it should generate local problem identifier UUID */ problem_data_add_basics(pd); char *problem_id = problem_data_save(pd); if (problem_id) notify_new_path(problem_id); else if (error) *error = xasprintf("Cannot create a new problem"); problem_data_free(pd); return problem_id; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'daemon, dbus: allow only root to create CCpp, Koops, vmcore and xorg Florian Weimer <fweimer@redhat.com>: This prevents users from feeding things that are not actually coredumps and excerpts from /proc to these analyzers. For example, it should not be possible to trigger a rule with “EVENT=post-create analyzer=CCpp” using NewProblem Related: #1212861 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void fix_hostname(struct SessionHandle *data, struct connectdata *conn, struct hostname *host) { size_t len; #ifndef USE_LIBIDN (void)data; (void)conn; #elif defined(CURL_DISABLE_VERBOSE_STRINGS) (void)conn; #endif /* set the name we use to display the host name */ host->dispname = host->name; len = strlen(host->name); if(host->name[len-1] == '.') /* strip off a single trailing dot if present, primarily for SNI but there's no use for it */ host->name[len-1]=0; if(!is_ASCII_name(host->name)) { #ifdef USE_LIBIDN /************************************************************* * Check name for non-ASCII and convert hostname to ACE form. *************************************************************/ if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) { char *ace_hostname = NULL; int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0); infof (data, "Input domain encoded as `%s'\n", stringprep_locale_charset ()); if(rc != IDNA_SUCCESS) infof(data, "Failed to convert %s to ACE; %s\n", host->name, Curl_idn_strerror(conn, rc)); else { /* tld_check_name() displays a warning if the host name contains "illegal" characters for this TLD */ (void)tld_check_name(data, ace_hostname); host->encalloc = ace_hostname; /* change the name pointer to point to the encoded hostname */ host->name = host->encalloc; } } #elif defined(USE_WIN32_IDN) /************************************************************* * Check name for non-ASCII and convert hostname to ACE form. *************************************************************/ char *ace_hostname = NULL; int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname); if(rc == 0) infof(data, "Failed to convert %s to ACE;\n", host->name); else { host->encalloc = ace_hostname; /* change the name pointer to point to the encoded hostname */ host->name = host->encalloc; } #else infof(data, "IDN support not present, can't parse Unicode domains\n"); #endif } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'fix_hostname: zero length host name caused -1 index offset If a URL is given with a zero-length host name, like in "http://:80" or just ":80", `fix_hostname()` will index the host name pointer with a -1 offset (as it blindly assumes a non-zero length) and both read and assign that address. CVE-2015-3144 Bug: http://curl.haxx.se/docs/adv_20150422D.html Reported-by: Hanno Böck'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()) { char *file; int file_len; long srcx, srcy, width, height; gdImagePtr im = NULL; php_stream *stream; FILE * fp = NULL; long ignore_warning; if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) { return; } if (width < 1 || height < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed"); RETURN_FALSE; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &file, &file_len) == FAILURE) { return; } } stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL); if (stream == NULL) { RETURN_FALSE; } /* try and avoid allocating a FILE* if the stream is not naturally a FILE* */ if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) { if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { goto out_err; } } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0); if (!io_ctx) { pefree(buff, 1); php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context"); goto out_err; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height); } else { im = (*ioctx_func_p)(io_ctx); } io_ctx->gd_free(io_ctx); pefree(buff, 1); } else if (php_stream_can_cast(stream, PHP_STREAM_AS_STDIO)) { /* try and force the stream to be FILE* */ if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) { goto out_err; } } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = (*func_p)(fp, srcx, srcy, width, height); break; #if defined(HAVE_GD_XPM) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(file); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im = gdImageCreateFromJpegEx(fp, ignore_warning); break; #endif default: im = (*func_p)(fp); break; } fflush(fp); } /* register_im: */ if (im) { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); php_stream_close(stream); return; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn); out_err: php_stream_close(stream); RETURN_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, "NewProblem") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } /* else */ response = g_variant_new("(s)", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, "GetProblems") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, "GetAllProblems") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "GetForeignProblems") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "ChownProblemDir") == 0) { const gchar *problem_dir; g_variant_get(parameters, "(&s)", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice("requested directory does not exist '%s'", problem_dir); } else { perror_msg("can't get stat of '%s'", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice("caller has access to the requested directory %s", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ChownError", _("Chowning directory failed. Check system logs for more details.")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, "GetInfo") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, "&s", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice("element '%s' %s", element_name, value ? "fetched" : "not found"); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, "{ss}", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new("(a{ss})", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new("(a{ss})", builder); if (builder) g_variant_builder_unref(builder); log_info("GetInfo: returning value for '%s'", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "SetElement") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value); if (element == NULL || element[0] == '\0' || strlen(element) > 64) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice("Can't get size of '%s/%s'", problem_id, element); char *error = xasprintf(_("Can't get size of '%s'"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("No problem space left")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, "DeleteElement") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, "(&s&s)", &problem_id, &element); struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id); char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, "DeleteProblem") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice("dir_name:'%s'", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, "&s", &element); g_variant_get_child(parameters, 1, "&s", &value); g_variant_get_child(parameters, 2, "x", &timestamp_from); g_variant_get_child(parameters, 3, "x", &timestamp_to); g_variant_get_child(parameters, 4, "b", &all); if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "Quit") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'dbus: report invalid element names Return D-Bus error in case of invalid problem element name. Related: #1214451 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int delete_path(const char *dump_dir_name) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dump_dir_name)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location); return 400; /* Bad Request */ } if (!dump_dir_accessible_by_uid(dump_dir_name, client_uid)) { if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dump_dir_name); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid); return 403; /* Forbidden */ } delete_dump_dir(dump_dir_name); return 0; /* success */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: add functions validating dump dir Move the code from abrt-server to shared library and fix the condition validating dump dir's path. As of now, abrt is allowed to process only direct sub-directories of the dump locations. Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int dd_delete(struct dump_dir *dd) { if (!dd->locked) { error_msg("unlocked problem directory %s cannot be deleted", dd->dd_dirname); return -1; } int r = delete_file_dir(dd->dd_dirname, /*skip_lock_file:*/ true); dd->locked = 0; /* delete_file_dir already removed .lock */ dd_close(dd); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code Florian Weimer <fweimer@redhat.com>: dd_opendir() should keep a file handle (opened with O_DIRECTORY) and use openat() and similar functions to access files in it. ... The file system manipulation functions should guard against hard links (check that link count is <= 1, just as in the user coredump code in abrt-hook-ccpp), possibly after opening the file with O_PATH first to avoid side effects on open/close. Related: #1214745 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int dd_chown(struct dump_dir *dd, uid_t new_uid) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ struct stat statbuf; if (!(stat(dd->dd_dirname, &statbuf) == 0 && S_ISDIR(statbuf.st_mode))) { perror_msg("stat('%s')", dd->dd_dirname); return 1; } struct passwd *pw = getpwuid(new_uid); if (!pw) { error_msg("UID %ld is not found in user database", (long)new_uid); return 1; } #if DUMP_DIR_OWNED_BY_USER > 0 uid_t owners_uid = pw->pw_uid; gid_t groups_gid = statbuf.st_gid; #else uid_t owners_uid = statbuf.st_uid; gid_t groups_gid = pw->pw_gid; #endif int chown_res = lchown(dd->dd_dirname, owners_uid, groups_gid); if (chown_res) perror_msg("lchown('%s')", dd->dd_dirname); else { dd_init_next_file(dd); char *full_name; while (chown_res == 0 && dd_get_next_file(dd, /*short_name*/ NULL, &full_name)) { log_debug("chowning %s", full_name); chown_res = lchown(full_name, owners_uid, groups_gid); if (chown_res) perror_msg("lchown('%s')", full_name); free(full_name); } } return chown_res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code Florian Weimer <fweimer@redhat.com>: dd_opendir() should keep a file handle (opened with O_DIRECTORY) and use openat() and similar functions to access files in it. ... The file system manipulation functions should guard against hard links (check that link count is <= 1, just as in the user coredump code in abrt-hook-ccpp), possibly after opening the file with O_PATH first to avoid side effects on open/close. Related: #1214745 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int create_symlink_lockfile(const char* lock_file, const char* pid) { while (symlink(pid, lock_file) != 0) { if (errno != EEXIST) { if (errno != ENOENT && errno != ENOTDIR && errno != EACCES) { perror_msg("Can't create lock file '%s'", lock_file); errno = 0; } return -1; } char pid_buf[sizeof(pid_t)*3 + 4]; ssize_t r = readlink(lock_file, pid_buf, sizeof(pid_buf) - 1); if (r < 0) { if (errno == ENOENT) { /* Looks like lock_file was deleted */ usleep(SYMLINK_RETRY_USLEEP); /* avoid CPU eating loop */ continue; } perror_msg("Can't read lock file '%s'", lock_file); errno = 0; return -1; } pid_buf[r] = '\0'; if (strcmp(pid_buf, pid) == 0) { log("Lock file '%s' is already locked by us", lock_file); return 0; } if (isdigit_str(pid_buf)) { char pid_str[sizeof("/proc/") + sizeof(pid_buf)]; snprintf(pid_str, sizeof(pid_str), "/proc/%s", pid_buf); if (access(pid_str, F_OK) == 0) { log("Lock file '%s' is locked by process %s", lock_file, pid_buf); return 0; } log("Lock file '%s' was locked by process %s, but it crashed?", lock_file, pid_buf); } /* The file may be deleted by now by other process. Ignore ENOENT */ if (unlink(lock_file) != 0 && errno != ENOENT) { perror_msg("Can't remove stale lock file '%s'", lock_file); errno = 0; return -1; } } log_info("Locked '%s'", lock_file); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code Florian Weimer <fweimer@redhat.com>: dd_opendir() should keep a file handle (opened with O_DIRECTORY) and use openat() and similar functions to access files in it. ... The file system manipulation functions should guard against hard links (check that link count is <= 1, just as in the user coredump code in abrt-hook-ccpp), possibly after opening the file with O_PATH first to avoid side effects on open/close. Related: #1214745 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __archive_read_filter_consume(struct archive_read_filter * filter, int64_t request) { int64_t skipped; if (request == 0) return 0; skipped = advance_file_pointer(filter, request); if (skipped == request) return (skipped); /* We hit EOF before we satisfied the skip request. */ if (skipped < 0) /* Map error code to 0 for error message below. */ skipped = 0; archive_set_error(&filter->archive->archive, ARCHIVE_ERRNO_MISC, "Truncated input file (needed %jd bytes, only %jd available)", (intmax_t)request, (intmax_t)skipped); return (ARCHIVE_FATAL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Add a check to archive_read_filter_consume to reject any attempts to move the file pointer by a negative amount. Note: Either this or commit 3865cf2 provides a fix for Issue 394.'</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 Exit_status safe_connect() { mysql= mysql_init(NULL); if (!mysql) { error("Failed on mysql_init."); return ERROR_STOP; } #ifdef HAVE_OPENSSL if (opt_use_ssl) { mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl); mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath); } mysql_options(mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*) &opt_ssl_verify_server_cert); #endif if (opt_plugin_dir && *opt_plugin_dir) mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); if (opt_protocol) mysql_options(mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol); if (opt_bind_addr) mysql_options(mysql, MYSQL_OPT_BIND, opt_bind_addr); #if defined (_WIN32) && !defined (EMBEDDED_LIBRARY) if (shared_memory_base_name) mysql_options(mysql, MYSQL_SHARED_MEMORY_BASE_NAME, shared_memory_base_name); #endif mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0); mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqlbinlog"); if (!mysql_real_connect(mysql, host, user, pass, 0, port, sock, 0)) { error("Failed on connect: %s", mysql_error(mysql)); return ERROR_STOP; } mysql->reconnect= 1; return OK_CONTINUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption # Changed the meaning of the --ssl=1 option of all client binaries to mean force ssl, not try ssl and fail over to eunecrypted # Added a new MYSQL_OPT_SSL_ENFORCE mysql_options() option to specify that an ssl connection is required. # Added a new macro SSL_SET_OPTIONS() to the client SSL handling headers that sets all the relevant SSL options at once. # Revamped all of the current native clients to use the new macro # Removed some Windows line endings. # Added proper handling of the new option into the ssl helper headers. # If SSL is mandatory assume that the media is secure enough for the sha256 plugin to do unencrypted password exchange even before establishing a connection. # Set the default ssl cipher to DHE-RSA-AES256-SHA if none is specified. # updated test cases that require a non-default cipher to spawn a mysql command line tool binary since mysqltest has no support for specifying ciphers. # updated the replication slave connection code to always enforce SSL if any of the SSL config options is present. # test cases added and updated. # added a mysql_get_option() API to return mysql_options() values. Used the new API inside the sha256 plugin. # Fixed compilation warnings because of unused variables. # Fixed test failures (mysql_ssl and bug13115401) # Fixed whitespace issues. # Fully implemented the mysql_get_option() function. # Added a test case for mysql_get_option() # fixed some trailing whitespace issues # fixed some uint/int warnings in mysql_client_test.c # removed shared memory option from non-windows get_options tests # moved MYSQL_OPT_LOCAL_INFILE to the uint options'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int connect_to_db(char *host, char *user,char *passwd) { char buff[20+FN_REFLEN]; DBUG_ENTER("connect_to_db"); verbose_msg("-- Connecting to %s...\n", host ? host : "localhost"); mysql_init(&mysql_connection); if (opt_compress) mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql_connection,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql_connection, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char *) &opt_enable_cleartext_plugin); if (!(mysql= mysql_real_connect(&mysql_connection,host,user,passwd, NULL,opt_mysql_port,opt_mysql_unix_port, 0))) { DB_error(&mysql_connection, "when trying to connect"); DBUG_RETURN(1); } if ((mysql_get_server_version(&mysql_connection) < 40100) || (opt_compatible_mode & 3)) { /* Don't dump SET NAMES with a pre-4.1 server (bug#7997). */ opt_set_charset= 0; /* Don't switch charsets for 4.1 and earlier. (bug#34192). */ server_supports_switching_charsets= FALSE; } /* As we're going to set SQL_MODE, it would be lost on reconnect, so we cannot reconnect. */ mysql->reconnect= 0; my_snprintf(buff, sizeof(buff), "/*!40100 SET @@SQL_MODE='%s' */", compatible_mode_normal_str); if (mysql_query_with_error_report(mysql, 0, buff)) DBUG_RETURN(1); /* set time_zone to UTC to allow dumping date types between servers with different time zone settings */ if (opt_tz_utc) { my_snprintf(buff, sizeof(buff), "/*!40103 SET TIME_ZONE='+00:00' */"); if (mysql_query_with_error_report(mysql, 0, buff)) DBUG_RETURN(1); } DBUG_RETURN(0); } /* connect_to_db */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MYSQL *db_connect(char *host, char *database, char *user, char *passwd) { MYSQL *mysql; if (verbose) fprintf(stdout, "Connecting to %s\n", host ? host : "localhost"); if (!(mysql= mysql_init(NULL))) return 0; if (opt_compress) mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS); if (opt_local_file) mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_file); #ifdef HAVE_OPENSSL if (opt_use_ssl) mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif if (opt_plugin_dir && *opt_plugin_dir) mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*)&opt_enable_cleartext_plugin); mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset); if (!(mysql_real_connect(mysql,host,user,passwd, database,opt_mysql_port,opt_mysql_unix_port, 0))) { ignore_errors=0; /* NO RETURN FROM db_error */ db_error(mysql); } mysql->reconnect= 0; if (verbose) fprintf(stdout, "Selecting database %s\n", database); if (mysql_select_db(mysql, database)) { ignore_errors=0; db_error(mysql); } return mysql; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_pfa(FILE *ifp, const char *ifp_filename, struct font_reader *fr) { /* Loop until no more input. We need to look for `currentfile eexec' to start eexec section (hex to binary conversion) and line of all zeros to switch back to ASCII. */ /* Don't use fgets() in case line-endings are indicated by bare \r's, as occurs in Macintosh fonts. */ /* 2.Aug.1999 - At the behest of Tom Kacvinsky <tjk@ams.org>, support binary PFA fonts. */ char buffer[LINESIZE]; int c = 0; int blocktyp = PFA_ASCII; char saved_orphan = 0; (void)ifp_filename; while (c != EOF) { char *line = buffer, *last = buffer; int crlf = 0; c = getc(ifp); while (c != EOF && c != '\r' && c != '\n' && last < buffer + LINESIZE - 1) { *last++ = c; c = getc(ifp); } /* handle the end of the line */ if (last == buffer + LINESIZE - 1) /* buffer overrun: don't append newline even if we have it */ ungetc(c, ifp); else if (c == '\r' && blocktyp != PFA_BINARY) { /* change CR or CR/LF into LF, unless reading binary data! (This condition was wrong before, caused Thanh problems - 6.Mar.2001) */ c = getc(ifp); if (c != '\n') ungetc(c, ifp), crlf = 1; else crlf = 2; *last++ = '\n'; } else if (c != EOF) *last++ = c; *last = 0; /* now that we have the line, handle it */ if (blocktyp == PFA_ASCII) { if (strncmp(line, "currentfile eexec", 17) == 0 && isspace(line[17])) { char saved_p; /* assert(line == buffer); */ for (line += 18; isspace(*line); line++) /* nada */; saved_p = *line; *line = 0; fr->output_ascii(buffer, line - buffer); *line = saved_p; blocktyp = PFA_EEXEC_TEST; if (!*line) continue; } else { fr->output_ascii(line, last - line); continue; } } /* check immediately after "currentfile eexec" for ASCII or binary */ if (blocktyp == PFA_EEXEC_TEST) { /* 8.Feb.2004: fix bug if first character in a binary eexec block is 0, reported by Werner Lemberg */ for (; line < last && isspace(*line); line++) /* nada */; if (line == last) continue; else if (last >= line + 4 && isxdigit(line[0]) && isxdigit(line[1]) && isxdigit(line[2]) && isxdigit(line[3])) blocktyp = PFA_HEX; else blocktyp = PFA_BINARY; memmove(buffer, line, last - line + 1); last = buffer + (last - line); line = buffer; /* patch up crlf fix */ if (blocktyp == PFA_BINARY && crlf) { last[-1] = '\r'; if (crlf == 2) *last++ = '\n'; } } /* blocktyp == PFA_HEX || blocktyp == PFA_BINARY */ if (all_zeroes(line)) { /* XXX not safe */ fr->output_ascii(line, last - line); blocktyp = PFA_ASCII; } else if (blocktyp == PFA_HEX) { int len = translate_hex_string(line, &saved_orphan); if (len) fr->output_binary((unsigned char *)line, len); } else fr->output_binary((unsigned char *)line, last - line); } fr->output_end(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes. - Don't overflow the small cs_start buffer (reported by Niels Thykier via the debian tracker (Jakub Wilk), found with a fuzzer ("American fuzzy lop")). - Cast arguments to <ctype.h> functions to unsigned char.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header TSRMLS_DC) { char *line; mime_header_entry prev_entry = {0}, entry; int prev_len, cur_len; /* didn't find boundary, abort */ if (!find_boundary(self, self->boundary TSRMLS_CC)) { return 0; } /* get lines of text, or CRLF_CRLF */ while( (line = get_line(self TSRMLS_CC)) && strlen(line) > 0 ) { /* add header to table */ char *key = line; char *value = NULL; if (php_rfc1867_encoding_translation(TSRMLS_C)) { self->input_encoding = zend_multibyte_encoding_detector(line, strlen(line), self->detect_order, self->detect_order_size TSRMLS_CC); } /* space in the beginning means same header */ if (!isspace(line[0])) { value = strchr(line, ':'); } if (value) { *value = 0; do { value++; } while(isspace(*value)); entry.value = estrdup(value); entry.key = estrdup(key); } else if (zend_llist_count(header)) { /* If no ':' on the line, add to previous line */ prev_len = strlen(prev_entry.value); cur_len = strlen(line); entry.value = emalloc(prev_len + cur_len + 1); memcpy(entry.value, prev_entry.value, prev_len); memcpy(entry.value + prev_len, line, cur_len); entry.value[cur_len + prev_len] = '\0'; entry.key = estrdup(prev_entry.key); zend_llist_remove_tail(header); } else { continue; } zend_llist_add_element(header, &entry); prev_entry = entry; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fixed bug #69364 - use smart_str to assemble strings'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(pcntl_fork) { pid_t id; id = fork(); if (id == -1) { PCNTL_G(last_error) = errno; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error %d", errno); } RETURN_LONG((long) id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_MINIT_FUNCTION(dir) { static char dirsep_str[2], pathsep_str[2]; zend_class_entry dir_class_entry; INIT_CLASS_ENTRY(dir_class_entry, "Directory", php_dir_class_functions); dir_class_entry_ptr = zend_register_internal_class(&dir_class_entry TSRMLS_CC); #ifdef ZTS ts_allocate_id(&dir_globals_id, sizeof(php_dir_globals), NULL, NULL); #endif dirsep_str[0] = DEFAULT_SLASH; dirsep_str[1] = '\0'; REGISTER_STRING_CONSTANT("DIRECTORY_SEPARATOR", dirsep_str, CONST_CS|CONST_PERSISTENT); pathsep_str[0] = ZEND_PATHS_SEPARATOR; pathsep_str[1] = '\0'; REGISTER_STRING_CONSTANT("PATH_SEPARATOR", pathsep_str, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SCANDIR_SORT_ASCENDING", PHP_SCANDIR_SORT_ASCENDING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SCANDIR_SORT_DESCENDING", PHP_SCANDIR_SORT_DESCENDING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SCANDIR_SORT_NONE", PHP_SCANDIR_SORT_NONE, CONST_CS | CONST_PERSISTENT); #ifdef HAVE_GLOB #ifdef GLOB_BRACE REGISTER_LONG_CONSTANT("GLOB_BRACE", GLOB_BRACE, CONST_CS | CONST_PERSISTENT); #else # define GLOB_BRACE 0 #endif #ifdef GLOB_MARK REGISTER_LONG_CONSTANT("GLOB_MARK", GLOB_MARK, CONST_CS | CONST_PERSISTENT); #else # define GLOB_MARK 0 #endif #ifdef GLOB_NOSORT REGISTER_LONG_CONSTANT("GLOB_NOSORT", GLOB_NOSORT, CONST_CS | CONST_PERSISTENT); #else # define GLOB_NOSORT 0 #endif #ifdef GLOB_NOCHECK REGISTER_LONG_CONSTANT("GLOB_NOCHECK", GLOB_NOCHECK, CONST_CS | CONST_PERSISTENT); #else # define GLOB_NOCHECK 0 #endif #ifdef GLOB_NOESCAPE REGISTER_LONG_CONSTANT("GLOB_NOESCAPE", GLOB_NOESCAPE, CONST_CS | CONST_PERSISTENT); #else # define GLOB_NOESCAPE 0 #endif #ifdef GLOB_ERR REGISTER_LONG_CONSTANT("GLOB_ERR", GLOB_ERR, CONST_CS | CONST_PERSISTENT); #else # define GLOB_ERR 0 #endif #ifndef GLOB_ONLYDIR # define GLOB_ONLYDIR (1<<30) # define GLOB_EMULATE_ONLYDIR # define GLOB_FLAGMASK (~GLOB_ONLYDIR) #else # define GLOB_FLAGMASK (~0) #endif /* This is used for checking validity of passed flags (passing invalid flags causes segfault in glob()!! */ #define GLOB_AVAILABLE_FLAGS (0 | GLOB_BRACE | GLOB_MARK | GLOB_NOSORT | GLOB_NOCHECK | GLOB_NOESCAPE | GLOB_ERR | GLOB_ONLYDIR) REGISTER_LONG_CONSTANT("GLOB_ONLYDIR", GLOB_ONLYDIR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("GLOB_AVAILABLE_FLAGS", GLOB_AVAILABLE_FLAGS, CONST_CS | CONST_PERSISTENT); #endif /* HAVE_GLOB */ return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: data_close(ftpbuf_t *ftp, databuf_t *data) { #if HAVE_OPENSSL_EXT SSL_CTX *ctx; #endif if (data == NULL) { return NULL; } if (data->listener != -1) { #if HAVE_OPENSSL_EXT if (data->ssl_active) { ctx = SSL_get_SSL_CTX(data->ssl_handle); SSL_CTX_free(ctx); SSL_shutdown(data->ssl_handle); SSL_free(data->ssl_handle); data->ssl_active = 0; } #endif closesocket(data->listener); } if (data->fd != -1) { #if HAVE_OPENSSL_EXT if (data->ssl_active) { ctx = SSL_get_SSL_CTX(data->ssl_handle); SSL_CTX_free(ctx); SSL_shutdown(data->ssl_handle); SSL_free(data->ssl_handle); data->ssl_active = 0; } #endif closesocket(data->fd); } if (ftp) { ftp->data = NULL; } efree(data); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_nb_continue_write(ftpbuf_t *ftp TSRMLS_DC) { long size; char *ptr; int ch; /* check if we can write more data */ if (!data_writeable(ftp, ftp->data->fd)) { return PHP_FTP_MOREDATA; } size = 0; ptr = ftp->data->buf; while (!php_stream_eof(ftp->stream) && (ch = php_stream_getc(ftp->stream)) != EOF) { if (ch == '\n' && ftp->type == FTPTYPE_ASCII) { *ptr++ = '\r'; size++; } *ptr++ = ch; size++; /* flush if necessary */ if (FTP_BUFSIZE - size < 2) { if (my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) { goto bail; } return PHP_FTP_MOREDATA; } } if (size && my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) { goto bail; } ftp->data = data_close(ftp, ftp->data); if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) { goto bail; } ftp->nb = 0; return PHP_FTP_FINISHED; bail: ftp->data = data_close(ftp, ftp->data); ftp->nb = 0; return PHP_FTP_FAILED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC) { php_stream *tmpstream = NULL; databuf_t *data = NULL; char *ptr; int ch, lastch; int size, rcvd; int lines; char **ret = NULL; char **entry; char *text; if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory."); return NULL; } if (!ftp_type(ftp, FTPTYPE_ASCII)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (!ftp_putcmd(ftp, cmd, path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) { goto bail; } /* some servers don't open a ftp-data connection if the directory is empty */ if (ftp->resp == 226) { ftp->data = data_close(ftp, data); php_stream_close(tmpstream); return ecalloc(1, sizeof(char**)); } /* pull data buffer into tmpfile */ if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; lines = 0; lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1) { goto bail; } php_stream_write(tmpstream, data->buf, rcvd); size += rcvd; for (ptr = data->buf; rcvd; rcvd--, ptr++) { if (*ptr == '\n' && lastch == '\r') { lines++; } else { size++; } lastch = *ptr; } } ftp->data = data = data_close(ftp, data); php_stream_rewind(tmpstream); ret = safe_emalloc((lines + 1), sizeof(char**), size * sizeof(char*)); entry = ret; text = (char*) (ret + lines + 1); *entry = text; lastch = 0; while ((ch = php_stream_getc(tmpstream)) != EOF) { if (ch == '\n' && lastch == '\r') { *(text - 1) = 0; *++entry = text; } else { *text++ = ch; } lastch = ch; } *entry = NULL; php_stream_close(tmpstream); if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) { efree(ret); return NULL; } return ret; bail: ftp->data = data_close(ftp, data); php_stream_close(tmpstream); if (ret) efree(ret); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Minor Coverity tweaks'</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 CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const { PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength)); tTcpIpPacketParsingResult packetReview; packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum, __FUNCTION__); if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) { auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset; auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader); auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0; VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen); VHeader->gso_size = (USHORT)m_ParentNBL->MSS(); VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen); VHeader->csum_offset = TCP_CHECKSUM_OFFSET; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <yhindin@rehat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { tTcpIpPacketParsingResult res = _res; ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); res.xxpStatus = ppresXxpIncomplete; res.TcpUdp = ppresIsUDP; res.XxpIpHeaderSize = udpDataStart; if (len >= udpDataStart) { UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); USHORT datagramLength = swap_short(pUdpHeader->udp_length); res.xxpStatus = ppresXxpKnown; // may be full or not, but the datagram length is known DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength)); } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <yhindin@rehat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(imagepsbbox) { zval *fnt; long sz = 0, sp = 0, wd = 0; char *str; int i, space = 0, add_width = 0, char_width, amount_kern; int cur_x, cur_y, dx, dy; int x1, y1, x2, y2, x3, y3, x4, y4; int *f_ind; int str_len, per_char = 0; int argc = ZEND_NUM_ARGS(); double angle = 0, sin_a = 0, cos_a = 0; BBox char_bbox, str_bbox = {0, 0, 0, 0}; if (argc != 3 && argc != 6) { ZEND_WRONG_PARAM_COUNT(); } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "srl|lld", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) { return; } if (argc == 6) { space = sp; add_width = wd; angle = angle * M_PI / 180; sin_a = sin(angle); cos_a = cos(angle); per_char = add_width || angle ? 1 : 0; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); #define max(a, b) (a > b ? a : b) #define min(a, b) (a < b ? a : b) #define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a) #define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a) if (per_char) { space += T1_GetCharWidth(*f_ind, ' '); cur_x = cur_y = 0; for (i = 0; i < str_len; i++) { if (str[i] == ' ') { char_bbox.llx = char_bbox.lly = char_bbox.ury = 0; char_bbox.urx = char_width = space; } else { char_bbox = T1_GetCharBBox(*f_ind, str[i]); char_width = T1_GetCharWidth(*f_ind, str[i]); } amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0; /* Transfer character bounding box to right place */ x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x; y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y; x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x; y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y; x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x; y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y; x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x; y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y; /* Find min & max values and compare them with current bounding box */ str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4)))); str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4)))); str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4)))); str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4)))); /* Move to the next base point */ dx = new_x(char_width + add_width + amount_kern, 0); dy = new_y(char_width + add_width + amount_kern, 0); cur_x += dx; cur_y += dy; /* printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy); */ } } else { str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING); } if (T1_errno) { RETURN_FALSE; } array_init(return_value); /* printf("%d %d %d %d\n", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury); */ add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void bpf_int_jit_compile(struct bpf_prog *prog) { struct bpf_binary_header *header = NULL; int proglen, oldproglen = 0; struct jit_context ctx = {}; u8 *image = NULL; int *addrs; int pass; int i; if (!bpf_jit_enable) return; if (!prog || !prog->len) return; addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL); if (!addrs) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < prog->len; i++) { proglen += 64; addrs[i] = proglen; } ctx.cleanup_addr = proglen; for (pass = 0; pass < 10; pass++) { proglen = do_jit(prog, addrs, image, oldproglen, &ctx); if (proglen <= 0) { image = NULL; if (header) bpf_jit_binary_free(header); goto out; } if (image) { if (proglen != oldproglen) { pr_err("bpf_jit: proglen=%d != oldproglen=%d\n", proglen, oldproglen); goto out; } break; } if (proglen == oldproglen) { header = bpf_jit_binary_alloc(proglen, &image, 1, jit_fill_hole); if (!header) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) bpf_jit_dump(prog->len, proglen, 0, image); if (image) { bpf_flush_icache(header, image + proglen); set_memory_ro((unsigned long)header, header->pages); prog->bpf_func = (void *)image; prog->jited = true; } out: kfree(addrs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'x86: bpf_jit: fix compilation of large bpf programs x86 has variable length encoding. x86 JIT compiler is trying to pick the shortest encoding for given bpf instruction. While doing so the jump targets are changing, so JIT is doing multiple passes over the program. Typical program needs 3 passes. Some very short programs converge with 2 passes. Large programs may need 4 or 5. But specially crafted bpf programs may hit the pass limit and if the program converges on the last iteration the JIT compiler will be producing an image full of 'int 3' insns. Fix this corner case by doing final iteration over bpf program. Fixes: 0a14842f5a3c ("net: filter: Just In Time compiler for x86-64") Reported-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: Alexei Starovoitov <ast@plumgrid.com> Tested-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream, uint16_t* data, unsigned data_length) { while (data_length != 0) { unsigned cursor = 0; uint32_t character = Utf8::ValueOf(stream, Utf8::kMaxEncodedSize, &cursor); // There's a total lack of bounds checking for stream // as it was already done in Reset. stream += cursor; if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) { *data++ = Utf16::LeadSurrogate(character); *data++ = Utf16::TrailSurrogate(character); DCHECK(data_length > 1); data_length -= 2; } else { *data++ = character; data_length -= 1; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'deps: fix out-of-band write in utf8 decoder Originally reported by: Kris Reeves <kris.re@bbhmedia.com> Reviewed-By: Trevor Norris <trev.norris@gmail.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 attach_child_main(void* data) { struct attach_clone_payload* payload = (struct attach_clone_payload*)data; int ipc_socket = payload->ipc_socket; lxc_attach_options_t* options = payload->options; struct lxc_proc_context_info* init_ctx = payload->init_ctx; #if HAVE_SYS_PERSONALITY_H long new_personality; #endif int ret; int status; int expected; long flags; int fd; uid_t new_uid; gid_t new_gid; /* wait for the initial thread to signal us that it's ready * for us to start initializing */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive notification from initial process (0)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* A description of the purpose of this functionality is * provided in the lxc-attach(1) manual page. We have to * remount here and not in the parent process, otherwise * /proc may not properly reflect the new pid namespace. */ if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) { ret = lxc_attach_remount_sys_proc(); if (ret < 0) { shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* now perform additional attachments*/ #if HAVE_SYS_PERSONALITY_H if (options->personality < 0) new_personality = init_ctx->personality; else new_personality = options->personality; if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) { ret = personality(new_personality); if (ret < 0) { SYSERROR("could not ensure correct architecture"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } #endif if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) { ret = lxc_attach_drop_privs(init_ctx); if (ret < 0) { ERROR("could not drop privileges"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */ ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env); if (ret < 0) { ERROR("could not set initial environment for attached process"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* set user / group id */ new_uid = 0; new_gid = 0; /* ignore errors, we will fall back to root in that case * (/proc was not mounted etc.) */ if (options->namespaces & CLONE_NEWUSER) lxc_attach_get_init_uidgid(&new_uid, &new_gid); if (options->uid != (uid_t)-1) new_uid = options->uid; if (options->gid != (gid_t)-1) new_gid = options->gid; /* setup the control tty */ if (options->stdin_fd && isatty(options->stdin_fd)) { if (setsid() < 0) { SYSERROR("unable to setsid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } if (ioctl(options->stdin_fd, TIOCSCTTY, (char *)NULL) < 0) { SYSERROR("unable to TIOCSTTY"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* try to set the uid/gid combination */ if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) { if (setgid(new_gid) || setgroups(0, NULL)) { SYSERROR("switching to container gid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) { SYSERROR("switching to container uid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* tell initial process it may now put us into the cgroups */ status = 1; ret = lxc_write_nointr(ipc_socket, &status, sizeof(status)); if (ret != sizeof(status)) { ERROR("error using IPC to notify initial process for initialization (1)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* wait for the initial thread to signal us that it has done * everything for us when it comes to cgroups etc. */ expected = 2; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive final notification from initial process (2)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } shutdown(ipc_socket, SHUT_RDWR); close(ipc_socket); /* set new apparmor profile/selinux context */ if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM)) { int on_exec; int proc_mounted; on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0; proc_mounted = mount_proc_if_needed("/"); if (proc_mounted == -1) { ERROR("Error mounting a sane /proc"); rexit(-1); } ret = lsm_process_label_set(init_ctx->lsm_label, init_ctx->container->lxc_conf, 0, on_exec); if (proc_mounted) umount("/proc"); if (ret < 0) { rexit(-1); } } if (init_ctx->container && init_ctx->container->lxc_conf && lxc_seccomp_load(init_ctx->container->lxc_conf) != 0) { ERROR("Loading seccomp policy"); rexit(-1); } lxc_proc_put_context_info(init_ctx); /* The following is done after the communication socket is * shut down. That way, all errors that might (though * unlikely) occur up until this point will have their messages * printed to the original stderr (if logging is so configured) * and not the fd the user supplied, if any. */ /* fd handling for stdin, stdout and stderr; * ignore errors here, user may want to make sure * the fds are closed, for example */ if (options->stdin_fd >= 0 && options->stdin_fd != 0) dup2(options->stdin_fd, 0); if (options->stdout_fd >= 0 && options->stdout_fd != 1) dup2(options->stdout_fd, 1); if (options->stderr_fd >= 0 && options->stderr_fd != 2) dup2(options->stderr_fd, 2); /* close the old fds */ if (options->stdin_fd > 2) close(options->stdin_fd); if (options->stdout_fd > 2) close(options->stdout_fd); if (options->stderr_fd > 2) close(options->stderr_fd); /* try to remove CLOEXEC flag from stdin/stdout/stderr, * but also here, ignore errors */ for (fd = 0; fd <= 2; fd++) { flags = fcntl(fd, F_GETFL); if (flags < 0) continue; if (flags & FD_CLOEXEC) { if (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) { SYSERROR("Unable to clear CLOEXEC from fd"); } } } /* we're done, so we can now do whatever the user intended us to do */ rexit(payload->exec_function(payload->exec_payload)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'CVE-2015-1334: Don't use the container's /proc during attach A user could otherwise over-mount /proc and prevent the apparmor profile or selinux label from being written which combined with a modified /bin/sh or other commonly used binary would lead to unconfined code execution. Reported-by: Roman Fiedler Signed-off-by: Stéphane Graber <stgraber@ubuntu.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (unlikely(iov_count > MAX_UIOVEC)) return -EINVAL; if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'sg_start_req(): use import_iovec() Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CloudInitSetup(const char *tmpDirPath) { int deployStatus = DEPLOY_ERROR; const char *cloudInitTmpDirPath = "/var/run/vmware-imc"; int forkExecResult; char command[1024]; Bool cloudInitTmpDirCreated = FALSE; snprintf(command, sizeof(command), "/bin/mkdir -p %s", cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); if (forkExecResult != 0) { SetDeployError("Error creating %s dir: %s", cloudInitTmpDirPath, strerror(errno)); goto done; } cloudInitTmpDirCreated = TRUE; snprintf(command, sizeof(command), "/bin/rm -f %s/cust.cfg %s/nics.txt", cloudInitTmpDirPath, cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); snprintf(command, sizeof(command), "/bin/cp %s/cust.cfg %s/cust.cfg", tmpDirPath, cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); if (forkExecResult != 0) { SetDeployError("Error copying cust.cfg file: %s", strerror(errno)); goto done; } snprintf(command, sizeof(command), "/usr/bin/test -f %s/nics.txt", tmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); /* * /usr/bin/test -f returns 0 if the file exists * non zero is returned if the file does not exist. * We need to copy the nics.txt only if it exists. */ if (forkExecResult == 0) { snprintf(command, sizeof(command), "/bin/cp %s/nics.txt %s/nics.txt", tmpDirPath, cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); if (forkExecResult != 0) { SetDeployError("Error copying nics.txt file: %s", strerror(errno)); goto done; } } deployStatus = DEPLOY_SUCCESS; done: if (DEPLOY_SUCCESS == deployStatus) { TransitionState(INPROGRESS, DONE); } else { if (cloudInitTmpDirCreated) { snprintf(command, sizeof(command), "/bin/rm -rf %s", cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; ForkExecAndWaitCommand(command); } sLog(log_error, "Setting generic error status in vmx. \n"); SetCustomizationStatusInVmx(TOOLSDEPLOYPKG_RUNNING, GUESTCUST_EVENT_CUSTOMIZE_FAILED, NULL); TransitionState(INPROGRESS, ERRORED); } return deployStatus; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int jas_stream_gobble(jas_stream_t *stream, int n) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void send_ext_audio_ack(VncState *vs) { vnc_lock_output(vs); vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE); vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); vnc_framebuffer_update(vs, 0, 0, surface_width(vs->vd->ds), surface_height(vs->vd->ds), VNC_ENCODING_AUDIO); vnc_unlock_output(vs); vnc_flush(vs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <pl@kamp.de> Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int spl_object_storage_detach(spl_SplObjectStorage *intern, zval *this, zval *obj TSRMLS_DC) /* {{{ */ { int hash_len, ret = FAILURE; char *hash = spl_object_storage_get_hash(intern, this, obj, &hash_len TSRMLS_CC); if (!hash) { return ret; } ret = zend_hash_del(&intern->storage, hash, hash_len); spl_object_storage_free_hash(intern, hash); return ret; } /* }}}*/ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(MultipleIterator, valid) { spl_SplObjectStorage *intern; spl_SplObjectStorageElement *element; zval *it, *retval = NULL; long expect, valid; intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!zend_hash_num_elements(&intern->storage)) { RETURN_FALSE; } expect = (intern->flags & MIT_NEED_ALL) ? 1 : 0; zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos); while (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == SUCCESS && !EG(exception)) { it = element->obj; zend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_valid, "valid", &retval); if (retval) { valid = Z_LVAL_P(retval); zval_ptr_dtor(&retval); } else { valid = 0; } if (expect != valid) { RETURN_BOOL(!expect); } zend_hash_move_forward_ex(&intern->storage, &intern->pos); } RETURN_BOOL(expect); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, serialize) { spl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); smart_str buf = {0}; spl_ptr_llist_element *current = intern->llist->head, *next; zval *flags; php_serialize_data_t var_hash; if (zend_parse_parameters_none() == FAILURE) { return; } PHP_VAR_SERIALIZE_INIT(var_hash); /* flags */ MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, intern->flags); php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC); zval_ptr_dtor(&flags); /* elements */ while (current) { smart_str_appendc(&buf, ':'); next = current->next; php_var_serialize(&buf, (zval **)&current->data, &var_hash TSRMLS_CC); current = next; } smart_str_0(&buf); /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.c) { RETURN_STRINGL(buf.c, buf.len, 0); } else { RETURN_NULL(); } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline FILE *xfmkstemp(char **tmpname, char *dir) { int fd; FILE *ret; fd = xmkstemp(tmpname, dir); if (fd == -1) return NULL; if (!(ret = fdopen(fd, "w+" UL_CLOEXECSTR))) { close(fd); return NULL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'chsh, chfn, vipw: fix filenames collision The utils when compiled WITHOUT libuser then mkostemp()ing "/etc/%s.XXXXXX" where the filename prefix is argv[0] basename. An attacker could repeatedly execute the util with modified argv[0] and after many many attempts mkostemp() may generate suffix which makes sense. The result maybe temporary file with name like rc.status ld.so.preload or krb5.keytab, etc. Note that distros usually use libuser based ch{sh,fn} or stuff from shadow-utils. It's probably very minor security bug. Addresses: CVE-2015-5224 Signed-off-by: Karel Zak <kzak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static zval **php_zip_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { ze_zip_object *obj; zval tmp_member; zval **retval = NULL; zip_prop_handler *hnd; zend_object_handlers *std_hnd; int ret; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; key = NULL; } ret = FAILURE; obj = (ze_zip_object *)zend_objects_get_address(object TSRMLS_CC); if (obj->prop_handler != NULL) { if (key) { ret = zend_hash_quick_find(obj->prop_handler, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, key->hash_value, (void **) &hnd); } else { ret = zend_hash_find(obj->prop_handler, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, (void **) &hnd); } } if (ret == FAILURE) { std_hnd = zend_get_std_object_handlers(); retval = std_hnd->get_property_ptr_ptr(object, member, key TSRMLS_CC); } if (member == &tmp_member) { zval_dtor(member); } return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tile_make_weights (PixopsFilterDimension *dim, double scale) { int n = ceil (1 / scale + 1); double *pixel_weights = g_malloc_n (sizeof (double) * SUBSAMPLE, n); int offset; int i; dim->n = n; dim->offset = 0; dim->weights = pixel_weights; for (offset = 0; offset < SUBSAMPLE; offset++) { double x = (double)offset / SUBSAMPLE; double a = x + 1 / scale; for (i = 0; i < n; i++) { if (i < x) { if (i + 1 > x) *(pixel_weights++) = (MIN (i + 1, a) - x) * scale; else *(pixel_weights++) = 0; } else { if (a > i) *(pixel_weights++) = (MIN (i + 1, a) - i) * scale; else *(pixel_weights++) = 0; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM The weights could grow very large under certain circumstances, in particular in security-relevant conditions, including the testsuite. By allowing the weight allocation to fail, this can be worked around. https://bugzilla.gnome.org/show_bug.cgi?id=754387'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void write_rle_data(TGAContext *ctx, TGAColor *color, guint *rle_count) { for (; *rle_count; (*rle_count)--) { g_memmove(ctx->pptr, (guchar *) color, ctx->pbuf->n_channels); ctx->pptr += ctx->pbuf->n_channels; ctx->pbuf_bytes_done += ctx->pbuf->n_channels; if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) return; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'tga: Wrap TGAColormap struct in its own API Instead of poking into it directly.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { struct inode *inode = mapping->host; int ret, needed_blocks; handle_t *handle; int retries = 0; struct page *page; pgoff_t index; unsigned from, to; trace_ext4_write_begin(inode, pos, len, flags); /* * Reserve one block more for addition to orphan list in case * we allocate blocks but write fails for some reason */ needed_blocks = ext4_writepage_trans_blocks(inode) + 1; index = pos >> PAGE_CACHE_SHIFT; from = pos & (PAGE_CACHE_SIZE - 1); to = from + len; retry: handle = ext4_journal_start(inode, needed_blocks); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out; } /* We cannot recurse into the filesystem as the transaction is already * started */ flags |= AOP_FLAG_NOFS; page = grab_cache_page_write_begin(mapping, index, flags); if (!page) { ext4_journal_stop(handle); ret = -ENOMEM; goto out; } *pagep = page; ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata, ext4_get_block); if (!ret && ext4_should_journal_data(inode)) { ret = walk_page_buffers(handle, page_buffers(page), from, to, NULL, do_journal_get_write_access); } if (ret) { unlock_page(page); page_cache_release(page); /* * block_write_begin may have instantiated a few blocks * outside i_size. Trim these off again. Don't need * i_size_read because we hold i_mutex. * * Add inode to orphan list in case we crash before * truncate finishes */ if (pos + len > inode->i_size && ext4_can_truncate(inode)) ext4_orphan_add(handle, inode); ext4_journal_stop(handle); if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might * still be on the orphan list; we need to * make sure the inode is removed from the * orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } } if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry; out: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ext4_ext_insert_extent(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_extent *newext, int flag) { struct ext4_extent_header *eh; struct ext4_extent *ex, *fex; struct ext4_extent *nearex; /* nearest extent */ struct ext4_ext_path *npath = NULL; int depth, len, err; ext4_lblk_t next; unsigned uninitialized = 0; BUG_ON(ext4_ext_get_actual_len(newext) == 0); depth = ext_depth(inode); ex = path[depth].p_ext; BUG_ON(path[depth].p_hdr == NULL); /* try to insert block into found extent and return */ if (ex && (flag != EXT4_GET_BLOCKS_PRE_IO) && ext4_can_extents_be_merged(inode, ex, newext)) { ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n", ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext), le32_to_cpu(ex->ee_block), ext4_ext_is_uninitialized(ex), ext4_ext_get_actual_len(ex), ext_pblock(ex)); err = ext4_ext_get_access(handle, inode, path + depth); if (err) return err; /* * ext4_can_extents_be_merged should have checked that either * both extents are uninitialized, or both aren't. Thus we * need to check only one of them here. */ if (ext4_ext_is_uninitialized(ex)) uninitialized = 1; ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex) + ext4_ext_get_actual_len(newext)); if (uninitialized) ext4_ext_mark_uninitialized(ex); eh = path[depth].p_hdr; nearex = ex; goto merge; } repeat: depth = ext_depth(inode); eh = path[depth].p_hdr; if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) goto has_space; /* probably next leaf has space for us? */ fex = EXT_LAST_EXTENT(eh); next = ext4_ext_next_leaf_block(inode, path); if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block) && next != EXT_MAX_BLOCK) { ext_debug("next leaf block - %d\n", next); BUG_ON(npath != NULL); npath = ext4_ext_find_extent(inode, next, NULL); if (IS_ERR(npath)) return PTR_ERR(npath); BUG_ON(npath->p_depth != path->p_depth); eh = npath[depth].p_hdr; if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) { ext_debug("next leaf isnt full(%d)\n", le16_to_cpu(eh->eh_entries)); path = npath; goto repeat; } ext_debug("next leaf has no free space(%d,%d)\n", le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max)); } /* * There is no free space in the found leaf. * We're gonna add a new leaf in the tree. */ err = ext4_ext_create_new_leaf(handle, inode, path, newext); if (err) goto cleanup; depth = ext_depth(inode); eh = path[depth].p_hdr; has_space: nearex = path[depth].p_ext; err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto cleanup; if (!nearex) { /* there is no extent in this leaf, create first one */ ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n", le32_to_cpu(newext->ee_block), ext_pblock(newext), ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext)); path[depth].p_ext = EXT_FIRST_EXTENT(eh); } else if (le32_to_cpu(newext->ee_block) > le32_to_cpu(nearex->ee_block)) { /* BUG_ON(newext->ee_block == nearex->ee_block); */ if (nearex != EXT_LAST_EXTENT(eh)) { len = EXT_MAX_EXTENT(eh) - nearex; len = (len - 1) * sizeof(struct ext4_extent); len = len < 0 ? 0 : len; ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, " "move %d from 0x%p to 0x%p\n", le32_to_cpu(newext->ee_block), ext_pblock(newext), ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext), nearex, len, nearex + 1, nearex + 2); memmove(nearex + 2, nearex + 1, len); } path[depth].p_ext = nearex + 1; } else { BUG_ON(newext->ee_block == nearex->ee_block); len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent); len = len < 0 ? 0 : len; ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, " "move %d from 0x%p to 0x%p\n", le32_to_cpu(newext->ee_block), ext_pblock(newext), ext4_ext_is_uninitialized(newext), ext4_ext_get_actual_len(newext), nearex, len, nearex + 1, nearex + 2); memmove(nearex + 1, nearex, len); path[depth].p_ext = nearex; } le16_add_cpu(&eh->eh_entries, 1); nearex = path[depth].p_ext; nearex->ee_block = newext->ee_block; ext4_ext_store_pblock(nearex, ext_pblock(newext)); nearex->ee_len = newext->ee_len; merge: /* try to merge extents to the right */ if (flag != EXT4_GET_BLOCKS_PRE_IO) ext4_ext_try_to_merge(inode, path, nearex); /* try to merge extents to the left */ /* time to correct all indexes above */ err = ext4_ext_correct_indexes(handle, inode, path); if (err) goto cleanup; err = ext4_ext_dirty(handle, inode, path + depth); cleanup: if (npath) { ext4_ext_drop_refs(npath); kfree(npath); } ext4_ext_invalidate_cache(inode); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int mount_proc_if_needed(const char *rootfs) { char path[MAXPATHLEN]; char link[20]; int linklen, ret; int mypid; ret = snprintf(path, MAXPATHLEN, "%s/proc/self", rootfs); if (ret < 0 || ret >= MAXPATHLEN) { SYSERROR("proc path name too long"); return -1; } memset(link, 0, 20); linklen = readlink(path, link, 20); mypid = (int)getpid(); INFO("I am %d, /proc/self points to '%s'", mypid, link); ret = snprintf(path, MAXPATHLEN, "%s/proc", rootfs); if (ret < 0 || ret >= MAXPATHLEN) { SYSERROR("proc path name too long"); return -1; } if (linklen < 0) /* /proc not mounted */ goto domount; if (atoi(link) != mypid) { /* wrong /procs mounted */ umount2(path, MNT_DETACH); /* ignore failure */ goto domount; } /* the right proc is already mounted */ return 0; domount: if (mount("proc", path, "proc", 0, NULL)) return -1; INFO("Mounted /proc in container for security transition"); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <serge.hallyn@ubuntu.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool cgm_bind_dir(const char *root, const char *dirname) { nih_local char *cgpath = NULL; /* /sys should have been mounted by now */ cgpath = NIH_MUST( nih_strdup(NULL, root) ); NIH_MUST( nih_strcat(&cgpath, NULL, "/sys/fs/cgroup") ); if (!dir_exists(cgpath)) { ERROR("%s does not exist", cgpath); return false; } /* mount a tmpfs there so we can create subdirs */ if (mount("cgroup", cgpath, "tmpfs", 0, "size=10000,mode=755")) { SYSERROR("Failed to mount tmpfs at %s", cgpath); return false; } NIH_MUST( nih_strcat(&cgpath, NULL, "/cgmanager") ); if (mkdir(cgpath, 0755) < 0) { SYSERROR("Failed to create %s", cgpath); return false; } if (mount(dirname, cgpath, "none", MS_BIND, 0)) { SYSERROR("Failed to bind mount %s to %s", dirname, cgpath); return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <serge.hallyn@ubuntu.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < ETH_MAX_L2_HDR_LEN) { l2_hdr->iov_len = 0; return false; } else { l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base); } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); switch (l3_proto) { case ETH_P_IP: l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, sizeof(struct ip_header)); if (bytes_read < sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len + sizeof(struct ip_header), l3_hdr->iov_base + sizeof(struct ip_header), l3_hdr->iov_len - sizeof(struct ip_header)); if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; } vmxnet_tx_pkt_calculate_hdr_len(pkt); pkt->packet_type = get_eth_packet_type(l2_hdr->iov_base); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'net/vmxnet3: Refine l2 header validation Validation of l2 header length assumed minimal packet size as eth_header + 2 * vlan_header regardless of the actual protocol. This caused crash for valid non-IP packets shorter than 22 bytes, as 'tx_pkt->packet_type' hasn't been assigned for such packets, and 'vmxnet3_on_tx_done_update_stats()' expects it to be properly set. Refine header length validation in 'vmxnet_tx_pkt_parse_headers'. Check its return value during packet processing flow. As a side effect, in case IPv4 and IPv6 header validation failure, corrupt packets will be dropped. Signed-off-by: Dana Rubin <dana.rubin@ravellosystems.com> Signed-off-by: Shmulik Ladkani <shmulik.ladkani@ravellosystems.com> Signed-off-by: Jason Wang <jasowang@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: crypto_bob2( struct exten *ep, /* extension pointer */ struct value *vp /* value pointer */ ) { RSA *rsa; /* GQ parameters */ DSA_SIG *sdsa; /* DSA parameters */ BN_CTX *bctx; /* BIGNUM context */ EVP_MD_CTX ctx; /* signature context */ tstamp_t tstamp; /* NTP timestamp */ BIGNUM *r, *k, *g, *y; u_char *ptr; u_int len; int s_len; /* * If the GQ parameters are not valid, something awful * happened or we are being tormented. */ if (gqkey_info == NULL) { msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable"); return (XEVNT_ID); } rsa = gqkey_info->pkey->pkey.rsa; /* * Extract r from the challenge. */ len = ntohl(ep->vallen); if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) { msyslog(LOG_ERR, "crypto_bob2: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } /* * Bob rolls random k (0 < k < n), computes y = k u^r mod n and * x = k^b mod n, then sends (y, hash(x)) to Alice. */ bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new(); sdsa = DSA_SIG_new(); BN_rand(k, len * 8, -1, 1); /* k */ BN_mod(k, k, rsa->n, bctx); BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */ BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */ sdsa->r = BN_dup(y); BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */ bighash(g, g); sdsa->s = BN_dup(g); BN_CTX_free(bctx); BN_free(r); BN_free(k); BN_free(g); BN_free(y); #ifdef DEBUG if (debug > 1) RSA_print_fp(stdout, rsa, 0); #endif /* * Encode the values in ASN.1 and sign. The filestamp is from * the local file. */ len = s_len = i2d_DSA_SIG(sdsa, NULL); if (s_len <= 0) { msyslog(LOG_ERR, "crypto_bob2: %s", ERR_error_string(ERR_get_error(), NULL)); DSA_SIG_free(sdsa); return (XEVNT_ERR); } memset(vp, 0, sizeof(struct value)); tstamp = crypto_time(); vp->tstamp = htonl(tstamp); vp->fstamp = htonl(gqkey_info->fstamp); vp->vallen = htonl(len); ptr = emalloc(len); vp->ptr = ptr; i2d_DSA_SIG(sdsa, &ptr); DSA_SIG_free(sdsa); if (tstamp == 0) return (XEVNT_OK); vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, len); if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { INSIST(len <= sign_siglen); vp->siglen = htonl(len); } return (XEVNT_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2014-9297'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: save_config( struct recvbuf *rbufp, int restrict_mask ) { char reply[128]; #ifdef SAVECONFIG char filespec[128]; char filename[128]; char fullpath[512]; const char savedconfig_eq[] = "savedconfig="; char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)]; time_t now; int fd; FILE *fptr; #endif if (RES_NOMODIFY & restrict_mask) { snprintf(reply, sizeof(reply), "saveconfig prohibited by restrict ... nomodify"); ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); NLOG(NLOG_SYSINFO) msyslog(LOG_NOTICE, "saveconfig from %s rejected due to nomodify restriction", stoa(&rbufp->recv_srcadr)); sys_restricted++; return; } #ifdef SAVECONFIG if (NULL == saveconfigdir) { snprintf(reply, sizeof(reply), "saveconfig prohibited, no saveconfigdir configured"); ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); NLOG(NLOG_SYSINFO) msyslog(LOG_NOTICE, "saveconfig from %s rejected, no saveconfigdir", stoa(&rbufp->recv_srcadr)); return; } if (0 == reqend - reqpt) return; strlcpy(filespec, reqpt, sizeof(filespec)); time(&now); /* * allow timestamping of the saved config filename with * strftime() format such as: * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf" * XXX: Nice feature, but not too safe. */ if (0 == strftime(filename, sizeof(filename), filespec, localtime(&now))) strlcpy(filename, filespec, sizeof(filename)); /* * Conceptually we should be searching for DIRSEP in filename, * however Windows actually recognizes both forward and * backslashes as equivalent directory separators at the API * level. On POSIX systems we could allow '\\' but such * filenames are tricky to manipulate from a shell, so just * reject both types of slashes on all platforms. */ if (strchr(filename, '\\') || strchr(filename, '/')) { snprintf(reply, sizeof(reply), "saveconfig does not allow directory in filename"); ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); msyslog(LOG_NOTICE, "saveconfig with path from %s rejected", stoa(&rbufp->recv_srcadr)); return; } snprintf(fullpath, sizeof(fullpath), "%s%s", saveconfigdir, filename); fd = open(fullpath, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR); if (-1 == fd) fptr = NULL; else fptr = fdopen(fd, "w"); if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) { snprintf(reply, sizeof(reply), "Unable to save configuration to file %s", filename); msyslog(LOG_ERR, "saveconfig %s from %s failed", filename, stoa(&rbufp->recv_srcadr)); } else { snprintf(reply, sizeof(reply), "Configuration saved to %s", filename); msyslog(LOG_NOTICE, "Configuration saved to %s (requested by %s)", fullpath, stoa(&rbufp->recv_srcadr)); /* * save the output filename in system variable * savedconfig, retrieved with: * ntpq -c "rv 0 savedconfig" */ snprintf(savedconfig, sizeof(savedconfig), "%s%s", savedconfig_eq, filename); set_sys_var(savedconfig, strlen(savedconfig) + 1, RO); } if (NULL != fptr) fclose(fptr); #else /* !SAVECONFIG follows */ snprintf(reply, sizeof(reply), "saveconfig unavailable, configured with --disable-saveconfig"); #endif ctl_putdata(reply, strlen(reply), 0); ctl_flushpkt(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': '[TALOS-CAN-0062] prevent directory traversal for VMS, too, when using 'saveconfig' command.'</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_principal_va(krb5_context context, krb5_principal princ, unsigned int rlen, const char *realm, va_list ap) { krb5_error_code retval = 0; char *r = NULL; krb5_data *data = NULL; krb5_int32 count = 0; krb5_int32 size = 2; /* initial guess at needed space */ char *component = NULL; data = malloc(size * sizeof(krb5_data)); if (!data) { retval = ENOMEM; } if (!retval) { r = strdup(realm); if (!r) { retval = ENOMEM; } } while (!retval && (component = va_arg(ap, char *))) { if (count == size) { krb5_data *new_data = NULL; size *= 2; new_data = realloc(data, size * sizeof(krb5_data)); if (new_data) { data = new_data; } else { retval = ENOMEM; } } if (!retval) { data[count].length = strlen(component); data[count].data = strdup(component); if (!data[count].data) { retval = ENOMEM; } count++; } } if (!retval) { princ->type = KRB5_NT_UNKNOWN; princ->magic = KV5M_PRINCIPAL; princ->realm = make_data(r, rlen); princ->data = data; princ->length = count; r = NULL; /* take ownership */ data = NULL; /* take ownership */ } if (data) { while (--count >= 0) { free(data[count].data); } free(data); } free(r); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Fix build_principal memory bug [CVE-2015-2697] In build_principal_va(), use k5memdup0() instead of strdup() to make a copy of the realm, to ensure that we allocate the correct number of bytes and do not read past the end of the input string. This bug affects krb5_build_principal(), krb5_build_principal_va(), and krb5_build_principal_alloc_va(). krb5_build_principal_ext() is not affected. CVE-2015-2697: In MIT krb5 1.7 and later, an authenticated attacker may be able to cause a KDC to crash using a TGS request with a large realm field beginning with a null byte. If the KDC attempts to find a referral to answer the request, it constructs a principal name for lookup using krb5_build_principal() with the requested realm. Due to a bug in this function, the null byte causes only one byte be allocated for the realm field of the constructed principal, far less than its length. Subsequent operations on the lookup principal may cause a read beyond the end of the mapped memory region, causing the KDC process to crash. CVSSv2: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8252 (new) target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: spnego_gss_delete_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { OM_uint32 ret = GSS_S_COMPLETE; spnego_gss_ctx_id_t *ctx = (spnego_gss_ctx_id_t *)context_handle; *minor_status = 0; if (context_handle == NULL) return (GSS_S_FAILURE); if (*ctx == NULL) return (GSS_S_COMPLETE); /* * If this is still an SPNEGO mech, release it locally. */ if ((*ctx)->magic_num == SPNEGO_MAGIC_ID) { (void) gss_delete_sec_context(minor_status, &(*ctx)->ctx_handle, output_token); (void) release_spnego_ctx(ctx); } else { ret = gss_delete_sec_context(minor_status, context_handle, output_token); } return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [ghudson@mit.edu: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: spnego_gss_unwrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t input_assoc_buffer, gss_buffer_t output_payload_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap_aead(minor_status, context_handle, input_message_buffer, input_assoc_buffer, output_payload_buffer, conf_state, qop_state); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [ghudson@mit.edu: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: spnego_gss_verify_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t msg_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_verify_mic(minor_status, context_handle, msg_buffer, token_buffer, qop_state); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [ghudson@mit.edu: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int huft_build(const unsigned *b, const unsigned n, const unsigned s, const unsigned short *d, const unsigned char *e, huft_t **t, unsigned *m) { unsigned a; /* counter for codes of length k */ unsigned c[BMAX + 1]; /* bit length count table */ unsigned eob_len; /* length of end-of-block code (value 256) */ unsigned f; /* i repeats in table every f entries */ int g; /* maximum code length */ int htl; /* table level */ unsigned i; /* counter, current code */ unsigned j; /* counter */ int k; /* number of bits in current code */ unsigned *p; /* pointer into c[], b[], or v[] */ huft_t *q; /* points to current table */ huft_t r; /* table entry for structure assignment */ huft_t *u[BMAX]; /* table stack */ unsigned v[N_MAX]; /* values in order of bit length */ int ws[BMAX + 1]; /* bits decoded stack */ int w; /* bits decoded */ unsigned x[BMAX + 1]; /* bit offsets, then code stack */ unsigned *xp; /* pointer into x */ int y; /* number of dummy codes added */ unsigned z; /* number of entries in current table */ /* Length of EOB code, if any */ eob_len = n > 256 ? b[256] : BMAX; *t = NULL; /* Generate counts for each bit length */ memset(c, 0, sizeof(c)); p = (unsigned *) b; /* cast allows us to reuse p for pointing to b */ i = n; do { c[*p]++; /* assume all entries <= BMAX */ p++; /* can't combine with above line (Solaris bug) */ } while (--i); if (c[0] == n) { /* null input - all zero length codes */ *m = 0; return 2; } /* Find minimum and maximum length, bound *m by those */ for (j = 1; (j <= BMAX) && (c[j] == 0); j++) continue; k = j; /* minimum code length */ for (i = BMAX; (c[i] == 0) && i; i--) continue; g = i; /* maximum code length */ *m = (*m < j) ? j : ((*m > i) ? i : *m); /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) { y -= c[j]; if (y < 0) return 2; /* bad input: more codes than bits */ } y -= c[i]; if (y < 0) return 2; c[i] += y; /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ j += *p++; *xp++ = j; } /* Make a table of values in order of bit lengths */ p = (unsigned *) b; i = 0; do { j = *p++; if (j != 0) { v[x[j]++] = i; } } while (++i < n); /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ p = v; /* grab values in bit order */ htl = -1; /* no tables yet--level -1 */ w = ws[0] = 0; /* bits decoded */ u[0] = NULL; /* just to keep compilers happy */ q = NULL; /* ditto */ z = 0; /* ditto */ /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) { a = c[k]; while (a--) { /* here i is the Huffman code of length k bits for value *p */ /* make tables up to required level */ while (k > ws[htl + 1]) { w = ws[++htl]; /* compute minimum size table less than or equal to *m bits */ z = g - w; z = z > *m ? *m : z; /* upper limit on table size */ j = k - w; f = 1 << j; if (f > a + 1) { /* try a k-w bit table */ /* too few codes for k-w bit table */ f -= a + 1; /* deduct codes from patterns left */ xp = c + k; while (++j < z) { /* try smaller tables up to z bits */ f <<= 1; if (f <= *++xp) { break; /* enough codes to use up j bits */ } f -= *xp; /* else deduct codes from patterns */ } } j = (w + j > eob_len && w < eob_len) ? eob_len - w : j; /* make EOB code end at table */ z = 1 << j; /* table entries for j-bit table */ ws[htl+1] = w + j; /* set bits decoded in stack */ /* allocate and link in new table */ q = xzalloc((z + 1) * sizeof(huft_t)); *t = q + 1; /* link to list for huft_free() */ t = &(q->v.t); u[htl] = ++q; /* table starts after link */ /* connect to last table, if there is one */ if (htl) { x[htl] = i; /* save pattern for backing up */ r.b = (unsigned char) (w - ws[htl - 1]); /* bits to dump before this table */ r.e = (unsigned char) (16 + j); /* bits in this table */ r.v.t = q; /* pointer to this table */ j = (i & ((1 << w) - 1)) >> ws[htl - 1]; u[htl - 1][j] = r; /* connect to last table */ } } /* set up table entry in r */ r.b = (unsigned char) (k - w); if (p >= v + n) { r.e = 99; /* out of values--invalid code */ } else if (*p < s) { r.e = (unsigned char) (*p < 256 ? 16 : 15); /* 256 is EOB code */ r.v.n = (unsigned short) (*p++); /* simple code is just the value */ } else { r.e = (unsigned char) e[*p - s]; /* non-simple--look up in lists */ r.v.n = d[*p++ - s]; } /* fill code-like entries with r */ f = 1 << (k - w); for (j = i >> w; j < z; j += f) { q[j] = r; } /* backwards increment the k-bit code i */ for (j = 1 << (k - 1); i & j; j >>= 1) { i ^= j; } i ^= j; /* backup over finished tables */ while ((i & ((1 << w) - 1)) != x[htl]) { w = ws[--htl]; } } } /* return actual size of base table */ *m = ws[1]; /* Return 1 if we were given an incomplete table */ return y != 0 && g != 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'unzip: test for bad archive SEGVing function old new delta huft_build 1296 1300 +4 Signed-off-by: Denys Vlasenko <vda.linux@googlemail.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: _PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic, const char *s, charset_t src_charset, charset_t dst_charset) { size_t count = 0; #ifdef DEVELOPER switch (dst_charset) { case CH_DOS: case CH_UNIX: smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)"); default: break; } switch (src_charset) { case CH_UTF16LE: case CH_UTF16BE: smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)"); default: break; } #endif if (!s) { return 0; } while (*s && !(((uint8_t)*s) & 0x80)) { s++; count++; } if (!*s) { return count; } while (*s) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(ic, s, src_charset, &c_size); s += c_size; switch (dst_charset) { case CH_UTF16LE: case CH_UTF16BE: case CH_UTF16MUNGED: if (c < 0x10000) { /* Unicode char fits into 16 bits. */ count += 1; } else { /* Double-width unicode char - 32 bits. */ count += 2; } break; case CH_UTF8: /* * this only checks ranges, and does not * check for invalid codepoints */ if (c < 0x80) { count += 1; } else if (c < 0x800) { count += 2; } else if (c < 0x10000) { count += 3; } else { count += 4; } break; default: /* * non-unicode encoding: * assume that each codepoint fits into * one unit in the destination encoding. */ count += 1; } } return count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: Fix handling of unicode near string endings Until now next_codepoint_ext() and next_codepoint_handle_ext() were using strnlen(str, 5) to determine how much string they should try to decode. This ended up looking past the end of the string when it was not null terminated and the final character looked like a multi-byte encoding. The fix is to let the caller say how long the string can be. Bug: https://bugzilla.samba.org/show_bug.cgi?id=11599 Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz> Pair-programmed-with: Andrew Bartlett <abartlet@samba.org> Reviewed-by: Ralph Boehme <slow@samba.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_const_colorp palette, int num_palette) { png_debug1(1, "in %s storage function", "PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) png_error(png_ptr, "Invalid palette length"); else { png_warning(png_ptr, "Invalid palette length"); return; } } if ((num_palette > 0 && palette == NULL) || (num_palette == 0 # ifdef PNG_MNG_FEATURES_SUPPORTED && (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 # endif )) { png_error(png_ptr, "Invalid palette"); } /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. * * 1.6.0: the above statement appears to be incorrect; something has to set * the palette inside png_struct on read. */ png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead * of num_palette entries, in case of an invalid PNG file that has * too-large sample values. */ png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr, PNG_MAX_PALETTE_LENGTH * (sizeof (png_color)))); if (num_palette > 0) memcpy(png_ptr->palette, palette, num_palette * (sizeof (png_color))); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; info_ptr->free_me |= PNG_FREE_PLTE; info_ptr->valid |= PNG_INFO_PLTE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Prevent reading over-length PLTE chunk (Cosmin Truta).'</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 xmlGROW (xmlParserCtxtPtr ctxt) { unsigned long curEnd = ctxt->input->end - ctxt->input->cur; unsigned long curBase = ctxt->input->cur - ctxt->input->base; if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) || (curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) && ((ctxt->input->buf) && (ctxt->input->buf->readcallback != (xmlInputReadCallback) xmlNop)) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup"); ctxt->instate = XML_PARSER_EOF; } xmlParserInputGrow(ctxt->input, INPUT_CHUNK); if ((ctxt->input->cur != NULL) && (*ctxt->input->cur == 0) && (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) xmlPopInput(ctxt); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Detect incoherency on GROW the current pointer to the input has to be between the base and end if not stop everything we have an internal state error.'</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: aiptek_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *usbdev = interface_to_usbdev(intf); struct usb_endpoint_descriptor *endpoint; struct aiptek *aiptek; struct input_dev *inputdev; int i; int speeds[] = { 0, AIPTEK_PROGRAMMABLE_DELAY_50, AIPTEK_PROGRAMMABLE_DELAY_400, AIPTEK_PROGRAMMABLE_DELAY_25, AIPTEK_PROGRAMMABLE_DELAY_100, AIPTEK_PROGRAMMABLE_DELAY_200, AIPTEK_PROGRAMMABLE_DELAY_300 }; int err = -ENOMEM; /* programmableDelay is where the command-line specified * delay is kept. We make it the first element of speeds[], * so therefore, your override speed is tried first, then the * remainder. Note that the default value of 400ms will be tried * if you do not specify any command line parameter. */ speeds[0] = programmableDelay; aiptek = kzalloc(sizeof(struct aiptek), GFP_KERNEL); inputdev = input_allocate_device(); if (!aiptek || !inputdev) { dev_warn(&intf->dev, "cannot allocate memory or input device\n"); goto fail1; } aiptek->data = usb_alloc_coherent(usbdev, AIPTEK_PACKET_LENGTH, GFP_ATOMIC, &aiptek->data_dma); if (!aiptek->data) { dev_warn(&intf->dev, "cannot allocate usb buffer\n"); goto fail1; } aiptek->urb = usb_alloc_urb(0, GFP_KERNEL); if (!aiptek->urb) { dev_warn(&intf->dev, "cannot allocate urb\n"); goto fail2; } aiptek->inputdev = inputdev; aiptek->usbdev = usbdev; aiptek->intf = intf; aiptek->ifnum = intf->altsetting[0].desc.bInterfaceNumber; aiptek->inDelay = 0; aiptek->endDelay = 0; aiptek->previousJitterable = 0; aiptek->lastMacro = -1; /* Set up the curSettings struct. Said struct contains the current * programmable parameters. The newSetting struct contains changes * the user makes to the settings via the sysfs interface. Those * changes are not "committed" to curSettings until the user * writes to the sysfs/.../execute file. */ aiptek->curSetting.pointerMode = AIPTEK_POINTER_EITHER_MODE; aiptek->curSetting.coordinateMode = AIPTEK_COORDINATE_ABSOLUTE_MODE; aiptek->curSetting.toolMode = AIPTEK_TOOL_BUTTON_PEN_MODE; aiptek->curSetting.xTilt = AIPTEK_TILT_DISABLE; aiptek->curSetting.yTilt = AIPTEK_TILT_DISABLE; aiptek->curSetting.mouseButtonLeft = AIPTEK_MOUSE_LEFT_BUTTON; aiptek->curSetting.mouseButtonMiddle = AIPTEK_MOUSE_MIDDLE_BUTTON; aiptek->curSetting.mouseButtonRight = AIPTEK_MOUSE_RIGHT_BUTTON; aiptek->curSetting.stylusButtonUpper = AIPTEK_STYLUS_UPPER_BUTTON; aiptek->curSetting.stylusButtonLower = AIPTEK_STYLUS_LOWER_BUTTON; aiptek->curSetting.jitterDelay = jitterDelay; aiptek->curSetting.programmableDelay = programmableDelay; /* Both structs should have equivalent settings */ aiptek->newSetting = aiptek->curSetting; /* Determine the usb devices' physical path. * Asketh not why we always pretend we're using "../input0", * but I suspect this will have to be refactored one * day if a single USB device can be a keyboard & a mouse * & a tablet, and the inputX number actually will tell * us something... */ usb_make_path(usbdev, aiptek->features.usbPath, sizeof(aiptek->features.usbPath)); strlcat(aiptek->features.usbPath, "/input0", sizeof(aiptek->features.usbPath)); /* Set up client data, pointers to open and close routines * for the input device. */ inputdev->name = "Aiptek"; inputdev->phys = aiptek->features.usbPath; usb_to_input_id(usbdev, &inputdev->id); inputdev->dev.parent = &intf->dev; input_set_drvdata(inputdev, aiptek); inputdev->open = aiptek_open; inputdev->close = aiptek_close; /* Now program the capacities of the tablet, in terms of being * an input device. */ for (i = 0; i < ARRAY_SIZE(eventTypes); ++i) __set_bit(eventTypes[i], inputdev->evbit); for (i = 0; i < ARRAY_SIZE(absEvents); ++i) __set_bit(absEvents[i], inputdev->absbit); for (i = 0; i < ARRAY_SIZE(relEvents); ++i) __set_bit(relEvents[i], inputdev->relbit); __set_bit(MSC_SERIAL, inputdev->mscbit); /* Set up key and button codes */ for (i = 0; i < ARRAY_SIZE(buttonEvents); ++i) __set_bit(buttonEvents[i], inputdev->keybit); for (i = 0; i < ARRAY_SIZE(macroKeyEvents); ++i) __set_bit(macroKeyEvents[i], inputdev->keybit); /* * Program the input device coordinate capacities. We do not yet * know what maximum X, Y, and Z values are, so we're putting fake * values in. Later, we'll ask the tablet to put in the correct * values. */ input_set_abs_params(inputdev, ABS_X, 0, 2999, 0, 0); input_set_abs_params(inputdev, ABS_Y, 0, 2249, 0, 0); input_set_abs_params(inputdev, ABS_PRESSURE, 0, 511, 0, 0); input_set_abs_params(inputdev, ABS_TILT_X, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0); input_set_abs_params(inputdev, ABS_TILT_Y, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0); input_set_abs_params(inputdev, ABS_WHEEL, AIPTEK_WHEEL_MIN, AIPTEK_WHEEL_MAX - 1, 0, 0); endpoint = &intf->altsetting[0].endpoint[0].desc; /* Go set up our URB, which is called when the tablet receives * input. */ usb_fill_int_urb(aiptek->urb, aiptek->usbdev, usb_rcvintpipe(aiptek->usbdev, endpoint->bEndpointAddress), aiptek->data, 8, aiptek_irq, aiptek, endpoint->bInterval); aiptek->urb->transfer_dma = aiptek->data_dma; aiptek->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* Program the tablet. This sets the tablet up in the mode * specified in newSetting, and also queries the tablet's * physical capacities. * * Sanity check: if a tablet doesn't like the slow programmatic * delay, we often get sizes of 0x0. Let's use that as an indicator * to try faster delays, up to 25 ms. If that logic fails, well, you'll * have to explain to us how your tablet thinks it's 0x0, and yet that's * not an error :-) */ for (i = 0; i < ARRAY_SIZE(speeds); ++i) { aiptek->curSetting.programmableDelay = speeds[i]; (void)aiptek_program_tablet(aiptek); if (input_abs_get_max(aiptek->inputdev, ABS_X) > 0) { dev_info(&intf->dev, "Aiptek using %d ms programming speed\n", aiptek->curSetting.programmableDelay); break; } } /* Murphy says that some day someone will have a tablet that fails the above test. That's you, Frederic Rodrigo */ if (i == ARRAY_SIZE(speeds)) { dev_info(&intf->dev, "Aiptek tried all speeds, no sane response\n"); goto fail3; } /* Associate this driver's struct with the usb interface. */ usb_set_intfdata(intf, aiptek); /* Set up the sysfs files */ err = sysfs_create_group(&intf->dev.kobj, &aiptek_attribute_group); if (err) { dev_warn(&intf->dev, "cannot create sysfs group err: %d\n", err); goto fail3; } /* Register the tablet as an Input Device */ err = input_register_device(aiptek->inputdev); if (err) { dev_warn(&intf->dev, "input_register_device returned err: %d\n", err); goto fail4; } return 0; fail4: sysfs_remove_group(&intf->dev.kobj, &aiptek_attribute_group); fail3: usb_free_urb(aiptek->urb); fail2: usb_free_coherent(usbdev, AIPTEK_PACKET_LENGTH, aiptek->data, aiptek->data_dma); fail1: usb_set_intfdata(intf, NULL); input_free_device(inputdev); kfree(aiptek); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-401'], 'message': 'Input: aiptek - fix crash on detecting device without endpoints The aiptek driver crashes in aiptek_probe() when a specially crafted USB device without endpoints is detected. This fix adds a check that the device has proper configuration expected by the driver. Also an error return value is changed to more matching one in one of the error paths. Reported-by: Ralf Spenneberg <ralf@spenneberg.net> Signed-off-by: Vladis Dronov <vdronov@redhat.com> Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.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: _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, const struct ldap_control_handler *control_handlers, struct ldap_message *msg) { uint8_t tag; asn1_start_tag(data, ASN1_SEQUENCE(0)); asn1_read_Integer(data, &msg->messageid); if (!asn1_peek_uint8(data, &tag)) return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); switch(tag) { case ASN1_APPLICATION(LDAP_TAG_BindRequest): { struct ldap_BindRequest *r = &msg->r.BindRequest; msg->type = LDAP_TAG_BindRequest; asn1_start_tag(data, tag); asn1_read_Integer(data, &r->version); asn1_read_OctetString_talloc(msg, data, &r->dn); if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(0))) { int pwlen; r->creds.password = ""; r->mechanism = LDAP_AUTH_MECH_SIMPLE; asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0)); pwlen = asn1_tag_remaining(data); if (pwlen == -1) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } if (pwlen != 0) { char *pw = talloc_array(msg, char, pwlen+1); if (!pw) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } asn1_read(data, pw, pwlen); pw[pwlen] = '\0'; r->creds.password = pw; } asn1_end_tag(data); } else if (asn1_peek_tag(data, ASN1_CONTEXT(3))){ asn1_start_tag(data, ASN1_CONTEXT(3)); r->mechanism = LDAP_AUTH_MECH_SASL; asn1_read_OctetString_talloc(msg, data, &r->creds.SASL.mechanism); if (asn1_peek_tag(data, ASN1_OCTET_STRING)) { /* optional */ DATA_BLOB tmp_blob = data_blob(NULL, 0); asn1_read_OctetString(data, msg, &tmp_blob); r->creds.SASL.secblob = talloc(msg, DATA_BLOB); if (!r->creds.SASL.secblob) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->creds.SASL.secblob = data_blob_talloc(r->creds.SASL.secblob, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->creds.SASL.secblob = NULL; } asn1_end_tag(data); } else { /* Neither Simple nor SASL bind */ return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_BindResponse): { struct ldap_BindResponse *r = &msg->r.BindResponse; msg->type = LDAP_TAG_BindResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, &r->response); if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(7))) { DATA_BLOB tmp_blob = data_blob(NULL, 0); asn1_read_ContextSimple(data, 7, &tmp_blob); r->SASL.secblob = talloc(msg, DATA_BLOB); if (!r->SASL.secblob) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->SASL.secblob = data_blob_talloc(r->SASL.secblob, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->SASL.secblob = NULL; } asn1_end_tag(data); break; } case ASN1_APPLICATION_SIMPLE(LDAP_TAG_UnbindRequest): { msg->type = LDAP_TAG_UnbindRequest; asn1_start_tag(data, tag); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchRequest): { struct ldap_SearchRequest *r = &msg->r.SearchRequest; int sizelimit, timelimit; const char **attrs = NULL; msg->type = LDAP_TAG_SearchRequest; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->basedn); asn1_read_enumerated(data, (int *)(void *)&(r->scope)); asn1_read_enumerated(data, (int *)(void *)&(r->deref)); asn1_read_Integer(data, &sizelimit); r->sizelimit = sizelimit; asn1_read_Integer(data, &timelimit); r->timelimit = timelimit; asn1_read_BOOLEAN(data, &r->attributesonly); r->tree = ldap_decode_filter_tree(msg, data); if (r->tree == NULL) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } asn1_start_tag(data, ASN1_SEQUENCE(0)); r->num_attributes = 0; r->attributes = NULL; while (asn1_tag_remaining(data) > 0) { const char *attr; if (!asn1_read_OctetString_talloc(msg, data, &attr)) return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); if (!add_string_to_array(msg, attr, &attrs, &r->num_attributes)) return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } r->attributes = attrs; asn1_end_tag(data); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchResultEntry): { struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry; msg->type = LDAP_TAG_SearchResultEntry; r->attributes = NULL; r->num_attributes = 0; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->dn); ldap_decode_attribs(msg, data, &r->attributes, &r->num_attributes); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchResultDone): { struct ldap_Result *r = &msg->r.SearchResultDone; msg->type = LDAP_TAG_SearchResultDone; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_SearchResultReference): { struct ldap_SearchResRef *r = &msg->r.SearchResultReference; msg->type = LDAP_TAG_SearchResultReference; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->referral); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyRequest): { struct ldap_ModifyRequest *r = &msg->r.ModifyRequest; msg->type = LDAP_TAG_ModifyRequest; asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_ModifyRequest)); asn1_read_OctetString_talloc(msg, data, &r->dn); asn1_start_tag(data, ASN1_SEQUENCE(0)); r->num_mods = 0; r->mods = NULL; while (asn1_tag_remaining(data) > 0) { struct ldap_mod mod; int v; ZERO_STRUCT(mod); asn1_start_tag(data, ASN1_SEQUENCE(0)); asn1_read_enumerated(data, &v); mod.type = v; ldap_decode_attrib(msg, data, &mod.attrib); asn1_end_tag(data); if (!add_mod_to_array_talloc(msg, &mod, &r->mods, &r->num_mods)) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } } asn1_end_tag(data); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyResponse): { struct ldap_Result *r = &msg->r.ModifyResponse; msg->type = LDAP_TAG_ModifyResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_AddRequest): { struct ldap_AddRequest *r = &msg->r.AddRequest; msg->type = LDAP_TAG_AddRequest; asn1_start_tag(data, tag); asn1_read_OctetString_talloc(msg, data, &r->dn); r->attributes = NULL; r->num_attributes = 0; ldap_decode_attribs(msg, data, &r->attributes, &r->num_attributes); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_AddResponse): { struct ldap_Result *r = &msg->r.AddResponse; msg->type = LDAP_TAG_AddResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest): { struct ldap_DelRequest *r = &msg->r.DelRequest; int len; char *dn; msg->type = LDAP_TAG_DelRequest; asn1_start_tag(data, ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest)); len = asn1_tag_remaining(data); if (len == -1) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } dn = talloc_array(msg, char, len+1); if (dn == NULL) break; asn1_read(data, dn, len); dn[len] = '\0'; r->dn = dn; asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_DelResponse): { struct ldap_Result *r = &msg->r.DelResponse; msg->type = LDAP_TAG_DelResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest): { struct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest; msg->type = LDAP_TAG_ModifyDNRequest; asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest)); asn1_read_OctetString_talloc(msg, data, &r->dn); asn1_read_OctetString_talloc(msg, data, &r->newrdn); asn1_read_BOOLEAN(data, &r->deleteolddn); r->newsuperior = NULL; if (asn1_tag_remaining(data) > 0) { int len; char *newsup; asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0)); len = asn1_tag_remaining(data); if (len == -1) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } newsup = talloc_array(msg, char, len+1); if (newsup == NULL) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } asn1_read(data, newsup, len); newsup[len] = '\0'; r->newsuperior = newsup; asn1_end_tag(data); } asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ModifyDNResponse): { struct ldap_Result *r = &msg->r.ModifyDNResponse; msg->type = LDAP_TAG_ModifyDNResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_CompareRequest): { struct ldap_CompareRequest *r = &msg->r.CompareRequest; msg->type = LDAP_TAG_CompareRequest; asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_CompareRequest)); asn1_read_OctetString_talloc(msg, data, &r->dn); asn1_start_tag(data, ASN1_SEQUENCE(0)); asn1_read_OctetString_talloc(msg, data, &r->attribute); asn1_read_OctetString(data, msg, &r->value); if (r->value.data) { talloc_steal(msg, r->value.data); } asn1_end_tag(data); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_CompareResponse): { struct ldap_Result *r = &msg->r.CompareResponse; msg->type = LDAP_TAG_CompareResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, r); asn1_end_tag(data); break; } case ASN1_APPLICATION_SIMPLE(LDAP_TAG_AbandonRequest): { struct ldap_AbandonRequest *r = &msg->r.AbandonRequest; msg->type = LDAP_TAG_AbandonRequest; asn1_start_tag(data, tag); asn1_read_implicit_Integer(data, &r->messageid); asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ExtendedRequest): { struct ldap_ExtendedRequest *r = &msg->r.ExtendedRequest; DATA_BLOB tmp_blob = data_blob(NULL, 0); msg->type = LDAP_TAG_ExtendedRequest; asn1_start_tag(data,tag); if (!asn1_read_ContextSimple(data, 0, &tmp_blob)) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } r->oid = blob2string_talloc(msg, tmp_blob); data_blob_free(&tmp_blob); if (!r->oid) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(1))) { asn1_read_ContextSimple(data, 1, &tmp_blob); r->value = talloc(msg, DATA_BLOB); if (!r->value) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->value = data_blob_talloc(r->value, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->value = NULL; } asn1_end_tag(data); break; } case ASN1_APPLICATION(LDAP_TAG_ExtendedResponse): { struct ldap_ExtendedResponse *r = &msg->r.ExtendedResponse; DATA_BLOB tmp_blob = data_blob(NULL, 0); msg->type = LDAP_TAG_ExtendedResponse; asn1_start_tag(data, tag); ldap_decode_response(msg, data, &r->response); if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(10))) { asn1_read_ContextSimple(data, 1, &tmp_blob); r->oid = blob2string_talloc(msg, tmp_blob); data_blob_free(&tmp_blob); if (!r->oid) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } } else { r->oid = NULL; } if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(11))) { asn1_read_ContextSimple(data, 1, &tmp_blob); r->value = talloc(msg, DATA_BLOB); if (!r->value) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } *r->value = data_blob_talloc(r->value, tmp_blob.data, tmp_blob.length); data_blob_free(&tmp_blob); } else { r->value = NULL; } asn1_end_tag(data); break; } default: return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } msg->controls = NULL; msg->controls_decoded = NULL; if (asn1_peek_tag(data, ASN1_CONTEXT(0))) { int i = 0; struct ldb_control **ctrl = NULL; bool *decoded = NULL; asn1_start_tag(data, ASN1_CONTEXT(0)); while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) { DATA_BLOB value; /* asn1_start_tag(data, ASN1_SEQUENCE(0)); */ ctrl = talloc_realloc(msg, ctrl, struct ldb_control *, i+2); if (!ctrl) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } decoded = talloc_realloc(msg, decoded, bool, i+1); if (!decoded) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } ctrl[i] = talloc(ctrl, struct ldb_control); if (!ctrl[i]) { return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); } if (!ldap_decode_control_wrapper(ctrl[i], data, ctrl[i], &value)) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } if (!ldap_decode_control_value(ctrl[i], value, control_handlers, ctrl[i])) { if (ctrl[i]->critical) { ctrl[i]->data = NULL; decoded[i] = false; i++; } else { talloc_free(ctrl[i]); ctrl[i] = NULL; } } else { decoded[i] = true; i++; } } if (ctrl != NULL) { ctrl[i] = NULL; } msg->controls = ctrl; msg->controls_decoded = decoded; asn1_end_tag(data); } asn1_end_tag(data); if ((data->has_error) || (data->nesting != NULL)) { return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); } return NT_STATUS_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <jra@samba.org> Reviewed-by: Ronnie Sahlberg <ronniesahlberg@gmail.com> Autobuild-User(master): Jeremy Allison <jra@samba.org> Autobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104 (cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool asn1_write_LDAPString(struct asn1_data *data, const char *s) { asn1_write(data, s, strlen(s)); return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <jra@samba.org> Reviewed-by: Volker Lendecke <Volker.Lendecke@SerNet.DE> Autobuild-User(master): Jeremy Allison <jra@samba.org> Autobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104 (cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool asn1_check_enumerated(struct asn1_data *data, int v) { uint8_t b; if (!asn1_start_tag(data, ASN1_ENUMERATED)) return false; asn1_read_uint8(data, &b); asn1_end_tag(data); if (v != b) data->has_error = false; return !data->has_error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return. BUG: https://bugzilla.samba.org/show_bug.cgi?id=9187 Signed-off-by: Jeremy Allison <jra@samba.org> Reviewed-by: Volker Lendecke <Volker.Lendecke@SerNet.DE> Autobuild-User(master): Jeremy Allison <jra@samba.org> Autobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104 (cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SMBC_server_internal(TALLOC_CTX *ctx, SMBCCTX *context, bool connect_if_not_found, const char *server, uint16_t port, const char *share, char **pp_workgroup, char **pp_username, char **pp_password, bool *in_cache) { SMBCSRV *srv=NULL; char *workgroup = NULL; struct cli_state *c = NULL; const char *server_n = server; int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0); uint32_t fs_attrs = 0; const char *username_used; NTSTATUS status; char *newserver, *newshare; int flags = 0; struct smbXcli_tcon *tcon = NULL; ZERO_STRUCT(c); *in_cache = false; if (server[0] == 0) { errno = EPERM; return NULL; } /* Look for a cached connection */ srv = SMBC_find_server(ctx, context, server, share, pp_workgroup, pp_username, pp_password); /* * If we found a connection and we're only allowed one share per * server... */ if (srv && share != NULL && *share != '\0' && smbc_getOptionOneSharePerServer(context)) { /* * ... then if there's no current connection to the share, * connect to it. SMBC_find_server(), or rather the function * pointed to by context->get_cached_srv_fn which * was called by SMBC_find_server(), will have issued a tree * disconnect if the requested share is not the same as the * one that was already connected. */ /* * Use srv->cli->desthost and srv->cli->share instead of * server and share below to connect to the actual share, * i.e., a normal share or a referred share from * 'msdfs proxy' share. */ if (!cli_state_has_tcon(srv->cli)) { /* Ensure we have accurate auth info */ SMBC_call_auth_fn(ctx, context, smbXcli_conn_remote_name(srv->cli->conn), srv->cli->share, pp_workgroup, pp_username, pp_password); if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); return NULL; } /* * We don't need to renegotiate encryption * here as the encryption context is not per * tid. */ status = cli_tree_connect(srv->cli, srv->cli->share, "?????", *pp_password, strlen(*pp_password)+1); if (!NT_STATUS_IS_OK(status)) { errno = map_errno_from_nt_status(status); cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); srv = NULL; } /* Determine if this share supports case sensitivity */ if (is_ipc) { DEBUG(4, ("IPC$ so ignore case sensitivity\n")); status = NT_STATUS_OK; } else { status = cli_get_fs_attr_info(c, &fs_attrs); } if (!NT_STATUS_IS_OK(status)) { DEBUG(4, ("Could not retrieve " "case sensitivity flag: %s.\n", nt_errstr(status))); /* * We can't determine the case sensitivity of * the share. We have no choice but to use the * user-specified case sensitivity setting. */ if (smbc_getOptionCaseSensitive(context)) { cli_set_case_sensitive(c, True); } else { cli_set_case_sensitive(c, False); } } else if (!is_ipc) { DEBUG(4, ("Case sensitive: %s\n", (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? "True" : "False"))); cli_set_case_sensitive( c, (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? True : False)); } /* * Regenerate the dev value since it's based on both * server and share */ if (srv) { const char *remote_name = smbXcli_conn_remote_name(srv->cli->conn); srv->dev = (dev_t)(str_checksum(remote_name) ^ str_checksum(srv->cli->share)); } } } /* If we have a connection... */ if (srv) { /* ... then we're done here. Give 'em what they came for. */ *in_cache = true; goto done; } /* If we're not asked to connect when a connection doesn't exist... */ if (! connect_if_not_found) { /* ... then we're done here. */ return NULL; } if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; return NULL; } DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server)); DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server)); status = NT_STATUS_UNSUCCESSFUL; if (smbc_getOptionUseKerberos(context)) { flags |= CLI_FULL_CONNECTION_USE_KERBEROS; } if (smbc_getOptionFallbackAfterKerberos(context)) { flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS; } if (smbc_getOptionUseCCache(context)) { flags |= CLI_FULL_CONNECTION_USE_CCACHE; } if (smbc_getOptionUseNTHash(context)) { flags |= CLI_FULL_CONNECTION_USE_NT_HASH; } if (port == 0) { if (share == NULL || *share == '\0' || is_ipc) { /* * Try 139 first for IPC$ */ status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20, smbc_getNetbiosName(context), SMB_SIGNING_DEFAULT, flags, &c); } } if (!NT_STATUS_IS_OK(status)) { /* * No IPC$ or 139 did not work */ status = cli_connect_nb(server_n, NULL, port, 0x20, smbc_getNetbiosName(context), SMB_SIGNING_DEFAULT, flags, &c); } if (!NT_STATUS_IS_OK(status)) { errno = map_errno_from_nt_status(status); return NULL; } cli_set_timeout(c, smbc_getTimeout(context)); status = smbXcli_negprot(c->conn, c->timeout, lp_client_min_protocol(), lp_client_max_protocol()); if (!NT_STATUS_IS_OK(status)) { cli_shutdown(c); errno = ETIMEDOUT; return NULL; } if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) { /* Ensure we ask for some initial credits. */ smb2cli_conn_set_max_credits(c->conn, DEFAULT_SMB2_MAX_CREDITS); } username_used = *pp_username; if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used, *pp_password, strlen(*pp_password), *pp_password, strlen(*pp_password), *pp_workgroup))) { /* Failed. Try an anonymous login, if allowed by flags. */ username_used = ""; if (smbc_getOptionNoAutoAnonymousLogin(context) || !NT_STATUS_IS_OK(cli_session_setup(c, username_used, *pp_password, 1, *pp_password, 0, *pp_workgroup))) { cli_shutdown(c); errno = EPERM; return NULL; } } DEBUG(4,(" session setup ok\n")); /* here's the fun part....to support 'msdfs proxy' shares (on Samba or windows) we have to issues a TRANS_GET_DFS_REFERRAL here before trying to connect to the original share. cli_check_msdfs_proxy() will fail if it is a normal share. */ if (smbXcli_conn_dfs_supported(c->conn) && cli_check_msdfs_proxy(ctx, c, share, &newserver, &newshare, /* FIXME: cli_check_msdfs_proxy() does not support smbc_smb_encrypt_level type */ context->internal->smb_encryption_level ? true : false, *pp_username, *pp_password, *pp_workgroup)) { cli_shutdown(c); srv = SMBC_server_internal(ctx, context, connect_if_not_found, newserver, port, newshare, pp_workgroup, pp_username, pp_password, in_cache); TALLOC_FREE(newserver); TALLOC_FREE(newshare); return srv; } /* must be a normal share */ status = cli_tree_connect(c, share, "?????", *pp_password, strlen(*pp_password)+1); if (!NT_STATUS_IS_OK(status)) { errno = map_errno_from_nt_status(status); cli_shutdown(c); return NULL; } DEBUG(4,(" tconx ok\n")); if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) { tcon = c->smb2.tcon; } else { tcon = c->smb1.tcon; } /* Determine if this share supports case sensitivity */ if (is_ipc) { DEBUG(4, ("IPC$ so ignore case sensitivity\n")); status = NT_STATUS_OK; } else { status = cli_get_fs_attr_info(c, &fs_attrs); } if (!NT_STATUS_IS_OK(status)) { DEBUG(4, ("Could not retrieve case sensitivity flag: %s.\n", nt_errstr(status))); /* * We can't determine the case sensitivity of the share. We * have no choice but to use the user-specified case * sensitivity setting. */ if (smbc_getOptionCaseSensitive(context)) { cli_set_case_sensitive(c, True); } else { cli_set_case_sensitive(c, False); } } else if (!is_ipc) { DEBUG(4, ("Case sensitive: %s\n", (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? "True" : "False"))); smbXcli_tcon_set_fs_attributes(tcon, fs_attrs); } if (context->internal->smb_encryption_level) { /* Attempt UNIX smb encryption. */ if (!NT_STATUS_IS_OK(cli_force_encryption(c, username_used, *pp_password, *pp_workgroup))) { /* * context->smb_encryption_level == 1 * means don't fail if encryption can't be negotiated, * == 2 means fail if encryption can't be negotiated. */ DEBUG(4,(" SMB encrypt failed\n")); if (context->internal->smb_encryption_level == 2) { cli_shutdown(c); errno = EPERM; return NULL; } } DEBUG(4,(" SMB encrypt ok\n")); } /* * Ok, we have got a nice connection * Let's allocate a server structure. */ srv = SMB_MALLOC_P(SMBCSRV); if (!srv) { cli_shutdown(c); errno = ENOMEM; return NULL; } ZERO_STRUCTP(srv); srv->cli = c; srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share)); srv->no_pathinfo = False; srv->no_pathinfo2 = False; srv->no_pathinfo3 = False; srv->no_nt_session = False; done: if (!pp_workgroup || !*pp_workgroup || !**pp_workgroup) { workgroup = talloc_strdup(ctx, smbc_getWorkgroup(context)); } else { workgroup = *pp_workgroup; } if(!workgroup) { if (c != NULL) { cli_shutdown(c); } SAFE_FREE(srv); return NULL; } /* set the credentials to make DFS work */ smbc_set_credentials_with_fallback(context, workgroup, *pp_username, *pp_password); return srv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2015-5296: s3:libsmb: force signing when requiring encryption in SMBC_server_internal() BUG: https://bugzilla.samba.org/show_bug.cgi?id=11536 Signed-off-by: Stefan Metzmacher <metze@samba.org> Reviewed-by: Jeremy Allison <jra@samba.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; upperdentry = ovl_dentry_upper(dentry); if (upperdentry) { mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } else { err = ovl_copy_up_last(dentry, attr, false); } ovl_drop_write(dentry); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'ovl: fix permission checking for setattr [Al Viro] The bug is in being too enthusiastic about optimizing ->setattr() away - instead of "copy verbatim with metadata" + "chmod/chown/utimes" (with the former being always safe and the latter failing in case of insufficient permissions) it tries to combine these two. Note that copyup itself will have to do ->setattr() anyway; _that_ is where the elevated capabilities are right. Having these two ->setattr() (one to set verbatim copy of metadata, another to do what overlayfs ->setattr() had been asked to do in the first place) combined is where it breaks. Signed-off-by: Miklos Szeredi <miklos@szeredi.hu> Cc: <stable@vger.kernel.org> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct file_list *recv_file_list(int f) { struct file_list *flist; int dstart, flags; int64 start_read; if (!first_flist) { if (show_filelist_p()) start_filelist_progress("receiving file list"); else if (inc_recurse && INFO_GTE(FLIST, 1) && !am_server) rprintf(FCLIENT, "receiving incremental file list\n"); rprintf(FLOG, "receiving file list\n"); if (usermap) parse_name_map(usermap, True); if (groupmap) parse_name_map(groupmap, False); } start_read = stats.total_read; #ifdef SUPPORT_HARD_LINKS if (preserve_hard_links && !first_flist) init_hard_links(); #endif flist = flist_new(0, "recv_file_list"); if (inc_recurse) { if (flist->ndx_start == 1) dir_flist = flist_new(FLIST_TEMP, "recv_file_list"); dstart = dir_flist->used; } else { dir_flist = flist; dstart = 0; } while ((flags = read_byte(f)) != 0) { struct file_struct *file; if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS)) flags |= read_byte(f) << 8; if (flags == (XMIT_EXTENDED_FLAGS|XMIT_IO_ERROR_ENDLIST)) { int err; if (!use_safe_inc_flist) { rprintf(FERROR, "Invalid flist flag: %x\n", flags); exit_cleanup(RERR_PROTOCOL); } err = read_varint(f); if (!ignore_errors) io_error |= err; break; } flist_expand(flist, 1); file = recv_file_entry(f, flist, flags); if (S_ISREG(file->mode)) { /* Already counted */ } else if (S_ISDIR(file->mode)) { if (inc_recurse) { flist_expand(dir_flist, 1); dir_flist->files[dir_flist->used++] = file; } stats.num_dirs++; } else if (S_ISLNK(file->mode)) stats.num_symlinks++; else if (IS_DEVICE(file->mode)) stats.num_symlinks++; else stats.num_specials++; flist->files[flist->used++] = file; maybe_emit_filelist_progress(flist->used); if (DEBUG_GTE(FLIST, 2)) { char *name = f_name(file, NULL); rprintf(FINFO, "recv_file_name(%s)\n", NS(name)); } } file_total += flist->used; if (DEBUG_GTE(FLIST, 2)) rprintf(FINFO, "received %d names\n", flist->used); if (show_filelist_p()) finish_filelist_progress(flist); if (need_unsorted_flist) { /* Create an extra array of index pointers that we can sort for * the generator's use (for wading through the files in sorted * order and for calling flist_find()). We keep the "files" * list unsorted for our exchange of index numbers with the * other side (since their names may not sort the same). */ if (!(flist->sorted = new_array(struct file_struct *, flist->used))) out_of_memory("recv_file_list"); memcpy(flist->sorted, flist->files, flist->used * sizeof (struct file_struct*)); if (inc_recurse && dir_flist->used > dstart) { static int dir_flist_malloced = 0; if (dir_flist_malloced < dir_flist->malloced) { dir_flist->sorted = realloc_array(dir_flist->sorted, struct file_struct *, dir_flist->malloced); dir_flist_malloced = dir_flist->malloced; } memcpy(dir_flist->sorted + dstart, dir_flist->files + dstart, (dir_flist->used - dstart) * sizeof (struct file_struct*)); fsort(dir_flist->sorted + dstart, dir_flist->used - dstart); } } else { flist->sorted = flist->files; if (inc_recurse && dir_flist->used > dstart) { dir_flist->sorted = dir_flist->files; fsort(dir_flist->sorted + dstart, dir_flist->used - dstart); } } if (inc_recurse) flist_done_allocating(flist); else if (f >= 0) { recv_id_list(f, flist); flist_eof = 1; if (DEBUG_GTE(FLIST, 3)) rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i()); } /* The --relative option sends paths with a leading slash, so we need * to specify the strip_root option here. We rejected leading slashes * for a non-relative transfer in recv_file_entry(). */ flist_sort_and_clean(flist, relative_paths); if (protocol_version < 30) { /* Recv the io_error flag */ int err = read_int(f); if (!ignore_errors) io_error |= err; } else if (inc_recurse && flist->ndx_start == 1) { if (!file_total || strcmp(flist->sorted[flist->low]->basename, ".") != 0) flist->parent_ndx = -1; } if (DEBUG_GTE(FLIST, 3)) output_flist(flist); if (DEBUG_GTE(FLIST, 2)) rprintf(FINFO, "recv_file_list done\n"); stats.flist_size += stats.total_read - start_read; stats.num_files += flist->used; return flist; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'Complain if an inc-recursive path is not right for its dir. This ensures that a malicious sender can't use a just-sent symlink as a trasnfer path.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */ { va_list va; char *message = NULL; va_start(va, format); zend_vspprintf(&message, 0, format, va); if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) { zend_throw_error(exception_ce, message); } else { zend_error(E_ERROR, "%s", message); } efree(message); va_end(va); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Use format string'</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: authhavekey( keyid_t id ) { symkey * sk; authkeylookups++; if (0 == id || cache_keyid == id) { return TRUE; } /* * Seach the bin for the key. If found and the key type * is zero, somebody marked it trusted without specifying * a key or key type. In this case consider the key missing. */ authkeyuncached++; for (sk = key_hash[KEYHASH(id)]; sk != NULL; sk = sk->hlink) { if (id == sk->keyid) { if (0 == sk->type) { authkeynotfound++; return FALSE; } break; } } /* * If the key is not found, or if it is found but not trusted, * the key is not considered found. */ if (NULL == sk) { authkeynotfound++; return FALSE; } if (!(KEY_TRUSTED & sk->flags)) { authnokey++; return FALSE; } /* * The key is found and trusted. Initialize the key cache. */ cache_keyid = sk->keyid; cache_type = sk->type; cache_flags = sk->flags; cache_secret = sk->secret; cache_secretsize = sk->secretsize; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': '[Sec 2936] Skeleton Key: Any trusted key system can serve time. HStenn.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdImagePtr gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor) { const int angle_rounded = (int)floor(angle * 100); if (bgcolor < 0 || (!src->trueColor && bgcolor >= gdMaxColors)) { return NULL; } /* impact perf a bit, but not that much. Implementation for palette images can be done at a later point. */ if (src->trueColor == 0) { if (bgcolor >= 0) { bgcolor = gdTrueColorAlpha(src->red[bgcolor], src->green[bgcolor], src->blue[bgcolor], src->alpha[bgcolor]); } gdImagePaletteToTrueColor(src); } /* no interpolation needed here */ switch (angle_rounded) { case 9000: return gdImageRotate90(src, 0); case 18000: return gdImageRotate180(src, 0); case 27000: return gdImageRotate270(src, 0); } if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) { return NULL; } switch (src->interpolation_id) { case GD_NEAREST_NEIGHBOUR: return gdImageRotateNearestNeighbour(src, angle, bgcolor); break; case GD_BILINEAR_FIXED: return gdImageRotateBilinear(src, angle, bgcolor); break; case GD_BICUBIC_FIXED: return gdImageRotateBicubicFixed(src, angle, bgcolor); break; default: return gdImageRotateGeneric(src, angle, bgcolor); } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'fix the fix for bug #70976 (imagerotate)'</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: PHPAPI zend_string *php_escape_shell_arg(char *str) { int x, y = 0, l = (int)strlen(str); zend_string *cmd; size_t estimate = (4 * l) + 3; cmd = zend_string_alloc(4 * l + 2, 0); /* worst case */ #ifdef PHP_WIN32 ZSTR_VAL(cmd)[y++] = '"'; #else ZSTR_VAL(cmd)[y++] = '\''; #endif for (x = 0; x < l; x++) { int mb_len = php_mblen(str + x, (l - x)); /* skip non-valid multibyte characters */ if (mb_len < 0) { continue; } else if (mb_len > 1) { memcpy(ZSTR_VAL(cmd) + y, str + x, mb_len); y += mb_len; x += mb_len - 1; continue; } switch (str[x]) { #ifdef PHP_WIN32 case '"': case '%': case '!': ZSTR_VAL(cmd)[y++] = ' '; break; #else case '\'': ZSTR_VAL(cmd)[y++] = '\''; ZSTR_VAL(cmd)[y++] = '\\'; ZSTR_VAL(cmd)[y++] = '\''; #endif /* fall-through */ default: ZSTR_VAL(cmd)[y++] = str[x]; } } #ifdef PHP_WIN32 if (y > 0 && '\\' == ZSTR_VAL(cmd)[y - 1]) { int k = 0, n = y - 1; for (; n >= 0 && '\\' == ZSTR_VAL(cmd)[n]; n--, k++); if (k % 2) { ZSTR_VAL(cmd)[y++] = '\\'; } } ZSTR_VAL(cmd)[y++] = '"'; #else ZSTR_VAL(cmd)[y++] = '\''; #endif ZSTR_VAL(cmd)[y] = '\0'; if ((estimate - y) > 4096) { /* realloc if the estimate was way overill * Arbitrary cutoff point of 4096 */ cmd = zend_string_truncate(cmd, y, 0); } ZSTR_LEN(cmd) = y; return cmd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Patch for Heap Buffer Overflow in EscapeShell Proposed patch for bug #71270'</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: receive( struct recvbuf *rbufp ) { register struct peer *peer; /* peer structure pointer */ register struct pkt *pkt; /* receive packet pointer */ u_char hisversion; /* packet version */ u_char hisleap; /* packet leap indicator */ u_char hismode; /* packet mode */ u_char hisstratum; /* packet stratum */ u_short restrict_mask; /* restrict bits */ const char *hm_str; /* hismode string */ const char *am_str; /* association match string */ int kissCode = NOKISS; /* Kiss Code */ int has_mac; /* length of MAC field */ int authlen; /* offset of MAC field */ int is_authentic = 0; /* cryptosum ok */ int retcode = AM_NOMATCH; /* match code */ keyid_t skeyid = 0; /* key IDs */ u_int32 opcode = 0; /* extension field opcode */ sockaddr_u *dstadr_sin; /* active runway */ struct peer *peer2; /* aux peer structure pointer */ endpt *match_ep; /* newpeer() local address */ l_fp p_org; /* origin timestamp */ l_fp p_rec; /* receive timestamp */ l_fp p_xmt; /* transmit timestamp */ #ifdef AUTOKEY char hostname[NTP_MAXSTRLEN + 1]; char *groupname = NULL; struct autokey *ap; /* autokey structure pointer */ int rval; /* cookie snatcher */ keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */ #endif /* AUTOKEY */ #ifdef HAVE_NTP_SIGND static unsigned char zero_key[16]; #endif /* HAVE_NTP_SIGND */ /* * Monitor the packet and get restrictions. Note that the packet * length for control and private mode packets must be checked * by the service routines. Some restrictions have to be handled * later in order to generate a kiss-o'-death packet. */ /* * Bogus port check is before anything, since it probably * reveals a clogging attack. */ sys_received++; if (0 == SRCPORT(&rbufp->recv_srcadr)) { sys_badlength++; return; /* bogus port */ } restrict_mask = restrictions(&rbufp->recv_srcadr); pkt = &rbufp->recv_pkt; DPRINTF(2, ("receive: at %ld %s<-%s flags %x restrict %03x org %#010x.%08x xmt %#010x.%08x\n", current_time, stoa(&rbufp->dstadr->sin), stoa(&rbufp->recv_srcadr), rbufp->dstadr->flags, restrict_mask, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); hisversion = PKT_VERSION(pkt->li_vn_mode); hisleap = PKT_LEAP(pkt->li_vn_mode); hismode = (int)PKT_MODE(pkt->li_vn_mode); hisstratum = PKT_TO_STRATUM(pkt->stratum); if (restrict_mask & RES_IGNORE) { sys_restricted++; return; /* ignore everything */ } if (hismode == MODE_PRIVATE) { if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) { sys_restricted++; return; /* no query private */ } process_private(rbufp, ((restrict_mask & RES_NOMODIFY) == 0)); return; } if (hismode == MODE_CONTROL) { if (restrict_mask & RES_NOQUERY) { sys_restricted++; return; /* no query control */ } process_control(rbufp, restrict_mask); return; } if (restrict_mask & RES_DONTSERVE) { sys_restricted++; return; /* no time serve */ } /* * This is for testing. If restricted drop ten percent of * surviving packets. */ if (restrict_mask & RES_FLAKE) { if ((double)ntp_random() / 0x7fffffff < .1) { sys_restricted++; return; /* no flakeway */ } } /* * Version check must be after the query packets, since they * intentionally use an early version. */ if (hisversion == NTP_VERSION) { sys_newversion++; /* new version */ } else if ( !(restrict_mask & RES_VERSION) && hisversion >= NTP_OLDVERSION) { sys_oldversion++; /* previous version */ } else { sys_badlength++; return; /* old version */ } /* * Figure out his mode and validate the packet. This has some * legacy raunch that probably should be removed. In very early * NTP versions mode 0 was equivalent to what later versions * would interpret as client mode. */ if (hismode == MODE_UNSPEC) { if (hisversion == NTP_OLDVERSION) { hismode = MODE_CLIENT; } else { sys_badlength++; return; /* invalid mode */ } } /* * Parse the extension field if present. We figure out whether * an extension field is present by measuring the MAC size. If * the number of words following the packet header is 0, no MAC * is present and the packet is not authenticated. If 1, the * packet is a crypto-NAK; if 3, the packet is authenticated * with DES; if 5, the packet is authenticated with MD5; if 6, * the packet is authenticated with SHA. If 2 or * 4, the packet * is a runt and discarded forthwith. If greater than 6, an * extension field is present, so we subtract the length of the * field and go around again. */ authlen = LEN_PKT_NOMAC; has_mac = rbufp->recv_length - authlen; while (has_mac > 0) { u_int32 len; #ifdef AUTOKEY u_int32 hostlen; struct exten *ep; #endif /*AUTOKEY */ if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) { sys_badlength++; return; /* bad length */ } if (has_mac <= (int)MAX_MAC_LEN) { skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]); break; } else { opcode = ntohl(((u_int32 *)pkt)[authlen / 4]); len = opcode & 0xffff; if ( len % 4 != 0 || len < 4 || (int)len + authlen > rbufp->recv_length) { sys_badlength++; return; /* bad length */ } #ifdef AUTOKEY /* * Extract calling group name for later. If * sys_groupname is non-NULL, there must be * a group name provided to elicit a response. */ if ( (opcode & 0x3fff0000) == CRYPTO_ASSOC && sys_groupname != NULL) { ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4]; hostlen = ntohl(ep->vallen); if ( hostlen >= sizeof(hostname) || hostlen > len - offsetof(struct exten, pkt)) { sys_badlength++; return; /* bad length */ } memcpy(hostname, &ep->pkt, hostlen); hostname[hostlen] = '\0'; groupname = strchr(hostname, '@'); if (groupname == NULL) { sys_declined++; return; } groupname++; } #endif /* AUTOKEY */ authlen += len; has_mac -= len; } } /* * If has_mac is < 0 we had a malformed packet. */ if (has_mac < 0) { sys_badlength++; return; /* bad length */ } /* * If authentication required, a MAC must be present. */ if (restrict_mask & RES_DONTTRUST && has_mac == 0) { sys_restricted++; return; /* access denied */ } /* * Update the MRU list and finger the cloggers. It can be a * little expensive, so turn it off for production use. * RES_LIMITED and RES_KOD will be cleared in the returned * restrict_mask unless one or both actions are warranted. */ restrict_mask = ntp_monitor(rbufp, restrict_mask); if (restrict_mask & RES_LIMITED) { sys_limitrejected++; if ( !(restrict_mask & RES_KOD) || MODE_BROADCAST == hismode || MODE_SERVER == hismode) { if (MODE_SERVER == hismode) DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n", stoa(&rbufp->recv_srcadr))); return; /* rate exceeded */ } if (hismode == MODE_CLIENT) fast_xmit(rbufp, MODE_SERVER, skeyid, restrict_mask); else fast_xmit(rbufp, MODE_ACTIVE, skeyid, restrict_mask); return; /* rate exceeded */ } restrict_mask &= ~RES_KOD; /* * We have tossed out as many buggy packets as possible early in * the game to reduce the exposure to a clogging attack. Now we * have to burn some cycles to find the association and * authenticate the packet if required. Note that we burn only * digest cycles, again to reduce exposure. There may be no * matching association and that's okay. * * More on the autokey mambo. Normally the local interface is * found when the association was mobilized with respect to a * designated remote address. We assume packets arriving from * the remote address arrive via this interface and the local * address used to construct the autokey is the unicast address * of the interface. However, if the sender is a broadcaster, * the interface broadcast address is used instead. * Notwithstanding this technobabble, if the sender is a * multicaster, the broadcast address is null, so we use the * unicast address anyway. Don't ask. */ peer = findpeer(rbufp, hismode, &retcode); dstadr_sin = &rbufp->dstadr->sin; NTOHL_FP(&pkt->org, &p_org); NTOHL_FP(&pkt->rec, &p_rec); NTOHL_FP(&pkt->xmt, &p_xmt); hm_str = modetoa(hismode); am_str = amtoa(retcode); /* * Authentication is conditioned by three switches: * * NOPEER (RES_NOPEER) do not mobilize an association unless * authenticated * NOTRUST (RES_DONTTRUST) do not allow access unless * authenticated (implies NOPEER) * enable (sys_authenticate) master NOPEER switch, by default * on * * The NOPEER and NOTRUST can be specified on a per-client basis * using the restrict command. The enable switch if on implies * NOPEER for all clients. There are four outcomes: * * NONE The packet has no MAC. * OK the packet has a MAC and authentication succeeds * ERROR the packet has a MAC and authentication fails * CRYPTO crypto-NAK. The MAC has four octets only. * * Note: The AUTH(x, y) macro is used to filter outcomes. If x * is zero, acceptable outcomes of y are NONE and OK. If x is * one, the only acceptable outcome of y is OK. */ if (has_mac == 0) { restrict_mask &= ~RES_MSSNTP; is_authentic = AUTH_NONE; /* not required */ DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n", current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, authlen, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); } else if (has_mac == 4) { restrict_mask &= ~RES_MSSNTP; is_authentic = AUTH_CRYPTO; /* crypto-NAK */ DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC4\n", current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, skeyid, authlen + has_mac, is_authentic, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); #ifdef HAVE_NTP_SIGND /* * If the signature is 20 bytes long, the last 16 of * which are zero, then this is a Microsoft client * wanting AD-style authentication of the server's * reply. * * This is described in Microsoft's WSPP docs, in MS-SNTP: * http://msdn.microsoft.com/en-us/library/cc212930.aspx */ } else if ( has_mac == MAX_MD5_LEN && (restrict_mask & RES_MSSNTP) && (retcode == AM_FXMIT || retcode == AM_NEWPASS) && (memcmp(zero_key, (char *)pkt + authlen + 4, MAX_MD5_LEN - 4) == 0)) { is_authentic = AUTH_NONE; #endif /* HAVE_NTP_SIGND */ } else { restrict_mask &= ~RES_MSSNTP; #ifdef AUTOKEY /* * For autokey modes, generate the session key * and install in the key cache. Use the socket * broadcast or unicast address as appropriate. */ if (crypto_flags && skeyid > NTP_MAXKEY) { /* * More on the autokey dance (AKD). A cookie is * constructed from public and private values. * For broadcast packets, the cookie is public * (zero). For packets that match no * association, the cookie is hashed from the * addresses and private value. For server * packets, the cookie was previously obtained * from the server. For symmetric modes, the * cookie was previously constructed using an * agreement protocol; however, should PKI be * unavailable, we construct a fake agreement as * the EXOR of the peer and host cookies. * * hismode ephemeral persistent * ======================================= * active 0 cookie# * passive 0% cookie# * client sys cookie 0% * server 0% sys cookie * broadcast 0 0 * * # if unsync, 0 * % can't happen */ if (has_mac < (int)MAX_MD5_LEN) { sys_badauth++; return; } if (hismode == MODE_BROADCAST) { /* * For broadcaster, use the interface * broadcast address when available; * otherwise, use the unicast address * found when the association was * mobilized. However, if this is from * the wildcard interface, game over. */ if ( crypto_flags && rbufp->dstadr == ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) { sys_restricted++; return; /* no wildcard */ } pkeyid = 0; if (!SOCK_UNSPEC(&rbufp->dstadr->bcast)) dstadr_sin = &rbufp->dstadr->bcast; } else if (peer == NULL) { pkeyid = session_key( &rbufp->recv_srcadr, dstadr_sin, 0, sys_private, 0); } else { pkeyid = peer->pcookie; } /* * The session key includes both the public * values and cookie. In case of an extension * field, the cookie used for authentication * purposes is zero. Note the hash is saved for * use later in the autokey mambo. */ if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) { session_key(&rbufp->recv_srcadr, dstadr_sin, skeyid, 0, 2); tkeyid = session_key( &rbufp->recv_srcadr, dstadr_sin, skeyid, pkeyid, 0); } else { tkeyid = session_key( &rbufp->recv_srcadr, dstadr_sin, skeyid, pkeyid, 2); } } #endif /* AUTOKEY */ /* * Compute the cryptosum. Note a clogging attack may * succeed in bloating the key cache. If an autokey, * purge it immediately, since we won't be needing it * again. If the packet is authentic, it can mobilize an * association. Note that there is no key zero. */ if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen, has_mac)) is_authentic = AUTH_ERROR; else is_authentic = AUTH_OK; #ifdef AUTOKEY if (crypto_flags && skeyid > NTP_MAXKEY) authtrust(skeyid, 0); #endif /* AUTOKEY */ DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x\n", current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, skeyid, authlen + has_mac, is_authentic, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); } /* * The association matching rules are implemented by a set of * routines and an association table. A packet matching an * association is processed by the peer process for that * association. If there are no errors, an ephemeral association * is mobilized: a broadcast packet mobilizes a broadcast client * aassociation; a manycast server packet mobilizes a manycast * client association; a symmetric active packet mobilizes a * symmetric passive association. */ switch (retcode) { /* * This is a client mode packet not matching any association. If * an ordinary client, simply toss a server mode packet back * over the fence. If a manycast client, we have to work a * little harder. */ case AM_FXMIT: /* * If authentication OK, send a server reply; otherwise, * send a crypto-NAK. */ if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) { if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic)) { fast_xmit(rbufp, MODE_SERVER, skeyid, restrict_mask); } else if (is_authentic == AUTH_ERROR) { fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask); sys_badauth++; } else { sys_restricted++; } return; /* hooray */ } /* * This must be manycast. Do not respond if not * configured as a manycast server. */ if (!sys_manycastserver) { sys_restricted++; return; /* not enabled */ } #ifdef AUTOKEY /* * Do not respond if not the same group. */ if (group_test(groupname, NULL)) { sys_declined++; return; } #endif /* AUTOKEY */ /* * Do not respond if we are not synchronized or our * stratum is greater than the manycaster or the * manycaster has already synchronized to us. */ if ( sys_leap == LEAP_NOTINSYNC || sys_stratum >= hisstratum || (!sys_cohort && sys_stratum == hisstratum + 1) || rbufp->dstadr->addr_refid == pkt->refid) { sys_declined++; return; /* no help */ } /* * Respond only if authentication succeeds. Don't do a * crypto-NAK, as that would not be useful. */ if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic)) fast_xmit(rbufp, MODE_SERVER, skeyid, restrict_mask); return; /* hooray */ /* * This is a server mode packet returned in response to a client * mode packet sent to a multicast group address (for * manycastclient) or to a unicast address (for pool). The * origin timestamp is a good nonce to reliably associate the * reply with what was sent. If there is no match, that's * curious and could be an intruder attempting to clog, so we * just ignore it. * * If the packet is authentic and the manycastclient or pool * association is found, we mobilize a client association and * copy pertinent variables from the manycastclient or pool * association to the new client association. If not, just * ignore the packet. * * There is an implosion hazard at the manycast client, since * the manycast servers send the server packet immediately. If * the guy is already here, don't fire up a duplicate. */ case AM_MANYCAST: #ifdef AUTOKEY /* * Do not respond if not the same group. */ if (group_test(groupname, NULL)) { sys_declined++; return; } #endif /* AUTOKEY */ if ((peer2 = findmanycastpeer(rbufp)) == NULL) { sys_restricted++; return; /* not enabled */ } if (!AUTH( (!(peer2->cast_flags & MDF_POOL) && sys_authenticate) || (restrict_mask & (RES_NOPEER | RES_DONTTRUST)), is_authentic)) { sys_restricted++; return; /* access denied */ } /* * Do not respond if unsynchronized or stratum is below * the floor or at or above the ceiling. */ if ( hisleap == LEAP_NOTINSYNC || hisstratum < sys_floor || hisstratum >= sys_ceiling) { sys_declined++; return; /* no help */ } peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr, MODE_CLIENT, hisversion, peer2->minpoll, peer2->maxpoll, FLAG_PREEMPT | (FLAG_IBURST & peer2->flags), MDF_UCAST | MDF_UCLNT, 0, skeyid, sys_ident); if (NULL == peer) { sys_declined++; return; /* ignore duplicate */ } /* * After each ephemeral pool association is spun, * accelerate the next poll for the pool solicitor so * the pool will fill promptly. */ if (peer2->cast_flags & MDF_POOL) peer2->nextdate = current_time + 1; /* * Further processing of the solicitation response would * simply detect its origin timestamp as bogus for the * brand-new association (it matches the prototype * association) and tinker with peer->nextdate delaying * first sync. */ return; /* solicitation response handled */ /* * This is the first packet received from a broadcast server. If * the packet is authentic and we are enabled as broadcast * client, mobilize a broadcast client association. We don't * kiss any frogs here. */ case AM_NEWBCL: #ifdef AUTOKEY /* * Do not respond if not the same group. */ if (group_test(groupname, sys_ident)) { sys_declined++; return; } #endif /* AUTOKEY */ if (sys_bclient == 0) { sys_restricted++; return; /* not enabled */ } if (!AUTH(sys_authenticate | (restrict_mask & (RES_NOPEER | RES_DONTTRUST)), is_authentic)) { sys_restricted++; return; /* access denied */ } /* * Do not respond if unsynchronized or stratum is below * the floor or at or above the ceiling. */ if ( hisleap == LEAP_NOTINSYNC || hisstratum < sys_floor || hisstratum >= sys_ceiling) { sys_declined++; return; /* no help */ } #ifdef AUTOKEY /* * Do not respond if Autokey and the opcode is not a * CRYPTO_ASSOC response with association ID. */ if ( crypto_flags && skeyid > NTP_MAXKEY && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) { sys_declined++; return; /* protocol error */ } #endif /* AUTOKEY */ /* * Broadcasts received via a multicast address may * arrive after a unicast volley has begun * with the same remote address. newpeer() will not * find duplicate associations on other local endpoints * if a non-NULL endpoint is supplied. multicastclient * ephemeral associations are unique across all local * endpoints. */ if (!(INT_MCASTOPEN & rbufp->dstadr->flags)) match_ep = rbufp->dstadr; else match_ep = NULL; /* * Determine whether to execute the initial volley. */ if (sys_bdelay != 0) { #ifdef AUTOKEY /* * If a two-way exchange is not possible, * neither is Autokey. */ if (crypto_flags && skeyid > NTP_MAXKEY) { sys_restricted++; return; /* no autokey */ } #endif /* AUTOKEY */ /* * Do not execute the volley. Start out in * broadcast client mode. */ peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep, MODE_BCLIENT, hisversion, pkt->ppoll, pkt->ppoll, FLAG_PREEMPT, MDF_BCLNT, 0, skeyid, sys_ident); if (NULL == peer) { sys_restricted++; return; /* ignore duplicate */ } else { peer->delay = sys_bdelay; peer->bxmt = p_xmt; } break; } /* * Execute the initial volley in order to calibrate the * propagation delay and run the Autokey protocol. * * Note that the minpoll is taken from the broadcast * packet, normally 6 (64 s) and that the poll interval * is fixed at this value. */ peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep, MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll, FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT, 0, skeyid, sys_ident); if (NULL == peer) { sys_restricted++; return; /* ignore duplicate */ } peer->bxmt = p_xmt; #ifdef AUTOKEY if (skeyid > NTP_MAXKEY) crypto_recv(peer, rbufp); #endif /* AUTOKEY */ return; /* hooray */ /* * This is the first packet received from a symmetric active * peer. If the packet is authentic and the first he sent, * mobilize a passive association. If not, kiss the frog. */ case AM_NEWPASS: #ifdef AUTOKEY /* * Do not respond if not the same group. */ if (group_test(groupname, sys_ident)) { sys_declined++; return; } #endif /* AUTOKEY */ if (!AUTH(sys_authenticate | (restrict_mask & (RES_NOPEER | RES_DONTTRUST)), is_authentic)) { /* * If authenticated but cannot mobilize an * association, send a symmetric passive * response without mobilizing an association. * This is for drat broken Windows clients. See * Microsoft KB 875424 for preferred workaround. */ if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic)) { fast_xmit(rbufp, MODE_PASSIVE, skeyid, restrict_mask); return; /* hooray */ } if (is_authentic == AUTH_ERROR) { fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask); sys_restricted++; return; } /* [Bug 2941] * If we got here, the packet isn't part of an * existing association, it isn't correctly * authenticated, and it didn't meet either of * the previous two special cases so we should * just drop it on the floor. For example, * crypto-NAKs (is_authentic == AUTH_CRYPTO) * will make it this far. This is just * debug-printed and not logged to avoid log * flooding. */ DPRINTF(2, ("receive: at %ld refusing to mobilize passive association" " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n", current_time, stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, skeyid, (authlen + has_mac), is_authentic)); sys_declined++; return; } /* * Do not respond if synchronized and if stratum is * below the floor or at or above the ceiling. Note, * this allows an unsynchronized peer to synchronize to * us. It would be very strange if he did and then was * nipped, but that could only happen if we were * operating at the top end of the range. It also means * we will spin an ephemeral association in response to * MODE_ACTIVE KoDs, which will time out eventually. */ if ( hisleap != LEAP_NOTINSYNC && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) { sys_declined++; return; /* no help */ } /* * The message is correctly authenticated and allowed. * Mobilize a symmetric passive association. */ if ((peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll, NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid, sys_ident)) == NULL) { sys_declined++; return; /* ignore duplicate */ } break; /* * Process regular packet. Nothing special. */ case AM_PROCPKT: #ifdef AUTOKEY /* * Do not respond if not the same group. */ if (group_test(groupname, peer->ident)) { sys_declined++; return; } #endif /* AUTOKEY */ if (MODE_BROADCAST == hismode) { u_char poll; int bail = 0; DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n", (current_time - peer->timelastrec), peer->ppoll, (1 << peer->ppoll) )); /* Things we can check: * * Did the poll interval change? * Is the poll interval in the packet in-range? * Did this packet arrive too soon? * Is the timestamp in this packet monotonic * with respect to the previous packet? */ /* This is noteworthy, not error-worthy */ if (pkt->ppoll != peer->ppoll) { msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %ud to %ud", stoa(&rbufp->recv_srcadr), peer->ppoll, pkt->ppoll); } poll = min(peer->maxpoll, max(peer->minpoll, pkt->ppoll)); /* This is error-worthy */ if (pkt->ppoll != poll) { msyslog(LOG_INFO, "receive: broadcast poll of %ud from %s is out-of-range (%d to %d)!", pkt->ppoll, stoa(&rbufp->recv_srcadr), peer->minpoll, peer->maxpoll); ++bail; } if ( (current_time - peer->timelastrec) < (1 << pkt->ppoll)) { msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %ld, not %d seconds!", stoa(&rbufp->recv_srcadr), (current_time - peer->timelastrec), (1 << pkt->ppoll) ); ++bail; } if (L_ISGT(&peer->bxmt, &p_xmt)) { msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x", stoa(&rbufp->recv_srcadr), peer->bxmt.l_ui, peer->bxmt.l_uf, p_xmt.l_ui, p_xmt.l_uf ); ++bail; } peer->bxmt = p_xmt; if (bail) { peer->timelastrec = current_time; sys_declined++; return; } } break; /* * A passive packet matches a passive association. This is * usually the result of reconfiguring a client on the fly. As * this association might be legitimate and this packet an * attempt to deny service, just ignore it. */ case AM_ERR: sys_declined++; return; /* * For everything else there is the bit bucket. */ default: sys_declined++; return; } #ifdef AUTOKEY /* * If the association is configured for Autokey, the packet must * have a public key ID; if not, the packet must have a * symmetric key ID. */ if ( is_authentic != AUTH_CRYPTO && ( ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY) || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) { sys_badauth++; return; } #endif /* AUTOKEY */ peer->received++; peer->flash &= ~PKT_TEST_MASK; if (peer->flags & FLAG_XBOGUS) { peer->flags &= ~FLAG_XBOGUS; peer->flash |= TEST3; } /* * Next comes a rigorous schedule of timestamp checking. If the * transmit timestamp is zero, the server has not initialized in * interleaved modes or is horribly broken. */ if (L_ISZERO(&p_xmt)) { peer->flash |= TEST3; /* unsynch */ /* * If the transmit timestamp duplicates a previous one, the * packet is a replay. This prevents the bad guys from replaying * the most recent packet, authenticated or not. */ } else if (L_ISEQU(&peer->xmt, &p_xmt)) { peer->flash |= TEST1; /* duplicate */ peer->oldpkt++; return; /* * If this is a broadcast mode packet, skip further checking. If * an initial volley, bail out now and let the client do its * stuff. If the origin timestamp is nonzero, this is an * interleaved broadcast. so restart the protocol. */ } else if (hismode == MODE_BROADCAST) { if (!L_ISZERO(&p_org) && !(peer->flags & FLAG_XB)) { peer->flags |= FLAG_XB; peer->aorg = p_xmt; peer->borg = rbufp->recv_time; report_event(PEVNT_XLEAVE, peer, NULL); return; } /* * Basic mode checks: * * If there is no origin timestamp, it's an initial packet. * * Otherwise, check for bogus packet in basic mode. * If it is bogus, switch to interleaved mode and resynchronize, * but only after confirming the packet is not bogus in * symmetric interleaved mode. * * This could also mean somebody is forging packets claiming to * be from us, attempting to cause our server to KoD us. */ } else if (peer->flip == 0) { if (0 < hisstratum && L_ISZERO(&p_org)) { L_CLR(&peer->aorg); } else if (!L_ISEQU(&p_org, &peer->aorg)) { peer->bogusorg++; peer->flash |= TEST2; /* bogus */ msyslog(LOG_INFO, "receive: Unexpected origin timestamp %#010x.%08x from %s xmt %#010x.%08x", ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), ntoa(&peer->srcadr), ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)); if ( !L_ISZERO(&peer->dst) && L_ISEQU(&p_org, &peer->dst)) { /* Might be the start of an interleave */ peer->flip = 1; report_event(PEVNT_XLEAVE, peer, NULL); } return; /* Bogus or possible interleave packet */ } else { L_CLR(&peer->aorg); } /* * Check for valid nonzero timestamp fields. */ } else if (L_ISZERO(&p_org) || L_ISZERO(&p_rec) || L_ISZERO(&peer->dst)) { peer->flash |= TEST3; /* unsynch */ /* * Check for bogus packet in interleaved symmetric mode. This * can happen if a packet is lost, duplicated or crossed. If * found, flip and resynchronize. */ } else if ( !L_ISZERO(&peer->dst) && !L_ISEQU(&p_org, &peer->dst)) { peer->bogusorg++; peer->flags |= FLAG_XBOGUS; peer->flash |= TEST2; /* bogus */ return; /* Bogus packet, we are done */ } /* * If this is a crypto_NAK, the server cannot authenticate a * client packet. The server might have just changed keys. Clear * the association and restart the protocol. */ if (is_authentic == AUTH_CRYPTO) { report_event(PEVNT_AUTH, peer, "crypto_NAK"); peer->flash |= TEST5; /* bad auth */ peer->badauth++; if (peer->flags & FLAG_PREEMPT) { unpeer(peer); return; } #ifdef AUTOKEY if (peer->crypto) peer_clear(peer, "AUTH"); #endif /* AUTOKEY */ return; /* * If the digest fails or it's missing for authenticated * associations, the client cannot authenticate a server * reply to a client packet previously sent. The loopback check * is designed to avoid a bait-and-switch attack, which was * possible in past versions. If symmetric modes, return a * crypto-NAK. The peer should restart the protocol. */ } else if (!AUTH(peer->keyid || has_mac || (restrict_mask & RES_DONTTRUST), is_authentic)) { report_event(PEVNT_AUTH, peer, "digest"); peer->flash |= TEST5; /* bad auth */ peer->badauth++; if ( has_mac && (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE)) fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask); if (peer->flags & FLAG_PREEMPT) { unpeer(peer); return; } #ifdef AUTOKEY if (peer->crypto) peer_clear(peer, "AUTH"); #endif /* AUTOKEY */ return; } /* * Update the state variables. */ if (peer->flip == 0) { if (hismode != MODE_BROADCAST) peer->rec = p_xmt; peer->dst = rbufp->recv_time; } peer->xmt = p_xmt; /* * Set the peer ppoll to the maximum of the packet ppoll and the * peer minpoll. If a kiss-o'-death, set the peer minpoll to * this maximum and advance the headway to give the sender some * headroom. Very intricate. */ /* * Check for any kiss codes. Note this is only used when a server * responds to a packet request */ kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid); /* * Check to see if this is a RATE Kiss Code * Currently this kiss code will accept whatever poll * rate that the server sends */ peer->ppoll = max(peer->minpoll, pkt->ppoll); if (kissCode == RATEKISS) { peer->selbroken++; /* Increment the KoD count */ report_event(PEVNT_RATE, peer, NULL); if (pkt->ppoll > peer->minpoll) peer->minpoll = peer->ppoll; peer->burst = peer->retry = 0; peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll); poll_update(peer, pkt->ppoll); return; /* kiss-o'-death */ } if (kissCode != NOKISS) { peer->selbroken++; /* Increment the KoD count */ return; /* Drop any other kiss code packets */ } /* * That was hard and I am sweaty, but the packet is squeaky * clean. Get on with real work. */ peer->timereceived = current_time; peer->timelastrec = current_time; if (is_authentic == AUTH_OK) peer->flags |= FLAG_AUTHENTIC; else peer->flags &= ~FLAG_AUTHENTIC; #ifdef AUTOKEY /* * More autokey dance. The rules of the cha-cha are as follows: * * 1. If there is no key or the key is not auto, do nothing. * * 2. If this packet is in response to the one just previously * sent or from a broadcast server, do the extension fields. * Otherwise, assume bogosity and bail out. * * 3. If an extension field contains a verified signature, it is * self-authenticated and we sit the dance. * * 4. If this is a server reply, check only to see that the * transmitted key ID matches the received key ID. * * 5. Check to see that one or more hashes of the current key ID * matches the previous key ID or ultimate original key ID * obtained from the broadcaster or symmetric peer. If no * match, sit the dance and call for new autokey values. * * In case of crypto error, fire the orchestra, stop dancing and * restart the protocol. */ if (peer->flags & FLAG_SKEY) { /* * Decrement remaining autokey hashes. This isn't * perfect if a packet is lost, but results in no harm. */ ap = (struct autokey *)peer->recval.ptr; if (ap != NULL) { if (ap->seq > 0) ap->seq--; } peer->flash |= TEST8; rval = crypto_recv(peer, rbufp); if (rval == XEVNT_OK) { peer->unreach = 0; } else { if (rval == XEVNT_ERR) { report_event(PEVNT_RESTART, peer, "crypto error"); peer_clear(peer, "CRYP"); peer->flash |= TEST9; /* bad crypt */ if (peer->flags & FLAG_PREEMPT) unpeer(peer); } return; } /* * If server mode, verify the receive key ID matches * the transmit key ID. */ if (hismode == MODE_SERVER) { if (skeyid == peer->keyid) peer->flash &= ~TEST8; /* * If an extension field is present, verify only that it * has been correctly signed. We don't need a sequence * check here, but the sequence continues. */ } else if (!(peer->flash & TEST8)) { peer->pkeyid = skeyid; /* * Now the fun part. Here, skeyid is the current ID in * the packet, pkeyid is the ID in the last packet and * tkeyid is the hash of skeyid. If the autokey values * have not been received, this is an automatic error. * If so, check that the tkeyid matches pkeyid. If not, * hash tkeyid and try again. If the number of hashes * exceeds the number remaining in the sequence, declare * a successful failure and refresh the autokey values. */ } else if (ap != NULL) { int i; for (i = 0; ; i++) { if ( tkeyid == peer->pkeyid || tkeyid == ap->key) { peer->flash &= ~TEST8; peer->pkeyid = skeyid; ap->seq -= i; break; } if (i > ap->seq) { peer->crypto &= ~CRYPTO_FLAG_AUTO; break; } tkeyid = session_key( &rbufp->recv_srcadr, dstadr_sin, tkeyid, pkeyid, 0); } if (peer->flash & TEST8) report_event(PEVNT_AUTH, peer, "keylist"); } if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */ peer->flash |= TEST8; /* bad autokey */ /* * The maximum lifetime of the protocol is about one * week before restarting the Autokey protocol to * refresh certificates and leapseconds values. */ if (current_time > peer->refresh) { report_event(PEVNT_RESTART, peer, "crypto refresh"); peer_clear(peer, "TIME"); return; } } #endif /* AUTOKEY */ /* * The dance is complete and the flash bits have been lit. Toss * the packet over the fence for processing, which may light up * more flashers. */ process_packet(peer, pkt, rbufp->recv_length); /* * In interleaved mode update the state variables. Also adjust the * transmit phase to avoid crossover. */ if (peer->flip != 0) { peer->rec = p_rec; peer->dst = rbufp->recv_time; if (peer->nextdate - current_time < (1U << min(peer->ppoll, peer->hpoll)) / 2) peer->nextdate++; else peer->nextdate--; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': '[Sec 2935] use L_SUB instead of L_ISGT. Juergen Perlinger'</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: fill_info_if_stats(void *data, interface_info_t *interface_info) { struct info_if_stats **ifsp = (struct info_if_stats **)data; struct info_if_stats *ifs = *ifsp; endpt *ep = interface_info->ep; ZERO(*ifs); if (IS_IPV6(&ep->sin)) { if (!client_v6_capable) { return; } ifs->v6_flag = 1; ifs->unaddr.addr6 = SOCK_ADDR6(&ep->sin); ifs->unbcast.addr6 = SOCK_ADDR6(&ep->bcast); ifs->unmask.addr6 = SOCK_ADDR6(&ep->mask); } else { ifs->v6_flag = 0; ifs->unaddr.addr = SOCK_ADDR4(&ep->sin); ifs->unbcast.addr = SOCK_ADDR4(&ep->bcast); ifs->unmask.addr = SOCK_ADDR4(&ep->mask); } ifs->v6_flag = htonl(ifs->v6_flag); strlcpy(ifs->name, ep->name, sizeof(ifs->name)); ifs->family = htons(ep->family); ifs->flags = htonl(ep->flags); ifs->last_ttl = htonl(ep->last_ttl); ifs->num_mcast = htonl(ep->num_mcast); ifs->received = htonl(ep->received); ifs->sent = htonl(ep->sent); ifs->notsent = htonl(ep->notsent); ifs->ifindex = htonl(ep->ifindex); /* scope no longer in endpt, in in6_addr typically */ ifs->scopeid = ifs->ifindex; ifs->ifnum = htonl(ep->ifnum); ifs->uptime = htonl(current_time - ep->starttime); ifs->ignore_packets = ep->ignore_packets; ifs->peercnt = htonl(ep->peercnt); ifs->action = interface_info->action; *ifsp = (struct info_if_stats *)more_pkt(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '[Bug 2939] reslist NULL pointer dereference [Bug 2940] Stack exhaustion in recursive traversal of restriction list -- these two where fixed together --'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': '[Sec 2942]: Off-path DoS attack on auth broadcast mode. HStenn.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check(str, sub, should) char *str; my_regmatch_t sub; char *should; { register int len; register int shlen; register char *p; static char grump[500]; register char *at = NULL; if (should != NULL && strcmp(should, "-") == 0) should = NULL; if (should != NULL && should[0] == '@') { at = should + 1; should = (char*) ""; } /* check rm_so and rm_eo for consistency */ if (sub.rm_so > sub.rm_eo || (sub.rm_so == -1 && sub.rm_eo != -1) || (sub.rm_so != -1 && sub.rm_eo == -1) || (sub.rm_so != -1 && sub.rm_so < 0) || (sub.rm_eo != -1 && sub.rm_eo < 0) ) { sprintf(grump, "start %ld end %ld", (long)sub.rm_so, (long)sub.rm_eo); return(grump); } /* check for no match */ if (sub.rm_so == -1 && should == NULL) return(NULL); if (sub.rm_so == -1) return((char*) "did not match"); /* check for in range */ if ((int) sub.rm_eo > (int) strlen(str)) { sprintf(grump, "start %ld end %ld, past end of string", (long)sub.rm_so, (long)sub.rm_eo); return(grump); } len = (int)(sub.rm_eo - sub.rm_so); shlen = (int)strlen(should); p = str + sub.rm_so; /* check for not supposed to match */ if (should == NULL) { sprintf(grump, "matched `%.*s'", len, p); return(grump); } /* check for wrong match */ if (len != shlen || strncmp(p, should, (size_t)shlen) != 0) { sprintf(grump, "matched `%.*s' instead", len, p); return(grump); } if (shlen > 0) return(NULL); /* check null match in right place */ if (at == NULL) return(NULL); shlen = strlen(at); if (shlen == 0) shlen = 1; /* force check for end-of-string */ if (strncmp(p, at, shlen) != 0) { sprintf(grump, "matched null at `%.20s'", p); return(grump); } return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Bug#21973610: BUFFER OVERFLOW ISSUES Description : Incorrect usage of sprintf/strcpy caused possible buffer overflow issues at various places. Solution : - Fixed mysql_plugin and mysqlshow - Fixed regex library issues Reviewed-By : Georgi Kodinov <georgi.kodinov@oracle.com> Reviewed-By : Venkata S Murthy Sidagam <venkata.sidagam@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: X509::X509(const char* i, size_t iSz, const char* s, size_t sSz, const char* b, int bSz, const char* a, int aSz) : issuer_(i, iSz), subject_(s, sSz), beforeDate_(b, bSz), afterDate_(a, aSz) {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': 'Bug #22738607: YASSL FUNCTION X509_NAME_GET_INDEX_BY_NID IS NOT WORKING AS EXPECTED.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes) { if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; while (bytes) { int copy = min(bytes, iov->iov_len - base); bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; base = 0; } } i->iov = iov; i->iov_offset = base; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <npiggin@suse.de> Signed-off-by: Ingo Molnar <mingo@elte.hu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, jas_seqent_t maxval) { int i; int j; jas_seqent_t v; jas_seqent_t *rowstart; jas_seqent_t *data; int rowstep; rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { data = rowstart; for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { v = *data; if (v < minval) { *data = minval; } else if (v > maxval) { *data = maxval; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Added fix for CVE-2016-2089.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_modify_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_modify_principal((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: setkey_principal3_2_svc(setkey3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->keyblocks, arg->n_keys); } else { log_unauth("kadm5_setkey_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setkey_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb) { int error = 0; struct cxio_rdev *rdev; rdev = (struct cxio_rdev *)tdev->ulp; if (cxio_fatal_error(rdev)) { kfree_skb(skb); return -EIO; } error = cxgb3_ofld_send(tdev, skb); if (error < 0) kfree_skb(skb); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'iw_cxgb3: Fix incorrectly returning error on success The cxgb3_*_send() functions return NET_XMIT_ values, which are positive integers values. So don't treat positive return values as an error. Signed-off-by: Steve Wise <swise@opengridcomputing.com> Signed-off-by: Hariprasad Shenai <hariprasad@chelsio.com> Signed-off-by: Doug Ledford <dledford@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 php_stream * php_stream_url_wrap_rfc2397(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *stream; php_stream_temp_data *ts; char *comma, *semi, *sep, *key; size_t mlen, dlen, plen, vlen; off_t newoffs; zval *meta = NULL; int base64 = 0, ilen; if (memcmp(path, "data:", 5)) { return NULL; } path += 5; dlen = strlen(path); if (dlen >= 2 && path[0] == '/' && path[1] == '/') { dlen -= 2; path += 2; } if ((comma = memchr(path, ',', dlen)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "rfc2397: no comma in URL"); return NULL; } if (comma != path) { /* meta info */ mlen = comma - path; dlen -= mlen; semi = memchr(path, ';', mlen); sep = memchr(path, '/', mlen); if (!semi && !sep) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "rfc2397: illegal media type"); return NULL; } MAKE_STD_ZVAL(meta); array_init(meta); if (!semi) { /* there is only a mime type */ add_assoc_stringl(meta, "mediatype", path, mlen, 1); mlen = 0; } else if (sep && sep < semi) { /* there is a mime type */ plen = semi - path; add_assoc_stringl(meta, "mediatype", path, plen, 1); mlen -= plen; path += plen; } else if (semi != path || mlen != sizeof(";base64")-1 || memcmp(path, ";base64", sizeof(";base64")-1)) { /* must be error since parameters are only allowed after mediatype */ zval_ptr_dtor(&meta); php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "rfc2397: illegal media type"); return NULL; } /* get parameters and potentially ';base64' */ while(semi && (semi == path)) { path++; mlen--; sep = memchr(path, '=', mlen); semi = memchr(path, ';', mlen); if (!sep || (semi && semi < sep)) { /* must be ';base64' or failure */ if (mlen != sizeof("base64")-1 || memcmp(path, "base64", sizeof("base64")-1)) { /* must be error since parameters are only allowed after mediatype and we have no '=' sign */ zval_ptr_dtor(&meta); php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "rfc2397: illegal parameter"); return NULL; } base64 = 1; mlen -= sizeof("base64") - 1; path += sizeof("base64") - 1; break; } /* found parameter ... the heart of cs ppl lies in +1/-1 or was it +2 this time? */ plen = sep - path; vlen = (semi ? semi - sep : mlen - plen) - 1 /* '=' */; key = estrndup(path, plen); add_assoc_stringl_ex(meta, key, plen + 1, sep + 1, vlen, 1); efree(key); plen += vlen + 1; mlen -= plen; path += plen; } if (mlen) { zval_ptr_dtor(&meta); php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "rfc2397: illegal URL"); return NULL; } } else { MAKE_STD_ZVAL(meta); array_init(meta); } add_assoc_bool(meta, "base64", base64); /* skip ',' */ comma++; dlen--; if (base64) { comma = (char*)php_base64_decode((const unsigned char *)comma, dlen, &ilen); if (!comma) { zval_ptr_dtor(&meta); php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "rfc2397: unable to decode"); return NULL; } } else { comma = estrndup(comma, dlen); ilen = dlen = php_url_decode(comma, dlen); } if ((stream = php_stream_temp_create_rel(0, ~0u)) != NULL) { /* store data */ php_stream_temp_write(stream, comma, ilen TSRMLS_CC); php_stream_temp_seek(stream, 0, SEEK_SET, &newoffs TSRMLS_CC); /* set special stream stuff (enforce exact mode) */ vlen = strlen(mode); if (vlen >= sizeof(stream->mode)) { vlen = sizeof(stream->mode) - 1; } memcpy(stream->mode, mode, vlen); stream->mode[vlen] = '\0'; stream->ops = &php_stream_rfc2397_ops; ts = (php_stream_temp_data*)stream->abstract; assert(ts != NULL); ts->mode = mode && mode[0] == 'r' && mode[1] != '+' ? TEMP_STREAM_READONLY : 0; ts->meta = meta; } efree(comma); return stream; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #71323 - Output of stream_get_meta_data can be falsified by its input'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'mm: migrate dirty page without clear_page_dirty_for_io etc clear_page_dirty_for_io() has accumulated writeback and memcg subtleties since v2.6.16 first introduced page migration; and the set_page_dirty() which completed its migration of PageDirty, later had to be moderated to __set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too. No actual problems seen with this procedure recently, but if you look into what the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually achieving, it turns out to be nothing more than moving the PageDirty flag, and its NR_FILE_DIRTY stat from one zone to another. It would be good to avoid a pile of irrelevant decrementations and incrementations, and improper event counting, and unnecessary descent of the radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which radix_tree_replace_slot() left in place anyway). Do the NR_FILE_DIRTY movement, like the other stats movements, while interrupts still disabled in migrate_page_move_mapping(); and don't even bother if the zone is the same. Do the PageDirty movement there under tree_lock too, where old page is frozen and newpage not yet visible: bearing in mind that as soon as newpage becomes visible in radix_tree, an un-page-locked set_page_dirty() might interfere (or perhaps that's just not possible: anything doing so should already hold an additional reference to the old page, preventing its migration; but play safe). But we do still need to transfer PageDirty in migrate_page_copy(), for those who don't go the mapping route through migrate_page_move_mapping(). Signed-off-by: Hugh Dickins <hughd@google.com> Cc: Christoph Lameter <cl@linux.com> Cc: "Kirill A. Shutemov" <kirill.shutemov@linux.intel.com> Cc: Rik van Riel <riel@redhat.com> Cc: Vlastimil Babka <vbabka@suse.cz> Cc: Davidlohr Bueso <dave@stgolabs.net> Cc: Oleg Nesterov <oleg@redhat.com> Cc: Sasha Levin <sasha.levin@oracle.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb) { int i; scm->fp = UNIXCB(skb).fp; UNIXCB(skb).fp = NULL; for (i = scm->fp->count-1; i >= 0; i--) unix_notinflight(scm->fp->fp[i]); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'unix: correctly track in-flight fds in sending process user_struct The commit referenced in the Fixes tag incorrectly accounted the number of in-flight fds over a unix domain socket to the original opener of the file-descriptor. This allows another process to arbitrary deplete the original file-openers resource limit for the maximum of open files. Instead the sending processes and its struct cred should be credited. To do so, we add a reference counted struct user_struct pointer to the scm_fp_list and use it to account for the number of inflight unix fds. Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets") Reported-by: David Herrmann <dh.herrmann@gmail.com> Cc: David Herrmann <dh.herrmann@gmail.com> Cc: Willy Tarreau <w@1wt.eu> Cc: Linus Torvalds <torvalds@linux-foundation.org> Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> 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 snd_timer_check_master(struct snd_timer_instance *master) { struct snd_timer_instance *slave, *tmp; /* check all pending slaves */ list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) { if (slave->slave_class == master->slave_class && slave->slave_id == master->slave_id) { list_move_tail(&slave->open_list, &master->slave_list_head); spin_lock_irq(&slave_active_lock); slave->master = master; slave->timer = master->timer; if (slave->flags & SNDRV_TIMER_IFLG_RUNNING) list_add_tail(&slave->active_list, &master->slave_active_head); spin_unlock_irq(&slave_active_lock); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-200', 'CWE-362'], 'message': 'ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <dvyukov@google.com> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL); if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = PIPE_DEF_BUFFERS; mutex_init(&pipe->mutex); return pipe; } kfree(pipe); } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'pipe: limit the per-user amount of pages allocated in pipes On no-so-small systems, it is possible for a single process to cause an OOM condition by filling large pipes with data that are never read. A typical process filling 4000 pipes with 1 MB of data will use 4 GB of memory. On small systems it may be tricky to set the pipe max size to prevent this from happening. This patch makes it possible to enforce a per-user soft limit above which new pipes will be limited to a single page, effectively limiting them to 4 kB each, as well as a hard limit above which no new pipes may be created for this user. This has the effect of protecting the system against memory abuse without hurting other users, and still allowing pipes to work correctly though with less data at once. The limit are controlled by two new sysctls : pipe-user-pages-soft, and pipe-user-pages-hard. Both may be disabled by setting them to zero. The default soft limit allows the default number of FDs per process (1024) to create pipes of the default size (64kB), thus reaching a limit of 64MB before starting to create only smaller pipes. With 256 processes limited to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB = 1084 MB of memory allocated for a user. The hard limit is disabled by default to avoid breaking existing applications that make intensive use of pipes (eg: for splicing). Reported-by: socketpair@gmail.com Reported-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Willy Tarreau <w@1wt.eu> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void rng_egd_request_entropy(RngBackend *b, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngEgd *s = RNG_EGD(b); RngRequest *req; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); while (size > 0) { uint8_t header[2]; uint8_t len = MIN(size, 255); /* synchronous entropy request */ header[0] = 0x02; header[1] = len; qemu_chr_fe_write(s->chr, header, sizeof(header)); size -= len; } s->parent.requests = g_slist_append(s->parent.requests, req); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'rng: add request queue support to rng-random Requests are now created in the RngBackend parent class and the code path is shared by both rng-egd and rng-random. This commit fixes the rng-random implementation which processed only one request at a time and simply discarded all but the most recent one. In the guest this manifested as delayed completion of reads from virtio-rng, i.e. a read was completed only after another read was issued. By switching rng-random to use the same request queue as rng-egd, the unsafe stack-based allocation of the entropy buffer is eliminated and replaced with g_malloc. Signed-off-by: Ladi Prosek <lprosek@redhat.com> Reviewed-by: Amit Shah <amit.shah@redhat.com> Message-Id: <1456994238-9585-5-git-send-email-lprosek@redhat.com> Signed-off-by: Amit Shah <amit.shah@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_XML_API zend_string *xml_utf8_encode(const char *s, size_t len, const XML_Char *encoding) { size_t pos = len; zend_string *str; unsigned int c; unsigned short (*encoder)(unsigned char) = NULL; xml_encoding *enc = xml_get_encoding(encoding); if (enc) { encoder = enc->encoding_function; } else { /* If the target encoding was unknown, fail */ return NULL; } if (encoder == NULL) { /* If no encoder function was specified, return the data as-is. */ str = zend_string_init(s, len, 0); return str; } /* This is the theoretical max (will never get beyond len * 2 as long * as we are converting from single-byte characters, though) */ str = zend_string_alloc(len * 4, 0); ZSTR_LEN(str) = 0; while (pos > 0) { c = encoder ? encoder((unsigned char)(*s)) : (unsigned short)(*s); if (c < 0x80) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (char) c; } else if (c < 0x800) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | (c >> 6)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f)); } else if (c < 0x10000) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xe0 | (c >> 12)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | ((c >> 6) & 0x3f)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f)); } else if (c < 0x200000) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xf0 | (c >> 18)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xe0 | ((c >> 12) & 0x3f)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | ((c >> 6) & 0x3f)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f)); } pos--; s++; } ZSTR_VAL(str)[ZSTR_LEN(str)] = '\0'; str = zend_string_truncate(str, ZSTR_LEN(str), 0); return str; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #71637: Multiple Heap Overflow due to integer overflows'</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 do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'netfilter: x_tables: introduce and use xt_copy_counters_from_user The three variants use same copy&pasted code, condense this into a helper and use that. Make sure info.name is 0-terminated. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim) { struct in_device *in_dev = ifa->ifa_dev; struct net_device *dev = in_dev->dev; struct in_ifaddr *ifa1; struct in_ifaddr *prim = ifa, *prim1 = NULL; __be32 brd = ifa->ifa_address | ~ifa->ifa_mask; __be32 any = ifa->ifa_address & ifa->ifa_mask; #define LOCAL_OK 1 #define BRD_OK 2 #define BRD0_OK 4 #define BRD1_OK 8 unsigned int ok = 0; int subnet = 0; /* Primary network */ int gone = 1; /* Address is missing */ int same_prefsrc = 0; /* Another primary with same IP */ if (ifa->ifa_flags & IFA_F_SECONDARY) { prim = inet_ifa_byprefix(in_dev, any, ifa->ifa_mask); if (!prim) { pr_warn("%s: bug: prim == NULL\n", __func__); return; } if (iprim && iprim != prim) { pr_warn("%s: bug: iprim != prim\n", __func__); return; } } else if (!ipv4_is_zeronet(any) && (any != ifa->ifa_local || ifa->ifa_prefixlen < 32)) { if (!(ifa->ifa_flags & IFA_F_NOPREFIXROUTE)) fib_magic(RTM_DELROUTE, dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST, any, ifa->ifa_prefixlen, prim); subnet = 1; } /* Deletion is more complicated than add. * We should take care of not to delete too much :-) * * Scan address list to be sure that addresses are really gone. */ for (ifa1 = in_dev->ifa_list; ifa1; ifa1 = ifa1->ifa_next) { if (ifa1 == ifa) { /* promotion, keep the IP */ gone = 0; continue; } /* Ignore IFAs from our subnet */ if (iprim && ifa1->ifa_mask == iprim->ifa_mask && inet_ifa_match(ifa1->ifa_address, iprim)) continue; /* Ignore ifa1 if it uses different primary IP (prefsrc) */ if (ifa1->ifa_flags & IFA_F_SECONDARY) { /* Another address from our subnet? */ if (ifa1->ifa_mask == prim->ifa_mask && inet_ifa_match(ifa1->ifa_address, prim)) prim1 = prim; else { /* We reached the secondaries, so * same_prefsrc should be determined. */ if (!same_prefsrc) continue; /* Search new prim1 if ifa1 is not * using the current prim1 */ if (!prim1 || ifa1->ifa_mask != prim1->ifa_mask || !inet_ifa_match(ifa1->ifa_address, prim1)) prim1 = inet_ifa_byprefix(in_dev, ifa1->ifa_address, ifa1->ifa_mask); if (!prim1) continue; if (prim1->ifa_local != prim->ifa_local) continue; } } else { if (prim->ifa_local != ifa1->ifa_local) continue; prim1 = ifa1; if (prim != prim1) same_prefsrc = 1; } if (ifa->ifa_local == ifa1->ifa_local) ok |= LOCAL_OK; if (ifa->ifa_broadcast == ifa1->ifa_broadcast) ok |= BRD_OK; if (brd == ifa1->ifa_broadcast) ok |= BRD1_OK; if (any == ifa1->ifa_broadcast) ok |= BRD0_OK; /* primary has network specific broadcasts */ if (prim1 == ifa1 && ifa1->ifa_prefixlen < 31) { __be32 brd1 = ifa1->ifa_address | ~ifa1->ifa_mask; __be32 any1 = ifa1->ifa_address & ifa1->ifa_mask; if (!ipv4_is_zeronet(any1)) { if (ifa->ifa_broadcast == brd1 || ifa->ifa_broadcast == any1) ok |= BRD_OK; if (brd == brd1 || brd == any1) ok |= BRD1_OK; if (any == brd1 || any == any1) ok |= BRD0_OK; } } } if (!(ok & BRD_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim); if (subnet && ifa->ifa_prefixlen < 31) { if (!(ok & BRD1_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, brd, 32, prim); if (!(ok & BRD0_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, any, 32, prim); } if (!(ok & LOCAL_OK)) { unsigned int addr_type; fib_magic(RTM_DELROUTE, RTN_LOCAL, ifa->ifa_local, 32, prim); /* Check, that this local address finally disappeared. */ addr_type = inet_addr_type_dev_table(dev_net(dev), dev, ifa->ifa_local); if (gone && addr_type != RTN_LOCAL) { /* And the last, but not the least thing. * We must flush stray FIB entries. * * First of all, we scan fib_info list searching * for stray nexthop entries, then ignite fib_flush. */ if (fib_sync_down_addr(dev_net(dev), ifa->ifa_local)) fib_flush(dev_net(dev)); } } #undef LOCAL_OK #undef BRD_OK #undef BRD0_OK #undef BRD1_OK } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <solar@openwall.com> Signed-off-by: David S. Miller <davem@davemloft.net> Tested-by: Cyrill Gorcunov <gorcunov@openvz.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbfl_identify_encoding(mbfl_string *string, enum mbfl_no_encoding *elist, int elistsz, int strict) { int i, n, num, bad; unsigned char *p; mbfl_identify_filter *flist, *filter; const mbfl_encoding *encoding; /* flist is an array of mbfl_identify_filter instances */ flist = (mbfl_identify_filter *)mbfl_calloc(elistsz, sizeof(mbfl_identify_filter)); if (flist == NULL) { return NULL; } num = 0; if (elist != NULL) { for (i = 0; i < elistsz; i++) { if (!mbfl_identify_filter_init(&flist[num], elist[i])) { num++; } } } /* feed data */ n = string->len; p = string->val; if (p != NULL) { bad = 0; while (n > 0) { for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag) { (*filter->filter_function)(*p, filter); if (filter->flag) { bad++; } } } if ((num - 1) <= bad && !strict) { break; } p++; n--; } } /* judge */ encoding = NULL; for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag) { if (strict && filter->status) { continue; } encoding = filter->encoding; break; } } /* fall-back judge */ if (!encoding) { for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag && (!strict || !filter->status)) { encoding = filter->encoding; break; } } } /* cleanup */ /* dtors should be called in reverse order */ i = num; while (--i >= 0) { mbfl_identify_filter_cleanup(&flist[i]); } mbfl_free((void *)flist); return encoding; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } truncate_pagecache(inode, ioffset); /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_dio; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset, ext4_lblk_t len, loff_t new_size, int flags, int mode) { struct inode *inode = file_inode(file); handle_t *handle; int ret = 0; int ret2 = 0; int retries = 0; int depth = 0; struct ext4_map_blocks map; unsigned int credits; loff_t epos; map.m_lblk = offset; map.m_len = len; /* * Don't normalize the request if it can fit in one extent so * that it doesn't get unnecessarily split into multiple * extents. */ if (len <= EXT_UNWRITTEN_MAX_LEN) flags |= EXT4_GET_BLOCKS_NO_NORMALIZE; /* Wait all existing dio workers, newcomers will block on i_mutex */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * credits to insert 1 extent into extent tree */ credits = ext4_chunk_trans_blocks(inode, len); /* * We can only call ext_depth() on extent based inodes */ if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) depth = ext_depth(inode); else depth = -1; retry: while (ret >= 0 && len) { /* * Recalculate credits when extent tree depth changes. */ if (depth >= 0 && depth != ext_depth(inode)) { credits = ext4_chunk_trans_blocks(inode, len); depth = ext_depth(inode); } handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); break; } ret = ext4_map_blocks(handle, inode, &map, flags); if (ret <= 0) { ext4_debug("inode #%lu: block %u: len %u: " "ext4_ext_map_blocks returned %d", inode->i_ino, map.m_lblk, map.m_len, ret); ext4_mark_inode_dirty(handle, inode); ret2 = ext4_journal_stop(handle); break; } map.m_lblk += ret; map.m_len = len = len - ret; epos = (loff_t)map.m_lblk << inode->i_blkbits; inode->i_ctime = ext4_current_time(inode); if (new_size) { if (epos > new_size) epos = new_size; if (ext4_update_inode_size(inode, epos) & 0x1) inode->i_mtime = inode->i_ctime; } else { if (epos > inode->i_size) ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS); } ext4_mark_inode_dirty(handle, inode); ret2 = ext4_journal_stop(handle); if (ret2) break; } if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) { ret = 0; goto retry; } ext4_inode_resume_unlocked_dio(inode); return ret > 0 ? ret2 : ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: move unlocked dio protection from ext4_alloc_file_blocks() Currently ext4_alloc_file_blocks() was handling protection against unlocked DIO. However we now need to sometimes call it under i_mmap_sem and sometimes not and DIO protection ranks above it (although strictly speaking this cannot currently create any deadlocks). Also ext4_zero_range() was actually getting & releasing unlocked DIO protection twice in some cases. Luckily it didn't introduce any real bug but it was a land mine waiting to be stepped on. So move DIO protection out from ext4_alloc_file_blocks() into the two callsites. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: srtp_protect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, void *rtp_hdr, unsigned int *pkt_octet_len) { srtp_hdr_t *hdr = (srtp_hdr_t*)rtp_hdr; uint32_t *enc_start; /* pointer to start of encrypted portion */ unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */ xtd_seq_num_t est; /* estimated xtd_seq_num_t of *hdr */ int delta; /* delta of local pkt idx and that in hdr */ err_status_t status; int tag_len; v128_t iv; unsigned int aad_len; debug_print(mod_srtp, "function srtp_protect_aead", NULL); /* * update the key usage limit, and check it to make sure that we * didn't just hit either the soft limit or the hard limit, and call * the event handler if we hit either. */ switch (key_limit_update(stream->limit)) { case key_event_normal: break; case key_event_hard_limit: srtp_handle_event(ctx, stream, event_key_hard_limit); return err_status_key_expired; case key_event_soft_limit: default: srtp_handle_event(ctx, stream, event_key_soft_limit); break; } /* get tag length from stream */ tag_len = auth_get_tag_length(stream->rtp_auth); /* * find starting point for encryption and length of data to be * encrypted - the encrypted portion starts after the rtp header * extension, if present; otherwise, it starts after the last csrc, * if any are present */ enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc; if (hdr->x == 1) { srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t*)enc_start; enc_start += (ntohs(xtn_hdr->length) + 1); } if (!((uint8_t*)enc_start < (uint8_t*)hdr + (*pkt_octet_len - tag_len))) return err_status_parse_err; enc_octet_len = (unsigned int)(*pkt_octet_len - ((uint8_t*)enc_start - (uint8_t*)hdr)); /* * estimate the packet index using the start of the replay window * and the sequence number from the header */ delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq)); status = rdbx_check(&stream->rtp_rdbx, delta); if (status) { if (status != err_status_replay_fail || !stream->allow_repeat_tx) { return status; /* we've been asked to reuse an index */ } } else { rdbx_add_index(&stream->rtp_rdbx, delta); } #ifdef NO_64BIT_MATH debug_print2(mod_srtp, "estimated packet index: %08x%08x", high32(est), low32(est)); #else debug_print(mod_srtp, "estimated packet index: %016llx", est); #endif /* * AEAD uses a new IV formation method */ srtp_calc_aead_iv(stream, &iv, &est, hdr); status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt); if (status) { return err_status_cipher_fail; } /* shift est, put into network byte order */ #ifdef NO_64BIT_MATH est = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16), low32(est) << 16)); #else est = be64_to_cpu(est << 16); #endif /* * Set the AAD over the RTP header */ aad_len = (uint8_t *)enc_start - (uint8_t *)hdr; status = cipher_set_aad(stream->rtp_cipher, (uint8_t*)hdr, aad_len); if (status) { return ( err_status_cipher_fail); } /* Encrypt the payload */ status = cipher_encrypt(stream->rtp_cipher, (uint8_t*)enc_start, &enc_octet_len); if (status) { return err_status_cipher_fail; } /* * If we're doing GCM, we need to get the tag * and append that to the output */ status = cipher_get_tag(stream->rtp_cipher, (uint8_t*)enc_start+enc_octet_len, &tag_len); if (status) { return ( err_status_cipher_fail); } enc_octet_len += tag_len; /* increase the packet length by the length of the auth tag */ *pkt_octet_len += tag_len; return err_status_ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Apply a7216c19582827cdbd5cacce5618db0b6be8d851 to 1.5.x throttle'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long restore_tm_user_regs(struct pt_regs *regs, struct mcontext __user *sr, struct mcontext __user *tm_sr) { long err; unsigned long msr, msr_hi; #ifdef CONFIG_VSX int i; #endif /* * restore general registers but not including MSR or SOFTE. Also * take care of keeping r2 (TLS) intact if not a signal. * See comment in signal_64.c:restore_tm_sigcontexts(); * TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR * were set by the signal delivery. */ err = restore_general_regs(regs, tm_sr); err |= restore_general_regs(&current->thread.ckpt_regs, sr); err |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]); err |= __get_user(msr, &sr->mc_gregs[PT_MSR]); if (err) return 1; /* Restore the previous little-endian mode */ regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE); /* * Do this before updating the thread state in * current->thread.fpr/vr/evr. That way, if we get preempted * and another task grabs the FPU/Altivec/SPE, it won't be * tempted to save the current CPU state into the thread_struct * and corrupt what we are writing there. */ discard_lazy_cpu_state(); #ifdef CONFIG_ALTIVEC regs->msr &= ~MSR_VEC; if (msr & MSR_VEC) { /* restore altivec registers from the stack */ if (__copy_from_user(&current->thread.vr_state, &sr->mc_vregs, sizeof(sr->mc_vregs)) || __copy_from_user(&current->thread.transact_vr, &tm_sr->mc_vregs, sizeof(sr->mc_vregs))) return 1; } else if (current->thread.used_vr) { memset(&current->thread.vr_state, 0, ELF_NVRREG * sizeof(vector128)); memset(&current->thread.transact_vr, 0, ELF_NVRREG * sizeof(vector128)); } /* Always get VRSAVE back */ if (__get_user(current->thread.vrsave, (u32 __user *)&sr->mc_vregs[32]) || __get_user(current->thread.transact_vrsave, (u32 __user *)&tm_sr->mc_vregs[32])) return 1; if (cpu_has_feature(CPU_FTR_ALTIVEC)) mtspr(SPRN_VRSAVE, current->thread.vrsave); #endif /* CONFIG_ALTIVEC */ regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1); if (copy_fpr_from_user(current, &sr->mc_fregs) || copy_transact_fpr_from_user(current, &tm_sr->mc_fregs)) return 1; #ifdef CONFIG_VSX regs->msr &= ~MSR_VSX; if (msr & MSR_VSX) { /* * Restore altivec registers from the stack to a local * buffer, then write this out to the thread_struct */ if (copy_vsx_from_user(current, &sr->mc_vsregs) || copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs)) return 1; } else if (current->thread.used_vsr) for (i = 0; i < 32 ; i++) { current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0; current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0; } #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE /* SPE regs are not checkpointed with TM, so this section is * simply the same as in restore_user_regs(). */ regs->msr &= ~MSR_SPE; if (msr & MSR_SPE) { if (__copy_from_user(current->thread.evr, &sr->mc_vregs, ELF_NEVRREG * sizeof(u32))) return 1; } else if (current->thread.used_spe) memset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32)); /* Always get SPEFSCR back */ if (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs + ELF_NEVRREG)) return 1; #endif /* CONFIG_SPE */ /* Now, recheckpoint. This loads up all of the checkpointed (older) * registers, including FP and V[S]Rs. After recheckpointing, the * transactional versions should be loaded. */ tm_enable(); /* Make sure the transaction is marked as failed */ current->thread.tm_texasr |= TEXASR_FS; /* This loads the checkpointed FP/VEC state, if used */ tm_recheckpoint(&current->thread, msr); /* Get the top half of the MSR */ if (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR])) return 1; /* Pull in MSR TM from user context */ regs->msr = (regs->msr & ~MSR_TS_MASK) | ((msr_hi<<32) & MSR_TS_MASK); /* This loads the speculative FP/VEC state, if used */ if (msr & MSR_FP) { do_load_up_transact_fpu(&current->thread); regs->msr |= (MSR_FP | current->thread.fpexc_mode); } #ifdef CONFIG_ALTIVEC if (msr & MSR_VEC) { do_load_up_transact_altivec(&current->thread); regs->msr |= MSR_VEC; } #endif return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-284', 'CWE-369'], 'message': 'powerpc/tm: Block signal return setting invalid MSR state Currently we allow both the MSR T and S bits to be set by userspace on a signal return. Unfortunately this is a reserved configuration and will cause a TM Bad Thing exception if attempted (via rfid). This patch checks for this case in both the 32 and 64 bit signals code. If both T and S are set, we mark the context as invalid. Found using a syscall fuzzer. Fixes: 2b0a576d15e0 ("powerpc: Add new transactional memory state to the signal context") Cc: stable@vger.kernel.org # v3.9+ Signed-off-by: Michael Neuling <mikey@neuling.org> Signed-off-by: Michael Ellerman <mpe@ellerman.id.au>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: http_splitline(struct worker *w, int fd, struct http *hp, const struct http_conn *htc, int h1, int h2, int h3) { char *p, *q; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); /* XXX: Assert a NUL at rx.e ? */ Tcheck(htc->rxbuf); /* Skip leading LWS */ for (p = htc->rxbuf.b ; vct_islws(*p); p++) continue; /* First field cannot contain SP, CRLF or CTL */ q = p; for (; !vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h1].b = q; hp->hd[h1].e = p; /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Second field cannot contain LWS or CTL */ q = p; for (; !vct_islws(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h2].b = q; hp->hd[h2].e = p; if (!Tlen(hp->hd[h2])) return (400); /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Third field is optional and cannot contain CTL */ q = p; if (!vct_iscrlf(*p)) { for (; !vct_iscrlf(*p); p++) if (!vct_issep(*p) && vct_isctl(*p)) return (400); } hp->hd[h3].b = q; hp->hd[h3].e = p; /* Skip CRLF */ p += vct_skipcrlf(p); *hp->hd[h1].e = '\0'; WSLH(w, fd, hp, h1); *hp->hd[h2].e = '\0'; WSLH(w, fd, hp, h2); if (hp->hd[h3].e != NULL) { *hp->hd[h3].e = '\0'; WSLH(w, fd, hp, h3); } return (http_dissect_hdrs(w, hp, fd, p, htc)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] regis.leroy@makina-corpus.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(openssl_random_pseudo_bytes) { long buffer_length; unsigned char *buffer = NULL; zval *zstrong_result_returned = NULL; int strong_result = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) { return; } if (buffer_length <= 0) { RETURN_FALSE; } if (zstrong_result_returned) { zval_dtor(zstrong_result_returned); ZVAL_BOOL(zstrong_result_returned, 0); } buffer = emalloc(buffer_length + 1); #ifdef PHP_WIN32 strong_result = 1; /* random/urandom equivalent on Windows */ if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) { efree(buffer); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); } RETURN_FALSE; } #else if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) { efree(buffer); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); } RETURN_FALSE; } #endif buffer[buffer_length] = 0; RETVAL_STRINGL((char *)buffer, buffer_length, 0); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, strong_result); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix bug #70014 - use RAND_bytes instead of deprecated RAND_pseudo_bytes'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(bcdiv) { char *left, *right; int left_len, right_len; long scale_param = 0; bc_num first, second, result; int scale = BCG(bc_precision), argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "ss|l", &left, &left_len, &right, &right_len, &scale_param) == FAILURE) { return; } if (argc == 3) { scale = (int) ((int)scale_param < 0) ? 0 : scale_param; } bc_init_num(&first TSRMLS_CC); bc_init_num(&second TSRMLS_CC); bc_init_num(&result TSRMLS_CC); php_str2num(&first, left TSRMLS_CC); php_str2num(&second, right TSRMLS_CC); switch (bc_divide(first, second, &result, scale TSRMLS_CC)) { case 0: /* OK */ if (result->n_scale > scale) { result->n_scale = scale; } Z_STRVAL_P(return_value) = bc_num2str(result); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; break; case -1: /* division by zero */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Division by zero"); break; } bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition We can not modify result since it can be copy of _zero_ or _one_, etc. and "copy" in bcmath is just bumping the refcount. Conflicts: main/php_version.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC) { unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker"); return; } /* Check the next two values for correctness. */ exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } if (offset_of_ifd > length) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid IFD start"); return; } ImageInfo->sections_found |= FOUND_IFD0; /* First directory starts at offset 8. Offsets starts at 0. */ exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, length/*-14*/, displacement, SECTION_IFD0 TSRMLS_CC); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process TIFF in JPEG done"); #endif /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72094 - Out of bounds heap read access in exif header processing'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(xml_parser_create) { php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) return -EMSGSIZE; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'net: fix infoleak in rtnetlink The stack object “map” has a total size of 32 bytes. Its last 4 bytes are padding generated by compiler. These padding bytes are not initialized and sent out via “nla_put”. Signed-off-by: Kangjie Lu <kjlu@gatech.edu> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct bpf_map *bpf_map_get_with_uref(u32 ufd) { struct fd f = fdget(ufd); struct bpf_map *map; map = __bpf_map_get(f); if (IS_ERR(map)) return map; bpf_map_inc(map, true); fdput(f); return map; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Alexei Starovoitov <ast@kernel.org> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit = -1, rightLimit; int i, restoreAlphaBlending = 0; if (border < 0) { /* Refuse to fill to a non-solid border */ return; } restoreAlphaBlending = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } if (y >= im->sy) { y = im->sy - 1; } for (i = x; i >= 0; i--) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); leftLimit = i; } if (leftLimit == -1) { im->alphaBlendingFlag = restoreAlphaBlending; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); i < im->sx; i++) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBlending; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix #66387: Stack overflow with imagefilltoborder The stack overflow is caused by the recursive algorithm in combination with a very large negative coordinate passed to gdImageFillToBorder(). As there is already a clipping for large positive coordinates to the width and height of the image, it seems to be consequent to clip to zero also.'</s>