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 ssl2_generate_key_material(SSL *s)
{
unsigned int i;
EVP_MD_CTX ctx;
unsigned char *km;
unsigned char c = '0';
const EVP_MD *md5;
int md_size;
md5 = EVP_md5();
# ifdef CHARSET_EBCDIC
c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see
* SSLv2 docu */
# endif
EVP_MD_CTX_init(&ctx);
km = s->s2->key_material;
if (s->session->master_key_length < 0 ||
s->session->master_key_length > (int)sizeof(s->session->master_key)) {
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
md_size = EVP_MD_size(md5);
if (md_size < 0)
return 0;
for (i = 0; i < s->s2->key_material_length; i += md_size) {
if (((km - s->s2->key_material) + md_size) >
(int)sizeof(s->s2->key_material)) {
/*
* EVP_DigestFinal_ex() below would write beyond buffer
*/
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
EVP_DigestInit_ex(&ctx, md5, NULL);
OPENSSL_assert(s->session->master_key_length >= 0
&& s->session->master_key_length
< (int)sizeof(s->session->master_key));
EVP_DigestUpdate(&ctx, s->session->master_key,
s->session->master_key_length);
EVP_DigestUpdate(&ctx, &c, 1);
c++;
EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length);
EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length);
EVP_DigestFinal_ex(&ctx, km, NULL);
km += md_size;
}
EVP_MD_CTX_cleanup(&ctx);
return 1;
}
Commit Message:
CWE ID: CWE-20 | int ssl2_generate_key_material(SSL *s)
{
unsigned int i;
EVP_MD_CTX ctx;
unsigned char *km;
unsigned char c = '0';
const EVP_MD *md5;
int md_size;
md5 = EVP_md5();
# ifdef CHARSET_EBCDIC
c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see
* SSLv2 docu */
# endif
EVP_MD_CTX_init(&ctx);
km = s->s2->key_material;
if (s->session->master_key_length < 0 ||
s->session->master_key_length > (int)sizeof(s->session->master_key)) {
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
md_size = EVP_MD_size(md5);
if (md_size < 0)
return 0;
for (i = 0; i < s->s2->key_material_length; i += md_size) {
if (((km - s->s2->key_material) + md_size) >
(int)sizeof(s->s2->key_material)) {
/*
* EVP_DigestFinal_ex() below would write beyond buffer
*/
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
EVP_DigestInit_ex(&ctx, md5, NULL);
OPENSSL_assert(s->session->master_key_length >= 0
&& s->session->master_key_length
<= (int)sizeof(s->session->master_key));
EVP_DigestUpdate(&ctx, s->session->master_key,
s->session->master_key_length);
EVP_DigestUpdate(&ctx, &c, 1);
c++;
EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length);
EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length);
EVP_DigestFinal_ex(&ctx, km, NULL);
km += md_size;
}
EVP_MD_CTX_cleanup(&ctx);
return 1;
}
| 164,801 |
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_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;
}
Commit Message: ccpp: stop reading hs_error.log from /tmp
The file might contain anything and there is no way to verify its
contents.
Related: #1211835
Signed-off-by: Jakub Filak <[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;
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);
}
/* Because of #1211835 and #1126850 */
#if 0
/* 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);
}
}
#endif
/* 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;
}
| 168,886 |
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 btif_hl_select_wakeup(void){
char sig_on = btif_hl_signal_select_wakeup;
BTIF_TRACE_DEBUG("btif_hl_select_wakeup");
return send(signal_fds[1], &sig_on, sizeof(sig_on), 0);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static inline int btif_hl_select_wakeup(void){
char sig_on = btif_hl_signal_select_wakeup;
BTIF_TRACE_DEBUG("btif_hl_select_wakeup");
return TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0));
}
| 173,444 |
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: local unsigned long crc32_big(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
register z_crc_t c;
register const z_crc_t FAR *buf4;
c = ZSWAP32((z_crc_t)crc);
c = ~c;
while (len && ((ptrdiff_t)buf & 3)) {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
len--;
}
buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
buf4--;
while (len >= 32) {
DOBIG32;
len -= 32;
}
while (len >= 4) {
DOBIG4;
len -= 4;
}
buf4++;
buf = (const unsigned char FAR *)buf4;
if (len) do {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
} while (--len);
c = ~c;
return (unsigned long)(ZSWAP32(c));
}
Commit Message: Avoid pre-decrement of pointer in big-endian CRC calculation.
There was a small optimization for PowerPCs to pre-increment a
pointer when accessing a word, instead of post-incrementing. This
required prefacing the loop with a decrement of the pointer,
possibly pointing before the object passed. This is not compliant
with the C standard, for which decrementing a pointer before its
allocated memory is undefined. When tested on a modern PowerPC
with a modern compiler, the optimization no longer has any effect.
Due to all that, and per the recommendation of a security audit of
the zlib code by Trail of Bits and TrustInSoft, in support of the
Mozilla Foundation, this "optimization" was removed, in order to
avoid the possibility of undefined behavior.
CWE ID: CWE-189 | local unsigned long crc32_big(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
register z_crc_t c;
register const z_crc_t FAR *buf4;
c = ZSWAP32((z_crc_t)crc);
c = ~c;
while (len && ((ptrdiff_t)buf & 3)) {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
len--;
}
buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
while (len >= 32) {
DOBIG32;
len -= 32;
}
while (len >= 4) {
DOBIG4;
len -= 4;
}
buf = (const unsigned char FAR *)buf4;
if (len) do {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
} while (--len);
c = ~c;
return (unsigned long)(ZSWAP32(c));
}
| 168,672 |
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 userfaultfd_unregister(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev, *cur;
int ret;
struct uffdio_range uffdio_unregister;
unsigned long new_flags;
bool found;
unsigned long start, end, vma_end;
const void __user *buf = (void __user *)arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
goto out;
ret = validate_range(mm, uffdio_unregister.start,
uffdio_unregister.len);
if (ret)
goto out;
start = uffdio_unregister.start;
end = start + uffdio_unregister.len;
ret = -ENOMEM;
if (!mmget_not_zero(mm))
goto out;
down_write(&mm->mmap_sem);
vma = find_vma_prev(mm, start, &prev);
if (!vma)
goto out_unlock;
/* check that there's at least one vma in the range */
ret = -EINVAL;
if (vma->vm_start >= end)
goto out_unlock;
/*
* If the first vma contains huge pages, make sure start address
* is aligned to huge page size.
*/
if (is_vm_hugetlb_page(vma)) {
unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
if (start & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Search for not compatible vmas.
*/
found = false;
ret = -EINVAL;
for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
cond_resched();
BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
!!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
/*
* Check not compatible vmas, not strictly required
* here as not compatible vmas cannot have an
* userfaultfd_ctx registered on them, but this
* provides for more strict behavior to notice
* unregistration errors.
*/
if (!vma_can_userfault(cur))
goto out_unlock;
found = true;
}
BUG_ON(!found);
if (vma->vm_start < start)
prev = vma;
ret = 0;
do {
cond_resched();
BUG_ON(!vma_can_userfault(vma));
/*
* Nothing to do: this vma is already registered into this
* userfaultfd and with the right tracking mode too.
*/
if (!vma->vm_userfaultfd_ctx.ctx)
goto skip;
WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
if (vma->vm_start > start)
start = vma->vm_start;
vma_end = min(end, vma->vm_end);
if (userfaultfd_missing(vma)) {
/*
* Wake any concurrent pending userfault while
* we unregister, so they will not hang
* permanently and it avoids userland to call
* UFFDIO_WAKE explicitly.
*/
struct userfaultfd_wake_range range;
range.start = start;
range.len = vma_end - start;
wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, start, vma_end, new_flags,
vma->anon_vma, vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX);
if (prev) {
vma = prev;
goto next;
}
if (vma->vm_start < start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
break;
}
if (vma->vm_end > end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
break;
}
next:
/*
* In the vma_merge() successful mprotect-like case 8:
* the next vma was merged into the current one and
* the current one has not been updated yet.
*/
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
skip:
prev = vma;
start = vma->vm_end;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
out_unlock:
up_write(&mm->mmap_sem);
mmput(mm);
out:
return ret;
}
Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping
The core dumping code has always run without holding the mmap_sem for
writing, despite that is the only way to ensure that the entire vma
layout will not change from under it. Only using some signal
serialization on the processes belonging to the mm is not nearly enough.
This was pointed out earlier. For example in Hugh's post from Jul 2017:
https://lkml.kernel.org/r/[email protected]
"Not strictly relevant here, but a related note: I was very surprised
to discover, only quite recently, how handle_mm_fault() may be called
without down_read(mmap_sem) - when core dumping. That seems a
misguided optimization to me, which would also be nice to correct"
In particular because the growsdown and growsup can move the
vm_start/vm_end the various loops the core dump does around the vma will
not be consistent if page faults can happen concurrently.
Pretty much all users calling mmget_not_zero()/get_task_mm() and then
taking the mmap_sem had the potential to introduce unexpected side
effects in the core dumping code.
Adding mmap_sem for writing around the ->core_dump invocation is a
viable long term fix, but it requires removing all copy user and page
faults and to replace them with get_dump_page() for all binary formats
which is not suitable as a short term fix.
For the time being this solution manually covers the places that can
confuse the core dump either by altering the vma layout or the vma flags
while it runs. Once ->core_dump runs under mmap_sem for writing the
function mmget_still_valid() can be dropped.
Allowing mmap_sem protected sections to run in parallel with the
coredump provides some minor parallelism advantage to the swapoff code
(which seems to be safe enough by never mangling any vma field and can
keep doing swapins in parallel to the core dumping) and to some other
corner case.
In order to facilitate the backporting I added "Fixes: 86039bd3b4e6"
however the side effect of this same race condition in /proc/pid/mem
should be reproducible since before 2.6.12-rc2 so I couldn't add any
other "Fixes:" because there's no hash beyond the git genesis commit.
Because find_extend_vma() is the only location outside of the process
context that could modify the "mm" structures under mmap_sem for
reading, by adding the mmget_still_valid() check to it, all other cases
that take the mmap_sem for reading don't need the new check after
mmget_not_zero()/get_task_mm(). The expand_stack() in page fault
context also doesn't need the new check, because all tasks under core
dumping are frozen.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Jann Horn <[email protected]>
Suggested-by: Oleg Nesterov <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Reviewed-by: Jann Horn <[email protected]>
Acked-by: Jason Gunthorpe <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev, *cur;
int ret;
struct uffdio_range uffdio_unregister;
unsigned long new_flags;
bool found;
unsigned long start, end, vma_end;
const void __user *buf = (void __user *)arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
goto out;
ret = validate_range(mm, uffdio_unregister.start,
uffdio_unregister.len);
if (ret)
goto out;
start = uffdio_unregister.start;
end = start + uffdio_unregister.len;
ret = -ENOMEM;
if (!mmget_not_zero(mm))
goto out;
down_write(&mm->mmap_sem);
if (!mmget_still_valid(mm))
goto out_unlock;
vma = find_vma_prev(mm, start, &prev);
if (!vma)
goto out_unlock;
/* check that there's at least one vma in the range */
ret = -EINVAL;
if (vma->vm_start >= end)
goto out_unlock;
/*
* If the first vma contains huge pages, make sure start address
* is aligned to huge page size.
*/
if (is_vm_hugetlb_page(vma)) {
unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
if (start & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Search for not compatible vmas.
*/
found = false;
ret = -EINVAL;
for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
cond_resched();
BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
!!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
/*
* Check not compatible vmas, not strictly required
* here as not compatible vmas cannot have an
* userfaultfd_ctx registered on them, but this
* provides for more strict behavior to notice
* unregistration errors.
*/
if (!vma_can_userfault(cur))
goto out_unlock;
found = true;
}
BUG_ON(!found);
if (vma->vm_start < start)
prev = vma;
ret = 0;
do {
cond_resched();
BUG_ON(!vma_can_userfault(vma));
/*
* Nothing to do: this vma is already registered into this
* userfaultfd and with the right tracking mode too.
*/
if (!vma->vm_userfaultfd_ctx.ctx)
goto skip;
WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
if (vma->vm_start > start)
start = vma->vm_start;
vma_end = min(end, vma->vm_end);
if (userfaultfd_missing(vma)) {
/*
* Wake any concurrent pending userfault while
* we unregister, so they will not hang
* permanently and it avoids userland to call
* UFFDIO_WAKE explicitly.
*/
struct userfaultfd_wake_range range;
range.start = start;
range.len = vma_end - start;
wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, start, vma_end, new_flags,
vma->anon_vma, vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX);
if (prev) {
vma = prev;
goto next;
}
if (vma->vm_start < start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
break;
}
if (vma->vm_end > end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
break;
}
next:
/*
* In the vma_merge() successful mprotect-like case 8:
* the next vma was merged into the current one and
* the current one has not been updated yet.
*/
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
skip:
prev = vma;
start = vma->vm_end;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
out_unlock:
up_write(&mm->mmap_sem);
mmput(mm);
out:
return ret;
}
| 169,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: int BrowserMainLoop::PreCreateThreads() {
if (parts_) {
TRACE_EVENT0("startup",
"BrowserMainLoop::CreateThreads:PreCreateThreads");
result_code_ = parts_->PreCreateThreads();
}
if (!base::SequencedWorkerPool::IsEnabled())
base::SequencedWorkerPool::EnableForProcess();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
base::FeatureList::InitializeInstance(
command_line->GetSwitchValueASCII(switches::kEnableFeatures),
command_line->GetSwitchValueASCII(switches::kDisableFeatures));
InitializeMemoryManagementComponent();
#if defined(OS_MACOSX)
if (base::CommandLine::InitializedForCurrentProcess() &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableHeapProfiling)) {
base::allocator::PeriodicallyShimNewMallocZones();
}
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
{
TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
PluginService::GetInstance()->Init();
}
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
CdmRegistry::GetInstance()->Init();
#endif
#if defined(OS_MACOSX)
ui::WindowResizeHelperMac::Get()->Init(base::ThreadTaskRunnerHandle::Get());
#endif
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
#if defined(USE_X11)
gpu_data_manager_visual_proxy_.reset(
new internal::GpuDataManagerVisualProxy(gpu_data_manager));
#endif
gpu_data_manager->Initialize();
#if !defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID)
if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
RenderProcessHost::SetRunRendererInProcess(true);
#endif
std::vector<url::Origin> origins =
GetContentClient()->browser()->GetOriginsRequiringDedicatedProcess();
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
for (auto origin : origins)
policy->AddIsolatedOrigin(origin);
EVP_set_buggy_rsa_parser(
base::FeatureList::IsEnabled(features::kBuggyRSAParser));
return result_code_;
}
Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6
https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604
BUG=778101
Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c
Reviewed-on: https://chromium-review.googlesource.com/747941
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: David Benjamin <[email protected]>
Commit-Queue: Steven Valdez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513774}
CWE ID: CWE-310 | int BrowserMainLoop::PreCreateThreads() {
if (parts_) {
TRACE_EVENT0("startup",
"BrowserMainLoop::CreateThreads:PreCreateThreads");
result_code_ = parts_->PreCreateThreads();
}
if (!base::SequencedWorkerPool::IsEnabled())
base::SequencedWorkerPool::EnableForProcess();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
base::FeatureList::InitializeInstance(
command_line->GetSwitchValueASCII(switches::kEnableFeatures),
command_line->GetSwitchValueASCII(switches::kDisableFeatures));
InitializeMemoryManagementComponent();
#if defined(OS_MACOSX)
if (base::CommandLine::InitializedForCurrentProcess() &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableHeapProfiling)) {
base::allocator::PeriodicallyShimNewMallocZones();
}
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
{
TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
PluginService::GetInstance()->Init();
}
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
CdmRegistry::GetInstance()->Init();
#endif
#if defined(OS_MACOSX)
ui::WindowResizeHelperMac::Get()->Init(base::ThreadTaskRunnerHandle::Get());
#endif
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
#if defined(USE_X11)
gpu_data_manager_visual_proxy_.reset(
new internal::GpuDataManagerVisualProxy(gpu_data_manager));
#endif
gpu_data_manager->Initialize();
#if !defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID)
if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
RenderProcessHost::SetRunRendererInProcess(true);
#endif
std::vector<url::Origin> origins =
GetContentClient()->browser()->GetOriginsRequiringDedicatedProcess();
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
for (auto origin : origins)
policy->AddIsolatedOrigin(origin);
return result_code_;
}
| 172,933 |
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: DECLAREcpFunc(cpContig2SeparateByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
/* unpack channels */
for (s = 0; s < spp; s++) {
for (row = 0; row < imagelength; row++) {
if (TIFFReadScanline(in, inbuf, row, 0) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = ((uint8*)inbuf) + s;
outp = (uint8*)outbuf;
for (n = imagewidth; n-- > 0;) {
*outp++ = *inp;
inp += spp;
}
if (TIFFWriteScanline(out, outbuf, row, s) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and
cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and
http://bugzilla.maptools.org/show_bug.cgi?id=2657
CWE ID: CWE-119 | DECLAREcpFunc(cpContig2SeparateByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
uint16 bps = 0;
(void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps != 8 )
{
TIFFError(TIFFFileName(in),
"Error, can only handle BitsPerSample=8 in %s",
"cpContig2SeparateByRow");
return 0;
}
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
/* unpack channels */
for (s = 0; s < spp; s++) {
for (row = 0; row < imagelength; row++) {
if (TIFFReadScanline(in, inbuf, row, 0) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = ((uint8*)inbuf) + s;
outp = (uint8*)outbuf;
for (n = imagewidth; n-- > 0;) {
*outp++ = *inp;
inp += spp;
}
if (TIFFWriteScanline(out, outbuf, row, s) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
| 168,412 |
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 NormalPageArena::shrinkObject(HeapObjectHeader* header, size_t newSize) {
ASSERT(header->checkHeader());
ASSERT(header->payloadSize() > newSize);
size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize);
ASSERT(header->size() > allocationSize);
size_t shrinkSize = header->size() - allocationSize;
if (isObjectAllocatedAtAllocationPoint(header)) {
m_currentAllocationPoint -= shrinkSize;
setRemainingAllocationSize(m_remainingAllocationSize + shrinkSize);
SET_MEMORY_INACCESSIBLE(m_currentAllocationPoint, shrinkSize);
header->setSize(allocationSize);
return true;
}
ASSERT(shrinkSize >= sizeof(HeapObjectHeader));
ASSERT(header->gcInfoIndex() > 0);
Address shrinkAddress = header->payloadEnd() - shrinkSize;
HeapObjectHeader* freedHeader = new (NotNull, shrinkAddress)
HeapObjectHeader(shrinkSize, header->gcInfoIndex());
freedHeader->markPromptlyFreed();
ASSERT(pageFromObject(reinterpret_cast<Address>(header)) ==
findPageFromAddress(reinterpret_cast<Address>(header)));
m_promptlyFreedSize += shrinkSize;
header->setSize(allocationSize);
SET_MEMORY_INACCESSIBLE(shrinkAddress + sizeof(HeapObjectHeader),
shrinkSize - sizeof(HeapObjectHeader));
return false;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | bool NormalPageArena::shrinkObject(HeapObjectHeader* header, size_t newSize) {
header->checkHeader();
ASSERT(header->payloadSize() > newSize);
size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize);
ASSERT(header->size() > allocationSize);
size_t shrinkSize = header->size() - allocationSize;
if (isObjectAllocatedAtAllocationPoint(header)) {
m_currentAllocationPoint -= shrinkSize;
setRemainingAllocationSize(m_remainingAllocationSize + shrinkSize);
SET_MEMORY_INACCESSIBLE(m_currentAllocationPoint, shrinkSize);
header->setSize(allocationSize);
return true;
}
ASSERT(shrinkSize >= sizeof(HeapObjectHeader));
ASSERT(header->gcInfoIndex() > 0);
Address shrinkAddress = header->payloadEnd() - shrinkSize;
HeapObjectHeader* freedHeader = new (NotNull, shrinkAddress)
HeapObjectHeader(shrinkSize, header->gcInfoIndex());
freedHeader->markPromptlyFreed();
ASSERT(pageFromObject(reinterpret_cast<Address>(header)) ==
findPageFromAddress(reinterpret_cast<Address>(header)));
m_promptlyFreedSize += shrinkSize;
header->setSize(allocationSize);
SET_MEMORY_INACCESSIBLE(shrinkAddress + sizeof(HeapObjectHeader),
shrinkSize - sizeof(HeapObjectHeader));
return false;
}
| 172,715 |
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 hns_nic_net_xmit_hw(struct net_device *ndev,
struct sk_buff *skb,
struct hns_nic_ring_data *ring_data)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
struct hnae_ring *ring = ring_data->ring;
struct device *dev = ring_to_dev(ring);
struct netdev_queue *dev_queue;
struct skb_frag_struct *frag;
int buf_num;
int seg_num;
dma_addr_t dma;
int size, next_to_use;
int i;
switch (priv->ops.maybe_stop_tx(&skb, &buf_num, ring)) {
case -EBUSY:
ring->stats.tx_busy++;
goto out_net_tx_busy;
case -ENOMEM:
ring->stats.sw_err_cnt++;
netdev_err(ndev, "no memory to xmit!\n");
goto out_err_tx_ok;
default:
break;
}
/* no. of segments (plus a header) */
seg_num = skb_shinfo(skb)->nr_frags + 1;
next_to_use = ring->next_to_use;
/* fill the first part */
size = skb_headlen(skb);
dma = dma_map_single(dev, skb->data, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX head DMA map failed\n");
ring->stats.sw_err_cnt++;
goto out_err_tx_ok;
}
priv->ops.fill_desc(ring, skb, size, dma, seg_num == 1 ? 1 : 0,
buf_num, DESC_TYPE_SKB, ndev->mtu);
/* fill the fragments */
for (i = 1; i < seg_num; i++) {
frag = &skb_shinfo(skb)->frags[i - 1];
size = skb_frag_size(frag);
dma = skb_frag_dma_map(dev, frag, 0, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX frag(%d) DMA map failed\n", i);
ring->stats.sw_err_cnt++;
goto out_map_frag_fail;
}
priv->ops.fill_desc(ring, skb_frag_page(frag), size, dma,
seg_num - 1 == i ? 1 : 0, buf_num,
DESC_TYPE_PAGE, ndev->mtu);
}
/*complete translate all packets*/
dev_queue = netdev_get_tx_queue(ndev, skb->queue_mapping);
netdev_tx_sent_queue(dev_queue, skb->len);
wmb(); /* commit all data before submit */
assert(skb->queue_mapping < priv->ae_handle->q_num);
hnae_queue_xmit(priv->ae_handle->qs[skb->queue_mapping], buf_num);
ring->stats.tx_pkts++;
ring->stats.tx_bytes += skb->len;
return NETDEV_TX_OK;
out_map_frag_fail:
while (ring->next_to_use != next_to_use) {
unfill_desc(ring);
if (ring->next_to_use != next_to_use)
dma_unmap_page(dev,
ring->desc_cb[ring->next_to_use].dma,
ring->desc_cb[ring->next_to_use].length,
DMA_TO_DEVICE);
else
dma_unmap_single(dev,
ring->desc_cb[next_to_use].dma,
ring->desc_cb[next_to_use].length,
DMA_TO_DEVICE);
}
out_err_tx_ok:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
out_net_tx_busy:
netif_stop_subqueue(ndev, skb->queue_mapping);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it.
*/
smp_mb();
return NETDEV_TX_BUSY;
}
Commit Message: net: hns: Fix a skb used after free bug
skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,
which cause hns_nic_net_xmit to use a freed skb.
BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...
[17659.112635] alloc_debug_processing+0x18c/0x1a0
[17659.117208] __slab_alloc+0x52c/0x560
[17659.120909] kmem_cache_alloc_node+0xac/0x2c0
[17659.125309] __alloc_skb+0x6c/0x260
[17659.128837] tcp_send_ack+0x8c/0x280
[17659.132449] __tcp_ack_snd_check+0x9c/0xf0
[17659.136587] tcp_rcv_established+0x5a4/0xa70
[17659.140899] tcp_v4_do_rcv+0x27c/0x620
[17659.144687] tcp_prequeue_process+0x108/0x170
[17659.149085] tcp_recvmsg+0x940/0x1020
[17659.152787] inet_recvmsg+0x124/0x180
[17659.156488] sock_recvmsg+0x64/0x80
[17659.160012] SyS_recvfrom+0xd8/0x180
[17659.163626] __sys_trace_return+0x0/0x4
[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13
[17659.174000] free_debug_processing+0x1d4/0x2c0
[17659.178486] __slab_free+0x240/0x390
[17659.182100] kmem_cache_free+0x24c/0x270
[17659.186062] kfree_skbmem+0xa0/0xb0
[17659.189587] __kfree_skb+0x28/0x40
[17659.193025] napi_gro_receive+0x168/0x1c0
[17659.197074] hns_nic_rx_up_pro+0x58/0x90
[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0
[17659.205352] hns_nic_common_poll+0x94/0x140
[17659.209576] net_rx_action+0x458/0x5e0
[17659.213363] __do_softirq+0x1b8/0x480
[17659.217062] run_ksoftirqd+0x64/0x80
[17659.220679] smpboot_thread_fn+0x224/0x310
[17659.224821] kthread+0x150/0x170
[17659.228084] ret_from_fork+0x10/0x40
BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...
[17751.080490] __slab_alloc+0x52c/0x560
[17751.084188] kmem_cache_alloc+0x244/0x280
[17751.088238] __build_skb+0x40/0x150
[17751.091764] build_skb+0x28/0x100
[17751.095115] __alloc_rx_skb+0x94/0x150
[17751.098900] __napi_alloc_skb+0x34/0x90
[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0
[17751.107097] hns_nic_common_poll+0x94/0x140
[17751.111333] net_rx_action+0x458/0x5e0
[17751.115123] __do_softirq+0x1b8/0x480
[17751.118823] run_ksoftirqd+0x64/0x80
[17751.122437] smpboot_thread_fn+0x224/0x310
[17751.126575] kthread+0x150/0x170
[17751.129838] ret_from_fork+0x10/0x40
[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43
[17751.139951] free_debug_processing+0x1d4/0x2c0
[17751.144436] __slab_free+0x240/0x390
[17751.148051] kmem_cache_free+0x24c/0x270
[17751.152014] kfree_skbmem+0xa0/0xb0
[17751.155543] __kfree_skb+0x28/0x40
[17751.159022] napi_gro_receive+0x168/0x1c0
[17751.163074] hns_nic_rx_up_pro+0x58/0x90
[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0
[17751.171358] hns_nic_common_poll+0x94/0x140
[17751.175585] net_rx_action+0x458/0x5e0
[17751.179373] __do_softirq+0x1b8/0x480
[17751.183076] run_ksoftirqd+0x64/0x80
[17751.186691] smpboot_thread_fn+0x224/0x310
[17751.190826] kthread+0x150/0x170
[17751.194093] ret_from_fork+0x10/0x40
Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: lipeng <[email protected]>
Reported-by: Jun He <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | int hns_nic_net_xmit_hw(struct net_device *ndev,
netdev_tx_t hns_nic_net_xmit_hw(struct net_device *ndev,
struct sk_buff *skb,
struct hns_nic_ring_data *ring_data)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
struct hnae_ring *ring = ring_data->ring;
struct device *dev = ring_to_dev(ring);
struct netdev_queue *dev_queue;
struct skb_frag_struct *frag;
int buf_num;
int seg_num;
dma_addr_t dma;
int size, next_to_use;
int i;
switch (priv->ops.maybe_stop_tx(&skb, &buf_num, ring)) {
case -EBUSY:
ring->stats.tx_busy++;
goto out_net_tx_busy;
case -ENOMEM:
ring->stats.sw_err_cnt++;
netdev_err(ndev, "no memory to xmit!\n");
goto out_err_tx_ok;
default:
break;
}
/* no. of segments (plus a header) */
seg_num = skb_shinfo(skb)->nr_frags + 1;
next_to_use = ring->next_to_use;
/* fill the first part */
size = skb_headlen(skb);
dma = dma_map_single(dev, skb->data, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX head DMA map failed\n");
ring->stats.sw_err_cnt++;
goto out_err_tx_ok;
}
priv->ops.fill_desc(ring, skb, size, dma, seg_num == 1 ? 1 : 0,
buf_num, DESC_TYPE_SKB, ndev->mtu);
/* fill the fragments */
for (i = 1; i < seg_num; i++) {
frag = &skb_shinfo(skb)->frags[i - 1];
size = skb_frag_size(frag);
dma = skb_frag_dma_map(dev, frag, 0, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX frag(%d) DMA map failed\n", i);
ring->stats.sw_err_cnt++;
goto out_map_frag_fail;
}
priv->ops.fill_desc(ring, skb_frag_page(frag), size, dma,
seg_num - 1 == i ? 1 : 0, buf_num,
DESC_TYPE_PAGE, ndev->mtu);
}
/*complete translate all packets*/
dev_queue = netdev_get_tx_queue(ndev, skb->queue_mapping);
netdev_tx_sent_queue(dev_queue, skb->len);
netif_trans_update(ndev);
ndev->stats.tx_bytes += skb->len;
ndev->stats.tx_packets++;
wmb(); /* commit all data before submit */
assert(skb->queue_mapping < priv->ae_handle->q_num);
hnae_queue_xmit(priv->ae_handle->qs[skb->queue_mapping], buf_num);
ring->stats.tx_pkts++;
ring->stats.tx_bytes += skb->len;
return NETDEV_TX_OK;
out_map_frag_fail:
while (ring->next_to_use != next_to_use) {
unfill_desc(ring);
if (ring->next_to_use != next_to_use)
dma_unmap_page(dev,
ring->desc_cb[ring->next_to_use].dma,
ring->desc_cb[ring->next_to_use].length,
DMA_TO_DEVICE);
else
dma_unmap_single(dev,
ring->desc_cb[next_to_use].dma,
ring->desc_cb[next_to_use].length,
DMA_TO_DEVICE);
}
out_err_tx_ok:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
out_net_tx_busy:
netif_stop_subqueue(ndev, skb->queue_mapping);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it.
*/
smp_mb();
return NETDEV_TX_BUSY;
}
| 169,404 |
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: struct key *key_alloc(struct key_type *type, const char *desc,
kuid_t uid, kgid_t gid, const struct cred *cred,
key_perm_t perm, unsigned long flags,
struct key_restriction *restrict_link)
{
struct key_user *user = NULL;
struct key *key;
size_t desclen, quotalen;
int ret;
key = ERR_PTR(-EINVAL);
if (!desc || !*desc)
goto error;
if (type->vet_description) {
ret = type->vet_description(desc);
if (ret < 0) {
key = ERR_PTR(ret);
goto error;
}
}
desclen = strlen(desc);
quotalen = desclen + 1 + type->def_datalen;
/* get hold of the key tracking for this user */
user = key_user_lookup(uid);
if (!user)
goto no_memory_1;
/* check that the user's quota permits allocation of another key and
* its description */
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxkeys : key_quota_maxkeys;
unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxbytes : key_quota_maxbytes;
spin_lock(&user->lock);
if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
if (user->qnkeys + 1 >= maxkeys ||
user->qnbytes + quotalen >= maxbytes ||
user->qnbytes + quotalen < user->qnbytes)
goto no_quota;
}
user->qnkeys++;
user->qnbytes += quotalen;
spin_unlock(&user->lock);
}
/* allocate and initialise the key and its description */
key = kmem_cache_zalloc(key_jar, GFP_KERNEL);
if (!key)
goto no_memory_2;
key->index_key.desc_len = desclen;
key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);
if (!key->index_key.description)
goto no_memory_3;
refcount_set(&key->usage, 1);
init_rwsem(&key->sem);
lockdep_set_class(&key->sem, &type->lock_class);
key->index_key.type = type;
key->user = user;
key->quotalen = quotalen;
key->datalen = type->def_datalen;
key->uid = uid;
key->gid = gid;
key->perm = perm;
key->restrict_link = restrict_link;
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
key->flags |= 1 << KEY_FLAG_IN_QUOTA;
if (flags & KEY_ALLOC_BUILT_IN)
key->flags |= 1 << KEY_FLAG_BUILTIN;
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC;
#endif
/* let the security module know about the key */
ret = security_key_alloc(key, cred, flags);
if (ret < 0)
goto security_error;
/* publish the key by giving it a serial number */
atomic_inc(&user->nkeys);
key_alloc_serial(key);
error:
return key;
security_error:
kfree(key->description);
kmem_cache_free(key_jar, key);
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
key = ERR_PTR(ret);
goto error;
no_memory_3:
kmem_cache_free(key_jar, key);
no_memory_2:
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
no_memory_1:
key = ERR_PTR(-ENOMEM);
goto error;
no_quota:
spin_unlock(&user->lock);
key_user_put(user);
key = ERR_PTR(-EDQUOT);
goto error;
}
Commit Message: KEYS: prevent creating a different user's keyrings
It was possible for an unprivileged user to create the user and user
session keyrings for another user. For example:
sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u
keyctl add keyring _uid_ses.4000 "" @u
sleep 15' &
sleep 1
sudo -u '#4000' keyctl describe @u
sudo -u '#4000' keyctl describe @us
This is problematic because these "fake" keyrings won't have the right
permissions. In particular, the user who created them first will own
them and will have full access to them via the possessor permissions,
which can be used to compromise the security of a user's keys:
-4: alswrv-----v------------ 3000 0 keyring: _uid.4000
-5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000
Fix it by marking user and user session keyrings with a flag
KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session
keyring by name, skip all keyrings that don't have the flag set.
Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed")
Cc: <[email protected]> [v2.6.26+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: | struct key *key_alloc(struct key_type *type, const char *desc,
kuid_t uid, kgid_t gid, const struct cred *cred,
key_perm_t perm, unsigned long flags,
struct key_restriction *restrict_link)
{
struct key_user *user = NULL;
struct key *key;
size_t desclen, quotalen;
int ret;
key = ERR_PTR(-EINVAL);
if (!desc || !*desc)
goto error;
if (type->vet_description) {
ret = type->vet_description(desc);
if (ret < 0) {
key = ERR_PTR(ret);
goto error;
}
}
desclen = strlen(desc);
quotalen = desclen + 1 + type->def_datalen;
/* get hold of the key tracking for this user */
user = key_user_lookup(uid);
if (!user)
goto no_memory_1;
/* check that the user's quota permits allocation of another key and
* its description */
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxkeys : key_quota_maxkeys;
unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxbytes : key_quota_maxbytes;
spin_lock(&user->lock);
if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
if (user->qnkeys + 1 >= maxkeys ||
user->qnbytes + quotalen >= maxbytes ||
user->qnbytes + quotalen < user->qnbytes)
goto no_quota;
}
user->qnkeys++;
user->qnbytes += quotalen;
spin_unlock(&user->lock);
}
/* allocate and initialise the key and its description */
key = kmem_cache_zalloc(key_jar, GFP_KERNEL);
if (!key)
goto no_memory_2;
key->index_key.desc_len = desclen;
key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);
if (!key->index_key.description)
goto no_memory_3;
refcount_set(&key->usage, 1);
init_rwsem(&key->sem);
lockdep_set_class(&key->sem, &type->lock_class);
key->index_key.type = type;
key->user = user;
key->quotalen = quotalen;
key->datalen = type->def_datalen;
key->uid = uid;
key->gid = gid;
key->perm = perm;
key->restrict_link = restrict_link;
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
key->flags |= 1 << KEY_FLAG_IN_QUOTA;
if (flags & KEY_ALLOC_BUILT_IN)
key->flags |= 1 << KEY_FLAG_BUILTIN;
if (flags & KEY_ALLOC_UID_KEYRING)
key->flags |= 1 << KEY_FLAG_UID_KEYRING;
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC;
#endif
/* let the security module know about the key */
ret = security_key_alloc(key, cred, flags);
if (ret < 0)
goto security_error;
/* publish the key by giving it a serial number */
atomic_inc(&user->nkeys);
key_alloc_serial(key);
error:
return key;
security_error:
kfree(key->description);
kmem_cache_free(key_jar, key);
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
key = ERR_PTR(ret);
goto error;
no_memory_3:
kmem_cache_free(key_jar, key);
no_memory_2:
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
no_memory_1:
key = ERR_PTR(-ENOMEM);
goto error;
no_quota:
spin_unlock(&user->lock);
key_user_put(user);
key = ERR_PTR(-EDQUOT);
goto error;
}
| 169,374 |
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 WebContentsImpl::DidFailProvisionalLoadWithError(
RenderViewHost* render_view_host,
const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
<< ", error_code: " << params.error_code
<< ", error_description: " << params.error_description
<< ", is_main_frame: " << params.is_main_frame
<< ", showing_repost_interstitial: " <<
params.showing_repost_interstitial
<< ", frame_id: " << params.frame_id;
GURL validated_url(params.url);
RenderProcessHost* render_process_host =
render_view_host->GetProcess();
RenderViewHost::FilterURL(render_process_host, false, &validated_url);
if (net::ERR_ABORTED == params.error_code) {
if (ShowingInterstitialPage()) {
LOG(WARNING) << "Discarding message during interstitial.";
return;
}
render_manager_.RendererAbortedProvisionalLoad(render_view_host);
}
FOR_EACH_OBSERVER(WebContentsObserver,
observers_,
DidFailProvisionalLoad(params.frame_id,
params.is_main_frame,
validated_url,
params.error_code,
params.error_description,
render_view_host));
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void WebContentsImpl::DidFailProvisionalLoadWithError(
RenderViewHost* render_view_host,
const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
<< ", error_code: " << params.error_code
<< ", error_description: " << params.error_description
<< ", is_main_frame: " << params.is_main_frame
<< ", showing_repost_interstitial: " <<
params.showing_repost_interstitial
<< ", frame_id: " << params.frame_id;
GURL validated_url(params.url);
RenderProcessHost* render_process_host =
render_view_host->GetProcess();
RenderViewHost::FilterURL(render_process_host, false, &validated_url);
if (net::ERR_ABORTED == params.error_code) {
if (ShowingInterstitialPage()) {
LOG(WARNING) << "Discarding message during interstitial.";
return;
}
render_manager_.RendererAbortedProvisionalLoad(render_view_host);
}
// Do not usually clear the pending entry if one exists, so that the user's
// typed URL is not lost when a navigation fails or is aborted. However, in
// cases that we don't show the pending entry (e.g., renderer-initiated
// navigations in an existing tab), we don't keep it around. That prevents
// spoofs on in-page navigations that don't go through
// DidStartProvisionalLoadForFrame.
// In general, we allow the view to clear the pending entry and typed URL if
// the user requests (e.g., hitting Escape with focus in the address bar).
// Note: don't touch the transient entry, since an interstitial may exist.
if (controller_.GetPendingEntry() != controller_.GetVisibleEntry())
controller_.DiscardPendingEntry();
FOR_EACH_OBSERVER(WebContentsObserver,
observers_,
DidFailProvisionalLoad(params.frame_id,
params.is_main_frame,
validated_url,
params.error_code,
params.error_description,
render_view_host));
}
| 171,189 |
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 *ReadVIPSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
buffer[MaxTextExtent],
*metadata;
Image
*image;
MagickBooleanType
status;
ssize_t
n;
unsigned int
channels,
marker;
VIPSBandFormat
format;
VIPSCoding
coding;
VIPSType
type;
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);
}
marker=ReadBlobLSBLong(image);
if (marker == VIPS_MAGIC_LSB)
image->endian=LSBEndian;
else if (marker == VIPS_MAGIC_MSB)
image->endian=MSBEndian;
else
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) ReadBlobLong(image);
image->rows=(size_t) ReadBlobLong(image);
channels=ReadBlobLong(image);
(void) ReadBlobLong(image); /* Legacy */
format=(VIPSBandFormat) ReadBlobLong(image);
switch(format)
{
case VIPSBandFormatUCHAR:
case VIPSBandFormatCHAR:
image->depth=8;
break;
case VIPSBandFormatUSHORT:
case VIPSBandFormatSHORT:
image->depth=16;
break;
case VIPSBandFormatUINT:
case VIPSBandFormatINT:
case VIPSBandFormatFLOAT:
image->depth=32;
break;
case VIPSBandFormatDOUBLE:
image->depth=64;
break;
default:
case VIPSBandFormatCOMPLEX:
case VIPSBandFormatDPCOMPLEX:
case VIPSBandFormatNOTSET:
ThrowReaderException(CoderError,"Unsupported band format");
}
coding=(VIPSCoding) ReadBlobLong(image);
type=(VIPSType) ReadBlobLong(image);
switch(type)
{
case VIPSTypeCMYK:
SetImageColorspace(image,CMYKColorspace);
if (channels == 5)
image->matte=MagickTrue;
break;
case VIPSTypeB_W:
case VIPSTypeGREY16:
SetImageColorspace(image,GRAYColorspace);
if (channels == 2)
image->matte=MagickTrue;
break;
case VIPSTypeRGB:
case VIPSTypeRGB16:
SetImageColorspace(image,RGBColorspace);
if (channels == 4)
image->matte=MagickTrue;
break;
case VIPSTypesRGB:
SetImageColorspace(image,sRGBColorspace);
if (channels == 4)
image->matte=MagickTrue;
break;
default:
case VIPSTypeFOURIER:
case VIPSTypeHISTOGRAM:
case VIPSTypeLAB:
case VIPSTypeLABS:
case VIPSTypeLABQ:
case VIPSTypeLCH:
case VIPSTypeMULTIBAND:
case VIPSTypeUCS:
case VIPSTypeXYZ:
case VIPSTypeYXY:
ThrowReaderException(CoderError,"Unsupported colorspace");
}
image->units=PixelsPerCentimeterResolution;
image->x_resolution=ReadBlobFloat(image)*10;
image->y_resolution=ReadBlobFloat(image)*10;
/*
Legacy, offsets, future
*/
(void) ReadBlobLongLong(image);
(void) ReadBlobLongLong(image);
(void) ReadBlobLongLong(image);
if (image_info->ping != MagickFalse)
return(image);
if (IsSupportedCombination(format,type) == MagickFalse)
ThrowReaderException(CoderError,
"Unsupported combination of band format and colorspace");
if (channels == 0 || channels > 5)
ThrowReaderException(CoderError,"Unsupported number of channels");
if (coding == VIPSCodingNONE)
status=ReadVIPSPixelsNONE(image,format,type,channels,exception);
else
ThrowReaderException(CoderError,"Unsupported coding");
metadata=(char *) NULL;
while ((n=ReadBlob(image,MaxTextExtent-1,(unsigned char *) buffer)) != 0)
{
buffer[n]='\0';
if (metadata == (char *) NULL)
metadata=ConstantString(buffer);
else
(void) ConcatenateString(&metadata,buffer);
}
if (metadata != (char *) NULL)
SetImageProperty(image,"vips:metadata",metadata);
(void) CloseBlob(image);
if (status == MagickFalse)
return((Image *) NULL);
return(image);
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadVIPSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
buffer[MaxTextExtent],
*metadata;
Image
*image;
MagickBooleanType
status;
ssize_t
n;
unsigned int
channels,
marker;
VIPSBandFormat
format;
VIPSCoding
coding;
VIPSType
type;
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);
}
marker=ReadBlobLSBLong(image);
if (marker == VIPS_MAGIC_LSB)
image->endian=LSBEndian;
else if (marker == VIPS_MAGIC_MSB)
image->endian=MSBEndian;
else
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) ReadBlobLong(image);
image->rows=(size_t) ReadBlobLong(image);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
channels=ReadBlobLong(image);
(void) ReadBlobLong(image); /* Legacy */
format=(VIPSBandFormat) ReadBlobLong(image);
switch(format)
{
case VIPSBandFormatUCHAR:
case VIPSBandFormatCHAR:
image->depth=8;
break;
case VIPSBandFormatUSHORT:
case VIPSBandFormatSHORT:
image->depth=16;
break;
case VIPSBandFormatUINT:
case VIPSBandFormatINT:
case VIPSBandFormatFLOAT:
image->depth=32;
break;
case VIPSBandFormatDOUBLE:
image->depth=64;
break;
default:
case VIPSBandFormatCOMPLEX:
case VIPSBandFormatDPCOMPLEX:
case VIPSBandFormatNOTSET:
ThrowReaderException(CoderError,"Unsupported band format");
}
coding=(VIPSCoding) ReadBlobLong(image);
type=(VIPSType) ReadBlobLong(image);
switch(type)
{
case VIPSTypeCMYK:
SetImageColorspace(image,CMYKColorspace);
if (channels == 5)
image->matte=MagickTrue;
break;
case VIPSTypeB_W:
case VIPSTypeGREY16:
SetImageColorspace(image,GRAYColorspace);
if (channels == 2)
image->matte=MagickTrue;
break;
case VIPSTypeRGB:
case VIPSTypeRGB16:
SetImageColorspace(image,RGBColorspace);
if (channels == 4)
image->matte=MagickTrue;
break;
case VIPSTypesRGB:
SetImageColorspace(image,sRGBColorspace);
if (channels == 4)
image->matte=MagickTrue;
break;
default:
case VIPSTypeFOURIER:
case VIPSTypeHISTOGRAM:
case VIPSTypeLAB:
case VIPSTypeLABS:
case VIPSTypeLABQ:
case VIPSTypeLCH:
case VIPSTypeMULTIBAND:
case VIPSTypeUCS:
case VIPSTypeXYZ:
case VIPSTypeYXY:
ThrowReaderException(CoderError,"Unsupported colorspace");
}
image->units=PixelsPerCentimeterResolution;
image->x_resolution=ReadBlobFloat(image)*10;
image->y_resolution=ReadBlobFloat(image)*10;
/*
Legacy, offsets, future
*/
(void) ReadBlobLongLong(image);
(void) ReadBlobLongLong(image);
(void) ReadBlobLongLong(image);
if (image_info->ping != MagickFalse)
return(image);
if (IsSupportedCombination(format,type) == MagickFalse)
ThrowReaderException(CoderError,
"Unsupported combination of band format and colorspace");
if (channels == 0 || channels > 5)
ThrowReaderException(CoderError,"Unsupported number of channels");
if (coding == VIPSCodingNONE)
status=ReadVIPSPixelsNONE(image,format,type,channels,exception);
else
ThrowReaderException(CoderError,"Unsupported coding");
metadata=(char *) NULL;
while ((n=ReadBlob(image,MaxTextExtent-1,(unsigned char *) buffer)) != 0)
{
buffer[n]='\0';
if (metadata == (char *) NULL)
metadata=ConstantString(buffer);
else
(void) ConcatenateString(&metadata,buffer);
}
if (metadata != (char *) NULL)
SetImageProperty(image,"vips:metadata",metadata);
(void) CloseBlob(image);
if (status == MagickFalse)
return((Image *) NULL);
return(image);
}
| 168,618 |
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 ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection(
blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) {
DCHECK_EQ(WORKER_NOT_READY, state_);
state_ = WORKER_READY;
agent_ptr_.Bind(std::move(devtools_agent_ptr_info));
if (!sessions().empty()) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&SetDevToolsAttachedOnIO,
context_weak_, version_id_, true));
}
RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_);
for (DevToolsSession* session : sessions()) {
session->SetRenderer(host, nullptr);
session->AttachToAgent(agent_ptr_);
}
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection(
blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) {
DCHECK_EQ(WORKER_NOT_READY, state_);
state_ = WORKER_READY;
agent_ptr_.Bind(std::move(devtools_agent_ptr_info));
if (!sessions().empty()) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&SetDevToolsAttachedOnIO,
context_weak_, version_id_, true));
}
for (DevToolsSession* session : sessions()) {
session->SetRenderer(worker_process_id_, nullptr);
session->AttachToAgent(agent_ptr_);
}
}
| 172,785 |
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_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
if (num > VIRTIO_PCI_QUEUE_MAX) {
error_report("Invalid number of PCI queues: 0x%x", num);
return -1;
}
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
Commit Message:
CWE ID: CWE-94 | int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
return -1;
}
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
if (num > VIRTIO_PCI_QUEUE_MAX) {
error_report("Invalid number of PCI queues: 0x%x", num);
return -1;
}
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
| 165,336 |
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: native_handle_t* native_handle_create(int numFds, int numInts)
{
native_handle_t* h = malloc(
sizeof(native_handle_t) + sizeof(int)*(numFds+numInts));
if (h) {
h->version = sizeof(native_handle_t);
h->numFds = numFds;
h->numInts = numInts;
}
return h;
}
Commit Message: Prevent integer overflow when allocating native_handle_t
User specified values of numInts and numFds can overflow
and cause malloc to allocate less than we expect, causing
heap corruption in subsequent operations on the allocation.
Bug: 19334482
Change-Id: I43c75f536ea4c08f14ca12ca6288660fd2d1ec55
CWE ID: CWE-189 | native_handle_t* native_handle_create(int numFds, int numInts)
{
if (numFds < 0 || numInts < 0 || numFds > kMaxNativeFds || numInts > kMaxNativeInts) {
return NULL;
}
size_t mallocSize = sizeof(native_handle_t) + (sizeof(int) * (numFds + numInts));
native_handle_t* h = malloc(mallocSize);
if (h) {
h->version = sizeof(native_handle_t);
h->numFds = numFds;
h->numInts = numInts;
}
return h;
}
| 174,123 |
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: do_prefetch_tables (const void *gcmM, size_t gcmM_size)
{
prefetch_table(gcmM, gcmM_size);
prefetch_table(gcmR, sizeof(gcmR));
}
Commit Message: GCM: move look-up table to .data section and unshare between processes
* cipher/cipher-gcm.c (ATTR_ALIGNED_64): New.
(gcmR): Move to 'gcm_table' structure.
(gcm_table): New structure for look-up table with counters before and
after.
(gcmR): New macro.
(prefetch_table): Handle input with length not multiple of 256.
(do_prefetch_tables): Modify pre- and post-table counters to unshare
look-up table pages between processes.
--
GnuPG-bug-id: 4541
Signed-off-by: Jussi Kivilinna <[email protected]>
CWE ID: CWE-310 | do_prefetch_tables (const void *gcmM, size_t gcmM_size)
{
/* Modify counters to trigger copy-on-write and unsharing if physical pages
* of look-up table are shared between processes. Modifying counters also
* causes checksums for pages to change and hint same-page merging algorithm
* that these pages are frequently changing. */
gcm_table.counter_head++;
gcm_table.counter_tail++;
/* Prefetch look-up tables to cache. */
prefetch_table(gcmM, gcmM_size);
prefetch_table(&gcm_table, sizeof(gcm_table));
}
| 169,650 |
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: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 8;
fwd_txfm_ref = fht8x8_ref;
}
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 | virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 8;
fwd_txfm_ref = fht8x8_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,563 |
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 LockContentsView::OnUsersChanged(
const std::vector<mojom::LoginUserInfoPtr>& users) {
main_view_->RemoveAllChildViews(true /*delete_children*/);
opt_secondary_big_view_ = nullptr;
users_list_ = nullptr;
rotation_actions_.clear();
users_.clear();
if (users.empty()) {
LOG_IF(FATAL, screen_type_ != LockScreen::ScreenType::kLogin)
<< "Empty user list received";
Shell::Get()->login_screen_controller()->ShowGaiaSignin(
false /*can_close*/, base::nullopt /*prefilled_account*/);
return;
}
for (const mojom::LoginUserInfoPtr& user : users) {
UserState state(user->basic_user_info->account_id);
state.fingerprint_state = user->allow_fingerprint_unlock
? mojom::FingerprintUnlockState::AVAILABLE
: mojom::FingerprintUnlockState::UNAVAILABLE;
users_.push_back(std::move(state));
}
auto box_layout =
std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal);
main_layout_ = box_layout.get();
main_layout_->set_main_axis_alignment(
views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER);
main_layout_->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER);
main_view_->SetLayoutManager(std::move(box_layout));
primary_big_view_ = AllocateLoginBigUserView(users[0], true /*is_primary*/);
main_view_->AddChildView(primary_big_view_);
if (users.size() == 2)
CreateLowDensityLayout(users);
else if (users.size() >= 3 && users.size() <= 6)
CreateMediumDensityLayout(users);
else if (users.size() >= 7)
CreateHighDensityLayout(users);
LayoutAuth(primary_big_view_, opt_secondary_big_view_, false /*animate*/);
OnBigUserChanged();
PreferredSizeChanged();
Layout();
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID: | void LockContentsView::OnUsersChanged(
const std::vector<mojom::LoginUserInfoPtr>& users) {
main_view_->RemoveAllChildViews(true /*delete_children*/);
opt_secondary_big_view_ = nullptr;
users_list_ = nullptr;
rotation_actions_.clear();
users_.clear();
if (users.empty()) {
LOG_IF(FATAL, screen_type_ != LockScreen::ScreenType::kLogin)
<< "Empty user list received";
Shell::Get()->login_screen_controller()->ShowGaiaSignin(
false /*can_close*/, base::nullopt /*prefilled_account*/);
return;
}
for (const mojom::LoginUserInfoPtr& user : users)
users_.push_back(UserState(user));
auto box_layout =
std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal);
main_layout_ = box_layout.get();
main_layout_->set_main_axis_alignment(
views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER);
main_layout_->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER);
main_view_->SetLayoutManager(std::move(box_layout));
primary_big_view_ = AllocateLoginBigUserView(users[0], true /*is_primary*/);
main_view_->AddChildView(primary_big_view_);
if (users.size() == 2)
CreateLowDensityLayout(users);
else if (users.size() >= 3 && users.size() <= 6)
CreateMediumDensityLayout(users);
else if (users.size() >= 7)
CreateHighDensityLayout(users);
LayoutAuth(primary_big_view_, opt_secondary_big_view_, false /*animate*/);
OnBigUserChanged();
PreferredSizeChanged();
Layout();
}
| 172,197 |
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 load_misc_binary(struct linux_binprm *bprm)
{
Node *fmt;
struct file * interp_file = NULL;
char iname[BINPRM_BUF_SIZE];
const char *iname_addr = iname;
int retval;
int fd_binary = -1;
retval = -ENOEXEC;
if (!enabled)
goto _ret;
/* to keep locking time low, we copy the interpreter string */
read_lock(&entries_lock);
fmt = check_file(bprm);
if (fmt)
strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE);
read_unlock(&entries_lock);
if (!fmt)
goto _ret;
if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) {
retval = remove_arg_zero(bprm);
if (retval)
goto _ret;
}
if (fmt->flags & MISC_FMT_OPEN_BINARY) {
/* if the binary should be opened on behalf of the
* interpreter than keep it open and assign descriptor
* to it */
fd_binary = get_unused_fd();
if (fd_binary < 0) {
retval = fd_binary;
goto _ret;
}
fd_install(fd_binary, bprm->file);
/* if the binary is not readable than enforce mm->dumpable=0
regardless of the interpreter's permissions */
would_dump(bprm, bprm->file);
allow_write_access(bprm->file);
bprm->file = NULL;
/* mark the bprm that fd should be passed to interp */
bprm->interp_flags |= BINPRM_FLAGS_EXECFD;
bprm->interp_data = fd_binary;
} else {
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
}
/* make argv[1] be the path to the binary */
retval = copy_strings_kernel (1, &bprm->interp, bprm);
if (retval < 0)
goto _error;
bprm->argc++;
/* add the interp as argv[0] */
retval = copy_strings_kernel (1, &iname_addr, bprm);
if (retval < 0)
goto _error;
bprm->argc ++;
bprm->interp = iname; /* for binfmt_script */
interp_file = open_exec (iname);
retval = PTR_ERR (interp_file);
if (IS_ERR (interp_file))
goto _error;
bprm->file = interp_file;
if (fmt->flags & MISC_FMT_CREDENTIALS) {
/*
* No need to call prepare_binprm(), it's already been
* done. bprm->buf is stale, update from interp_file.
*/
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
} else
retval = prepare_binprm (bprm);
if (retval < 0)
goto _error;
retval = search_binary_handler(bprm);
if (retval < 0)
goto _error;
_ret:
return retval;
_error:
if (fd_binary > 0)
sys_close(fd_binary);
bprm->interp_flags = 0;
bprm->interp_data = 0;
goto _ret;
}
Commit Message: exec: do not leave bprm->interp on stack
If a series of scripts are executed, each triggering module loading via
unprintable bytes in the script header, kernel stack contents can leak
into the command line.
Normally execution of binfmt_script and binfmt_misc happens recursively.
However, when modules are enabled, and unprintable bytes exist in the
bprm->buf, execution will restart after attempting to load matching
binfmt modules. Unfortunately, the logic in binfmt_script and
binfmt_misc does not expect to get restarted. They leave bprm->interp
pointing to their local stack. This means on restart bprm->interp is
left pointing into unused stack memory which can then be copied into the
userspace argv areas.
After additional study, it seems that both recursion and restart remains
the desirable way to handle exec with scripts, misc, and modules. As
such, we need to protect the changes to interp.
This changes the logic to require allocation for any changes to the
bprm->interp. To avoid adding a new kmalloc to every exec, the default
value is left as-is. Only when passing through binfmt_script or
binfmt_misc does an allocation take place.
For a proof of concept, see DoTest.sh from:
http://www.halfdog.net/Security/2012/LinuxKernelBinfmtScriptStackDataDisclosure/
Signed-off-by: Kees Cook <[email protected]>
Cc: halfdog <[email protected]>
Cc: P J P <[email protected]>
Cc: Alexander Viro <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static int load_misc_binary(struct linux_binprm *bprm)
{
Node *fmt;
struct file * interp_file = NULL;
char iname[BINPRM_BUF_SIZE];
const char *iname_addr = iname;
int retval;
int fd_binary = -1;
retval = -ENOEXEC;
if (!enabled)
goto _ret;
/* to keep locking time low, we copy the interpreter string */
read_lock(&entries_lock);
fmt = check_file(bprm);
if (fmt)
strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE);
read_unlock(&entries_lock);
if (!fmt)
goto _ret;
if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) {
retval = remove_arg_zero(bprm);
if (retval)
goto _ret;
}
if (fmt->flags & MISC_FMT_OPEN_BINARY) {
/* if the binary should be opened on behalf of the
* interpreter than keep it open and assign descriptor
* to it */
fd_binary = get_unused_fd();
if (fd_binary < 0) {
retval = fd_binary;
goto _ret;
}
fd_install(fd_binary, bprm->file);
/* if the binary is not readable than enforce mm->dumpable=0
regardless of the interpreter's permissions */
would_dump(bprm, bprm->file);
allow_write_access(bprm->file);
bprm->file = NULL;
/* mark the bprm that fd should be passed to interp */
bprm->interp_flags |= BINPRM_FLAGS_EXECFD;
bprm->interp_data = fd_binary;
} else {
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
}
/* make argv[1] be the path to the binary */
retval = copy_strings_kernel (1, &bprm->interp, bprm);
if (retval < 0)
goto _error;
bprm->argc++;
/* add the interp as argv[0] */
retval = copy_strings_kernel (1, &iname_addr, bprm);
if (retval < 0)
goto _error;
bprm->argc ++;
/* Update interp in case binfmt_script needs it. */
retval = bprm_change_interp(iname, bprm);
if (retval < 0)
goto _error;
interp_file = open_exec (iname);
retval = PTR_ERR (interp_file);
if (IS_ERR (interp_file))
goto _error;
bprm->file = interp_file;
if (fmt->flags & MISC_FMT_CREDENTIALS) {
/*
* No need to call prepare_binprm(), it's already been
* done. bprm->buf is stale, update from interp_file.
*/
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
} else
retval = prepare_binprm (bprm);
if (retval < 0)
goto _error;
retval = search_binary_handler(bprm);
if (retval < 0)
goto _error;
_ret:
return retval;
_error:
if (fd_binary > 0)
sys_close(fd_binary);
bprm->interp_flags = 0;
bprm->interp_data = 0;
goto _ret;
}
| 166,197 |
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 ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
blobRegistry().addDataToStream(url, streamData);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
void BlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry()) {
WebThreadSafeData webThreadSafeData(streamData);
registry->addDataToStream(url, webThreadSafeData);
}
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
| 170,680 |
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: GLboolean WebGL2RenderingContextBase::isTransformFeedback(
WebGLTransformFeedback* feedback) {
if (isContextLost() || !feedback)
return 0;
if (!feedback->HasEverBeenBound())
return 0;
return ContextGL()->IsTransformFeedback(feedback->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | GLboolean WebGL2RenderingContextBase::isTransformFeedback(
WebGLTransformFeedback* feedback) {
if (isContextLost() || !feedback || !feedback->Validate(ContextGroup(), this))
return 0;
if (!feedback->HasEverBeenBound())
return 0;
return ContextGL()->IsTransformFeedback(feedback->Object());
}
| 173,126 |
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 void sem_getref(struct sem_array *sma)
{
spin_lock(&(sma)->sem_perm.lock);
ipc_rcu_getref(sma);
ipc_unlock(&(sma)->sem_perm);
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static inline void sem_getref(struct sem_array *sma)
{
sem_lock(sma, NULL, -1);
WARN_ON_ONCE(!ipc_rcu_getref(sma));
sem_unlock(sma, -1);
}
| 165,973 |
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: handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
Commit Message: CVE-2017-13038/PPP: Do bounds checking.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by Katie Holly.
CWE ID: CWE-125 | handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
if (length < 2) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
if (!ND_TTEST_16BITS(p)) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
| 167,844 |
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: pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize)
{
/* Assume we can multiply by 'size' without overflow because we are
* just working in a single buffer.
*/
toIndex *= pixelSize;
fromIndex *= pixelSize;
if (pixelSize < 8) /* Sub-byte */
{
/* Mask to select the location of the copied pixel: */
unsigned int destMask = ((1U<<pixelSize)-1) << (8-pixelSize-(toIndex&7));
/* The following read the entire pixels and clears the extra: */
unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
unsigned int sourceByte = fromBuffer[fromIndex >> 3];
/* Don't rely on << or >> supporting '0' here, just in case: */
fromIndex &= 7;
if (fromIndex > 0) sourceByte <<= fromIndex;
if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
}
else /* One or more bytes */
memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
int littleendian)
{
/* Assume we can multiply by 'size' without overflow because we are
* just working in a single buffer.
*/
toIndex *= pixelSize;
fromIndex *= pixelSize;
if (pixelSize < 8) /* Sub-byte */
{
/* Mask to select the location of the copied pixel: */
unsigned int destMask = ((1U<<pixelSize)-1) <<
(littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
/* The following read the entire pixels and clears the extra: */
unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
unsigned int sourceByte = fromBuffer[fromIndex >> 3];
/* Don't rely on << or >> supporting '0' here, just in case: */
fromIndex &= 7;
if (littleendian)
{
if (fromIndex > 0) sourceByte >>= fromIndex;
if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
}
else
{
if (fromIndex > 0) sourceByte <<= fromIndex;
if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
}
toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
}
else /* One or more bytes */
memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
}
| 173,685 |
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 touch(const char *path) {
return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264 | int touch(const char *path) {
return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
}
| 170,104 |
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 SetState(MediaStreamType stream_type, MediaRequestState new_state) {
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
state_[static_cast<MediaStreamType>(i)] = new_state;
}
} else {
state_[stream_type] = new_state;
}
MediaObserver* media_observer =
GetContentClient()->browser()->GetMediaObserver();
if (!media_observer)
return;
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), stream_type, new_state);
}
Commit Message: Fix MediaObserver notifications in MediaStreamManager.
This CL fixes the stream type used to notify MediaObserver about
cancelled MediaStream requests.
Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate
that all stream types should be cancelled.
However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this
way and the request to update the UI is ignored.
This CL sends a separate notification for each stream type so that the
UI actually gets updated for all stream types in use.
Bug: 816033
Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405
Reviewed-on: https://chromium-review.googlesource.com/939630
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540122}
CWE ID: CWE-20 | void SetState(MediaStreamType stream_type, MediaRequestState new_state) {
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
state_[static_cast<MediaStreamType>(i)] = new_state;
}
} else {
state_[stream_type] = new_state;
}
MediaObserver* media_observer =
GetContentClient()->browser()->GetMediaObserver();
if (!media_observer)
return;
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), static_cast<MediaStreamType>(i),
new_state);
}
} else {
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), stream_type, new_state);
}
}
| 172,734 |
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: jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
int new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
uint32_t new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
| 165,496 |
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: xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
xmlNodePtr inst, xsltStylePreCompPtr castedComp)
{
#ifdef XSLT_REFACTORED
xsltStyleItemForEachPtr comp = (xsltStyleItemForEachPtr) castedComp;
#else
xsltStylePreCompPtr comp = castedComp;
#endif
int i;
xmlXPathObjectPtr res = NULL;
xmlNodePtr cur, curInst;
xmlNodeSetPtr list = NULL;
xmlNodeSetPtr oldList;
int oldXPProximityPosition, oldXPContextSize;
xmlNodePtr oldContextNode;
xsltTemplatePtr oldCurTemplRule;
xmlDocPtr oldXPDoc;
xsltDocumentPtr oldDocInfo;
xmlXPathContextPtr xpctxt;
if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) {
xsltGenericError(xsltGenericErrorContext,
"xsltForEach(): Bad arguments.\n");
return;
}
if (comp == NULL) {
xsltTransformError(ctxt, NULL, inst,
"Internal error in xsltForEach(): "
"The XSLT 'for-each' instruction was not compiled.\n");
return;
}
if ((comp->select == NULL) || (comp->comp == NULL)) {
xsltTransformError(ctxt, NULL, inst,
"Internal error in xsltForEach(): "
"The selecting expression of the XSLT 'for-each' "
"instruction was not compiled correctly.\n");
return;
}
xpctxt = ctxt->xpathCtxt;
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
"xsltForEach: select %s\n", comp->select));
#endif
/*
* Save context states.
*/
oldDocInfo = ctxt->document;
oldList = ctxt->nodeList;
oldContextNode = ctxt->node;
/*
* The "current template rule" is cleared for the instantiation of
* xsl:for-each.
*/
oldCurTemplRule = ctxt->currentTemplateRule;
ctxt->currentTemplateRule = NULL;
oldXPDoc = xpctxt->doc;
oldXPProximityPosition = xpctxt->proximityPosition;
oldXPContextSize = xpctxt->contextSize;
/*
* Set up XPath.
*/
xpctxt->node = contextNode;
#ifdef XSLT_REFACTORED
if (comp->inScopeNs != NULL) {
xpctxt->namespaces = comp->inScopeNs->list;
xpctxt->nsNr = comp->inScopeNs->xpathNumber;
} else {
xpctxt->namespaces = NULL;
xpctxt->nsNr = 0;
}
#else
xpctxt->namespaces = comp->nsList;
xpctxt->nsNr = comp->nsNr;
#endif
/*
* Evaluate the 'select' expression.
*/
res = xmlXPathCompiledEval(comp->comp, ctxt->xpathCtxt);
if (res != NULL) {
if (res->type == XPATH_NODESET)
list = res->nodesetval;
else {
xsltTransformError(ctxt, NULL, inst,
"The 'select' expression does not evaluate to a node set.\n");
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
"xsltForEach: select didn't evaluate to a node list\n"));
#endif
goto error;
}
} else {
xsltTransformError(ctxt, NULL, inst,
"Failed to evaluate the 'select' expression.\n");
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
if ((list == NULL) || (list->nodeNr <= 0))
goto exit;
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
"xsltForEach: select evaluates to %d nodes\n", list->nodeNr));
#endif
/*
* Restore XPath states for the "current node".
*/
xpctxt->contextSize = oldXPContextSize;
xpctxt->proximityPosition = oldXPProximityPosition;
xpctxt->node = contextNode;
/*
* Set the list; this has to be done already here for xsltDoSortFunction().
*/
ctxt->nodeList = list;
/*
* Handle xsl:sort instructions and skip them for further processing.
* BUG TODO: We are not using namespaced potentially defined on the
* xsl:sort element; XPath expression might fail.
*/
curInst = inst->children;
if (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) {
int nbsorts = 0;
xmlNodePtr sorts[XSLT_MAX_SORT];
sorts[nbsorts++] = curInst;
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(curInst, contextNode, NULL, ctxt);
#endif
curInst = curInst->next;
while (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) {
if (nbsorts >= XSLT_MAX_SORT) {
xsltTransformError(ctxt, NULL, curInst,
"The number of xsl:sort instructions exceeds the "
"maximum (%d) allowed by this processor.\n",
XSLT_MAX_SORT);
goto error;
} else {
sorts[nbsorts++] = curInst;
}
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(curInst, contextNode, NULL, ctxt);
#endif
curInst = curInst->next;
}
xsltDoSortFunction(ctxt, sorts, nbsorts);
}
xpctxt->contextSize = list->nodeNr;
/*
* Instantiate the sequence constructor for each selected node.
*/
for (i = 0; i < list->nodeNr; i++) {
cur = list->nodeTab[i];
/*
* The selected node becomes the "current node".
*/
ctxt->node = cur;
/*
* An xsl:for-each can change the current context doc.
* OPTIMIZE TODO: Get rid of the need to set the context doc.
*/
if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL))
xpctxt->doc = cur->doc;
xpctxt->proximityPosition = i + 1;
xsltApplySequenceConstructor(ctxt, cur, curInst, NULL);
}
exit:
error:
if (res != NULL)
xmlXPathFreeObject(res);
/*
* Restore old states.
*/
ctxt->document = oldDocInfo;
ctxt->nodeList = oldList;
ctxt->node = oldContextNode;
ctxt->currentTemplateRule = oldCurTemplRule;
xpctxt->doc = oldXPDoc;
xpctxt->contextSize = oldXPContextSize;
xpctxt->proximityPosition = oldXPProximityPosition;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
xmlNodePtr inst, xsltStylePreCompPtr castedComp)
{
#ifdef XSLT_REFACTORED
xsltStyleItemForEachPtr comp = (xsltStyleItemForEachPtr) castedComp;
#else
xsltStylePreCompPtr comp = castedComp;
#endif
int i;
xmlXPathObjectPtr res = NULL;
xmlNodePtr cur, curInst;
xmlNodeSetPtr list = NULL;
xmlNodeSetPtr oldList;
int oldXPProximityPosition, oldXPContextSize;
xmlNodePtr oldContextNode;
xsltTemplatePtr oldCurTemplRule;
xmlDocPtr oldXPDoc;
xsltDocumentPtr oldDocInfo;
xmlXPathContextPtr xpctxt;
if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) {
xsltGenericError(xsltGenericErrorContext,
"xsltForEach(): Bad arguments.\n");
return;
}
if (comp == NULL) {
xsltTransformError(ctxt, NULL, inst,
"Internal error in xsltForEach(): "
"The XSLT 'for-each' instruction was not compiled.\n");
return;
}
if ((comp->select == NULL) || (comp->comp == NULL)) {
xsltTransformError(ctxt, NULL, inst,
"Internal error in xsltForEach(): "
"The selecting expression of the XSLT 'for-each' "
"instruction was not compiled correctly.\n");
return;
}
xpctxt = ctxt->xpathCtxt;
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
"xsltForEach: select %s\n", comp->select));
#endif
/*
* Save context states.
*/
oldDocInfo = ctxt->document;
oldList = ctxt->nodeList;
oldContextNode = ctxt->node;
/*
* The "current template rule" is cleared for the instantiation of
* xsl:for-each.
*/
oldCurTemplRule = ctxt->currentTemplateRule;
ctxt->currentTemplateRule = NULL;
oldXPDoc = xpctxt->doc;
oldXPProximityPosition = xpctxt->proximityPosition;
oldXPContextSize = xpctxt->contextSize;
/*
* Evaluate the 'select' expression.
*/
res = xsltPreCompEval(ctxt, contextNode, comp);
if (res != NULL) {
if (res->type == XPATH_NODESET)
list = res->nodesetval;
else {
xsltTransformError(ctxt, NULL, inst,
"The 'select' expression does not evaluate to a node set.\n");
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
"xsltForEach: select didn't evaluate to a node list\n"));
#endif
goto error;
}
} else {
xsltTransformError(ctxt, NULL, inst,
"Failed to evaluate the 'select' expression.\n");
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
if ((list == NULL) || (list->nodeNr <= 0))
goto exit;
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext,
"xsltForEach: select evaluates to %d nodes\n", list->nodeNr));
#endif
/*
* Set the list; this has to be done already here for xsltDoSortFunction().
*/
ctxt->nodeList = list;
/*
* Handle xsl:sort instructions and skip them for further processing.
* BUG TODO: We are not using namespaced potentially defined on the
* xsl:sort element; XPath expression might fail.
*/
curInst = inst->children;
if (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) {
int nbsorts = 0;
xmlNodePtr sorts[XSLT_MAX_SORT];
sorts[nbsorts++] = curInst;
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(curInst, contextNode, NULL, ctxt);
#endif
curInst = curInst->next;
while (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) {
if (nbsorts >= XSLT_MAX_SORT) {
xsltTransformError(ctxt, NULL, curInst,
"The number of xsl:sort instructions exceeds the "
"maximum (%d) allowed by this processor.\n",
XSLT_MAX_SORT);
goto error;
} else {
sorts[nbsorts++] = curInst;
}
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(curInst, contextNode, NULL, ctxt);
#endif
curInst = curInst->next;
}
xsltDoSortFunction(ctxt, sorts, nbsorts);
}
xpctxt->contextSize = list->nodeNr;
/*
* Instantiate the sequence constructor for each selected node.
*/
for (i = 0; i < list->nodeNr; i++) {
cur = list->nodeTab[i];
/*
* The selected node becomes the "current node".
*/
ctxt->node = cur;
/*
* An xsl:for-each can change the current context doc.
* OPTIMIZE TODO: Get rid of the need to set the context doc.
*/
if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL))
xpctxt->doc = cur->doc;
xpctxt->proximityPosition = i + 1;
xsltApplySequenceConstructor(ctxt, cur, curInst, NULL);
}
exit:
error:
if (res != NULL)
xmlXPathFreeObject(res);
/*
* Restore old states.
*/
ctxt->document = oldDocInfo;
ctxt->nodeList = oldList;
ctxt->node = oldContextNode;
ctxt->currentTemplateRule = oldCurTemplRule;
xpctxt->doc = oldXPDoc;
xpctxt->contextSize = oldXPContextSize;
xpctxt->proximityPosition = oldXPProximityPosition;
}
| 173,327 |
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: SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
{
struct fs_struct *fs, *new_fs = NULL;
struct files_struct *fd, *new_fd = NULL;
struct cred *new_cred = NULL;
struct nsproxy *new_nsproxy = NULL;
int do_sysvsem = 0;
int err;
/*
* If unsharing a user namespace must also unshare the thread.
*/
if (unshare_flags & CLONE_NEWUSER)
unshare_flags |= CLONE_THREAD;
/*
* If unsharing a pid namespace must also unshare the thread.
*/
if (unshare_flags & CLONE_NEWPID)
unshare_flags |= CLONE_THREAD;
/*
* If unsharing a thread from a thread group, must also unshare vm.
*/
if (unshare_flags & CLONE_THREAD)
unshare_flags |= CLONE_VM;
/*
* If unsharing vm, must also unshare signal handlers.
*/
if (unshare_flags & CLONE_VM)
unshare_flags |= CLONE_SIGHAND;
/*
* If unsharing namespace, must also unshare filesystem information.
*/
if (unshare_flags & CLONE_NEWNS)
unshare_flags |= CLONE_FS;
err = check_unshare_flags(unshare_flags);
if (err)
goto bad_unshare_out;
/*
* CLONE_NEWIPC must also detach from the undolist: after switching
* to a new ipc namespace, the semaphore arrays from the old
* namespace are unreachable.
*/
if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
do_sysvsem = 1;
err = unshare_fs(unshare_flags, &new_fs);
if (err)
goto bad_unshare_out;
err = unshare_fd(unshare_flags, &new_fd);
if (err)
goto bad_unshare_cleanup_fs;
err = unshare_userns(unshare_flags, &new_cred);
if (err)
goto bad_unshare_cleanup_fd;
err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
new_cred, new_fs);
if (err)
goto bad_unshare_cleanup_cred;
if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
if (do_sysvsem) {
/*
* CLONE_SYSVSEM is equivalent to sys_exit().
*/
exit_sem(current);
}
if (new_nsproxy)
switch_task_namespaces(current, new_nsproxy);
task_lock(current);
if (new_fs) {
fs = current->fs;
spin_lock(&fs->lock);
current->fs = new_fs;
if (--fs->users)
new_fs = NULL;
else
new_fs = fs;
spin_unlock(&fs->lock);
}
if (new_fd) {
fd = current->files;
current->files = new_fd;
new_fd = fd;
}
task_unlock(current);
if (new_cred) {
/* Install the new user namespace */
commit_creds(new_cred);
new_cred = NULL;
}
}
bad_unshare_cleanup_cred:
if (new_cred)
put_cred(new_cred);
bad_unshare_cleanup_fd:
if (new_fd)
put_files_struct(new_fd);
bad_unshare_cleanup_fs:
if (new_fs)
free_fs_struct(new_fs);
bad_unshare_out:
return err;
}
Commit Message: userns: Don't allow CLONE_NEWUSER | CLONE_FS
Don't allowing sharing the root directory with processes in a
different user namespace. There doesn't seem to be any point, and to
allow it would require the overhead of putting a user namespace
reference in fs_struct (for permission checks) and incrementing that
reference count on practically every call to fork.
So just perform the inexpensive test of forbidding sharing fs_struct
acrosss processes in different user namespaces. We already disallow
other forms of threading when unsharing a user namespace so this
should be no real burden in practice.
This updates setns, clone, and unshare to disallow multiple user
namespaces sharing an fs_struct.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
{
struct fs_struct *fs, *new_fs = NULL;
struct files_struct *fd, *new_fd = NULL;
struct cred *new_cred = NULL;
struct nsproxy *new_nsproxy = NULL;
int do_sysvsem = 0;
int err;
/*
* If unsharing a user namespace must also unshare the thread.
*/
if (unshare_flags & CLONE_NEWUSER)
unshare_flags |= CLONE_THREAD | CLONE_FS;
/*
* If unsharing a pid namespace must also unshare the thread.
*/
if (unshare_flags & CLONE_NEWPID)
unshare_flags |= CLONE_THREAD;
/*
* If unsharing a thread from a thread group, must also unshare vm.
*/
if (unshare_flags & CLONE_THREAD)
unshare_flags |= CLONE_VM;
/*
* If unsharing vm, must also unshare signal handlers.
*/
if (unshare_flags & CLONE_VM)
unshare_flags |= CLONE_SIGHAND;
/*
* If unsharing namespace, must also unshare filesystem information.
*/
if (unshare_flags & CLONE_NEWNS)
unshare_flags |= CLONE_FS;
err = check_unshare_flags(unshare_flags);
if (err)
goto bad_unshare_out;
/*
* CLONE_NEWIPC must also detach from the undolist: after switching
* to a new ipc namespace, the semaphore arrays from the old
* namespace are unreachable.
*/
if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
do_sysvsem = 1;
err = unshare_fs(unshare_flags, &new_fs);
if (err)
goto bad_unshare_out;
err = unshare_fd(unshare_flags, &new_fd);
if (err)
goto bad_unshare_cleanup_fs;
err = unshare_userns(unshare_flags, &new_cred);
if (err)
goto bad_unshare_cleanup_fd;
err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
new_cred, new_fs);
if (err)
goto bad_unshare_cleanup_cred;
if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
if (do_sysvsem) {
/*
* CLONE_SYSVSEM is equivalent to sys_exit().
*/
exit_sem(current);
}
if (new_nsproxy)
switch_task_namespaces(current, new_nsproxy);
task_lock(current);
if (new_fs) {
fs = current->fs;
spin_lock(&fs->lock);
current->fs = new_fs;
if (--fs->users)
new_fs = NULL;
else
new_fs = fs;
spin_unlock(&fs->lock);
}
if (new_fd) {
fd = current->files;
current->files = new_fd;
new_fd = fd;
}
task_unlock(current);
if (new_cred) {
/* Install the new user namespace */
commit_creds(new_cred);
new_cred = NULL;
}
}
bad_unshare_cleanup_cred:
if (new_cred)
put_cred(new_cred);
bad_unshare_cleanup_fd:
if (new_fd)
put_files_struct(new_fd);
bad_unshare_cleanup_fs:
if (new_fs)
free_fs_struct(new_fs);
bad_unshare_out:
return err;
}
| 166,106 |
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: mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t count = m->str_range;
uint32_t lhs;
int rv, oneed_separator, in_type;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, count) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o,
nbytes, count);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (in_type = cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[0] << 8) | p->hs[1];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[1] << 8) | p->hs[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[0] << 24) | (p->hl[1] << 16) |
(p->hl[2] << 8) | p->hl[3];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[3] << 24) | (p->hl[2] << 16) |
(p->hl[1] << 8) | p->hl[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[1] << 24) | (p->hl[0] << 16) |
(p->hl[3] << 8) | p->hl[2];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
default:
break;
}
switch (in_type) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (OFFSET_OOB(nbytes, offset, 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (OFFSET_OOB(nbytes, offset, m->vallen))
return 0;
break;
case FILE_REGEX:
if (nbytes < offset)
return 0;
break;
case FILE_INDIRECT:
if (offset == 0)
return 0;
if (nbytes < offset)
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
recursion_level, BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, F(ms, m, "%u"), offset) == -1) {
free(rbuf);
return -1;
}
if (file_printf(ms, "%s", rbuf) == -1) {
free(rbuf);
return -1;
}
}
free(rbuf);
return rv;
case FILE_USE:
if (nbytes < offset)
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
case FILE_CLEAR:
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
return 1;
}
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 | mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t lhs;
int rv, oneed_separator, in_type;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, m) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu)\n", m->type, m->flag, offset, o, nbytes);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (in_type = cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[0] << 8) | p->hs[1];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[1] << 8) | p->hs[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[0] << 24) | (p->hl[1] << 16) |
(p->hl[2] << 8) | p->hl[3];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[3] << 24) | (p->hl[2] << 16) |
(p->hl[1] << 8) | p->hl[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[1] << 24) | (p->hl[0] << 16) |
(p->hl[3] << 8) | p->hl[2];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
default:
break;
}
switch (in_type) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (OFFSET_OOB(nbytes, offset, 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (OFFSET_OOB(nbytes, offset, m->vallen))
return 0;
break;
case FILE_REGEX:
if (nbytes < offset)
return 0;
break;
case FILE_INDIRECT:
if (offset == 0)
return 0;
if (nbytes < offset)
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
recursion_level, BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, F(ms, m, "%u"), offset) == -1) {
free(rbuf);
return -1;
}
if (file_printf(ms, "%s", rbuf) == -1) {
free(rbuf);
return -1;
}
}
free(rbuf);
return rv;
case FILE_USE:
if (nbytes < offset)
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
case FILE_CLEAR:
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
return 1;
}
| 166,360 |
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 CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context,
MIMETypeCheck mime_type_check) const {
if (ErrorOccurred())
return false;
KURL sheet_url = GetResponse().Url();
if (sheet_url.IsLocalFile()) {
if (parser_context) {
parser_context->Count(WebFeature::kLocalCSSFile);
}
String extension;
int last_dot = sheet_url.LastPathComponent().ReverseFind('.');
if (last_dot != -1)
extension = sheet_url.LastPathComponent().Substring(last_dot + 1);
if (!EqualIgnoringASCIICase(
MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) {
if (parser_context) {
parser_context->CountDeprecation(
WebFeature::kLocalCSSFileExtensionRejected);
}
if (RuntimeEnabledFeatures::RequireCSSExtensionForFileEnabled()) {
return false;
}
}
}
if (mime_type_check == MIMETypeCheck::kLax)
return true;
AtomicString content_type = HttpContentType();
return content_type.IsEmpty() ||
DeprecatedEqualIgnoringCase(content_type, "text/css") ||
DeprecatedEqualIgnoringCase(content_type,
"application/x-unknown-content-type");
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Dave Tapuska <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254 | bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context,
MIMETypeCheck mime_type_check) const {
if (ErrorOccurred())
return false;
KURL sheet_url = GetResponse().Url();
if (sheet_url.IsLocalFile()) {
if (parser_context) {
parser_context->Count(WebFeature::kLocalCSSFile);
}
String extension;
int last_dot = sheet_url.LastPathComponent().ReverseFind('.');
if (last_dot != -1)
extension = sheet_url.LastPathComponent().Substring(last_dot + 1);
if (!EqualIgnoringASCIICase(
MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) {
if (parser_context) {
parser_context->CountDeprecation(
WebFeature::kLocalCSSFileExtensionRejected);
}
return false;
}
}
if (mime_type_check == MIMETypeCheck::kLax)
return true;
AtomicString content_type = HttpContentType();
return content_type.IsEmpty() ||
DeprecatedEqualIgnoringCase(content_type, "text/css") ||
DeprecatedEqualIgnoringCase(content_type,
"application/x-unknown-content-type");
}
| 173,186 |
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 WebLocalFrameImpl::LoadJavaScriptURL(const KURL& url) {
DCHECK(GetFrame());
Document* owner_document = GetFrame()->GetDocument();
if (!owner_document || !GetFrame()->GetPage())
return;
if (SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs(
owner_document->Url().Protocol()))
return;
String script = DecodeURLEscapeSequences(
url.GetString().Substring(strlen("javascript:")));
UserGestureIndicator gesture_indicator(
UserGestureToken::Create(owner_document, UserGestureToken::kNewGesture));
v8::HandleScope handle_scope(ToIsolate(GetFrame()));
v8::Local<v8::Value> result =
GetFrame()->GetScriptController().ExecuteScriptInMainWorldAndReturnValue(
ScriptSourceCode(script));
if (result.IsEmpty() || !result->IsString())
return;
String script_result = ToCoreString(v8::Local<v8::String>::Cast(result));
if (!GetFrame()->GetNavigationScheduler().LocationChangePending()) {
GetFrame()->Loader().ReplaceDocumentWhileExecutingJavaScriptURL(
script_result, owner_document);
}
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732 | void WebLocalFrameImpl::LoadJavaScriptURL(const KURL& url) {
DCHECK(GetFrame());
Document* owner_document = GetFrame()->GetDocument();
if (!owner_document || !GetFrame()->GetPage())
return;
if (SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs(
owner_document->Url().Protocol()))
return;
String script = DecodeURLEscapeSequences(
url.GetString().Substring(strlen("javascript:")));
UserGestureIndicator gesture_indicator(
UserGestureToken::Create(owner_document, UserGestureToken::kNewGesture));
v8::HandleScope handle_scope(ToIsolate(GetFrame()));
v8::Local<v8::Value> result =
GetFrame()->GetScriptController().ExecuteScriptInMainWorldAndReturnValue(
ScriptSourceCode(script));
if (result.IsEmpty() || !result->IsString())
return;
String script_result = ToCoreString(v8::Local<v8::String>::Cast(result));
if (!GetFrame()->GetNavigationScheduler().LocationChangePending()) {
GetFrame()->Loader().ReplaceDocumentWhileExecutingJavaScriptURL(
script_result, owner_document);
}
}
| 172,301 |
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 ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE || pg > 6) {
return -1;
}
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
if (pg == 6) {
return -1; /* avoid page pg + 1 */
}
ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK);
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
Commit Message:
CWE ID: CWE-399 | static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE || pg > 6) {
return -1;
}
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
if (pg == 6) {
qemu_sglist_destroy(&ehci->isgl);
return -1; /* avoid page pg + 1 */
}
ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK);
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
| 164,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: void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
phaseFrac = (EAS_I32)pWTVoice->phaseFrac;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119 | void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
phaseFrac = (EAS_I32)pWTVoice->phaseFrac;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
| 173,919 |
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 sk_buff *ipv6_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
struct ipv6hdr *ipv6h;
const struct net_offload *ops;
int proto;
struct frag_hdr *fptr;
unsigned int unfrag_ip6hlen;
unsigned int payload_len;
u8 *prevhdr;
int offset = 0;
bool encap, udpfrag;
int nhoff;
bool gso_partial;
skb_reset_network_header(skb);
nhoff = skb_network_header(skb) - skb_mac_header(skb);
if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h))))
goto out;
encap = SKB_GSO_CB(skb)->encap_level > 0;
if (encap)
features &= skb->dev->hw_enc_features;
SKB_GSO_CB(skb)->encap_level += sizeof(*ipv6h);
ipv6h = ipv6_hdr(skb);
__skb_pull(skb, sizeof(*ipv6h));
segs = ERR_PTR(-EPROTONOSUPPORT);
proto = ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr);
if (skb->encapsulation &&
skb_shinfo(skb)->gso_type & (SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6))
udpfrag = proto == IPPROTO_UDP && encap;
else
udpfrag = proto == IPPROTO_UDP && !skb->encapsulation;
ops = rcu_dereference(inet6_offloads[proto]);
if (likely(ops && ops->callbacks.gso_segment)) {
skb_reset_transport_header(skb);
segs = ops->callbacks.gso_segment(skb, features);
}
if (IS_ERR_OR_NULL(segs))
goto out;
gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL);
for (skb = segs; skb; skb = skb->next) {
ipv6h = (struct ipv6hdr *)(skb_mac_header(skb) + nhoff);
if (gso_partial)
payload_len = skb_shinfo(skb)->gso_size +
SKB_GSO_CB(skb)->data_offset +
skb->head - (unsigned char *)(ipv6h + 1);
else
payload_len = skb->len - nhoff - sizeof(*ipv6h);
ipv6h->payload_len = htons(payload_len);
skb->network_header = (u8 *)ipv6h - skb->head;
if (udpfrag) {
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
fptr = (struct frag_hdr *)((u8 *)ipv6h + unfrag_ip6hlen);
fptr->frag_off = htons(offset);
if (skb->next)
fptr->frag_off |= htons(IP6_MF);
offset += (ntohs(ipv6h->payload_len) -
sizeof(struct frag_hdr));
}
if (encap)
skb_reset_inner_headers(skb);
}
out:
return segs;
}
Commit Message: ipv6: Prevent overrun when parsing v6 header options
The KASAN warning repoted below was discovered with a syzkaller
program. The reproducer is basically:
int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP);
send(s, &one_byte_of_data, 1, MSG_MORE);
send(s, &more_than_mtu_bytes_data, 2000, 0);
The socket() call sets the nexthdr field of the v6 header to
NEXTHDR_HOP, the first send call primes the payload with a non zero
byte of data, and the second send call triggers the fragmentation path.
The fragmentation code tries to parse the header options in order
to figure out where to insert the fragment option. Since nexthdr points
to an invalid option, the calculation of the size of the network header
can made to be much larger than the linear section of the skb and data
is read outside of it.
This fix makes ip6_find_1stfrag return an error if it detects
running out-of-bounds.
[ 42.361487] ==================================================================
[ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730
[ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789
[ 42.366469]
[ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41
[ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014
[ 42.368824] Call Trace:
[ 42.369183] dump_stack+0xb3/0x10b
[ 42.369664] print_address_description+0x73/0x290
[ 42.370325] kasan_report+0x252/0x370
[ 42.370839] ? ip6_fragment+0x11c8/0x3730
[ 42.371396] check_memory_region+0x13c/0x1a0
[ 42.371978] memcpy+0x23/0x50
[ 42.372395] ip6_fragment+0x11c8/0x3730
[ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110
[ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0
[ 42.374263] ? ip6_forward+0x2e30/0x2e30
[ 42.374803] ip6_finish_output+0x584/0x990
[ 42.375350] ip6_output+0x1b7/0x690
[ 42.375836] ? ip6_finish_output+0x990/0x990
[ 42.376411] ? ip6_fragment+0x3730/0x3730
[ 42.376968] ip6_local_out+0x95/0x160
[ 42.377471] ip6_send_skb+0xa1/0x330
[ 42.377969] ip6_push_pending_frames+0xb3/0xe0
[ 42.378589] rawv6_sendmsg+0x2051/0x2db0
[ 42.379129] ? rawv6_bind+0x8b0/0x8b0
[ 42.379633] ? _copy_from_user+0x84/0xe0
[ 42.380193] ? debug_check_no_locks_freed+0x290/0x290
[ 42.380878] ? ___sys_sendmsg+0x162/0x930
[ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120
[ 42.382074] ? sock_has_perm+0x1f6/0x290
[ 42.382614] ? ___sys_sendmsg+0x167/0x930
[ 42.383173] ? lock_downgrade+0x660/0x660
[ 42.383727] inet_sendmsg+0x123/0x500
[ 42.384226] ? inet_sendmsg+0x123/0x500
[ 42.384748] ? inet_recvmsg+0x540/0x540
[ 42.385263] sock_sendmsg+0xca/0x110
[ 42.385758] SYSC_sendto+0x217/0x380
[ 42.386249] ? SYSC_connect+0x310/0x310
[ 42.386783] ? __might_fault+0x110/0x1d0
[ 42.387324] ? lock_downgrade+0x660/0x660
[ 42.387880] ? __fget_light+0xa1/0x1f0
[ 42.388403] ? __fdget+0x18/0x20
[ 42.388851] ? sock_common_setsockopt+0x95/0xd0
[ 42.389472] ? SyS_setsockopt+0x17f/0x260
[ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe
[ 42.390650] SyS_sendto+0x40/0x50
[ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.391731] RIP: 0033:0x7fbbb711e383
[ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c
[ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383
[ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003
[ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018
[ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad
[ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00
[ 42.397257]
[ 42.397411] Allocated by task 3789:
[ 42.397702] save_stack_trace+0x16/0x20
[ 42.398005] save_stack+0x46/0xd0
[ 42.398267] kasan_kmalloc+0xad/0xe0
[ 42.398548] kasan_slab_alloc+0x12/0x20
[ 42.398848] __kmalloc_node_track_caller+0xcb/0x380
[ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0
[ 42.399654] __alloc_skb+0xf8/0x580
[ 42.400003] sock_wmalloc+0xab/0xf0
[ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0
[ 42.400813] ip6_append_data+0x1a8/0x2f0
[ 42.401122] rawv6_sendmsg+0x11ee/0x2db0
[ 42.401505] inet_sendmsg+0x123/0x500
[ 42.401860] sock_sendmsg+0xca/0x110
[ 42.402209] ___sys_sendmsg+0x7cb/0x930
[ 42.402582] __sys_sendmsg+0xd9/0x190
[ 42.402941] SyS_sendmsg+0x2d/0x50
[ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.403718]
[ 42.403871] Freed by task 1794:
[ 42.404146] save_stack_trace+0x16/0x20
[ 42.404515] save_stack+0x46/0xd0
[ 42.404827] kasan_slab_free+0x72/0xc0
[ 42.405167] kfree+0xe8/0x2b0
[ 42.405462] skb_free_head+0x74/0xb0
[ 42.405806] skb_release_data+0x30e/0x3a0
[ 42.406198] skb_release_all+0x4a/0x60
[ 42.406563] consume_skb+0x113/0x2e0
[ 42.406910] skb_free_datagram+0x1a/0xe0
[ 42.407288] netlink_recvmsg+0x60d/0xe40
[ 42.407667] sock_recvmsg+0xd7/0x110
[ 42.408022] ___sys_recvmsg+0x25c/0x580
[ 42.408395] __sys_recvmsg+0xd6/0x190
[ 42.408753] SyS_recvmsg+0x2d/0x50
[ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.409513]
[ 42.409665] The buggy address belongs to the object at ffff88000969e780
[ 42.409665] which belongs to the cache kmalloc-512 of size 512
[ 42.410846] The buggy address is located 24 bytes inside of
[ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980)
[ 42.411941] The buggy address belongs to the page:
[ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0
[ 42.413298] flags: 0x100000000008100(slab|head)
[ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c
[ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000
[ 42.415074] page dumped because: kasan: bad access detected
[ 42.415604]
[ 42.415757] Memory state around the buggy address:
[ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 42.418273] ^
[ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419882] ==================================================================
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Craig Gallek <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125 | static struct sk_buff *ipv6_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
struct ipv6hdr *ipv6h;
const struct net_offload *ops;
int proto;
struct frag_hdr *fptr;
unsigned int unfrag_ip6hlen;
unsigned int payload_len;
u8 *prevhdr;
int offset = 0;
bool encap, udpfrag;
int nhoff;
bool gso_partial;
skb_reset_network_header(skb);
nhoff = skb_network_header(skb) - skb_mac_header(skb);
if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h))))
goto out;
encap = SKB_GSO_CB(skb)->encap_level > 0;
if (encap)
features &= skb->dev->hw_enc_features;
SKB_GSO_CB(skb)->encap_level += sizeof(*ipv6h);
ipv6h = ipv6_hdr(skb);
__skb_pull(skb, sizeof(*ipv6h));
segs = ERR_PTR(-EPROTONOSUPPORT);
proto = ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr);
if (skb->encapsulation &&
skb_shinfo(skb)->gso_type & (SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6))
udpfrag = proto == IPPROTO_UDP && encap;
else
udpfrag = proto == IPPROTO_UDP && !skb->encapsulation;
ops = rcu_dereference(inet6_offloads[proto]);
if (likely(ops && ops->callbacks.gso_segment)) {
skb_reset_transport_header(skb);
segs = ops->callbacks.gso_segment(skb, features);
}
if (IS_ERR_OR_NULL(segs))
goto out;
gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL);
for (skb = segs; skb; skb = skb->next) {
ipv6h = (struct ipv6hdr *)(skb_mac_header(skb) + nhoff);
if (gso_partial)
payload_len = skb_shinfo(skb)->gso_size +
SKB_GSO_CB(skb)->data_offset +
skb->head - (unsigned char *)(ipv6h + 1);
else
payload_len = skb->len - nhoff - sizeof(*ipv6h);
ipv6h->payload_len = htons(payload_len);
skb->network_header = (u8 *)ipv6h - skb->head;
if (udpfrag) {
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
if (unfrag_ip6hlen < 0)
return ERR_PTR(unfrag_ip6hlen);
fptr = (struct frag_hdr *)((u8 *)ipv6h + unfrag_ip6hlen);
fptr->frag_off = htons(offset);
if (skb->next)
fptr->frag_off |= htons(IP6_MF);
offset += (ntohs(ipv6h->payload_len) -
sizeof(struct frag_hdr));
}
if (encap)
skb_reset_inner_headers(skb);
}
out:
return segs;
}
| 168,130 |
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: Cues::Cues(
Segment* pSegment,
long long start_,
long long size_,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_start(start_),
m_size(size_),
m_element_start(element_start),
m_element_size(element_size),
m_cue_points(NULL),
m_count(0),
m_preload_count(0),
m_pos(start_)
{
}
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 | Cues::Cues(
Cues::~Cues() {
const long n = m_count + m_preload_count;
CuePoint** p = m_cue_points;
CuePoint** const q = p + n;
while (p != q) {
CuePoint* const pCP = *p++;
assert(pCP);
delete pCP;
}
delete[] m_cue_points;
}
| 174,262 |
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 ssize_t qib_write(struct file *fp, const char __user *data,
size_t count, loff_t *off)
{
const struct qib_cmd __user *ucmd;
struct qib_ctxtdata *rcd;
const void __user *src;
size_t consumed, copy = 0;
struct qib_cmd cmd;
ssize_t ret = 0;
void *dest;
if (count < sizeof(cmd.type)) {
ret = -EINVAL;
goto bail;
}
ucmd = (const struct qib_cmd __user *) data;
if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) {
ret = -EFAULT;
goto bail;
}
consumed = sizeof(cmd.type);
switch (cmd.type) {
case QIB_CMD_ASSIGN_CTXT:
case QIB_CMD_USER_INIT:
copy = sizeof(cmd.cmd.user_info);
dest = &cmd.cmd.user_info;
src = &ucmd->cmd.user_info;
break;
case QIB_CMD_RECV_CTRL:
copy = sizeof(cmd.cmd.recv_ctrl);
dest = &cmd.cmd.recv_ctrl;
src = &ucmd->cmd.recv_ctrl;
break;
case QIB_CMD_CTXT_INFO:
copy = sizeof(cmd.cmd.ctxt_info);
dest = &cmd.cmd.ctxt_info;
src = &ucmd->cmd.ctxt_info;
break;
case QIB_CMD_TID_UPDATE:
case QIB_CMD_TID_FREE:
copy = sizeof(cmd.cmd.tid_info);
dest = &cmd.cmd.tid_info;
src = &ucmd->cmd.tid_info;
break;
case QIB_CMD_SET_PART_KEY:
copy = sizeof(cmd.cmd.part_key);
dest = &cmd.cmd.part_key;
src = &ucmd->cmd.part_key;
break;
case QIB_CMD_DISARM_BUFS:
case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */
copy = 0;
src = NULL;
dest = NULL;
break;
case QIB_CMD_POLL_TYPE:
copy = sizeof(cmd.cmd.poll_type);
dest = &cmd.cmd.poll_type;
src = &ucmd->cmd.poll_type;
break;
case QIB_CMD_ARMLAUNCH_CTRL:
copy = sizeof(cmd.cmd.armlaunch_ctrl);
dest = &cmd.cmd.armlaunch_ctrl;
src = &ucmd->cmd.armlaunch_ctrl;
break;
case QIB_CMD_SDMA_INFLIGHT:
copy = sizeof(cmd.cmd.sdma_inflight);
dest = &cmd.cmd.sdma_inflight;
src = &ucmd->cmd.sdma_inflight;
break;
case QIB_CMD_SDMA_COMPLETE:
copy = sizeof(cmd.cmd.sdma_complete);
dest = &cmd.cmd.sdma_complete;
src = &ucmd->cmd.sdma_complete;
break;
case QIB_CMD_ACK_EVENT:
copy = sizeof(cmd.cmd.event_mask);
dest = &cmd.cmd.event_mask;
src = &ucmd->cmd.event_mask;
break;
default:
ret = -EINVAL;
goto bail;
}
if (copy) {
if ((count - consumed) < copy) {
ret = -EINVAL;
goto bail;
}
if (copy_from_user(dest, src, copy)) {
ret = -EFAULT;
goto bail;
}
consumed += copy;
}
rcd = ctxt_fp(fp);
if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) {
ret = -EINVAL;
goto bail;
}
switch (cmd.type) {
case QIB_CMD_ASSIGN_CTXT:
ret = qib_assign_ctxt(fp, &cmd.cmd.user_info);
if (ret)
goto bail;
break;
case QIB_CMD_USER_INIT:
ret = qib_do_user_init(fp, &cmd.cmd.user_info);
if (ret)
goto bail;
ret = qib_get_base_info(fp, (void __user *) (unsigned long)
cmd.cmd.user_info.spu_base_info,
cmd.cmd.user_info.spu_base_info_size);
break;
case QIB_CMD_RECV_CTRL:
ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl);
break;
case QIB_CMD_CTXT_INFO:
ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *)
(unsigned long) cmd.cmd.ctxt_info);
break;
case QIB_CMD_TID_UPDATE:
ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info);
break;
case QIB_CMD_TID_FREE:
ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info);
break;
case QIB_CMD_SET_PART_KEY:
ret = qib_set_part_key(rcd, cmd.cmd.part_key);
break;
case QIB_CMD_DISARM_BUFS:
(void)qib_disarm_piobufs_ifneeded(rcd);
ret = disarm_req_delay(rcd);
break;
case QIB_CMD_PIOAVAILUPD:
qib_force_pio_avail_update(rcd->dd);
break;
case QIB_CMD_POLL_TYPE:
rcd->poll_type = cmd.cmd.poll_type;
break;
case QIB_CMD_ARMLAUNCH_CTRL:
rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl);
break;
case QIB_CMD_SDMA_INFLIGHT:
ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp),
(u32 __user *) (unsigned long)
cmd.cmd.sdma_inflight);
break;
case QIB_CMD_SDMA_COMPLETE:
ret = qib_sdma_get_complete(rcd->ppd,
user_sdma_queue_fp(fp),
(u32 __user *) (unsigned long)
cmd.cmd.sdma_complete);
break;
case QIB_CMD_ACK_EVENT:
ret = qib_user_event_ack(rcd, subctxt_fp(fp),
cmd.cmd.event_mask);
break;
}
if (ret >= 0)
ret = consumed;
bail:
return ret;
}
Commit Message: IB/security: Restrict use of the write() interface
The drivers/infiniband stack uses write() as a replacement for
bi-directional ioctl(). This is not safe. There are ways to
trigger write calls that result in the return structure that
is normally written to user space being shunted off to user
specified kernel memory instead.
For the immediate repair, detect and deny suspicious accesses to
the write API.
For long term, update the user space libraries and the kernel API
to something that doesn't present the same security vulnerabilities
(likely a structured ioctl() interface).
The impacted uAPI interfaces are generally only available if
hardware from drivers/infiniband is installed in the system.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
[ Expanded check to all known write() entry points ]
Cc: [email protected]
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-264 | static ssize_t qib_write(struct file *fp, const char __user *data,
size_t count, loff_t *off)
{
const struct qib_cmd __user *ucmd;
struct qib_ctxtdata *rcd;
const void __user *src;
size_t consumed, copy = 0;
struct qib_cmd cmd;
ssize_t ret = 0;
void *dest;
if (WARN_ON_ONCE(!ib_safe_file_access(fp)))
return -EACCES;
if (count < sizeof(cmd.type)) {
ret = -EINVAL;
goto bail;
}
ucmd = (const struct qib_cmd __user *) data;
if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) {
ret = -EFAULT;
goto bail;
}
consumed = sizeof(cmd.type);
switch (cmd.type) {
case QIB_CMD_ASSIGN_CTXT:
case QIB_CMD_USER_INIT:
copy = sizeof(cmd.cmd.user_info);
dest = &cmd.cmd.user_info;
src = &ucmd->cmd.user_info;
break;
case QIB_CMD_RECV_CTRL:
copy = sizeof(cmd.cmd.recv_ctrl);
dest = &cmd.cmd.recv_ctrl;
src = &ucmd->cmd.recv_ctrl;
break;
case QIB_CMD_CTXT_INFO:
copy = sizeof(cmd.cmd.ctxt_info);
dest = &cmd.cmd.ctxt_info;
src = &ucmd->cmd.ctxt_info;
break;
case QIB_CMD_TID_UPDATE:
case QIB_CMD_TID_FREE:
copy = sizeof(cmd.cmd.tid_info);
dest = &cmd.cmd.tid_info;
src = &ucmd->cmd.tid_info;
break;
case QIB_CMD_SET_PART_KEY:
copy = sizeof(cmd.cmd.part_key);
dest = &cmd.cmd.part_key;
src = &ucmd->cmd.part_key;
break;
case QIB_CMD_DISARM_BUFS:
case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */
copy = 0;
src = NULL;
dest = NULL;
break;
case QIB_CMD_POLL_TYPE:
copy = sizeof(cmd.cmd.poll_type);
dest = &cmd.cmd.poll_type;
src = &ucmd->cmd.poll_type;
break;
case QIB_CMD_ARMLAUNCH_CTRL:
copy = sizeof(cmd.cmd.armlaunch_ctrl);
dest = &cmd.cmd.armlaunch_ctrl;
src = &ucmd->cmd.armlaunch_ctrl;
break;
case QIB_CMD_SDMA_INFLIGHT:
copy = sizeof(cmd.cmd.sdma_inflight);
dest = &cmd.cmd.sdma_inflight;
src = &ucmd->cmd.sdma_inflight;
break;
case QIB_CMD_SDMA_COMPLETE:
copy = sizeof(cmd.cmd.sdma_complete);
dest = &cmd.cmd.sdma_complete;
src = &ucmd->cmd.sdma_complete;
break;
case QIB_CMD_ACK_EVENT:
copy = sizeof(cmd.cmd.event_mask);
dest = &cmd.cmd.event_mask;
src = &ucmd->cmd.event_mask;
break;
default:
ret = -EINVAL;
goto bail;
}
if (copy) {
if ((count - consumed) < copy) {
ret = -EINVAL;
goto bail;
}
if (copy_from_user(dest, src, copy)) {
ret = -EFAULT;
goto bail;
}
consumed += copy;
}
rcd = ctxt_fp(fp);
if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) {
ret = -EINVAL;
goto bail;
}
switch (cmd.type) {
case QIB_CMD_ASSIGN_CTXT:
ret = qib_assign_ctxt(fp, &cmd.cmd.user_info);
if (ret)
goto bail;
break;
case QIB_CMD_USER_INIT:
ret = qib_do_user_init(fp, &cmd.cmd.user_info);
if (ret)
goto bail;
ret = qib_get_base_info(fp, (void __user *) (unsigned long)
cmd.cmd.user_info.spu_base_info,
cmd.cmd.user_info.spu_base_info_size);
break;
case QIB_CMD_RECV_CTRL:
ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl);
break;
case QIB_CMD_CTXT_INFO:
ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *)
(unsigned long) cmd.cmd.ctxt_info);
break;
case QIB_CMD_TID_UPDATE:
ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info);
break;
case QIB_CMD_TID_FREE:
ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info);
break;
case QIB_CMD_SET_PART_KEY:
ret = qib_set_part_key(rcd, cmd.cmd.part_key);
break;
case QIB_CMD_DISARM_BUFS:
(void)qib_disarm_piobufs_ifneeded(rcd);
ret = disarm_req_delay(rcd);
break;
case QIB_CMD_PIOAVAILUPD:
qib_force_pio_avail_update(rcd->dd);
break;
case QIB_CMD_POLL_TYPE:
rcd->poll_type = cmd.cmd.poll_type;
break;
case QIB_CMD_ARMLAUNCH_CTRL:
rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl);
break;
case QIB_CMD_SDMA_INFLIGHT:
ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp),
(u32 __user *) (unsigned long)
cmd.cmd.sdma_inflight);
break;
case QIB_CMD_SDMA_COMPLETE:
ret = qib_sdma_get_complete(rcd->ppd,
user_sdma_queue_fp(fp),
(u32 __user *) (unsigned long)
cmd.cmd.sdma_complete);
break;
case QIB_CMD_ACK_EVENT:
ret = qib_user_event_ack(rcd, subctxt_fp(fp),
cmd.cmd.event_mask);
break;
}
if (ret >= 0)
ret = consumed;
bail:
return ret;
}
| 167,241 |
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 impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip,
impeg2d_video_decode_op_t *ps_op)
{
UWORD32 u4_bits_read;
dec_state_t *ps_dec;
UWORD32 u4_size = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
ps_dec = (dec_state_t *)pv_dec;
ps_op->s_ivd_video_decode_op_t.u4_error_code = 0;
if (u4_size > MAX_BITSTREAM_BUFFER_SIZE)
{
u4_size = MAX_BITSTREAM_BUFFER_SIZE;
}
memcpy(ps_dec->pu1_input_buffer, ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, u4_size);
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), ps_dec->pu1_input_buffer,
u4_size);
{
{
IMPEG2D_ERROR_CODES_T e_error;
e_error = impeg2d_process_video_header(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0)
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0;
ps_dec->u2_header_done = 0;
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width;
}
impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE);
return;
}
}
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size;
ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0;
/* MOD */
ps_dec->u2_header_done = 1;
}
}
Commit Message: Adding check for min_width and min_height
Add check for min_wd and min_ht. Stride is updated if header
decode is done.
Bug: 74078669
Change-Id: Ided95395e1138335dbb4b05131a8551f6f7bbfcd
(cherry picked from commit 84eba4863dd50083951db83ea3cc81e015bf51da)
CWE ID: CWE-787 | void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip,
impeg2d_video_decode_op_t *ps_op)
{
UWORD32 u4_bits_read;
dec_state_t *ps_dec;
UWORD32 u4_size = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
ps_dec = (dec_state_t *)pv_dec;
ps_op->s_ivd_video_decode_op_t.u4_error_code = 0;
if (u4_size > MAX_BITSTREAM_BUFFER_SIZE)
{
u4_size = MAX_BITSTREAM_BUFFER_SIZE;
}
memcpy(ps_dec->pu1_input_buffer, ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, u4_size);
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), ps_dec->pu1_input_buffer,
u4_size);
{
{
IMPEG2D_ERROR_CODES_T e_error;
e_error = impeg2d_process_video_header(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0)
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0;
ps_dec->u2_header_done = 0;
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width;
}
impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE);
return;
}
}
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size;
ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0;
/* Set the stride */
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = ps_dec->u2_horizontal_size;
}
/* MOD */
ps_dec->u2_header_done = 1;
}
}
| 174,086 |
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 WebMediaPlayerMS::HasSingleSecurityOrigin() const {
DCHECK(thread_checker_.CalledOnValidThread());
return true;
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool WebMediaPlayerMS::HasSingleSecurityOrigin() const {
| 172,622 |
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 cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)
{
int ret;
/* MBIM backwards compatible function? */
if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)
return -ENODEV;
/* The NCM data altsetting is fixed, so we hard-coded it.
* Additionally, generic NCM devices are assumed to accept arbitrarily
* placed NDP.
*/
ret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0);
/*
* We should get an event when network connection is "connected" or
* "disconnected". Set network connection in "disconnected" state
* (carrier is OFF) during attach, so the IP network stack does not
* start IPv6 negotiation and more.
*/
usbnet_link_change(dev, 0, 0);
return ret;
}
Commit Message: cdc_ncm: do not call usbnet_link_change from cdc_ncm_bind
usbnet_link_change will call schedule_work and should be
avoided if bind is failing. Otherwise we will end up with
scheduled work referring to a netdev which has gone away.
Instead of making the call conditional, we can just defer
it to usbnet_probe, using the driver_info flag made for
this purpose.
Fixes: 8a34b0ae8778 ("usbnet: cdc_ncm: apply usbnet_link_change")
Reported-by: Andrey Konovalov <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Bjørn Mork <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)
{
/* MBIM backwards compatible function? */
if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)
return -ENODEV;
/* The NCM data altsetting is fixed, so we hard-coded it.
* Additionally, generic NCM devices are assumed to accept arbitrarily
* placed NDP.
*/
return cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0);
}
| 167,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 MagickBooleanType WriteCALSImage(const ImageInfo *image_info,
Image *image)
{
char
header[MaxTextExtent];
Image
*group4_image;
ImageInfo
*write_info;
MagickBooleanType
status;
register ssize_t
i;
size_t
density,
length,
orient_x,
orient_y;
ssize_t
count;
unsigned char
*group4;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Create standard CALS header.
*/
count=WriteCALSRecord(image,"srcdocid: NONE");
(void) count;
count=WriteCALSRecord(image,"dstdocid: NONE");
count=WriteCALSRecord(image,"txtfilid: NONE");
count=WriteCALSRecord(image,"figid: NONE");
count=WriteCALSRecord(image,"srcgph: NONE");
count=WriteCALSRecord(image,"doccls: NONE");
count=WriteCALSRecord(image,"rtype: 1");
orient_x=0;
orient_y=0;
switch (image->orientation)
{
case TopRightOrientation:
{
orient_x=180;
orient_y=270;
break;
}
case BottomRightOrientation:
{
orient_x=180;
orient_y=90;
break;
}
case BottomLeftOrientation:
{
orient_y=90;
break;
}
case LeftTopOrientation:
{
orient_x=270;
break;
}
case RightTopOrientation:
{
orient_x=270;
orient_y=180;
break;
}
case RightBottomOrientation:
{
orient_x=90;
orient_y=180;
break;
}
case LeftBottomOrientation:
{
orient_x=90;
break;
}
default:
{
orient_y=270;
break;
}
}
(void) FormatLocaleString(header,sizeof(header),"rorient: %03ld,%03ld",
(long) orient_x,(long) orient_y);
count=WriteCALSRecord(image,header);
(void) FormatLocaleString(header,sizeof(header),"rpelcnt: %06lu,%06lu",
(unsigned long) image->columns,(unsigned long) image->rows);
count=WriteCALSRecord(image,header);
density=200;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
(void) ParseGeometry(image_info->density,&geometry_info);
density=(size_t) floor(geometry_info.rho+0.5);
}
(void) FormatLocaleString(header,sizeof(header),"rdensty: %04lu",
(unsigned long) density);
count=WriteCALSRecord(image,header);
count=WriteCALSRecord(image,"notes: NONE");
(void) ResetMagickMemory(header,' ',128);
for (i=0; i < 5; i++)
(void) WriteBlob(image,128,(unsigned char *) header);
/*
Write CALS pixels.
*/
write_info=CloneImageInfo(image_info);
(void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent);
(void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent);
group4_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (group4_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,
&image->exception);
group4_image=DestroyImage(group4_image);
if (group4 == (unsigned char *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
write_info=DestroyImageInfo(write_info);
if (WriteBlob(image,length,group4) != (ssize_t) length)
status=MagickFalse;
group4=(unsigned char *) RelinquishMagickMemory(group4);
(void) CloseBlob(image);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/571
CWE ID: CWE-772 | static MagickBooleanType WriteCALSImage(const ImageInfo *image_info,
Image *image)
{
char
header[MaxTextExtent];
Image
*group4_image;
ImageInfo
*write_info;
MagickBooleanType
status;
register ssize_t
i;
size_t
density,
length,
orient_x,
orient_y;
ssize_t
count;
unsigned char
*group4;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Create standard CALS header.
*/
count=WriteCALSRecord(image,"srcdocid: NONE");
(void) count;
count=WriteCALSRecord(image,"dstdocid: NONE");
count=WriteCALSRecord(image,"txtfilid: NONE");
count=WriteCALSRecord(image,"figid: NONE");
count=WriteCALSRecord(image,"srcgph: NONE");
count=WriteCALSRecord(image,"doccls: NONE");
count=WriteCALSRecord(image,"rtype: 1");
orient_x=0;
orient_y=0;
switch (image->orientation)
{
case TopRightOrientation:
{
orient_x=180;
orient_y=270;
break;
}
case BottomRightOrientation:
{
orient_x=180;
orient_y=90;
break;
}
case BottomLeftOrientation:
{
orient_y=90;
break;
}
case LeftTopOrientation:
{
orient_x=270;
break;
}
case RightTopOrientation:
{
orient_x=270;
orient_y=180;
break;
}
case RightBottomOrientation:
{
orient_x=90;
orient_y=180;
break;
}
case LeftBottomOrientation:
{
orient_x=90;
break;
}
default:
{
orient_y=270;
break;
}
}
(void) FormatLocaleString(header,sizeof(header),"rorient: %03ld,%03ld",
(long) orient_x,(long) orient_y);
count=WriteCALSRecord(image,header);
(void) FormatLocaleString(header,sizeof(header),"rpelcnt: %06lu,%06lu",
(unsigned long) image->columns,(unsigned long) image->rows);
count=WriteCALSRecord(image,header);
density=200;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
(void) ParseGeometry(image_info->density,&geometry_info);
density=(size_t) floor(geometry_info.rho+0.5);
}
(void) FormatLocaleString(header,sizeof(header),"rdensty: %04lu",
(unsigned long) density);
count=WriteCALSRecord(image,header);
count=WriteCALSRecord(image,"notes: NONE");
(void) ResetMagickMemory(header,' ',128);
for (i=0; i < 5; i++)
(void) WriteBlob(image,128,(unsigned char *) header);
/*
Write CALS pixels.
*/
write_info=CloneImageInfo(image_info);
(void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent);
(void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent);
group4_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (group4_image == (Image *) NULL)
{
write_info=DestroyImageInfo(write_info);
(void) CloseBlob(image);
return(MagickFalse);
}
group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,
&image->exception);
group4_image=DestroyImage(group4_image);
if (group4 == (unsigned char *) NULL)
{
write_info=DestroyImageInfo(write_info);
(void) CloseBlob(image);
return(MagickFalse);
}
write_info=DestroyImageInfo(write_info);
if (WriteBlob(image,length,group4) != (ssize_t) length)
status=MagickFalse;
group4=(unsigned char *) RelinquishMagickMemory(group4);
(void) CloseBlob(image);
return(status);
}
| 167,967 |
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 ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info*)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
__be32 frag_id = 0;
int ptr, offset = 0, err=0;
u8 *prevhdr, nexthdr = 0;
struct net *net = dev_net(skb_dst(skb)->dev);
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (!skb->local_df && skb->len > mtu) {
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
mtu -= hlen + sizeof(struct frag_hdr);
if (skb_has_frag_list(skb)) {
int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < hlen)
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
return -ENOMEM;
}
__skb_pull(skb, hlen);
fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
ipv6_select_ident(fh);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
frag_id = fh->identification;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next != NULL)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(skb);
if(!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
dst_release(&rt->dst);
return 0;
}
while (frag) {
skb = frag->next;
kfree_skb(frag);
frag = skb;
}
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
dst_release(&rt->dst);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
*prevhdr = NEXTHDR_FRAGMENT;
/*
* Keep copying data until we run out.
*/
while(left > 0) {
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/*
* Allocate buffer.
*/
if ((frag = alloc_skb(len+hlen+sizeof(struct frag_hdr)+LL_ALLOCATED_SPACE(rt->dst.dev), GFP_ATOMIC)) == NULL) {
NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n");
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, LL_RESERVED_SPACE(rt->dst.dev));
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
if (!frag_id) {
ipv6_select_ident(fh);
frag_id = fh->identification;
} else
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len))
BUG();
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
kfree_skb(skb);
return err;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info*)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
__be32 frag_id = 0;
int ptr, offset = 0, err=0;
u8 *prevhdr, nexthdr = 0;
struct net *net = dev_net(skb_dst(skb)->dev);
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (!skb->local_df && skb->len > mtu) {
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
mtu -= hlen + sizeof(struct frag_hdr);
if (skb_has_frag_list(skb)) {
int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < hlen)
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
return -ENOMEM;
}
__skb_pull(skb, hlen);
fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
ipv6_select_ident(fh, rt);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
frag_id = fh->identification;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next != NULL)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(skb);
if(!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
dst_release(&rt->dst);
return 0;
}
while (frag) {
skb = frag->next;
kfree_skb(frag);
frag = skb;
}
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
dst_release(&rt->dst);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
*prevhdr = NEXTHDR_FRAGMENT;
/*
* Keep copying data until we run out.
*/
while(left > 0) {
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/*
* Allocate buffer.
*/
if ((frag = alloc_skb(len+hlen+sizeof(struct frag_hdr)+LL_ALLOCATED_SPACE(rt->dst.dev), GFP_ATOMIC)) == NULL) {
NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n");
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, LL_RESERVED_SPACE(rt->dst.dev));
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
if (!frag_id) {
ipv6_select_ident(fh, rt);
frag_id = fh->identification;
} else
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len))
BUG();
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
kfree_skb(skb);
return err;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
| 165,852 |
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 *ReadDPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[4],
value[MaxTextExtent];
DPXInfo
dpx;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
extent,
samples_per_pixel;
ssize_t
count,
n,
row,
y;
unsigned char
component_type;
/*
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 DPX file header.
*/
offset=0;
count=ReadBlob(image,4,(unsigned char *) magick);
offset+=count;
if ((count != 4) || ((LocaleNCompare(magick,"SDPX",4) != 0) &&
(LocaleNCompare((char *) magick,"XPDS",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->endian=LSBEndian;
if (LocaleNCompare(magick,"SDPX",4) == 0)
image->endian=MSBEndian;
(void) ResetMagickMemory(&dpx,0,sizeof(dpx));
dpx.file.image_offset=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.file.version),(unsigned char *)
dpx.file.version);
(void) FormatImageProperty(image,"dpx:file.version","%.8s",dpx.file.version);
dpx.file.file_size=ReadBlobLong(image);
offset+=4;
dpx.file.ditto_key=ReadBlobLong(image);
offset+=4;
if (dpx.file.ditto_key != ~0U)
(void) FormatImageProperty(image,"dpx:file.ditto.key","%u",
dpx.file.ditto_key);
dpx.file.generic_size=ReadBlobLong(image);
offset+=4;
dpx.file.industry_size=ReadBlobLong(image);
offset+=4;
dpx.file.user_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.file.filename),(unsigned char *)
dpx.file.filename);
(void) FormatImageProperty(image,"dpx:file.filename","%.100s",
dpx.file.filename);
(void) FormatImageProperty(image,"document","%.100s",dpx.file.filename);
offset+=ReadBlob(image,sizeof(dpx.file.timestamp),(unsigned char *)
dpx.file.timestamp);
if (*dpx.file.timestamp != '\0')
(void) FormatImageProperty(image,"dpx:file.timestamp","%.24s",
dpx.file.timestamp);
offset+=ReadBlob(image,sizeof(dpx.file.creator),(unsigned char *)
dpx.file.creator);
if (*dpx.file.creator == '\0')
{
(void) FormatImageProperty(image,"dpx:file.creator","%.100s",
GetMagickVersion((size_t *) NULL));
(void) FormatImageProperty(image,"software","%.100s",
GetMagickVersion((size_t *) NULL));
}
else
{
(void) FormatImageProperty(image,"dpx:file.creator","%.100s",
dpx.file.creator);
(void) FormatImageProperty(image,"software","%.100s",dpx.file.creator);
}
offset+=ReadBlob(image,sizeof(dpx.file.project),(unsigned char *)
dpx.file.project);
if (*dpx.file.project != '\0')
{
(void) FormatImageProperty(image,"dpx:file.project","%.200s",
dpx.file.project);
(void) FormatImageProperty(image,"comment","%.100s",dpx.file.project);
}
offset+=ReadBlob(image,sizeof(dpx.file.copyright),(unsigned char *)
dpx.file.copyright);
if (*dpx.file.copyright != '\0')
{
(void) FormatImageProperty(image,"dpx:file.copyright","%.200s",
dpx.file.copyright);
(void) FormatImageProperty(image,"copyright","%.100s",
dpx.file.copyright);
}
dpx.file.encrypt_key=ReadBlobLong(image);
offset+=4;
if (dpx.file.encrypt_key != ~0U)
(void) FormatImageProperty(image,"dpx:file.encrypt_key","%u",
dpx.file.encrypt_key);
offset+=ReadBlob(image,sizeof(dpx.file.reserve),(unsigned char *)
dpx.file.reserve);
/*
Read DPX image header.
*/
dpx.image.orientation=ReadBlobShort(image);
if (dpx.image.orientation > 7)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset+=2;
if (dpx.image.orientation != (unsigned short) ~0)
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
dpx.image.orientation);
switch (dpx.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
dpx.image.number_elements=ReadBlobShort(image);
if (dpx.image.number_elements > MaxNumberImageElements)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset+=2;
dpx.image.pixels_per_line=ReadBlobLong(image);
offset+=4;
image->columns=dpx.image.pixels_per_line;
dpx.image.lines_per_element=ReadBlobLong(image);
offset+=4;
image->rows=dpx.image.lines_per_element;
for (i=0; i < 8; i++)
{
char
property[MaxTextExtent];
dpx.image.image_element[i].data_sign=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].low_data=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].low_quantity=ReadBlobFloat(image);
offset+=4;
dpx.image.image_element[i].high_data=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].high_quantity=ReadBlobFloat(image);
offset+=4;
dpx.image.image_element[i].descriptor=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].transfer_characteristic=(unsigned char)
ReadBlobByte(image);
(void) FormatLocaleString(property,MaxTextExtent,
"dpx:image.element[%lu].transfer-characteristic",(long) i);
(void) FormatImageProperty(image,property,"%s",
GetImageTransferCharacteristic((DPXTransferCharacteristic)
dpx.image.image_element[i].transfer_characteristic));
offset++;
dpx.image.image_element[i].colorimetric=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].bit_size=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].packing=ReadBlobShort(image);
offset+=2;
dpx.image.image_element[i].encoding=ReadBlobShort(image);
offset+=2;
dpx.image.image_element[i].data_offset=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].end_of_line_padding=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].end_of_image_padding=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.image.image_element[i].description),
(unsigned char *) dpx.image.image_element[i].description);
}
(void) SetImageColorspace(image,RGBColorspace);
offset+=ReadBlob(image,sizeof(dpx.image.reserve),(unsigned char *)
dpx.image.reserve);
if (dpx.file.image_offset >= 1664U)
{
/*
Read DPX orientation header.
*/
dpx.orientation.x_offset=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.x_offset != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.x_offset","%u",
dpx.orientation.x_offset);
dpx.orientation.y_offset=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.y_offset != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.y_offset","%u",
dpx.orientation.y_offset);
dpx.orientation.x_center=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.orientation.x_center) != MagickFalse)
(void) FormatImageProperty(image,"dpx:orientation.x_center","%g",
dpx.orientation.x_center);
dpx.orientation.y_center=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.orientation.y_center) != MagickFalse)
(void) FormatImageProperty(image,"dpx:orientation.y_center","%g",
dpx.orientation.y_center);
dpx.orientation.x_size=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.x_size != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.x_size","%u",
dpx.orientation.x_size);
dpx.orientation.y_size=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.y_size != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.y_size","%u",
dpx.orientation.y_size);
offset+=ReadBlob(image,sizeof(dpx.orientation.filename),(unsigned char *)
dpx.orientation.filename);
if (*dpx.orientation.filename != '\0')
(void) FormatImageProperty(image,"dpx:orientation.filename","%.100s",
dpx.orientation.filename);
offset+=ReadBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *)
dpx.orientation.timestamp);
if (*dpx.orientation.timestamp != '\0')
(void) FormatImageProperty(image,"dpx:orientation.timestamp","%.24s",
dpx.orientation.timestamp);
offset+=ReadBlob(image,sizeof(dpx.orientation.device),(unsigned char *)
dpx.orientation.device);
if (*dpx.orientation.device != '\0')
(void) FormatImageProperty(image,"dpx:orientation.device","%.32s",
dpx.orientation.device);
offset+=ReadBlob(image,sizeof(dpx.orientation.serial),(unsigned char *)
dpx.orientation.serial);
if (*dpx.orientation.serial != '\0')
(void) FormatImageProperty(image,"dpx:orientation.serial","%.32s",
dpx.orientation.serial);
for (i=0; i < 4; i++)
{
dpx.orientation.border[i]=ReadBlobShort(image);
offset+=2;
}
if ((dpx.orientation.border[0] != (unsigned short) (~0)) &&
(dpx.orientation.border[1] != (unsigned short) (~0)))
(void) FormatImageProperty(image,"dpx:orientation.border","%dx%d%+d%+d", dpx.orientation.border[0],dpx.orientation.border[1],
dpx.orientation.border[2],dpx.orientation.border[3]);
for (i=0; i < 2; i++)
{
dpx.orientation.aspect_ratio[i]=ReadBlobLong(image);
offset+=4;
}
if ((dpx.orientation.aspect_ratio[0] != ~0U) &&
(dpx.orientation.aspect_ratio[1] != ~0U))
(void) FormatImageProperty(image,"dpx:orientation.aspect_ratio",
"%ux%u",dpx.orientation.aspect_ratio[0],
dpx.orientation.aspect_ratio[1]);
offset+=ReadBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *)
dpx.orientation.reserve);
}
if (dpx.file.image_offset >= 1920U)
{
/*
Read DPX film header.
*/
offset+=ReadBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id);
if (*dpx.film.id != '\0')
(void) FormatImageProperty(image,"dpx:film.id","%.2s",dpx.film.id);
offset+=ReadBlob(image,sizeof(dpx.film.type),(unsigned char *)
dpx.film.type);
if (*dpx.film.type != '\0')
(void) FormatImageProperty(image,"dpx:film.type","%.2s",dpx.film.type);
offset+=ReadBlob(image,sizeof(dpx.film.offset),(unsigned char *)
dpx.film.offset);
if (*dpx.film.offset != '\0')
(void) FormatImageProperty(image,"dpx:film.offset","%.2s",
dpx.film.offset);
offset+=ReadBlob(image,sizeof(dpx.film.prefix),(unsigned char *)
dpx.film.prefix);
if (*dpx.film.prefix != '\0')
(void) FormatImageProperty(image,"dpx:film.prefix","%.6s",
dpx.film.prefix);
offset+=ReadBlob(image,sizeof(dpx.film.count),(unsigned char *)
dpx.film.count);
if (*dpx.film.count != '\0')
(void) FormatImageProperty(image,"dpx:film.count","%.4s",
dpx.film.count);
offset+=ReadBlob(image,sizeof(dpx.film.format),(unsigned char *)
dpx.film.format);
if (*dpx.film.format != '\0')
(void) FormatImageProperty(image,"dpx:film.format","%.4s",
dpx.film.format);
dpx.film.frame_position=ReadBlobLong(image);
offset+=4;
if (dpx.film.frame_position != ~0U)
(void) FormatImageProperty(image,"dpx:film.frame_position","%u",
dpx.film.frame_position);
dpx.film.sequence_extent=ReadBlobLong(image);
offset+=4;
if (dpx.film.sequence_extent != ~0U)
(void) FormatImageProperty(image,"dpx:film.sequence_extent","%u",
dpx.film.sequence_extent);
dpx.film.held_count=ReadBlobLong(image);
offset+=4;
if (dpx.film.held_count != ~0U)
(void) FormatImageProperty(image,"dpx:film.held_count","%u",
dpx.film.held_count);
dpx.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
dpx.film.frame_rate);
dpx.film.shutter_angle=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.film.shutter_angle) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.shutter_angle","%g",
dpx.film.shutter_angle);
offset+=ReadBlob(image,sizeof(dpx.film.frame_id),(unsigned char *)
dpx.film.frame_id);
if (*dpx.film.frame_id != '\0')
(void) FormatImageProperty(image,"dpx:film.frame_id","%.32s",
dpx.film.frame_id);
offset+=ReadBlob(image,sizeof(dpx.film.slate),(unsigned char *)
dpx.film.slate);
if (*dpx.film.slate != '\0')
(void) FormatImageProperty(image,"dpx:film.slate","%.100s",
dpx.film.slate);
offset+=ReadBlob(image,sizeof(dpx.film.reserve),(unsigned char *)
dpx.film.reserve);
}
if (dpx.file.image_offset >= 2048U)
{
/*
Read DPX television header.
*/
dpx.television.time_code=(unsigned int) ReadBlobLong(image);
offset+=4;
TimeCodeToString(dpx.television.time_code,value);
(void) SetImageProperty(image,"dpx:television.time.code",value);
dpx.television.user_bits=(unsigned int) ReadBlobLong(image);
offset+=4;
TimeCodeToString(dpx.television.user_bits,value);
(void) SetImageProperty(image,"dpx:television.user.bits",value);
dpx.television.interlace=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.interlace != 0)
(void) FormatImageProperty(image,"dpx:television.interlace","%.20g",
(double) dpx.television.interlace);
dpx.television.field_number=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.field_number != 0)
(void) FormatImageProperty(image,"dpx:television.field_number","%.20g",
(double) dpx.television.field_number);
dpx.television.video_signal=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.video_signal != 0)
(void) FormatImageProperty(image,"dpx:television.video_signal","%.20g",
(double) dpx.television.video_signal);
dpx.television.padding=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.padding != 0)
(void) FormatImageProperty(image,"dpx:television.padding","%d",
dpx.television.padding);
dpx.television.horizontal_sample_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.horizontal_sample_rate) != MagickFalse)
(void) FormatImageProperty(image,
"dpx:television.horizontal_sample_rate","%g",
dpx.television.horizontal_sample_rate);
dpx.television.vertical_sample_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.vertical_sample_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.vertical_sample_rate",
"%g",dpx.television.vertical_sample_rate);
dpx.television.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.frame_rate","%g",
dpx.television.frame_rate);
dpx.television.time_offset=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.time_offset) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.time_offset","%g",
dpx.television.time_offset);
dpx.television.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.gamma) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.gamma","%g",
dpx.television.gamma);
dpx.television.black_level=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.black_level) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.black_level","%g",
dpx.television.black_level);
dpx.television.black_gain=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.black_gain) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.black_gain","%g",
dpx.television.black_gain);
dpx.television.break_point=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.break_point) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.break_point","%g",
dpx.television.break_point);
dpx.television.white_level=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.white_level) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.white_level","%g",
dpx.television.white_level);
dpx.television.integration_times=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.integration_times) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.integration_times",
"%g",dpx.television.integration_times);
offset+=ReadBlob(image,sizeof(dpx.television.reserve),(unsigned char *)
dpx.television.reserve);
}
if (dpx.file.image_offset > 2080U)
{
/*
Read DPX user header.
*/
offset+=ReadBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id);
if (*dpx.user.id != '\0')
(void) FormatImageProperty(image,"dpx:user.id","%.32s",dpx.user.id);
if ((dpx.file.user_size != ~0U) &&
((size_t) dpx.file.user_size > sizeof(dpx.user.id)))
{
StringInfo
*profile;
profile=BlobToStringInfo((const void *) NULL,
dpx.file.user_size-sizeof(dpx.user.id));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user-data",profile);
profile=DestroyStringInfo(profile);
}
}
for ( ; offset < (MagickOffsetType) dpx.file.image_offset; offset++)
(void) ReadBlobByte(image);
/*
Read DPX image header.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
for (n=0; n < (ssize_t) dpx.image.number_elements; n++)
{
/*
Convert DPX raster image to pixel packets.
*/
if ((dpx.image.image_element[n].data_offset != ~0U) &&
(dpx.image.image_element[n].data_offset != 0U))
{
MagickOffsetType
data_offset;
data_offset=(MagickOffsetType) dpx.image.image_element[n].data_offset;
if (data_offset < offset)
offset=SeekBlob(image,data_offset,SEEK_SET);
else
for ( ; offset < data_offset; offset++)
(void) ReadBlobByte(image);
if (offset != data_offset)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
SetPrimaryChromaticity((DPXColorimetric)
dpx.image.image_element[n].colorimetric,&image->chromaticity);
image->depth=dpx.image.image_element[n].bit_size;
samples_per_pixel=1;
quantum_type=GrayQuantum;
component_type=dpx.image.image_element[n].descriptor;
switch (component_type)
{
case CbYCrY422ComponentType:
{
samples_per_pixel=2;
quantum_type=CbYCrYQuantum;
break;
}
case CbYACrYA4224ComponentType:
case CbYCr444ComponentType:
{
samples_per_pixel=3;
quantum_type=CbYCrQuantum;
break;
}
case RGBComponentType:
{
samples_per_pixel=3;
quantum_type=RGBQuantum;
break;
}
case ABGRComponentType:
case RGBAComponentType:
{
image->matte=MagickTrue;
samples_per_pixel=4;
quantum_type=RGBAQuantum;
break;
}
default:
break;
}
switch (component_type)
{
case CbYCrY422ComponentType:
case CbYACrYA4224ComponentType:
case CbYCr444ComponentType:
{
(void) SetImageColorspace(image,Rec709YCbCrColorspace);
break;
}
case LumaComponentType:
{
(void) SetImageColorspace(image,GRAYColorspace);
break;
}
default:
{
(void) SetImageColorspace(image,RGBColorspace);
if (dpx.image.image_element[n].transfer_characteristic == LogarithmicColorimetric)
(void) SetImageColorspace(image,LogColorspace);
if (dpx.image.image_element[n].transfer_characteristic == PrintingDensityColorimetric)
(void) SetImageColorspace(image,LogColorspace);
break;
}
}
extent=GetBytesPerRow(image->columns,samples_per_pixel,image->depth,
dpx.image.image_element[n].packing == 0 ? MagickFalse : MagickTrue);
/*
DPX any-bit pixel format.
*/
status=MagickTrue;
row=0;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumQuantum(quantum_info,32);
SetQuantumPack(quantum_info,dpx.image.image_element[n].packing == 0 ?
MagickTrue : MagickFalse);
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
offset;
unsigned char
*pixels;
if (status == MagickFalse)
continue;
pixels=GetQuantumPixels(quantum_info);
{
count=ReadBlob(image,extent,pixels);
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
}
if (count != (ssize_t) extent)
status=MagickFalse;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) length;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadDPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[4],
value[MaxTextExtent];
DPXInfo
dpx;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
extent,
samples_per_pixel;
ssize_t
count,
n,
row,
y;
unsigned char
component_type;
/*
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 DPX file header.
*/
offset=0;
count=ReadBlob(image,4,(unsigned char *) magick);
offset+=count;
if ((count != 4) || ((LocaleNCompare(magick,"SDPX",4) != 0) &&
(LocaleNCompare((char *) magick,"XPDS",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->endian=LSBEndian;
if (LocaleNCompare(magick,"SDPX",4) == 0)
image->endian=MSBEndian;
(void) ResetMagickMemory(&dpx,0,sizeof(dpx));
dpx.file.image_offset=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.file.version),(unsigned char *)
dpx.file.version);
(void) FormatImageProperty(image,"dpx:file.version","%.8s",dpx.file.version);
dpx.file.file_size=ReadBlobLong(image);
offset+=4;
dpx.file.ditto_key=ReadBlobLong(image);
offset+=4;
if (dpx.file.ditto_key != ~0U)
(void) FormatImageProperty(image,"dpx:file.ditto.key","%u",
dpx.file.ditto_key);
dpx.file.generic_size=ReadBlobLong(image);
offset+=4;
dpx.file.industry_size=ReadBlobLong(image);
offset+=4;
dpx.file.user_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.file.filename),(unsigned char *)
dpx.file.filename);
(void) FormatImageProperty(image,"dpx:file.filename","%.100s",
dpx.file.filename);
(void) FormatImageProperty(image,"document","%.100s",dpx.file.filename);
offset+=ReadBlob(image,sizeof(dpx.file.timestamp),(unsigned char *)
dpx.file.timestamp);
if (*dpx.file.timestamp != '\0')
(void) FormatImageProperty(image,"dpx:file.timestamp","%.24s",
dpx.file.timestamp);
offset+=ReadBlob(image,sizeof(dpx.file.creator),(unsigned char *)
dpx.file.creator);
if (*dpx.file.creator == '\0')
{
(void) FormatImageProperty(image,"dpx:file.creator","%.100s",
GetMagickVersion((size_t *) NULL));
(void) FormatImageProperty(image,"software","%.100s",
GetMagickVersion((size_t *) NULL));
}
else
{
(void) FormatImageProperty(image,"dpx:file.creator","%.100s",
dpx.file.creator);
(void) FormatImageProperty(image,"software","%.100s",dpx.file.creator);
}
offset+=ReadBlob(image,sizeof(dpx.file.project),(unsigned char *)
dpx.file.project);
if (*dpx.file.project != '\0')
{
(void) FormatImageProperty(image,"dpx:file.project","%.200s",
dpx.file.project);
(void) FormatImageProperty(image,"comment","%.100s",dpx.file.project);
}
offset+=ReadBlob(image,sizeof(dpx.file.copyright),(unsigned char *)
dpx.file.copyright);
if (*dpx.file.copyright != '\0')
{
(void) FormatImageProperty(image,"dpx:file.copyright","%.200s",
dpx.file.copyright);
(void) FormatImageProperty(image,"copyright","%.100s",
dpx.file.copyright);
}
dpx.file.encrypt_key=ReadBlobLong(image);
offset+=4;
if (dpx.file.encrypt_key != ~0U)
(void) FormatImageProperty(image,"dpx:file.encrypt_key","%u",
dpx.file.encrypt_key);
offset+=ReadBlob(image,sizeof(dpx.file.reserve),(unsigned char *)
dpx.file.reserve);
/*
Read DPX image header.
*/
dpx.image.orientation=ReadBlobShort(image);
if (dpx.image.orientation > 7)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset+=2;
if (dpx.image.orientation != (unsigned short) ~0)
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
dpx.image.orientation);
switch (dpx.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
dpx.image.number_elements=ReadBlobShort(image);
if (dpx.image.number_elements > MaxNumberImageElements)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset+=2;
dpx.image.pixels_per_line=ReadBlobLong(image);
offset+=4;
image->columns=dpx.image.pixels_per_line;
dpx.image.lines_per_element=ReadBlobLong(image);
offset+=4;
image->rows=dpx.image.lines_per_element;
for (i=0; i < 8; i++)
{
char
property[MaxTextExtent];
dpx.image.image_element[i].data_sign=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].low_data=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].low_quantity=ReadBlobFloat(image);
offset+=4;
dpx.image.image_element[i].high_data=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].high_quantity=ReadBlobFloat(image);
offset+=4;
dpx.image.image_element[i].descriptor=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].transfer_characteristic=(unsigned char)
ReadBlobByte(image);
(void) FormatLocaleString(property,MaxTextExtent,
"dpx:image.element[%lu].transfer-characteristic",(long) i);
(void) FormatImageProperty(image,property,"%s",
GetImageTransferCharacteristic((DPXTransferCharacteristic)
dpx.image.image_element[i].transfer_characteristic));
offset++;
dpx.image.image_element[i].colorimetric=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].bit_size=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].packing=ReadBlobShort(image);
offset+=2;
dpx.image.image_element[i].encoding=ReadBlobShort(image);
offset+=2;
dpx.image.image_element[i].data_offset=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].end_of_line_padding=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].end_of_image_padding=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.image.image_element[i].description),
(unsigned char *) dpx.image.image_element[i].description);
}
(void) SetImageColorspace(image,RGBColorspace);
offset+=ReadBlob(image,sizeof(dpx.image.reserve),(unsigned char *)
dpx.image.reserve);
if (dpx.file.image_offset >= 1664U)
{
/*
Read DPX orientation header.
*/
dpx.orientation.x_offset=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.x_offset != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.x_offset","%u",
dpx.orientation.x_offset);
dpx.orientation.y_offset=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.y_offset != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.y_offset","%u",
dpx.orientation.y_offset);
dpx.orientation.x_center=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.orientation.x_center) != MagickFalse)
(void) FormatImageProperty(image,"dpx:orientation.x_center","%g",
dpx.orientation.x_center);
dpx.orientation.y_center=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.orientation.y_center) != MagickFalse)
(void) FormatImageProperty(image,"dpx:orientation.y_center","%g",
dpx.orientation.y_center);
dpx.orientation.x_size=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.x_size != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.x_size","%u",
dpx.orientation.x_size);
dpx.orientation.y_size=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.y_size != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.y_size","%u",
dpx.orientation.y_size);
offset+=ReadBlob(image,sizeof(dpx.orientation.filename),(unsigned char *)
dpx.orientation.filename);
if (*dpx.orientation.filename != '\0')
(void) FormatImageProperty(image,"dpx:orientation.filename","%.100s",
dpx.orientation.filename);
offset+=ReadBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *)
dpx.orientation.timestamp);
if (*dpx.orientation.timestamp != '\0')
(void) FormatImageProperty(image,"dpx:orientation.timestamp","%.24s",
dpx.orientation.timestamp);
offset+=ReadBlob(image,sizeof(dpx.orientation.device),(unsigned char *)
dpx.orientation.device);
if (*dpx.orientation.device != '\0')
(void) FormatImageProperty(image,"dpx:orientation.device","%.32s",
dpx.orientation.device);
offset+=ReadBlob(image,sizeof(dpx.orientation.serial),(unsigned char *)
dpx.orientation.serial);
if (*dpx.orientation.serial != '\0')
(void) FormatImageProperty(image,"dpx:orientation.serial","%.32s",
dpx.orientation.serial);
for (i=0; i < 4; i++)
{
dpx.orientation.border[i]=ReadBlobShort(image);
offset+=2;
}
if ((dpx.orientation.border[0] != (unsigned short) (~0)) &&
(dpx.orientation.border[1] != (unsigned short) (~0)))
(void) FormatImageProperty(image,"dpx:orientation.border","%dx%d%+d%+d", dpx.orientation.border[0],dpx.orientation.border[1],
dpx.orientation.border[2],dpx.orientation.border[3]);
for (i=0; i < 2; i++)
{
dpx.orientation.aspect_ratio[i]=ReadBlobLong(image);
offset+=4;
}
if ((dpx.orientation.aspect_ratio[0] != ~0U) &&
(dpx.orientation.aspect_ratio[1] != ~0U))
(void) FormatImageProperty(image,"dpx:orientation.aspect_ratio",
"%ux%u",dpx.orientation.aspect_ratio[0],
dpx.orientation.aspect_ratio[1]);
offset+=ReadBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *)
dpx.orientation.reserve);
}
if (dpx.file.image_offset >= 1920U)
{
/*
Read DPX film header.
*/
offset+=ReadBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id);
if (*dpx.film.id != '\0')
(void) FormatImageProperty(image,"dpx:film.id","%.2s",dpx.film.id);
offset+=ReadBlob(image,sizeof(dpx.film.type),(unsigned char *)
dpx.film.type);
if (*dpx.film.type != '\0')
(void) FormatImageProperty(image,"dpx:film.type","%.2s",dpx.film.type);
offset+=ReadBlob(image,sizeof(dpx.film.offset),(unsigned char *)
dpx.film.offset);
if (*dpx.film.offset != '\0')
(void) FormatImageProperty(image,"dpx:film.offset","%.2s",
dpx.film.offset);
offset+=ReadBlob(image,sizeof(dpx.film.prefix),(unsigned char *)
dpx.film.prefix);
if (*dpx.film.prefix != '\0')
(void) FormatImageProperty(image,"dpx:film.prefix","%.6s",
dpx.film.prefix);
offset+=ReadBlob(image,sizeof(dpx.film.count),(unsigned char *)
dpx.film.count);
if (*dpx.film.count != '\0')
(void) FormatImageProperty(image,"dpx:film.count","%.4s",
dpx.film.count);
offset+=ReadBlob(image,sizeof(dpx.film.format),(unsigned char *)
dpx.film.format);
if (*dpx.film.format != '\0')
(void) FormatImageProperty(image,"dpx:film.format","%.4s",
dpx.film.format);
dpx.film.frame_position=ReadBlobLong(image);
offset+=4;
if (dpx.film.frame_position != ~0U)
(void) FormatImageProperty(image,"dpx:film.frame_position","%u",
dpx.film.frame_position);
dpx.film.sequence_extent=ReadBlobLong(image);
offset+=4;
if (dpx.film.sequence_extent != ~0U)
(void) FormatImageProperty(image,"dpx:film.sequence_extent","%u",
dpx.film.sequence_extent);
dpx.film.held_count=ReadBlobLong(image);
offset+=4;
if (dpx.film.held_count != ~0U)
(void) FormatImageProperty(image,"dpx:film.held_count","%u",
dpx.film.held_count);
dpx.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
dpx.film.frame_rate);
dpx.film.shutter_angle=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.film.shutter_angle) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.shutter_angle","%g",
dpx.film.shutter_angle);
offset+=ReadBlob(image,sizeof(dpx.film.frame_id),(unsigned char *)
dpx.film.frame_id);
if (*dpx.film.frame_id != '\0')
(void) FormatImageProperty(image,"dpx:film.frame_id","%.32s",
dpx.film.frame_id);
offset+=ReadBlob(image,sizeof(dpx.film.slate),(unsigned char *)
dpx.film.slate);
if (*dpx.film.slate != '\0')
(void) FormatImageProperty(image,"dpx:film.slate","%.100s",
dpx.film.slate);
offset+=ReadBlob(image,sizeof(dpx.film.reserve),(unsigned char *)
dpx.film.reserve);
}
if (dpx.file.image_offset >= 2048U)
{
/*
Read DPX television header.
*/
dpx.television.time_code=(unsigned int) ReadBlobLong(image);
offset+=4;
TimeCodeToString(dpx.television.time_code,value);
(void) SetImageProperty(image,"dpx:television.time.code",value);
dpx.television.user_bits=(unsigned int) ReadBlobLong(image);
offset+=4;
TimeCodeToString(dpx.television.user_bits,value);
(void) SetImageProperty(image,"dpx:television.user.bits",value);
dpx.television.interlace=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.interlace != 0)
(void) FormatImageProperty(image,"dpx:television.interlace","%.20g",
(double) dpx.television.interlace);
dpx.television.field_number=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.field_number != 0)
(void) FormatImageProperty(image,"dpx:television.field_number","%.20g",
(double) dpx.television.field_number);
dpx.television.video_signal=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.video_signal != 0)
(void) FormatImageProperty(image,"dpx:television.video_signal","%.20g",
(double) dpx.television.video_signal);
dpx.television.padding=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.padding != 0)
(void) FormatImageProperty(image,"dpx:television.padding","%d",
dpx.television.padding);
dpx.television.horizontal_sample_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.horizontal_sample_rate) != MagickFalse)
(void) FormatImageProperty(image,
"dpx:television.horizontal_sample_rate","%g",
dpx.television.horizontal_sample_rate);
dpx.television.vertical_sample_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.vertical_sample_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.vertical_sample_rate",
"%g",dpx.television.vertical_sample_rate);
dpx.television.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.frame_rate","%g",
dpx.television.frame_rate);
dpx.television.time_offset=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.time_offset) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.time_offset","%g",
dpx.television.time_offset);
dpx.television.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.gamma) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.gamma","%g",
dpx.television.gamma);
dpx.television.black_level=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.black_level) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.black_level","%g",
dpx.television.black_level);
dpx.television.black_gain=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.black_gain) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.black_gain","%g",
dpx.television.black_gain);
dpx.television.break_point=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.break_point) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.break_point","%g",
dpx.television.break_point);
dpx.television.white_level=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.white_level) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.white_level","%g",
dpx.television.white_level);
dpx.television.integration_times=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.integration_times) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.integration_times",
"%g",dpx.television.integration_times);
offset+=ReadBlob(image,sizeof(dpx.television.reserve),(unsigned char *)
dpx.television.reserve);
}
if (dpx.file.image_offset > 2080U)
{
/*
Read DPX user header.
*/
offset+=ReadBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id);
if (*dpx.user.id != '\0')
(void) FormatImageProperty(image,"dpx:user.id","%.32s",dpx.user.id);
if ((dpx.file.user_size != ~0U) &&
((size_t) dpx.file.user_size > sizeof(dpx.user.id)))
{
StringInfo
*profile;
profile=BlobToStringInfo((const void *) NULL,
dpx.file.user_size-sizeof(dpx.user.id));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user-data",profile);
profile=DestroyStringInfo(profile);
}
}
for ( ; offset < (MagickOffsetType) dpx.file.image_offset; offset++)
(void) ReadBlobByte(image);
/*
Read DPX image header.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (n=0; n < (ssize_t) dpx.image.number_elements; n++)
{
/*
Convert DPX raster image to pixel packets.
*/
if ((dpx.image.image_element[n].data_offset != ~0U) &&
(dpx.image.image_element[n].data_offset != 0U))
{
MagickOffsetType
data_offset;
data_offset=(MagickOffsetType) dpx.image.image_element[n].data_offset;
if (data_offset < offset)
offset=SeekBlob(image,data_offset,SEEK_SET);
else
for ( ; offset < data_offset; offset++)
(void) ReadBlobByte(image);
if (offset != data_offset)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
SetPrimaryChromaticity((DPXColorimetric)
dpx.image.image_element[n].colorimetric,&image->chromaticity);
image->depth=dpx.image.image_element[n].bit_size;
samples_per_pixel=1;
quantum_type=GrayQuantum;
component_type=dpx.image.image_element[n].descriptor;
switch (component_type)
{
case CbYCrY422ComponentType:
{
samples_per_pixel=2;
quantum_type=CbYCrYQuantum;
break;
}
case CbYACrYA4224ComponentType:
case CbYCr444ComponentType:
{
samples_per_pixel=3;
quantum_type=CbYCrQuantum;
break;
}
case RGBComponentType:
{
samples_per_pixel=3;
quantum_type=RGBQuantum;
break;
}
case ABGRComponentType:
case RGBAComponentType:
{
image->matte=MagickTrue;
samples_per_pixel=4;
quantum_type=RGBAQuantum;
break;
}
default:
break;
}
switch (component_type)
{
case CbYCrY422ComponentType:
case CbYACrYA4224ComponentType:
case CbYCr444ComponentType:
{
(void) SetImageColorspace(image,Rec709YCbCrColorspace);
break;
}
case LumaComponentType:
{
(void) SetImageColorspace(image,GRAYColorspace);
break;
}
default:
{
(void) SetImageColorspace(image,RGBColorspace);
if (dpx.image.image_element[n].transfer_characteristic == LogarithmicColorimetric)
(void) SetImageColorspace(image,LogColorspace);
if (dpx.image.image_element[n].transfer_characteristic == PrintingDensityColorimetric)
(void) SetImageColorspace(image,LogColorspace);
break;
}
}
extent=GetBytesPerRow(image->columns,samples_per_pixel,image->depth,
dpx.image.image_element[n].packing == 0 ? MagickFalse : MagickTrue);
/*
DPX any-bit pixel format.
*/
status=MagickTrue;
row=0;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumQuantum(quantum_info,32);
SetQuantumPack(quantum_info,dpx.image.image_element[n].packing == 0 ?
MagickTrue : MagickFalse);
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
offset;
unsigned char
*pixels;
if (status == MagickFalse)
continue;
pixels=GetQuantumPixels(quantum_info);
{
count=ReadBlob(image,extent,pixels);
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
}
if (count != (ssize_t) extent)
status=MagickFalse;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) length;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,561 |
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: OMX_ERRORTYPE SoftAACEncoder2::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPortFormat:
{
OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
formatParams->eEncoding =
(formatParams->nPortIndex == 0)
? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
aacParams->nBitRate = mBitRate;
aacParams->nAudioBandWidth = 0;
aacParams->nAACtools = 0;
aacParams->nAACERtools = 0;
aacParams->eAACProfile = (OMX_AUDIO_AACPROFILETYPE) mAACProfile;
aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
aacParams->nChannels = mNumChannels;
aacParams->nSampleRate = mSampleRate;
aacParams->nFrameLength = 0;
switch (mSBRMode) {
case 1: // sbr on
switch (mSBRRatio) {
case 0:
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR;
break;
case 1:
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR;
break;
case 2:
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR;
break;
default:
ALOGE("invalid SBR ratio %d", mSBRRatio);
TRESPASS();
}
break;
case 0: // sbr off
case -1: // sbr undefined
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR;
break;
default:
ALOGE("invalid SBR mode %d", mSBRMode);
TRESPASS();
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAACEncoder2::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPortFormat:
{
OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
formatParams->eEncoding =
(formatParams->nPortIndex == 0)
? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
aacParams->nBitRate = mBitRate;
aacParams->nAudioBandWidth = 0;
aacParams->nAACtools = 0;
aacParams->nAACERtools = 0;
aacParams->eAACProfile = (OMX_AUDIO_AACPROFILETYPE) mAACProfile;
aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
aacParams->nChannels = mNumChannels;
aacParams->nSampleRate = mSampleRate;
aacParams->nFrameLength = 0;
switch (mSBRMode) {
case 1: // sbr on
switch (mSBRRatio) {
case 0:
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR;
break;
case 1:
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR;
break;
case 2:
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR;
break;
default:
ALOGE("invalid SBR ratio %d", mSBRRatio);
TRESPASS();
}
break;
case 0: // sbr off
case -1: // sbr undefined
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR;
aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR;
break;
default:
ALOGE("invalid SBR mode %d", mSBRMode);
TRESPASS();
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,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: void PlatformSensorProviderMac::CreateSensorInternal(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
switch (type) {
case mojom::SensorType::AMBIENT_LIGHT: {
scoped_refptr<PlatformSensor> sensor =
new PlatformSensorAmbientLightMac(std::move(mapping), this);
callback.Run(std::move(sensor));
break;
}
case mojom::SensorType::ACCELEROMETER: {
callback.Run(base::MakeRefCounted<PlatformSensorAccelerometerMac>(
std::move(mapping), this));
break;
}
case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES: {
auto fusion_algorithm = std::make_unique<
RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>();
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(fusion_algorithm), callback);
break;
}
case mojom::SensorType::RELATIVE_ORIENTATION_QUATERNION: {
auto orientation_quaternion_fusion_algorithm_using_euler_angles =
std::make_unique<
OrientationQuaternionFusionAlgorithmUsingEulerAngles>(
false /* absolute */);
PlatformSensorFusion::Create(
std::move(mapping), this,
std::move(orientation_quaternion_fusion_algorithm_using_euler_angles),
callback);
break;
}
default:
callback.Run(nullptr);
}
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void PlatformSensorProviderMac::CreateSensorInternal(
mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
const CreateSensorCallback& callback) {
switch (type) {
case mojom::SensorType::AMBIENT_LIGHT: {
scoped_refptr<PlatformSensor> sensor =
new PlatformSensorAmbientLightMac(reading_buffer, this);
callback.Run(std::move(sensor));
break;
}
case mojom::SensorType::ACCELEROMETER: {
callback.Run(base::MakeRefCounted<PlatformSensorAccelerometerMac>(
reading_buffer, this));
break;
}
case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES: {
auto fusion_algorithm = std::make_unique<
RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>();
PlatformSensorFusion::Create(reading_buffer, this,
std::move(fusion_algorithm), callback);
break;
}
case mojom::SensorType::RELATIVE_ORIENTATION_QUATERNION: {
auto orientation_quaternion_fusion_algorithm_using_euler_angles =
std::make_unique<
OrientationQuaternionFusionAlgorithmUsingEulerAngles>(
false /* absolute */);
PlatformSensorFusion::Create(
reading_buffer, this,
std::move(orientation_quaternion_fusion_algorithm_using_euler_angles),
callback);
break;
}
default:
callback.Run(nullptr);
}
}
| 172,846 |
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 MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1613
CWE ID: CWE-119 | static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| 169,597 |
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: SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
const void __user * __user *, pages,
const int __user *, nodes,
int __user *, status, int, flags)
{
const struct cred *cred = current_cred(), *tcred;
struct task_struct *task;
struct mm_struct *mm;
int err;
nodemask_t task_nodes;
/* Check flags */
if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
return -EINVAL;
if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
return -EPERM;
/* Find the mm_struct */
rcu_read_lock();
task = pid ? find_task_by_vpid(pid) : current;
if (!task) {
rcu_read_unlock();
return -ESRCH;
}
get_task_struct(task);
/*
* Check if this process has the right to modify the specified
* process. The right exists if the process has administrative
* capabilities, superuser privileges or the same
* userid as the target process.
*/
tcred = __task_cred(task);
if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) &&
!uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) &&
!capable(CAP_SYS_NICE)) {
rcu_read_unlock();
err = -EPERM;
goto out;
}
rcu_read_unlock();
err = security_task_movememory(task);
if (err)
goto out;
task_nodes = cpuset_mems_allowed(task);
mm = get_task_mm(task);
put_task_struct(task);
if (!mm)
return -EINVAL;
if (nodes)
err = do_pages_move(mm, task_nodes, nr_pages, pages,
nodes, status, flags);
else
err = do_pages_stat(mm, nr_pages, pages, status);
mmput(mm);
return err;
out:
put_task_struct(task);
return err;
}
Commit Message: Sanitize 'move_pages()' permission checks
The 'move_paghes()' system call was introduced long long ago with the
same permission checks as for sending a signal (except using
CAP_SYS_NICE instead of CAP_SYS_KILL for the overriding capability).
That turns out to not be a great choice - while the system call really
only moves physical page allocations around (and you need other
capabilities to do a lot of it), you can check the return value to map
out some the virtual address choices and defeat ASLR of a binary that
still shares your uid.
So change the access checks to the more common 'ptrace_may_access()'
model instead.
This tightens the access checks for the uid, and also effectively
changes the CAP_SYS_NICE check to CAP_SYS_PTRACE, but it's unlikely that
anybody really _uses_ this legacy system call any more (we hav ebetter
NUMA placement models these days), so I expect nobody to notice.
Famous last words.
Reported-by: Otto Ebeling <[email protected]>
Acked-by: Eric W. Biederman <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
const void __user * __user *, pages,
const int __user *, nodes,
int __user *, status, int, flags)
{
struct task_struct *task;
struct mm_struct *mm;
int err;
nodemask_t task_nodes;
/* Check flags */
if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
return -EINVAL;
if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
return -EPERM;
/* Find the mm_struct */
rcu_read_lock();
task = pid ? find_task_by_vpid(pid) : current;
if (!task) {
rcu_read_unlock();
return -ESRCH;
}
get_task_struct(task);
/*
* Check if this process has the right to modify the specified
* process. Use the regular "ptrace_may_access()" checks.
*/
if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
rcu_read_unlock();
err = -EPERM;
goto out;
}
rcu_read_unlock();
err = security_task_movememory(task);
if (err)
goto out;
task_nodes = cpuset_mems_allowed(task);
mm = get_task_mm(task);
put_task_struct(task);
if (!mm)
return -EINVAL;
if (nodes)
err = do_pages_move(mm, task_nodes, nr_pages, pages,
nodes, status, flags);
else
err = do_pages_stat(mm, nr_pages, pages, status);
mmput(mm);
return err;
out:
put_task_struct(task);
return err;
}
| 167,770 |
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: header_put_be_3byte (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3)
{ psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_3byte */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_put_be_3byte (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = (x >> 16) ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = x ;
} /* header_put_be_3byte */
| 170,048 |
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: xsltCopyNamespaceList(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNsPtr cur) {
xmlNsPtr ret = NULL, tmp;
xmlNsPtr p = NULL,q;
if (cur == NULL)
return(NULL);
if (cur->type != XML_NAMESPACE_DECL)
return(NULL);
/*
* One can add namespaces only on element nodes
*/
if ((node != NULL) && (node->type != XML_ELEMENT_NODE))
node = NULL;
while (cur != NULL) {
if (cur->type != XML_NAMESPACE_DECL)
break;
/*
* Avoid duplicating namespace declarations in the tree if
* a matching declaration is in scope.
*/
if (node != NULL) {
if ((node->ns != NULL) &&
(xmlStrEqual(node->ns->prefix, cur->prefix)) &&
(xmlStrEqual(node->ns->href, cur->href))) {
cur = cur->next;
continue;
}
tmp = xmlSearchNs(node->doc, node, cur->prefix);
if ((tmp != NULL) && (xmlStrEqual(tmp->href, cur->href))) {
cur = cur->next;
continue;
}
}
#ifdef XSLT_REFACTORED
/*
* Namespace exclusion and ns-aliasing is performed at
* compilation-time in the refactored code.
*/
q = xmlNewNs(node, cur->href, cur->prefix);
if (p == NULL) {
ret = p = q;
} else {
p->next = q;
p = q;
}
#else
/*
* TODO: Remove this if the refactored code gets enabled.
*/
if (!xmlStrEqual(cur->href, XSLT_NAMESPACE)) {
const xmlChar *URI;
/* TODO apply cascading */
URI = (const xmlChar *) xmlHashLookup(ctxt->style->nsAliases,
cur->href);
if (URI == UNDEFINED_DEFAULT_NS)
continue;
if (URI != NULL) {
q = xmlNewNs(node, URI, cur->prefix);
} else {
q = xmlNewNs(node, cur->href, cur->prefix);
}
if (p == NULL) {
ret = p = q;
} else {
p->next = q;
p = q;
}
}
#endif
cur = cur->next;
}
return(ret);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltCopyNamespaceList(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNsPtr cur) {
xmlNsPtr ret = NULL, tmp;
xmlNsPtr p = NULL,q;
if (cur == NULL)
return(NULL);
if (cur->type != XML_NAMESPACE_DECL)
return(NULL);
/*
* One can add namespaces only on element nodes
*/
if ((node != NULL) && (node->type != XML_ELEMENT_NODE))
node = NULL;
while (cur != NULL) {
if (cur->type != XML_NAMESPACE_DECL)
break;
/*
* Avoid duplicating namespace declarations in the tree if
* a matching declaration is in scope.
*/
if (node != NULL) {
if ((node->ns != NULL) &&
(xmlStrEqual(node->ns->prefix, cur->prefix)) &&
(xmlStrEqual(node->ns->href, cur->href))) {
cur = cur->next;
continue;
}
tmp = xmlSearchNs(node->doc, node, cur->prefix);
if ((tmp != NULL) && (xmlStrEqual(tmp->href, cur->href))) {
cur = cur->next;
continue;
}
}
#ifdef XSLT_REFACTORED
/*
* Namespace exclusion and ns-aliasing is performed at
* compilation-time in the refactored code.
*/
q = xmlNewNs(node, cur->href, cur->prefix);
if (p == NULL) {
ret = p = q;
} else {
p->next = q;
p = q;
}
#else
/*
* TODO: Remove this if the refactored code gets enabled.
*/
if (!xmlStrEqual(cur->href, XSLT_NAMESPACE)) {
const xmlChar *URI;
/* TODO apply cascading */
URI = (const xmlChar *) xmlHashLookup(ctxt->style->nsAliases,
cur->href);
if (URI == UNDEFINED_DEFAULT_NS) {
cur = cur->next;
continue;
}
if (URI != NULL) {
q = xmlNewNs(node, URI, cur->prefix);
} else {
q = xmlNewNs(node, cur->href, cur->prefix);
}
if (p == NULL) {
ret = p = q;
} else {
p->next = q;
p = q;
}
}
#endif
cur = cur->next;
}
return(ret);
}
| 173,305 |
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 journal_unmap_buffer(journal_t *journal, struct buffer_head *bh)
{
transaction_t *transaction;
struct journal_head *jh;
int may_free = 1;
int ret;
BUFFER_TRACE(bh, "entry");
/*
* It is safe to proceed here without the j_list_lock because the
* buffers cannot be stolen by try_to_free_buffers as long as we are
* holding the page lock. --sct
*/
if (!buffer_jbd(bh))
goto zap_buffer_unlocked;
/* OK, we have data buffer in journaled mode */
write_lock(&journal->j_state_lock);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
jh = jbd2_journal_grab_journal_head(bh);
if (!jh)
goto zap_buffer_no_jh;
/*
* We cannot remove the buffer from checkpoint lists until the
* transaction adding inode to orphan list (let's call it T)
* is committed. Otherwise if the transaction changing the
* buffer would be cleaned from the journal before T is
* committed, a crash will cause that the correct contents of
* the buffer will be lost. On the other hand we have to
* clear the buffer dirty bit at latest at the moment when the
* transaction marking the buffer as freed in the filesystem
* structures is committed because from that moment on the
* buffer can be reallocated and used by a different page.
* Since the block hasn't been freed yet but the inode has
* already been added to orphan list, it is safe for us to add
* the buffer to BJ_Forget list of the newest transaction.
*/
transaction = jh->b_transaction;
if (transaction == NULL) {
/* First case: not on any transaction. If it
* has no checkpoint link, then we can zap it:
* it's a writeback-mode buffer so we don't care
* if it hits disk safely. */
if (!jh->b_cp_transaction) {
JBUFFER_TRACE(jh, "not on any transaction: zap");
goto zap_buffer;
}
if (!buffer_dirty(bh)) {
/* bdflush has written it. We can drop it now */
goto zap_buffer;
}
/* OK, it must be in the journal but still not
* written fully to disk: it's metadata or
* journaled data... */
if (journal->j_running_transaction) {
/* ... and once the current transaction has
* committed, the buffer won't be needed any
* longer. */
JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget");
ret = __dispose_buffer(jh,
journal->j_running_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* There is no currently-running transaction. So the
* orphan record which we wrote for this file must have
* passed into commit. We must attach this buffer to
* the committing transaction, if it exists. */
if (journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "give to committing trans");
ret = __dispose_buffer(jh,
journal->j_committing_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* The orphan record's transaction has
* committed. We can cleanse this buffer */
clear_buffer_jbddirty(bh);
goto zap_buffer;
}
}
} else if (transaction == journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "on committing transaction");
/*
* The buffer is committing, we simply cannot touch
* it. So we just set j_next_transaction to the
* running transaction (if there is one) and mark
* buffer as freed so that commit code knows it should
* clear dirty bits when it is done with the buffer.
*/
set_buffer_freed(bh);
if (journal->j_running_transaction && buffer_jbddirty(bh))
jh->b_next_transaction = journal->j_running_transaction;
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return 0;
} else {
/* Good, the buffer belongs to the running transaction.
* We are writing our own transaction's data, not any
* previous one's, so it is safe to throw it away
* (remember that we expect the filesystem to have set
* i_size already for this truncate so recovery will not
* expose the disk blocks we are discarding here.) */
J_ASSERT_JH(jh, transaction == journal->j_running_transaction);
JBUFFER_TRACE(jh, "on running transaction");
may_free = __dispose_buffer(jh, transaction);
}
zap_buffer:
jbd2_journal_put_journal_head(jh);
zap_buffer_no_jh:
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
zap_buffer_unlocked:
clear_buffer_dirty(bh);
J_ASSERT_BH(bh, !buffer_jbddirty(bh));
clear_buffer_mapped(bh);
clear_buffer_req(bh);
clear_buffer_new(bh);
bh->b_bdev = NULL;
return may_free;
}
Commit Message: jbd2: clear BH_Delay & BH_Unwritten in journal_unmap_buffer
journal_unmap_buffer()'s zap_buffer: code clears a lot of buffer head
state ala discard_buffer(), but does not touch _Delay or _Unwritten as
discard_buffer() does.
This can be problematic in some areas of the ext4 code which assume
that if they have found a buffer marked unwritten or delay, then it's
a live one. Perhaps those spots should check whether it is mapped
as well, but if jbd2 is going to tear down a buffer, let's really
tear it down completely.
Without this I get some fsx failures on sub-page-block filesystems
up until v3.2, at which point 4e96b2dbbf1d7e81f22047a50f862555a6cb87cb
and 189e868fa8fdca702eb9db9d8afc46b5cb9144c9 make the failures go
away, because buried within that large change is some more flag
clearing. I still think it's worth doing in jbd2, since
->invalidatepage leads here directly, and it's the right place
to clear away these flags.
Signed-off-by: Eric Sandeen <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-119 | static int journal_unmap_buffer(journal_t *journal, struct buffer_head *bh)
{
transaction_t *transaction;
struct journal_head *jh;
int may_free = 1;
int ret;
BUFFER_TRACE(bh, "entry");
/*
* It is safe to proceed here without the j_list_lock because the
* buffers cannot be stolen by try_to_free_buffers as long as we are
* holding the page lock. --sct
*/
if (!buffer_jbd(bh))
goto zap_buffer_unlocked;
/* OK, we have data buffer in journaled mode */
write_lock(&journal->j_state_lock);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
jh = jbd2_journal_grab_journal_head(bh);
if (!jh)
goto zap_buffer_no_jh;
/*
* We cannot remove the buffer from checkpoint lists until the
* transaction adding inode to orphan list (let's call it T)
* is committed. Otherwise if the transaction changing the
* buffer would be cleaned from the journal before T is
* committed, a crash will cause that the correct contents of
* the buffer will be lost. On the other hand we have to
* clear the buffer dirty bit at latest at the moment when the
* transaction marking the buffer as freed in the filesystem
* structures is committed because from that moment on the
* buffer can be reallocated and used by a different page.
* Since the block hasn't been freed yet but the inode has
* already been added to orphan list, it is safe for us to add
* the buffer to BJ_Forget list of the newest transaction.
*/
transaction = jh->b_transaction;
if (transaction == NULL) {
/* First case: not on any transaction. If it
* has no checkpoint link, then we can zap it:
* it's a writeback-mode buffer so we don't care
* if it hits disk safely. */
if (!jh->b_cp_transaction) {
JBUFFER_TRACE(jh, "not on any transaction: zap");
goto zap_buffer;
}
if (!buffer_dirty(bh)) {
/* bdflush has written it. We can drop it now */
goto zap_buffer;
}
/* OK, it must be in the journal but still not
* written fully to disk: it's metadata or
* journaled data... */
if (journal->j_running_transaction) {
/* ... and once the current transaction has
* committed, the buffer won't be needed any
* longer. */
JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget");
ret = __dispose_buffer(jh,
journal->j_running_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* There is no currently-running transaction. So the
* orphan record which we wrote for this file must have
* passed into commit. We must attach this buffer to
* the committing transaction, if it exists. */
if (journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "give to committing trans");
ret = __dispose_buffer(jh,
journal->j_committing_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* The orphan record's transaction has
* committed. We can cleanse this buffer */
clear_buffer_jbddirty(bh);
goto zap_buffer;
}
}
} else if (transaction == journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "on committing transaction");
/*
* The buffer is committing, we simply cannot touch
* it. So we just set j_next_transaction to the
* running transaction (if there is one) and mark
* buffer as freed so that commit code knows it should
* clear dirty bits when it is done with the buffer.
*/
set_buffer_freed(bh);
if (journal->j_running_transaction && buffer_jbddirty(bh))
jh->b_next_transaction = journal->j_running_transaction;
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return 0;
} else {
/* Good, the buffer belongs to the running transaction.
* We are writing our own transaction's data, not any
* previous one's, so it is safe to throw it away
* (remember that we expect the filesystem to have set
* i_size already for this truncate so recovery will not
* expose the disk blocks we are discarding here.) */
J_ASSERT_JH(jh, transaction == journal->j_running_transaction);
JBUFFER_TRACE(jh, "on running transaction");
may_free = __dispose_buffer(jh, transaction);
}
zap_buffer:
jbd2_journal_put_journal_head(jh);
zap_buffer_no_jh:
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
zap_buffer_unlocked:
clear_buffer_dirty(bh);
J_ASSERT_BH(bh, !buffer_jbddirty(bh));
clear_buffer_mapped(bh);
clear_buffer_req(bh);
clear_buffer_new(bh);
clear_buffer_delay(bh);
clear_buffer_unwritten(bh);
bh->b_bdev = NULL;
return may_free;
}
| 165,741 |
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 ThreadableBlobRegistry::registerStreamURL(const KURL& url, const String& type)
{
if (isMainThread()) {
blobRegistry().registerStreamURL(url, type);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type));
callOnMainThread(®isterStreamURLTask, context.leakPtr());
}
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void ThreadableBlobRegistry::registerStreamURL(const KURL& url, const String& type)
void BlobRegistry::registerStreamURL(const KURL& url, const String& type)
{
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry())
registry->registerStreamURL(url, type);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type));
callOnMainThread(®isterStreamURLTask, context.leakPtr());
}
}
| 170,688 |
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: IMPEG2D_ERROR_CODES_T impeg2d_init_video_state(dec_state_t *ps_dec, e_video_type_t e_video_type)
{
/*-----------------------------------------------------------------------*/
/* Bit Stream that conforms to MPEG-1 <ISO/IEC 11172-2> standard */
/*-----------------------------------------------------------------------*/
if(e_video_type == MPEG_1_VIDEO)
{
ps_dec->u2_is_mpeg2 = 0;
/*-------------------------------------------------------------------*/
/* force MPEG-1 parameters for proper decoder behavior */
/* see ISO/IEC 13818-2 section D.9.14 */
/*-------------------------------------------------------------------*/
ps_dec->u2_progressive_sequence = 1;
ps_dec->u2_intra_dc_precision = 0;
ps_dec->u2_picture_structure = FRAME_PICTURE;
ps_dec->u2_frame_pred_frame_dct = 1;
ps_dec->u2_concealment_motion_vectors = 0;
ps_dec->u2_q_scale_type = 0;
ps_dec->u2_intra_vlc_format = 0;
ps_dec->u2_alternate_scan = 0;
ps_dec->u2_repeat_first_field = 0;
ps_dec->u2_progressive_frame = 1;
ps_dec->u2_frame_rate_extension_n = 0;
ps_dec->u2_frame_rate_extension_d = 0;
ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg1;
/*-------------------------------------------------------------------*/
/* Setting of parameters other than those mentioned in MPEG2 standard*/
/* but used in decoding process. */
/*-------------------------------------------------------------------*/
}
/*-----------------------------------------------------------------------*/
/* Bit Stream that conforms to MPEG-2 */
/*-----------------------------------------------------------------------*/
else
{
ps_dec->u2_is_mpeg2 = 1;
ps_dec->u2_full_pel_forw_vector = 0;
ps_dec->u2_forw_f_code = 7;
ps_dec->u2_full_pel_back_vector = 0;
ps_dec->u2_back_f_code = 7;
ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg2;
}
impeg2d_init_function_ptr(ps_dec);
/* Set the frame Width and frame Height */
ps_dec->u2_frame_height = ALIGN16(ps_dec->u2_vertical_size);
ps_dec->u2_frame_width = ALIGN16(ps_dec->u2_horizontal_size);
ps_dec->u2_num_horiz_mb = (ps_dec->u2_horizontal_size + 15) >> 4;
if (ps_dec->u2_frame_height > ps_dec->u2_create_max_height || ps_dec->u2_frame_width > ps_dec->u2_create_max_width)
{
return IMPEG2D_PIC_SIZE_NOT_SUPPORTED;
}
ps_dec->u2_num_flds_decoded = 0;
/* Calculate the frame period */
{
UWORD32 numer;
UWORD32 denom;
numer = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][1] *
(UWORD32)(ps_dec->u2_frame_rate_extension_d + 1);
denom = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][0] *
(UWORD32)(ps_dec->u2_frame_rate_extension_n + 1);
ps_dec->u2_framePeriod = (numer * 1000 * 100) / denom;
}
if(VERTICAL_SCAN == ps_dec->u2_alternate_scan)
{
ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_vertical;
}
else
{
ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_zig_zag;
}
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Adding Error Check for f_code Parameters
In MPEG1, the valid range for the forward and backward f_code parameters
is [1, 7]. Adding a check to enforce this. Without the check, the value
could be 0. We read (f_code - 1) bits from the stream and reading a
negative number of bits from the stream is undefined.
Bug: 64550583
Test: monitored temp ALOGD() output
Change-Id: Ia452cd43a28e9d566401f515947164635361782f
(cherry picked from commit 71d734b83d72e8a59f73f1230982da97615d2689)
CWE ID: CWE-200 | IMPEG2D_ERROR_CODES_T impeg2d_init_video_state(dec_state_t *ps_dec, e_video_type_t e_video_type)
{
/*-----------------------------------------------------------------------*/
/* Bit Stream that conforms to MPEG-1 <ISO/IEC 11172-2> standard */
/*-----------------------------------------------------------------------*/
if(e_video_type == MPEG_1_VIDEO)
{
ps_dec->u2_is_mpeg2 = 0;
/*-------------------------------------------------------------------*/
/* force MPEG-1 parameters for proper decoder behavior */
/* see ISO/IEC 13818-2 section D.9.14 */
/*-------------------------------------------------------------------*/
ps_dec->u2_progressive_sequence = 1;
ps_dec->u2_intra_dc_precision = 0;
ps_dec->u2_picture_structure = FRAME_PICTURE;
ps_dec->u2_frame_pred_frame_dct = 1;
ps_dec->u2_concealment_motion_vectors = 0;
ps_dec->u2_q_scale_type = 0;
ps_dec->u2_intra_vlc_format = 0;
ps_dec->u2_alternate_scan = 0;
ps_dec->u2_repeat_first_field = 0;
ps_dec->u2_progressive_frame = 1;
ps_dec->u2_frame_rate_extension_n = 0;
ps_dec->u2_frame_rate_extension_d = 0;
ps_dec->u2_forw_f_code = 7;
ps_dec->u2_back_f_code = 7;
ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg1;
/*-------------------------------------------------------------------*/
/* Setting of parameters other than those mentioned in MPEG2 standard*/
/* but used in decoding process. */
/*-------------------------------------------------------------------*/
}
/*-----------------------------------------------------------------------*/
/* Bit Stream that conforms to MPEG-2 */
/*-----------------------------------------------------------------------*/
else
{
ps_dec->u2_is_mpeg2 = 1;
ps_dec->u2_full_pel_forw_vector = 0;
ps_dec->u2_forw_f_code = 7;
ps_dec->u2_full_pel_back_vector = 0;
ps_dec->u2_back_f_code = 7;
ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg2;
}
impeg2d_init_function_ptr(ps_dec);
/* Set the frame Width and frame Height */
ps_dec->u2_frame_height = ALIGN16(ps_dec->u2_vertical_size);
ps_dec->u2_frame_width = ALIGN16(ps_dec->u2_horizontal_size);
ps_dec->u2_num_horiz_mb = (ps_dec->u2_horizontal_size + 15) >> 4;
if (ps_dec->u2_frame_height > ps_dec->u2_create_max_height || ps_dec->u2_frame_width > ps_dec->u2_create_max_width)
{
return IMPEG2D_PIC_SIZE_NOT_SUPPORTED;
}
ps_dec->u2_num_flds_decoded = 0;
/* Calculate the frame period */
{
UWORD32 numer;
UWORD32 denom;
numer = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][1] *
(UWORD32)(ps_dec->u2_frame_rate_extension_d + 1);
denom = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][0] *
(UWORD32)(ps_dec->u2_frame_rate_extension_n + 1);
ps_dec->u2_framePeriod = (numer * 1000 * 100) / denom;
}
if(VERTICAL_SCAN == ps_dec->u2_alternate_scan)
{
ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_vertical;
}
else
{
ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_zig_zag;
}
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
| 174,104 |
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 GLES2DecoderImpl::SimulateAttrib0(GLuint max_vertex_accessed) {
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return false;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_.GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return false;
}
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
GLsizei num_vertices = max_vertex_accessed + 1;
GLsizei size_needed = num_vertices * sizeof(Vec4); // NOLINT
if (size_needed > attrib_0_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
attrib_0_buffer_matches_value_ = false;
}
if (attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3]))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
return true;
}
Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0."""
TEST=none
BUG=95625
[email protected]
Review URL: http://codereview.chromium.org/7796016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool GLES2DecoderImpl::SimulateAttrib0(GLuint max_vertex_accessed) {
bool GLES2DecoderImpl::SimulateAttrib0(
GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_.GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return true;
}
// Make a buffer with a single repeated vec4 value enough to
// simulate the constant value that is supposed to be here.
// This is required to emulate GLES2 on GL.
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
GLuint num_vertices = max_vertex_accessed + 1;
GLuint size_needed = 0;
if (num_vertices == 0 ||
!SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)),
&size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
if (static_cast<GLsizei>(size_needed) > attrib_0_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
attrib_0_buffer_matches_value_ = false;
}
if (attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3]))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
*simulated = true;
return true;
}
| 170,332 |
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: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size,
png_bytep output, png_size_t output_size)
{
png_size_t count = 0;
png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */
png_ptr->zstream.avail_in = size;
while (1)
{
int ret, avail;
/* Reset the output buffer each time round - we empty it
* after every inflate call.
*/
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = png_ptr->zbuf_size;
ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out;
/* First copy/count any new output - but only if we didn't
* get an error code.
*/
if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0)
{
if (output != 0 && output_size > count)
{
png_size_t copy = output_size - count;
if ((png_size_t) avail < copy) copy = (png_size_t) avail;
png_memcpy(output + count, png_ptr->zbuf, copy);
}
count += avail;
}
if (ret == Z_OK)
continue;
/* Termination conditions - always reset the zstream, it
* must be left in inflateInit state.
*/
png_ptr->zstream.avail_in = 0;
inflateReset(&png_ptr->zstream);
if (ret == Z_STREAM_END)
return count; /* NOTE: may be zero. */
/* Now handle the error codes - the API always returns 0
* and the error message is dumped into the uncompressed
* buffer if available.
*/
{
PNG_CONST char *msg;
if (png_ptr->zstream.msg != 0)
msg = png_ptr->zstream.msg;
else
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char umsg[52];
switch (ret)
{
case Z_BUF_ERROR:
msg = "Buffer error in compressed datastream in %s chunk";
break;
case Z_DATA_ERROR:
msg = "Data error in compressed datastream in %s chunk";
break;
default:
msg = "Incomplete compressed datastream in %s chunk";
break;
}
png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name);
msg = umsg;
#else
msg = "Damaged compressed datastream in chunk other than IDAT";
#endif
}
png_warning(png_ptr, msg);
}
/* 0 means an error - notice that this code simple ignores
* zero length compressed chunks as a result.
*/
return 0;
}
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size,
png_bytep output, png_size_t output_size)
{
png_size_t count = 0;
png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */
png_ptr->zstream.avail_in = size;
while (1)
{
int ret, avail;
/* Reset the output buffer each time round - we empty it
* after every inflate call.
*/
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = png_ptr->zbuf_size;
ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out;
/* First copy/count any new output - but only if we didn't
* get an error code.
*/
if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0)
{
if (output != 0 && output_size > count)
{
png_size_t copy = output_size - count;
if ((png_size_t) avail < copy) copy = (png_size_t) avail;
png_memcpy(output + count, png_ptr->zbuf, copy);
}
count += avail;
}
if (ret == Z_OK)
continue;
/* Termination conditions - always reset the zstream, it
* must be left in inflateInit state.
*/
png_ptr->zstream.avail_in = 0;
inflateReset(&png_ptr->zstream);
if (ret == Z_STREAM_END)
return count; /* NOTE: may be zero. */
/* Now handle the error codes - the API always returns 0
* and the error message is dumped into the uncompressed
* buffer if available.
*/
{
PNG_CONST char *msg;
if (png_ptr->zstream.msg != 0)
msg = png_ptr->zstream.msg;
else
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char umsg[52];
switch (ret)
{
case Z_BUF_ERROR:
msg = "Buffer error in compressed datastream in %s chunk";
break;
case Z_DATA_ERROR:
msg = "Data error in compressed datastream in %s chunk";
break;
default:
msg = "Incomplete compressed datastream in %s chunk";
break;
}
png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name);
msg = umsg;
png_warning(png_ptr, msg);
#else
msg = "Damaged compressed datastream in chunk other than IDAT";
#endif
}
#ifndef PNG_STDIO_SUPPORTED
png_warning(png_ptr, msg);
#endif
}
/* 0 means an error - notice that this code simple ignores
* zero length compressed chunks as a result.
*/
return 0;
}
}
| 172,179 |
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 ContentBrowserClient::ShouldSwapProcessesForNavigation(
const GURL& current_url,
const GURL& new_url) {
return false;
}
Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances.
BUG=174943
TEST=Can't post message to CWS. See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12301013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ContentBrowserClient::ShouldSwapProcessesForNavigation(
SiteInstance* site_instance,
const GURL& current_url,
const GURL& new_url) {
return false;
}
| 171,438 |
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 sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sco_pinfo *pi = sco_pi(sk);
lock_sock(sk);
if (sk->sk_state == BT_CONNECT2 &&
test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {
sco_conn_defer_accept(pi->conn->hcon, pi->setting);
sk->sk_state = BT_CONFIG;
msg->msg_namelen = 0;
release_sock(sk);
return 0;
}
release_sock(sk);
return bt_sock_recvmsg(iocb, sock, msg, len, flags);
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sco_pinfo *pi = sco_pi(sk);
lock_sock(sk);
if (sk->sk_state == BT_CONNECT2 &&
test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {
sco_conn_defer_accept(pi->conn->hcon, pi->setting);
sk->sk_state = BT_CONFIG;
release_sock(sk);
return 0;
}
release_sock(sk);
return bt_sock_recvmsg(iocb, sock, msg, len, flags);
}
| 166,495 |
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[]) {
struct mg_context *ctx;
base::AtExitManager exit;
base::WaitableEvent shutdown_event(false, false);
CommandLine::Init(argc, argv);
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
#if defined(OS_POSIX)
signal(SIGPIPE, SIG_IGN);
#endif
srand((unsigned int)time(NULL));
chrome::RegisterPathProvider();
TestTimeouts::Initialize();
InitChromeDriverLogging(*cmd_line);
std::string port = "9515";
std::string root;
std::string url_base;
if (cmd_line->HasSwitch("port"))
port = cmd_line->GetSwitchValueASCII("port");
if (cmd_line->HasSwitch("root"))
root = cmd_line->GetSwitchValueASCII("root");
if (cmd_line->HasSwitch("url-base"))
url_base = cmd_line->GetSwitchValueASCII("url-base");
webdriver::SessionManager* manager = webdriver::SessionManager::GetInstance();
manager->set_port(port);
manager->set_url_base(url_base);
ctx = mg_start();
if (!SetMongooseOptions(ctx, port, root)) {
mg_stop(ctx);
#if defined(OS_WIN)
return WSAEADDRINUSE;
#else
return EADDRINUSE;
#endif
}
webdriver::Dispatcher dispatcher(ctx, url_base);
webdriver::InitCallbacks(ctx, &dispatcher, &shutdown_event, root.empty());
std::cout << "Started ChromeDriver" << std::endl
<< "port=" << port << std::endl;
if (root.length()) {
VLOG(1) << "Serving files from the current working directory";
}
shutdown_event.Wait();
mg_stop(ctx);
return (EXIT_SUCCESS);
}
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 | int main(int argc, char *argv[]) {
struct mg_context *ctx;
base::AtExitManager exit;
base::WaitableEvent shutdown_event(false, false);
CommandLine::Init(argc, argv);
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
#if defined(OS_POSIX)
signal(SIGPIPE, SIG_IGN);
#endif
srand((unsigned int)time(NULL));
chrome::RegisterPathProvider();
TestTimeouts::Initialize();
std::string port = "9515";
std::string root;
std::string url_base;
bool verbose = false;
if (cmd_line->HasSwitch("port"))
port = cmd_line->GetSwitchValueASCII("port");
if (cmd_line->HasSwitch("root"))
root = cmd_line->GetSwitchValueASCII("root");
if (cmd_line->HasSwitch("url-base"))
url_base = cmd_line->GetSwitchValueASCII("url-base");
// Whether or not to do verbose logging.
if (cmd_line->HasSwitch("verbose"))
verbose = true;
webdriver::InitWebDriverLogging(
verbose ? logging::LOG_INFO : logging::LOG_WARNING);
webdriver::SessionManager* manager = webdriver::SessionManager::GetInstance();
manager->set_port(port);
manager->set_url_base(url_base);
ctx = mg_start();
if (!SetMongooseOptions(ctx, port, root)) {
mg_stop(ctx);
#if defined(OS_WIN)
return WSAEADDRINUSE;
#else
return EADDRINUSE;
#endif
}
webdriver::Dispatcher dispatcher(ctx, url_base);
webdriver::InitCallbacks(ctx, &dispatcher, &shutdown_event, root.empty());
std::cout << "Started ChromeDriver" << std::endl
<< "port=" << port << std::endl;
if (root.length()) {
VLOG(1) << "Serving files from the current working directory";
}
shutdown_event.Wait();
mg_stop(ctx);
return (EXIT_SUCCESS);
}
| 170,462 |
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 BaseRenderingContext2D::ClearResolvedFilters() {
for (auto& state : state_stack_)
state->ClearResolvedFilter();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Chris Harrelson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200 | void BaseRenderingContext2D::ClearResolvedFilters() {
void BaseRenderingContext2D::SetOriginTaintedByContent() {
SetOriginTainted();
origin_tainted_by_content_ = true;
for (auto& state : state_stack_)
state->ClearResolvedFilter();
}
| 172,905 |
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 ChromeRenderProcessObserver::OnWriteTcmallocHeapProfile(
const FilePath::StringType& filename) {
#if !defined(OS_WIN)
if (!IsHeapProfilerRunning())
return;
char* profile = GetHeapProfile();
if (!profile) {
LOG(WARNING) << "Unable to get heap profile.";
return;
}
std::string result(profile);
delete profile;
RenderThread::Get()->Send(
new ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK(filename, result));
#endif
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
[email protected]
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ChromeRenderProcessObserver::OnWriteTcmallocHeapProfile(
| 170,667 |
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 handle_wrmsr(struct kvm_vcpu *vcpu)
{
struct msr_data msr;
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
if (vmx_set_msr(vcpu, &msr) != 0) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(vcpu);
return 1;
}
Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR
Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is
written to certain MSRs. The behavior is "almost" identical for AMD and Intel
(ignoring MSRs that are not implemented in either architecture since they would
anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
non-canonical address is written on Intel but not on AMD (which ignores the top
32-bits).
Accordingly, this patch injects a #GP on the MSRs which behave identically on
Intel and AMD. To eliminate the differences between the architecutres, the
value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to
canonical value before writing instead of injecting a #GP.
Some references from Intel and AMD manuals:
According to Intel SDM description of WRMSR instruction #GP is expected on
WRMSR "If the source register contains a non-canonical address and ECX
specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE,
IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP."
According to AMD manual instruction manual:
LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the
LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical
form, a general-protection exception (#GP) occurs."
IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the
base field must be in canonical form or a #GP fault will occur."
IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must
be in canonical form."
This patch fixes CVE-2014-3610.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int handle_wrmsr(struct kvm_vcpu *vcpu)
{
struct msr_data msr;
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
if (kvm_set_msr(vcpu, &msr) != 0) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(vcpu);
return 1;
}
| 166,349 |
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 NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(
process_->GetBrowserContext());
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
interceptor->GetResponseBody(interception_id, std::move(callback));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(browser_context_);
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
interceptor->GetResponseBody(interception_id, std::move(callback));
}
| 172,758 |
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: find_file (const char *currpath, grub_fshelp_node_t currroot,
grub_fshelp_node_t *currfound,
struct grub_fshelp_find_file_closure *c)
{
#ifndef _MSC_VER
char fpath[grub_strlen (currpath) + 1];
#else
char *fpath = grub_malloc (grub_strlen (currpath) + 1);
#endif
char *name = fpath;
char *next;
enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;
grub_fshelp_node_t currnode = currroot;
grub_fshelp_node_t oldnode = currroot;
c->currroot = currroot;
grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);
/* Remove all leading slashes. */
while (*name == '/')
name++;
if (! *name)
{
*currfound = currnode;
return 0;
}
for (;;)
{
int found;
struct find_file_closure cc;
/* Extract the actual part from the pathname. */
next = grub_strchr (name, '/');
if (next)
{
/* Remove all leading slashes. */
while (*next == '/')
*(next++) = '\0';
}
/* At this point it is expected that the current node is a
directory, check if this is true. */
if (type != GRUB_FSHELP_DIR)
{
free_node (currnode, c);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
}
cc.name = name;
cc.type = &type;
cc.oldnode = &oldnode;
cc.currnode = &currnode;
/* Iterate over the directory. */
found = c->iterate_dir (currnode, iterate, &cc);
if (! found)
{
if (grub_errno)
return grub_errno;
break;
}
/* Read in the symlink and follow it. */
if (type == GRUB_FSHELP_SYMLINK)
{
char *symlink;
/* Test if the symlink does not loop. */
if (++(c->symlinknest) == 8)
{
free_node (currnode, c);
free_node (oldnode, c);
return grub_error (GRUB_ERR_SYMLINK_LOOP,
"too deep nesting of symlinks");
}
symlink = c->read_symlink (currnode);
free_node (currnode, c);
if (!symlink)
{
free_node (oldnode, c);
return grub_errno;
}
/* The symlink is an absolute path, go back to the root inode. */
if (symlink[0] == '/')
{
free_node (oldnode, c);
oldnode = c->rootnode;
}
/* Lookup the node the symlink points to. */
find_file (symlink, oldnode, &currnode, c);
type = c->foundtype;
grub_free (symlink);
if (grub_errno)
{
free_node (oldnode, c);
return grub_errno;
}
}
free_node (oldnode, c);
/* Found the node! */
if (! next || *next == '\0')
{
*currfound = currnode;
c->foundtype = type;
return 0;
}
name = next;
}
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found");
}
Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack
CWE ID: CWE-119 | find_file (const char *currpath, grub_fshelp_node_t currroot,
grub_fshelp_node_t *currfound,
struct grub_fshelp_find_file_closure *c)
{
char *fpath = grub_malloc (grub_strlen (currpath) + 1);
char *name = fpath;
char *next;
enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;
grub_fshelp_node_t currnode = currroot;
grub_fshelp_node_t oldnode = currroot;
c->currroot = currroot;
grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);
/* Remove all leading slashes. */
while (*name == '/')
name++;
if (! *name)
{
*currfound = currnode;
free (fpath);
return 0;
}
for (;;)
{
int found;
struct find_file_closure cc;
/* Extract the actual part from the pathname. */
next = grub_strchr (name, '/');
if (next)
{
/* Remove all leading slashes. */
while (*next == '/')
*(next++) = '\0';
}
/* At this point it is expected that the current node is a
directory, check if this is true. */
if (type != GRUB_FSHELP_DIR)
{
free_node (currnode, c);
free (fpath);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
}
cc.name = name;
cc.type = &type;
cc.oldnode = &oldnode;
cc.currnode = &currnode;
/* Iterate over the directory. */
found = c->iterate_dir (currnode, iterate, &cc);
if (! found)
{
if (grub_errno) {
free (fpath);
return grub_errno;
}
break;
}
/* Read in the symlink and follow it. */
if (type == GRUB_FSHELP_SYMLINK)
{
char *symlink;
/* Test if the symlink does not loop. */
if (++(c->symlinknest) == 8)
{
free_node (currnode, c);
free_node (oldnode, c);
free (fpath);
return grub_error (GRUB_ERR_SYMLINK_LOOP,
"too deep nesting of symlinks");
}
symlink = c->read_symlink (currnode);
free_node (currnode, c);
if (!symlink)
{
free_node (oldnode, c);
free (fpath);
return grub_errno;
}
/* The symlink is an absolute path, go back to the root inode. */
if (symlink[0] == '/')
{
free_node (oldnode, c);
oldnode = c->rootnode;
}
/* Lookup the node the symlink points to. */
find_file (symlink, oldnode, &currnode, c);
type = c->foundtype;
grub_free (symlink);
if (grub_errno)
{
free_node (oldnode, c);
free (fpath);
return grub_errno;
}
}
free_node (oldnode, c);
/* Found the node! */
if (! next || *next == '\0')
{
*currfound = currnode;
c->foundtype = type;
free (fpath);
return 0;
}
name = next;
}
free (fpath);
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found");
}
| 168,089 |
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 ndp_msg_check_valid(struct ndp_msg *msg)
{
size_t len = ndp_msg_payload_len(msg);
enum ndp_msg_type msg_type = ndp_msg_type(msg);
if (len < ndp_msg_type_info(msg_type)->raw_struct_size)
return false;
return true;
}
Commit Message: libndb: reject redirect and router advertisements from non-link-local
RFC4861 suggests that these messages should only originate from
link-local addresses in 6.1.2 (RA) and 8.1. (redirect):
Mitigates CVE-2016-3698.
Signed-off-by: Lubomir Rintel <[email protected]>
Signed-off-by: Jiri Pirko <[email protected]>
CWE ID: CWE-284 | static bool ndp_msg_check_valid(struct ndp_msg *msg)
{
size_t len = ndp_msg_payload_len(msg);
enum ndp_msg_type msg_type = ndp_msg_type(msg);
if (len < ndp_msg_type_info(msg_type)->raw_struct_size)
return false;
if (ndp_msg_type_info(msg_type)->addrto_validate)
return ndp_msg_type_info(msg_type)->addrto_validate(&msg->addrto);
else
return true;
}
| 169,971 |
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 WebGLRenderingContextBase::TexImageImpl(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLenum format,
GLenum type,
Image* image,
WebGLImageConversion::ImageHtmlDomSource dom_source,
bool flip_y,
bool premultiply_alpha,
const IntRect& source_image_rect,
GLsizei depth,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
Vector<uint8_t> data;
IntRect sub_rect = source_image_rect;
if (sub_rect == SentinelEmptyRect()) {
sub_rect = SafeGetImageSize(image);
}
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(func_name, function_id, image, sub_rect,
depth, unpack_image_height,
&selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = sub_rect;
if (flip_y) {
adjusted_source_image_rect.SetY(image->height() -
adjusted_source_image_rect.MaxY());
}
WebGLImageConversion::ImageExtractor image_extractor(
image, dom_source, premultiply_alpha,
unpack_colorspace_conversion_ == GL_NONE);
if (!image_extractor.ImagePixelData()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
WebGLImageConversion::DataFormat source_data_format =
image_extractor.ImageSourceFormat();
WebGLImageConversion::AlphaOp alpha_op = image_extractor.ImageAlphaOp();
const void* image_pixel_data = image_extractor.ImagePixelData();
bool need_conversion = true;
if (type == GL_UNSIGNED_BYTE &&
source_data_format == WebGLImageConversion::kDataFormatRGBA8 &&
format == GL_RGBA && alpha_op == WebGLImageConversion::kAlphaDoNothing &&
!flip_y && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (!WebGLImageConversion::PackImageData(
image, image_pixel_data, format, type, flip_y, alpha_op,
source_data_format, image_extractor.ImageWidth(),
image_extractor.ImageHeight(), adjusted_source_image_rect, depth,
image_extractor.ImageSourceUnpackAlignment(), unpack_image_height,
data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "packImage error");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
if (function_id == kTexImage2D) {
TexImage2DBase(target, level, internalformat,
adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), 0, format, type,
need_conversion ? data.data() : image_pixel_data);
} else if (function_id == kTexSubImage2D) {
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type,
need_conversion ? data.data() : image_pixel_data);
} else {
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), depth, 0, format, type,
need_conversion ? data.data() : image_pixel_data);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(
target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), depth, format, type,
need_conversion ? data.data() : image_pixel_data);
}
}
}
Commit Message: Tighten about IntRect use in WebGL with overflow detection
BUG=784183
TEST=test case in the bug in ASAN build
[email protected]
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: Ie25ca328af99de7828e28e6a6e3d775f1bebc43f
Reviewed-on: https://chromium-review.googlesource.com/811826
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522213}
CWE ID: CWE-125 | void WebGLRenderingContextBase::TexImageImpl(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLenum format,
GLenum type,
Image* image,
WebGLImageConversion::ImageHtmlDomSource dom_source,
bool flip_y,
bool premultiply_alpha,
const IntRect& source_image_rect,
GLsizei depth,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
Vector<uint8_t> data;
IntRect sub_rect = source_image_rect;
if (sub_rect.IsValid() && sub_rect == SentinelEmptyRect()) {
sub_rect = SafeGetImageSize(image);
}
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(func_name, function_id, image, sub_rect,
depth, unpack_image_height,
&selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = sub_rect;
if (flip_y) {
adjusted_source_image_rect.SetY(image->height() -
adjusted_source_image_rect.MaxY());
}
WebGLImageConversion::ImageExtractor image_extractor(
image, dom_source, premultiply_alpha,
unpack_colorspace_conversion_ == GL_NONE);
if (!image_extractor.ImagePixelData()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
WebGLImageConversion::DataFormat source_data_format =
image_extractor.ImageSourceFormat();
WebGLImageConversion::AlphaOp alpha_op = image_extractor.ImageAlphaOp();
const void* image_pixel_data = image_extractor.ImagePixelData();
bool need_conversion = true;
if (type == GL_UNSIGNED_BYTE &&
source_data_format == WebGLImageConversion::kDataFormatRGBA8 &&
format == GL_RGBA && alpha_op == WebGLImageConversion::kAlphaDoNothing &&
!flip_y && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (!WebGLImageConversion::PackImageData(
image, image_pixel_data, format, type, flip_y, alpha_op,
source_data_format, image_extractor.ImageWidth(),
image_extractor.ImageHeight(), adjusted_source_image_rect, depth,
image_extractor.ImageSourceUnpackAlignment(), unpack_image_height,
data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "packImage error");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
if (function_id == kTexImage2D) {
TexImage2DBase(target, level, internalformat,
adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), 0, format, type,
need_conversion ? data.data() : image_pixel_data);
} else if (function_id == kTexSubImage2D) {
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type,
need_conversion ? data.data() : image_pixel_data);
} else {
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), depth, 0, format, type,
need_conversion ? data.data() : image_pixel_data);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(
target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), depth, format, type,
need_conversion ? data.data() : image_pixel_data);
}
}
}
| 172,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: krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_gss_ctx_id_rec *ctx;
size_t i;
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
if (data_set == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*data_set = GSS_C_NO_BUFFER_SET;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (!ctx->established)
return GSS_S_NO_CONTEXT;
for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/
sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) {
return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status,
context_handle,
desired_object,
data_set);
}
}
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_gss_ctx_id_rec *ctx;
size_t i;
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
if (data_set == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*data_set = GSS_C_NO_BUFFER_SET;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (ctx->terminated || !ctx->established)
return GSS_S_NO_CONTEXT;
for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/
sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) {
return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status,
context_handle,
desired_object,
data_set);
}
}
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
| 166,815 |
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: status_t OMXNodeInstance::getParameter(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
OMX_ERRORTYPE err = OMX_GetParameter(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getParameter, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::getParameter(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_GetParameter(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getParameter, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
| 174,135 |
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 expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, "w.ufdio");
umask(old_umask);
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
Commit Message: Don't follow symlinks on file creation (CVE-2017-7501)
Open newly created files with O_EXCL to prevent symlink tricks.
When reopening hardlinks for writing the actual content, use append
mode instead. This is compatible with the write-only permissions but
is not destructive in case we got redirected to somebody elses file,
verify the target before actually writing anything.
As these are files with the temporary suffix, errors mean a local
user with sufficient privileges to break the installation of the package
anyway is trying to goof us on purpose, don't bother trying to mend it
(we couldn't fix the hardlink case anyhow) but just bail out.
Based on a patch by Florian Festi.
CWE ID: CWE-59 | static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, exclusive ? "wx.ufdio" : "a.ufdio");
umask(old_umask);
/* If reopening, make sure the file is what we expect */
if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
| 168,267 |
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 xt_compat_check_entry_offsets(const void *base,
unsigned int target_offset,
unsigned int next_offset)
{
const struct compat_xt_entry_target *t;
const char *e = base;
if (target_offset + sizeof(*t) > next_offset)
return -EINVAL;
t = (void *)(e + target_offset);
if (t->u.target_size < sizeof(*t))
return -EINVAL;
if (target_offset + t->u.target_size > next_offset)
return -EINVAL;
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
target_offset + sizeof(struct compat_xt_standard_target) != next_offset)
return -EINVAL;
return 0;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264 | int xt_compat_check_entry_offsets(const void *base,
int xt_compat_check_entry_offsets(const void *base, const char *elems,
unsigned int target_offset,
unsigned int next_offset)
{
long size_of_base_struct = elems - (const char *)base;
const struct compat_xt_entry_target *t;
const char *e = base;
if (target_offset < size_of_base_struct)
return -EINVAL;
if (target_offset + sizeof(*t) > next_offset)
return -EINVAL;
t = (void *)(e + target_offset);
if (t->u.target_size < sizeof(*t))
return -EINVAL;
if (target_offset + t->u.target_size > next_offset)
return -EINVAL;
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
target_offset + sizeof(struct compat_xt_standard_target) != next_offset)
return -EINVAL;
return 0;
}
| 167,222 |
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: SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
char *buf;
size_t buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval entry, inf;
zval *pcount, *pmembers;
spl_SplObjectStorageElement *element;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
pcount = var_tmp_var(&var_hash);
if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
while (count-- > 0) {
spl_SplObjectStorageElement *pelement;
zend_string *hash;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
/* store reference to allow cross-references between different elements */
if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) {
goto outexcept;
}
if (Z_TYPE(entry) != IS_OBJECT) {
zval_ptr_dtor(&entry);
goto outexcept;
}
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) {
zval_ptr_dtor(&entry);
goto outexcept;
}
} else {
ZVAL_UNDEF(&inf);
}
hash = spl_object_storage_get_hash(intern, getThis(), &entry);
if (!hash) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash);
spl_object_storage_free_hash(intern, hash);
if (pelement) {
if (!Z_ISUNDEF(pelement->inf)) {
var_push_dtor(&var_hash, &pelement->inf);
}
if (!Z_ISUNDEF(pelement->obj)) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf);
var_replace(&var_hash, &entry, &element->obj);
var_replace(&var_hash, &inf, &element->inf);
zval_ptr_dtor(&entry);
ZVAL_UNDEF(&entry);
zval_ptr_dtor(&inf);
ZVAL_UNDEF(&inf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
pmembers = var_tmp_var(&var_hash);
if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) {
goto outexcept;
}
/* copy members */
object_properties_load(&intern->std, Z_ARRVAL_P(pmembers));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
Commit Message: Fix bug #73257 and bug #73258 - SplObjectStorage unserialize allows use of non-object as key
CWE ID: CWE-119 | SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
char *buf;
size_t buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval entry, inf;
zval *pcount, *pmembers;
spl_SplObjectStorageElement *element;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
pcount = var_tmp_var(&var_hash);
if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
ZVAL_UNDEF(&entry);
ZVAL_UNDEF(&inf);
while (count-- > 0) {
spl_SplObjectStorageElement *pelement;
zend_string *hash;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
/* store reference to allow cross-references between different elements */
if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) {
goto outexcept;
}
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) {
zval_ptr_dtor(&entry);
goto outexcept;
}
}
if (Z_TYPE(entry) != IS_OBJECT) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
hash = spl_object_storage_get_hash(intern, getThis(), &entry);
if (!hash) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash);
spl_object_storage_free_hash(intern, hash);
if (pelement) {
if (!Z_ISUNDEF(pelement->inf)) {
var_push_dtor(&var_hash, &pelement->inf);
}
if (!Z_ISUNDEF(pelement->obj)) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf);
var_replace(&var_hash, &entry, &element->obj);
var_replace(&var_hash, &inf, &element->inf);
zval_ptr_dtor(&entry);
ZVAL_UNDEF(&entry);
zval_ptr_dtor(&inf);
ZVAL_UNDEF(&inf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
pmembers = var_tmp_var(&var_hash);
if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) {
goto outexcept;
}
/* copy members */
object_properties_load(&intern->std, Z_ARRVAL_P(pmembers));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
| 168,812 |
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 PrintPreviewDataService::RemoveEntry(
const std::string& preview_ui_addr_str) {
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it != data_store_map_.end())
data_store_map_.erase(it);
}
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 PrintPreviewDataService::RemoveEntry(
void PrintPreviewDataService::RemoveEntry(int32 preview_ui_id) {
data_store_map_.erase(preview_ui_id);
}
| 170,823 |
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 lockd_down_net(struct svc_serv *serv, struct net *net)
{
struct lockd_net *ln = net_generic(net, lockd_net_id);
if (ln->nlmsvc_users) {
if (--ln->nlmsvc_users == 0) {
nlm_shutdown_hosts_net(net);
cancel_delayed_work_sync(&ln->grace_period_end);
locks_end_grace(&ln->lockd_manager);
svc_shutdown_net(serv, net);
dprintk("lockd_down_net: per-net data destroyed; net=%p\n", net);
}
} else {
printk(KERN_ERR "lockd_down_net: no users! task=%p, net=%p\n",
nlmsvc_task, net);
BUG();
}
}
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 void lockd_down_net(struct svc_serv *serv, struct net *net)
{
struct lockd_net *ln = net_generic(net, lockd_net_id);
if (ln->nlmsvc_users) {
if (--ln->nlmsvc_users == 0) {
nlm_shutdown_hosts_net(net);
svc_shutdown_net(serv, net);
dprintk("lockd_down_net: per-net data destroyed; net=%p\n", net);
}
} else {
printk(KERN_ERR "lockd_down_net: no users! task=%p, net=%p\n",
nlmsvc_task, net);
BUG();
}
}
| 168,135 |
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 send_write_chunks(struct svcxprt_rdma *xprt,
struct rpcrdma_write_array *wr_ary,
struct rpcrdma_msg *rdma_resp,
struct svc_rqst *rqstp,
struct svc_rdma_req_map *vec)
{
u32 xfer_len = rqstp->rq_res.page_len;
int write_len;
u32 xdr_off;
int chunk_off;
int chunk_no;
int nchunks;
struct rpcrdma_write_array *res_ary;
int ret;
res_ary = (struct rpcrdma_write_array *)
&rdma_resp->rm_body.rm_chunks[1];
/* Write chunks start at the pagelist */
nchunks = be32_to_cpu(wr_ary->wc_nchunks);
for (xdr_off = rqstp->rq_res.head[0].iov_len, chunk_no = 0;
xfer_len && chunk_no < nchunks;
chunk_no++) {
struct rpcrdma_segment *arg_ch;
u64 rs_offset;
arg_ch = &wr_ary->wc_array[chunk_no].wc_target;
write_len = min(xfer_len, be32_to_cpu(arg_ch->rs_length));
/* Prepare the response chunk given the length actually
* written */
xdr_decode_hyper((__be32 *)&arg_ch->rs_offset, &rs_offset);
svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no,
arg_ch->rs_handle,
arg_ch->rs_offset,
write_len);
chunk_off = 0;
while (write_len) {
ret = send_write(xprt, rqstp,
be32_to_cpu(arg_ch->rs_handle),
rs_offset + chunk_off,
xdr_off,
write_len,
vec);
if (ret <= 0)
goto out_err;
chunk_off += ret;
xdr_off += ret;
xfer_len -= ret;
write_len -= ret;
}
}
/* Update the req with the number of chunks actually used */
svc_rdma_xdr_encode_write_list(rdma_resp, chunk_no);
return rqstp->rq_res.page_len;
out_err:
pr_err("svcrdma: failed to send write chunks, rc=%d\n", ret);
return -EIO;
}
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 int send_write_chunks(struct svcxprt_rdma *xprt,
/* Load the xdr_buf into the ctxt's sge array, and DMA map each
* element as it is added.
*
* Returns the number of sge elements loaded on success, or
* a negative errno on failure.
*/
static int svc_rdma_map_reply_msg(struct svcxprt_rdma *rdma,
struct svc_rdma_op_ctxt *ctxt,
struct xdr_buf *xdr, __be32 *wr_lst)
{
unsigned int len, sge_no, remaining, page_off;
struct page **ppages;
unsigned char *base;
u32 xdr_pad;
int ret;
sge_no = 1;
ret = svc_rdma_dma_map_buf(rdma, ctxt, sge_no++,
xdr->head[0].iov_base,
xdr->head[0].iov_len);
if (ret < 0)
return ret;
/* If a Write chunk is present, the xdr_buf's page list
* is not included inline. However the Upper Layer may
* have added XDR padding in the tail buffer, and that
* should not be included inline.
*/
if (wr_lst) {
base = xdr->tail[0].iov_base;
len = xdr->tail[0].iov_len;
xdr_pad = xdr_padsize(xdr->page_len);
if (len && xdr_pad) {
base += xdr_pad;
len -= xdr_pad;
}
goto tail;
}
ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT);
page_off = xdr->page_base & ~PAGE_MASK;
remaining = xdr->page_len;
while (remaining) {
len = min_t(u32, PAGE_SIZE - page_off, remaining);
ret = svc_rdma_dma_map_page(rdma, ctxt, sge_no++,
*ppages++, page_off, len);
if (ret < 0)
return ret;
remaining -= len;
page_off = 0;
}
base = xdr->tail[0].iov_base;
len = xdr->tail[0].iov_len;
tail:
if (len) {
ret = svc_rdma_dma_map_buf(rdma, ctxt, sge_no++, base, len);
if (ret < 0)
return ret;
}
return sge_no - 1;
}
| 168,170 |
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 UpdateProperty(IBusProperty* ibus_prop) {
DLOG(INFO) << "UpdateProperty";
DCHECK(ibus_prop);
ImePropertyList prop_list; // our representation.
if (!FlattenProperty(ibus_prop, &prop_list)) {
LOG(ERROR) << "Malformed properties are detected";
return;
}
if (!prop_list.empty()) {
update_ime_property_(language_library_, prop_list);
}
}
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 UpdateProperty(IBusProperty* ibus_prop) {
FOR_EACH_OBSERVER(Observer, observers_,
OnRegisterImeProperties(prop_list));
}
| 170,550 |
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 AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest) {
DCHECK_LT(index_into_window_, window_size_);
DCHECK_LT(playback_rate_, 1.0);
DCHECK_NE(playback_rate_, 0.0);
if (audio_buffer_.forward_bytes() < bytes_per_frame_)
return false;
int input_step = ceil(window_size_ * playback_rate_);
AlignToFrameBoundary(&input_step);
int output_step = window_size_;
DCHECK_LT(input_step, output_step);
int bytes_to_crossfade = bytes_in_crossfade_;
if (muted_ || bytes_to_crossfade > input_step)
bytes_to_crossfade = 0;
int intro_crossfade_begin = input_step - bytes_to_crossfade;
int intro_crossfade_end = input_step;
int outtro_crossfade_begin = output_step - bytes_to_crossfade;
if (index_into_window_ < intro_crossfade_begin) {
CopyWithAdvance(dest);
index_into_window_ += bytes_per_frame_;
return true;
}
if (index_into_window_ < intro_crossfade_end) {
int offset = index_into_window_ - intro_crossfade_begin;
uint8* place_to_copy = crossfade_buffer_.get() + offset;
CopyWithoutAdvance(place_to_copy);
CopyWithAdvance(dest);
index_into_window_ += bytes_per_frame_;
return true;
}
int audio_buffer_offset = index_into_window_ - intro_crossfade_end;
if (audio_buffer_.forward_bytes() < audio_buffer_offset + bytes_per_frame_)
return false;
DCHECK_GE(index_into_window_, intro_crossfade_end);
CopyWithoutAdvance(dest, audio_buffer_offset);
if (index_into_window_ >= outtro_crossfade_begin) {
int offset_into_crossfade_buffer =
index_into_window_ - outtro_crossfade_begin;
uint8* intro_frame_ptr =
crossfade_buffer_.get() + offset_into_crossfade_buffer;
OutputCrossfadedFrame(dest, intro_frame_ptr);
}
index_into_window_ += bytes_per_frame_;
return true;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest) {
bool AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest,
int input_step,
int output_step) {
// Ensure we don't run into OOB read/write situation.
CHECK_LT(input_step, output_step);
DCHECK_LT(index_into_window_, window_size_);
DCHECK_LT(playback_rate_, 1.0);
DCHECK_NE(playback_rate_, 0.0);
if (audio_buffer_.forward_bytes() < bytes_per_frame_)
return false;
int bytes_to_crossfade = bytes_in_crossfade_;
if (muted_ || bytes_to_crossfade > input_step)
bytes_to_crossfade = 0;
int intro_crossfade_begin = input_step - bytes_to_crossfade;
int intro_crossfade_end = input_step;
int outtro_crossfade_begin = output_step - bytes_to_crossfade;
if (index_into_window_ < intro_crossfade_begin) {
CopyWithAdvance(dest);
index_into_window_ += bytes_per_frame_;
return true;
}
if (index_into_window_ < intro_crossfade_end) {
int offset = index_into_window_ - intro_crossfade_begin;
uint8* place_to_copy = crossfade_buffer_.get() + offset;
CopyWithoutAdvance(place_to_copy);
CopyWithAdvance(dest);
index_into_window_ += bytes_per_frame_;
return true;
}
int audio_buffer_offset = index_into_window_ - intro_crossfade_end;
if (audio_buffer_.forward_bytes() < audio_buffer_offset + bytes_per_frame_)
return false;
DCHECK_GE(index_into_window_, intro_crossfade_end);
CopyWithoutAdvance(dest, audio_buffer_offset);
if (index_into_window_ >= outtro_crossfade_begin) {
int offset_into_crossfade_buffer =
index_into_window_ - outtro_crossfade_begin;
uint8* intro_frame_ptr =
crossfade_buffer_.get() + offset_into_crossfade_buffer;
OutputCrossfadedFrame(dest, intro_frame_ptr);
}
index_into_window_ += bytes_per_frame_;
return true;
}
| 171,529 |
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 GpuProcessHost::OnChannelEstablished(
const IPC::ChannelHandle& channel_handle) {
DCHECK(gpu_process_);
EstablishChannelCallback callback = channel_requests_.front();
channel_requests_.pop();
if (!channel_handle.name.empty() &&
!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) {
Send(new GpuMsg_CloseChannel(channel_handle));
EstablishChannelError(callback,
IPC::ChannelHandle(),
base::kNullProcessHandle,
content::GPUInfo());
RouteOnUIThread(GpuHostMsg_OnLogMessage(
logging::LOG_WARNING,
"WARNING",
"Hardware acceleration is unavailable."));
return;
}
callback.Run(channel_handle, gpu_process_,
GpuDataManagerImpl::GetInstance()->GetGPUInfo());
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuProcessHost::OnChannelEstablished(
const IPC::ChannelHandle& channel_handle) {
EstablishChannelCallback callback = channel_requests_.front();
channel_requests_.pop();
if (!channel_handle.name.empty() &&
!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) {
Send(new GpuMsg_CloseChannel(channel_handle));
EstablishChannelError(callback,
IPC::ChannelHandle(),
base::kNullProcessHandle,
content::GPUInfo());
RouteOnUIThread(GpuHostMsg_OnLogMessage(
logging::LOG_WARNING,
"WARNING",
"Hardware acceleration is unavailable."));
return;
}
callback.Run(channel_handle,
GpuDataManagerImpl::GetInstance()->GetGPUInfo());
}
| 170,922 |
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 StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
#ifdef DEBUG
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
#endif
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
switch (ssn->state) {
case TCP_SYN_SENT:
if(StreamTcpPacketStateSynSent(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_SYN_RECV:
if(StreamTcpPacketStateSynRecv(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_ESTABLISHED:
if(StreamTcpPacketStateEstablished(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_FIN_WAIT1:
if(StreamTcpPacketStateFinWait1(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_FIN_WAIT2:
if(StreamTcpPacketStateFinWait2(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSING:
if(StreamTcpPacketStateClosing(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSE_WAIT:
if(StreamTcpPacketStateCloseWait(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_LAST_ACK:
if(StreamTcpPacketStateLastAck(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_TIME_WAIT:
if(StreamTcpPacketStateTimeWait(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
break;
default:
SCLogDebug("packet received on default state");
break;
}
skip:
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
Commit Message: stream: support RST getting lost/ignored
In case of a valid RST on a SYN, the state is switched to 'TCP_CLOSED'.
However, the target of the RST may not have received it, or may not
have accepted it. Also, the RST may have been injected, so the supposed
sender may not actually be aware of the RST that was sent in it's name.
In this case the previous behavior was to switch the state to CLOSED and
accept no further TCP updates or stream reassembly.
This patch changes this. It still switches the state to CLOSED, as this
is by far the most likely to be correct. However, it will reconsider
the state if the receiver continues to talk.
To do this on each state change the previous state will be recorded in
TcpSession::pstate. If a non-RST packet is received after a RST, this
TcpSession::pstate is used to try to continue the conversation.
If the (supposed) sender of the RST is also continueing the conversation
as normal, it's highly likely it didn't send the RST. In this case
a stream event is generated.
Ticket: #2501
Reported-By: Kirill Shipulin
CWE ID: | int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
#ifdef DEBUG
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
#endif
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
| 169,114 |
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: pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image)
{
pdf_gstate *gstate = pr->gstate + pr->gtop;
fz_matrix image_ctm;
fz_rect bbox;
softmask_save softmask = { NULL };
if (pr->super.hidden)
return;
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
bbox = fz_unit_rect;
fz_transform_rect(&bbox, &image_ctm);
if (image->mask)
{
/* apply blend group even though we skip the soft mask */
if (gstate->blendmode)
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1);
fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);
}
else
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
if (!image->colorspace)
{
switch (gstate->fill.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_fill_image_mask(ctx, pr->dev, image, &image_ctm,
gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->fill.pattern)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
else
{
fz_fill_image(ctx, pr->dev, image, &image_ctm, gstate->fill.alpha, &gstate->fill.color_params);
}
if (image->mask)
{
fz_pop_clip(ctx, pr->dev);
if (gstate->blendmode)
fz_end_group(ctx, pr->dev);
}
else
pdf_end_group(ctx, pr, &softmask);
}
static void
if (pr->clip)
{
gstate->clip_depth++;
fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox);
pr->clip = 0;
}
if (pr->super.hidden)
dostroke = dofill = 0;
if (dofill || dostroke)
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
if (dofill && dostroke)
{
/* We may need to push a knockout group */
if (gstate->stroke.alpha == 0)
{
/* No need for group, as stroke won't do anything */
}
else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL)
{
/* No need for group, as stroke won't show up */
}
else
{
knockout_group = 1;
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1);
}
}
if (dofill)
{
switch (gstate->fill.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm,
gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->fill.pattern)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
/* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */
fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (dostroke)
{
switch (gstate->stroke.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm,
gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->stroke.pattern)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->stroke.shade)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (knockout_group)
fz_end_group(ctx, pr->dev);
if (dofill || dostroke)
pdf_end_group(ctx, pr, &softmask);
}
Commit Message:
CWE ID: CWE-20 | pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image)
{
pdf_gstate *gstate = pr->gstate + pr->gtop;
fz_matrix image_ctm;
fz_rect bbox;
if (pr->super.hidden)
return;
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
bbox = fz_unit_rect;
fz_transform_rect(&bbox, &image_ctm);
if (image->mask && gstate->blendmode)
{
/* apply blend group even though we skip the soft mask */
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1);
fz_try(ctx)
fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);
fz_catch(ctx)
{
fz_end_group(ctx, pr->dev);
fz_rethrow(ctx);
}
fz_try(ctx)
pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);
fz_always(ctx)
{
fz_pop_clip(ctx, pr->dev);
fz_end_group(ctx, pr->dev);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
else if (image->mask)
{
fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);
fz_try(ctx)
pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);
fz_always(ctx)
fz_pop_clip(ctx, pr->dev);
fz_catch(ctx)
fz_rethrow(ctx);
}
else
{
softmask_save softmask = { NULL };
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
fz_try(ctx)
pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);
fz_always(ctx)
pdf_end_group(ctx, pr, &softmask);
fz_catch(ctx)
fz_rethrow(ctx);
}
}
static void
if (pr->clip)
{
gstate->clip_depth++;
fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox);
pr->clip = 0;
}
if (pr->super.hidden)
dostroke = dofill = 0;
if (dofill || dostroke)
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
if (dofill && dostroke)
{
/* We may need to push a knockout group */
if (gstate->stroke.alpha == 0)
{
/* No need for group, as stroke won't do anything */
}
else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL)
{
/* No need for group, as stroke won't show up */
}
else
{
knockout_group = 1;
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1);
}
}
if (dofill)
{
switch (gstate->fill.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm,
gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->fill.pattern)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
/* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */
fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (dostroke)
{
switch (gstate->stroke.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm,
gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->stroke.pattern)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->stroke.shade)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (knockout_group)
fz_end_group(ctx, pr->dev);
if (dofill || dostroke)
pdf_end_group(ctx, pr, &softmask);
}
| 164,580 |
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 x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
Commit Message: net: fix a kernel infoleak in x25 module
Stack object "dte_facilities" is allocated in x25_rx_call_request(),
which is supposed to be initialized in x25_negotiate_facilities.
However, 5 fields (8 bytes in total) are not initialized. This
object is then copied to userland via copy_to_user, thus infoleak
occurs.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk,
struct x25_facilities *new, struct x25_dte_facilities *dte)
{
struct x25_sock *x25 = x25_sk(sk);
struct x25_facilities *ours = &x25->facilities;
struct x25_facilities theirs;
int len;
memset(&theirs, 0, sizeof(theirs));
memcpy(new, ours, sizeof(*new));
memset(dte, 0, sizeof(*dte));
len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask);
if (len < 0)
return len;
/*
* They want reverse charging, we won't accept it.
*/
if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) {
SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n");
return -1;
}
new->reverse = theirs.reverse;
if (theirs.throughput) {
int theirs_in = theirs.throughput & 0x0f;
int theirs_out = theirs.throughput & 0xf0;
int ours_in = ours->throughput & 0x0f;
int ours_out = ours->throughput & 0xf0;
if (!ours_in || theirs_in < ours_in) {
SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n");
new->throughput = (new->throughput & 0xf0) | theirs_in;
}
if (!ours_out || theirs_out < ours_out) {
SOCK_DEBUG(sk,
"X.25: outbound throughput negotiated\n");
new->throughput = (new->throughput & 0x0f) | theirs_out;
}
}
if (theirs.pacsize_in && theirs.pacsize_out) {
if (theirs.pacsize_in < ours->pacsize_in) {
SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n");
new->pacsize_in = theirs.pacsize_in;
}
if (theirs.pacsize_out < ours->pacsize_out) {
SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n");
new->pacsize_out = theirs.pacsize_out;
}
}
if (theirs.winsize_in && theirs.winsize_out) {
if (theirs.winsize_in < ours->winsize_in) {
SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n");
new->winsize_in = theirs.winsize_in;
}
if (theirs.winsize_out < ours->winsize_out) {
SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n");
new->winsize_out = theirs.winsize_out;
}
}
return len;
}
| 167,235 |
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: WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate)
: delegate_(delegate),
state_(INITIALIZED),
waiting_(false),
callback_(NULL),
handshake_request_(new WebSocketHandshakeRequestHandler),
handshake_response_(new WebSocketHandshakeResponseHandler),
started_to_send_handshake_request_(false),
handshake_request_sent_(0),
response_cookies_save_index_(0),
send_frame_handler_(new WebSocketFrameHandler),
receive_frame_handler_(new WebSocketFrameHandler) {
}
Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob
Don't post SendPending if it is already posted.
BUG=89795
TEST=none
Review URL: http://codereview.chromium.org/7488007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate)
: delegate_(delegate),
state_(INITIALIZED),
waiting_(false),
callback_(NULL),
handshake_request_(new WebSocketHandshakeRequestHandler),
handshake_response_(new WebSocketHandshakeResponseHandler),
started_to_send_handshake_request_(false),
handshake_request_sent_(0),
response_cookies_save_index_(0),
send_frame_handler_(new WebSocketFrameHandler),
receive_frame_handler_(new WebSocketFrameHandler),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
}
| 170,308 |
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 bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic
Jann reported that the original commit back in b2157399cc98
("bpf: prevent out-of-bounds speculation") was not sufficient
to stop CPU from speculating out of bounds memory access:
While b2157399cc98 only focussed on masking array map access
for unprivileged users for tail calls and data access such
that the user provided index gets sanitized from BPF program
and syscall side, there is still a more generic form affected
from BPF programs that applies to most maps that hold user
data in relation to dynamic map access when dealing with
unknown scalars or "slow" known scalars as access offset, for
example:
- Load a map value pointer into R6
- Load an index into R7
- Do a slow computation (e.g. with a memory dependency) that
loads a limit into R8 (e.g. load the limit from a map for
high latency, then mask it to make the verifier happy)
- Exit if R7 >= R8 (mispredicted branch)
- Load R0 = R6[R7]
- Load R0 = R6[R0]
For unknown scalars there are two options in the BPF verifier
where we could derive knowledge from in order to guarantee
safe access to the memory: i) While </>/<=/>= variants won't
allow to derive any lower or upper bounds from the unknown
scalar where it would be safe to add it to the map value
pointer, it is possible through ==/!= test however. ii) another
option is to transform the unknown scalar into a known scalar,
for example, through ALU ops combination such as R &= <imm>
followed by R |= <imm> or any similar combination where the
original information from the unknown scalar would be destroyed
entirely leaving R with a constant. The initial slow load still
precedes the latter ALU ops on that register, so the CPU
executes speculatively from that point. Once we have the known
scalar, any compare operation would work then. A third option
only involving registers with known scalars could be crafted
as described in [0] where a CPU port (e.g. Slow Int unit)
would be filled with many dependent computations such that
the subsequent condition depending on its outcome has to wait
for evaluation on its execution port and thereby executing
speculatively if the speculated code can be scheduled on a
different execution port, or any other form of mistraining
as described in [1], for example. Given this is not limited
to only unknown scalars, not only map but also stack access
is affected since both is accessible for unprivileged users
and could potentially be used for out of bounds access under
speculation.
In order to prevent any of these cases, the verifier is now
sanitizing pointer arithmetic on the offset such that any
out of bounds speculation would be masked in a way where the
pointer arithmetic result in the destination register will
stay unchanged, meaning offset masked into zero similar as
in array_index_nospec() case. With regards to implementation,
there are three options that were considered: i) new insn
for sanitation, ii) push/pop insn and sanitation as inlined
BPF, iii) reuse of ax register and sanitation as inlined BPF.
Option i) has the downside that we end up using from reserved
bits in the opcode space, but also that we would require
each JIT to emit masking as native arch opcodes meaning
mitigation would have slow adoption till everyone implements
it eventually which is counter-productive. Option ii) and iii)
have both in common that a temporary register is needed in
order to implement the sanitation as inlined BPF since we
are not allowed to modify the source register. While a push /
pop insn in ii) would be useful to have in any case, it
requires once again that every JIT needs to implement it
first. While possible, amount of changes needed would also
be unsuitable for a -stable patch. Therefore, the path which
has fewer changes, less BPF instructions for the mitigation
and does not require anything to be changed in the JITs is
option iii) which this work is pursuing. The ax register is
already mapped to a register in all JITs (modulo arm32 where
it's mapped to stack as various other BPF registers there)
and used in constant blinding for JITs-only so far. It can
be reused for verifier rewrites under certain constraints.
The interpreter's tmp "register" has therefore been remapped
into extending the register set with hidden ax register and
reusing that for a number of instructions that needed the
prior temporary variable internally (e.g. div, mod). This
allows for zero increase in stack space usage in the interpreter,
and enables (restricted) generic use in rewrites otherwise as
long as such a patchlet does not make use of these instructions.
The sanitation mask is dynamic and relative to the offset the
map value or stack pointer currently holds.
There are various cases that need to be taken under consideration
for the masking, e.g. such operation could look as follows:
ptr += val or val += ptr or ptr -= val. Thus, the value to be
sanitized could reside either in source or in destination
register, and the limit is different depending on whether
the ALU op is addition or subtraction and depending on the
current known and bounded offset. The limit is derived as
follows: limit := max_value_size - (smin_value + off). For
subtraction: limit := umax_value + off. This holds because
we do not allow any pointer arithmetic that would
temporarily go out of bounds or would have an unknown
value with mixed signed bounds where it is unclear at
verification time whether the actual runtime value would
be either negative or positive. For example, we have a
derived map pointer value with constant offset and bounded
one, so limit based on smin_value works because the verifier
requires that statically analyzed arithmetic on the pointer
must be in bounds, and thus it checks if resulting
smin_value + off and umax_value + off is still within map
value bounds at time of arithmetic in addition to time of
access. Similarly, for the case of stack access we derive
the limit as follows: MAX_BPF_STACK + off for subtraction
and -off for the case of addition where off := ptr_reg->off +
ptr_reg->var_off.value. Subtraction is a special case for
the masking which can be in form of ptr += -val, ptr -= -val,
or ptr -= val. In the first two cases where we know that
the value is negative, we need to temporarily negate the
value in order to do the sanitation on a positive value
where we later swap the ALU op, and restore original source
register if the value was in source.
The sanitation of pointer arithmetic alone is still not fully
sufficient as is, since a scenario like the following could
happen ...
PTR += 0x1000 (e.g. K-based imm)
PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON
PTR += 0x1000
PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON
[...]
... which under speculation could end up as ...
PTR += 0x1000
PTR -= 0 [ truncated by mitigation ]
PTR += 0x1000
PTR -= 0 [ truncated by mitigation ]
[...]
... and therefore still access out of bounds. To prevent such
case, the verifier is also analyzing safety for potential out
of bounds access under speculative execution. Meaning, it is
also simulating pointer access under truncation. We therefore
"branch off" and push the current verification state after the
ALU operation with known 0 to the verification stack for later
analysis. Given the current path analysis succeeded it is
likely that the one under speculation can be pruned. In any
case, it is also subject to existing complexity limits and
therefore anything beyond this point will be rejected. In
terms of pruning, it needs to be ensured that the verification
state from speculative execution simulation must never prune
a non-speculative execution path, therefore, we mark verifier
state accordingly at the time of push_stack(). If verifier
detects out of bounds access under speculative execution from
one of the possible paths that includes a truncation, it will
reject such program.
Given we mask every reg-based pointer arithmetic for
unprivileged programs, we've been looking into how it could
affect real-world programs in terms of size increase. As the
majority of programs are targeted for privileged-only use
case, we've unconditionally enabled masking (with its alu
restrictions on top of it) for privileged programs for the
sake of testing in order to check i) whether they get rejected
in its current form, and ii) by how much the number of
instructions and size will increase. We've tested this by
using Katran, Cilium and test_l4lb from the kernel selftests.
For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o
and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb
we've used test_l4lb.o as well as test_l4lb_noinline.o. We
found that none of the programs got rejected by the verifier
with this change, and that impact is rather minimal to none.
balancer_kern.o had 13,904 bytes (1,738 insns) xlated and
7,797 bytes JITed before and after the change. Most complex
program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated
and 18,538 bytes JITed before and after and none of the other
tail call programs in bpf_lxc.o had any changes either. For
the older bpf_lxc_opt_-DUNKNOWN.o object we found a small
increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed
before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed
after the change. Other programs from that object file had
similar small increase. Both test_l4lb.o had no change and
remained at 6,544 bytes (817 insns) xlated and 3,401 bytes
JITed and for test_l4lb_noinline.o constant at 5,080 bytes
(634 insns) xlated and 3,313 bytes JITed. This can be explained
in that LLVM typically optimizes stack based pointer arithmetic
by using K-based operations and that use of dynamic map access
is not overly frequent. However, in future we may decide to
optimize the algorithm further under known guarantees from
branch and value speculation. Latter seems also unclear in
terms of prediction heuristics that today's CPUs apply as well
as whether there could be collisions in e.g. the predictor's
Value History/Pattern Table for triggering out of bounds access,
thus masking is performed unconditionally at this point but could
be subject to relaxation later on. We were generally also
brainstorming various other approaches for mitigation, but the
blocker was always lack of available registers at runtime and/or
overhead for runtime tracking of limits belonging to a specific
pointer. Thus, we found this to be minimally intrusive under
given constraints.
With that in place, a simple example with sanitized access on
unprivileged load at post-verification time looks as follows:
# bpftool prog dump xlated id 282
[...]
28: (79) r1 = *(u64 *)(r7 +0)
29: (79) r2 = *(u64 *)(r7 +8)
30: (57) r1 &= 15
31: (79) r3 = *(u64 *)(r0 +4608)
32: (57) r3 &= 1
33: (47) r3 |= 1
34: (2d) if r2 > r3 goto pc+19
35: (b4) (u32) r11 = (u32) 20479 |
36: (1f) r11 -= r2 | Dynamic sanitation for pointer
37: (4f) r11 |= r2 | arithmetic with registers
38: (87) r11 = -r11 | containing bounded or known
39: (c7) r11 s>>= 63 | scalars in order to prevent
40: (5f) r11 &= r2 | out of bounds speculation.
41: (0f) r4 += r11 |
42: (71) r4 = *(u8 *)(r4 +0)
43: (6f) r4 <<= r1
[...]
For the case where the scalar sits in the destination register
as opposed to the source register, the following code is emitted
for the above example:
[...]
16: (b4) (u32) r11 = (u32) 20479
17: (1f) r11 -= r2
18: (4f) r11 |= r2
19: (87) r11 = -r11
20: (c7) r11 s>>= 63
21: (5f) r2 &= r11
22: (0f) r2 += r0
23: (61) r0 = *(u32 *)(r2 +0)
[...]
JIT blinding example with non-conflicting use of r10:
[...]
d5: je 0x0000000000000106 _
d7: mov 0x0(%rax),%edi |
da: mov $0xf153246,%r10d | Index load from map value and
e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f.
e7: and %r10,%rdi |_
ea: mov $0x2f,%r10d |
f0: sub %rdi,%r10 | Sanitized addition. Both use r10
f3: or %rdi,%r10 | but do not interfere with each
f6: neg %r10 | other. (Neither do these instructions
f9: sar $0x3f,%r10 | interfere with the use of ax as temp
fd: and %r10,%rdi | in interpreter.)
100: add %rax,%rdi |_
103: mov 0x0(%rdi),%eax
[...]
Tested that it fixes Jann's reproducer, and also checked that test_verifier
and test_progs suite with interpreter, JIT and JIT with hardening enabled
on x86-64 and arm64 runs successfully.
[0] Speculose: Analyzing the Security Implications of Speculative
Execution in CPUs, Giorgi Maisuradze and Christian Rossow,
https://arxiv.org/pdf/1801.04084.pdf
[1] A Systematic Evaluation of Transient Execution Attacks and
Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz,
Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens,
Dmitry Evtyushkin, Daniel Gruss,
https://arxiv.org/pdf/1811.05441.pdf
Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
CWE ID: CWE-189 | static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx,
bool speculative)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
elem->st.speculative |= speculative;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
| 170,244 |
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: cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type)
{
int rc = pcmk_ok;
cib_remote_opaque_t *private = cib->variant_opaque;
if (private->passwd == NULL) {
struct termios settings;
int rc;
rc = tcgetattr(0, &settings);
settings.c_lflag &= ~ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
fprintf(stderr, "Password: ");
private->passwd = calloc(1, 1024);
rc = scanf("%s", private->passwd);
fprintf(stdout, "\n");
/* fprintf(stderr, "entered: '%s'\n", buffer); */
if (rc < 1) {
private->passwd = NULL;
}
settings.c_lflag |= ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
}
if (private->server == NULL || private->user == NULL) {
rc = -EINVAL;
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->command));
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->callback));
}
if (rc == pcmk_ok) {
xmlNode *hello =
cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL);
crm_xml_add(hello, F_CIB_CLIENTNAME, name);
crm_send_remote_msg(private->command.session, hello, private->command.encrypted);
free_xml(hello);
}
if (rc == pcmk_ok) {
fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port);
cib->state = cib_connected_command;
cib->type = cib_command;
} else {
fprintf(stderr, "%s: Connection to %s:%d failed: %s\n",
name, private->server, private->port, pcmk_strerror(rc));
}
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type)
{
int rc = pcmk_ok;
cib_remote_opaque_t *private = cib->variant_opaque;
if (private->passwd == NULL) {
struct termios settings;
int rc;
rc = tcgetattr(0, &settings);
settings.c_lflag &= ~ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
fprintf(stderr, "Password: ");
private->passwd = calloc(1, 1024);
rc = scanf("%s", private->passwd);
fprintf(stdout, "\n");
/* fprintf(stderr, "entered: '%s'\n", buffer); */
if (rc < 1) {
private->passwd = NULL;
}
settings.c_lflag |= ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
}
if (private->server == NULL || private->user == NULL) {
rc = -EINVAL;
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->command), FALSE);
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->callback), TRUE);
}
if (rc == pcmk_ok) {
xmlNode *hello =
cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL);
crm_xml_add(hello, F_CIB_CLIENTNAME, name);
crm_send_remote_msg(private->command.session, hello, private->command.encrypted);
free_xml(hello);
}
if (rc == pcmk_ok) {
fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port);
cib->state = cib_connected_command;
cib->type = cib_command;
} else {
fprintf(stderr, "%s: Connection to %s:%d failed: %s\n",
name, private->server, private->port, pcmk_strerror(rc));
}
return rc;
}
| 166,153 |
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: lquery_in(PG_FUNCTION_ARGS)
{
char *buf = (char *) PG_GETARG_POINTER(0);
char *ptr;
int num = 0,
totallen = 0,
numOR = 0;
int state = LQPRS_WAITLEVEL;
lquery *result;
nodeitem *lptr = NULL;
lquery_level *cur,
*curqlevel,
*tmpql;
lquery_variant *lrptr = NULL;
bool hasnot = false;
bool wasbad = false;
int charlen;
int pos = 0;
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (charlen == 1)
{
if (t_iseq(ptr, '.'))
num++;
else if (t_iseq(ptr, '|'))
numOR++;
}
ptr += charlen;
}
num++;
curqlevel = tmpql = (lquery_level *) palloc0(ITEMSIZE * num);
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (state == LQPRS_WAITLEVEL)
{
if (ISALNUM(ptr))
{
GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1));
lptr->start = ptr;
state = LQPRS_WAITDELIM;
curqlevel->numvar = 1;
}
else if (charlen == 1 && t_iseq(ptr, '!'))
{
GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1));
lptr->start = ptr + 1;
state = LQPRS_WAITDELIM;
curqlevel->numvar = 1;
curqlevel->flag |= LQL_NOT;
hasnot = true;
}
else if (charlen == 1 && t_iseq(ptr, '*'))
state = LQPRS_WAITOPEN;
else
UNCHAR;
}
else if (state == LQPRS_WAITVAR)
{
if (ISALNUM(ptr))
{
lptr++;
lptr->start = ptr;
state = LQPRS_WAITDELIM;
curqlevel->numvar++;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITDELIM)
{
if (charlen == 1 && t_iseq(ptr, '@'))
{
if (lptr->start == ptr)
UNCHAR;
lptr->flag |= LVAR_INCASE;
curqlevel->flag |= LVAR_INCASE;
}
else if (charlen == 1 && t_iseq(ptr, '*'))
{
if (lptr->start == ptr)
UNCHAR;
lptr->flag |= LVAR_ANYEND;
curqlevel->flag |= LVAR_ANYEND;
}
else if (charlen == 1 && t_iseq(ptr, '%'))
{
if (lptr->start == ptr)
UNCHAR;
lptr->flag |= LVAR_SUBLEXEME;
curqlevel->flag |= LVAR_SUBLEXEME;
}
else if (charlen == 1 && t_iseq(ptr, '|'))
{
lptr->len = ptr - lptr->start -
((lptr->flag & LVAR_SUBLEXEME) ? 1 : 0) -
((lptr->flag & LVAR_INCASE) ? 1 : 0) -
((lptr->flag & LVAR_ANYEND) ? 1 : 0);
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
state = LQPRS_WAITVAR;
}
else if (charlen == 1 && t_iseq(ptr, '.'))
{
lptr->len = ptr - lptr->start -
((lptr->flag & LVAR_SUBLEXEME) ? 1 : 0) -
((lptr->flag & LVAR_INCASE) ? 1 : 0) -
((lptr->flag & LVAR_ANYEND) ? 1 : 0);
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
state = LQPRS_WAITLEVEL;
curqlevel = NEXTLEV(curqlevel);
}
else if (ISALNUM(ptr))
{
if (lptr->flag)
UNCHAR;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITOPEN)
{
if (charlen == 1 && t_iseq(ptr, '{'))
state = LQPRS_WAITFNUM;
else if (charlen == 1 && t_iseq(ptr, '.'))
{
curqlevel->low = 0;
curqlevel->high = 0xffff;
curqlevel = NEXTLEV(curqlevel);
state = LQPRS_WAITLEVEL;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITFNUM)
{
if (charlen == 1 && t_iseq(ptr, ','))
state = LQPRS_WAITSNUM;
else if (t_isdigit(ptr))
{
curqlevel->low = atoi(ptr);
state = LQPRS_WAITND;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITSNUM)
{
if (t_isdigit(ptr))
{
curqlevel->high = atoi(ptr);
state = LQPRS_WAITCLOSE;
}
else if (charlen == 1 && t_iseq(ptr, '}'))
{
curqlevel->high = 0xffff;
state = LQPRS_WAITEND;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITCLOSE)
{
if (charlen == 1 && t_iseq(ptr, '}'))
state = LQPRS_WAITEND;
else if (!t_isdigit(ptr))
UNCHAR;
}
else if (state == LQPRS_WAITND)
{
if (charlen == 1 && t_iseq(ptr, '}'))
{
curqlevel->high = curqlevel->low;
state = LQPRS_WAITEND;
}
else if (charlen == 1 && t_iseq(ptr, ','))
state = LQPRS_WAITSNUM;
else if (!t_isdigit(ptr))
UNCHAR;
}
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 | lquery_in(PG_FUNCTION_ARGS)
{
char *buf = (char *) PG_GETARG_POINTER(0);
char *ptr;
int num = 0,
totallen = 0,
numOR = 0;
int state = LQPRS_WAITLEVEL;
lquery *result;
nodeitem *lptr = NULL;
lquery_level *cur,
*curqlevel,
*tmpql;
lquery_variant *lrptr = NULL;
bool hasnot = false;
bool wasbad = false;
int charlen;
int pos = 0;
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (charlen == 1)
{
if (t_iseq(ptr, '.'))
num++;
else if (t_iseq(ptr, '|'))
numOR++;
}
ptr += charlen;
}
num++;
if (num > MaxAllocSize / ITEMSIZE)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of levels (%d) exceeds the maximum allowed (%d)",
num, (int) (MaxAllocSize / ITEMSIZE))));
curqlevel = tmpql = (lquery_level *) palloc0(ITEMSIZE * num);
ptr = buf;
while (*ptr)
{
charlen = pg_mblen(ptr);
if (state == LQPRS_WAITLEVEL)
{
if (ISALNUM(ptr))
{
GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1));
lptr->start = ptr;
state = LQPRS_WAITDELIM;
curqlevel->numvar = 1;
}
else if (charlen == 1 && t_iseq(ptr, '!'))
{
GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1));
lptr->start = ptr + 1;
state = LQPRS_WAITDELIM;
curqlevel->numvar = 1;
curqlevel->flag |= LQL_NOT;
hasnot = true;
}
else if (charlen == 1 && t_iseq(ptr, '*'))
state = LQPRS_WAITOPEN;
else
UNCHAR;
}
else if (state == LQPRS_WAITVAR)
{
if (ISALNUM(ptr))
{
lptr++;
lptr->start = ptr;
state = LQPRS_WAITDELIM;
curqlevel->numvar++;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITDELIM)
{
if (charlen == 1 && t_iseq(ptr, '@'))
{
if (lptr->start == ptr)
UNCHAR;
lptr->flag |= LVAR_INCASE;
curqlevel->flag |= LVAR_INCASE;
}
else if (charlen == 1 && t_iseq(ptr, '*'))
{
if (lptr->start == ptr)
UNCHAR;
lptr->flag |= LVAR_ANYEND;
curqlevel->flag |= LVAR_ANYEND;
}
else if (charlen == 1 && t_iseq(ptr, '%'))
{
if (lptr->start == ptr)
UNCHAR;
lptr->flag |= LVAR_SUBLEXEME;
curqlevel->flag |= LVAR_SUBLEXEME;
}
else if (charlen == 1 && t_iseq(ptr, '|'))
{
lptr->len = ptr - lptr->start -
((lptr->flag & LVAR_SUBLEXEME) ? 1 : 0) -
((lptr->flag & LVAR_INCASE) ? 1 : 0) -
((lptr->flag & LVAR_ANYEND) ? 1 : 0);
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
state = LQPRS_WAITVAR;
}
else if (charlen == 1 && t_iseq(ptr, '.'))
{
lptr->len = ptr - lptr->start -
((lptr->flag & LVAR_SUBLEXEME) ? 1 : 0) -
((lptr->flag & LVAR_INCASE) ? 1 : 0) -
((lptr->flag & LVAR_ANYEND) ? 1 : 0);
if (lptr->wlen > 255)
ereport(ERROR,
(errcode(ERRCODE_NAME_TOO_LONG),
errmsg("name of level is too long"),
errdetail("Name length is %d, must "
"be < 256, in position %d.",
lptr->wlen, pos)));
state = LQPRS_WAITLEVEL;
curqlevel = NEXTLEV(curqlevel);
}
else if (ISALNUM(ptr))
{
if (lptr->flag)
UNCHAR;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITOPEN)
{
if (charlen == 1 && t_iseq(ptr, '{'))
state = LQPRS_WAITFNUM;
else if (charlen == 1 && t_iseq(ptr, '.'))
{
curqlevel->low = 0;
curqlevel->high = 0xffff;
curqlevel = NEXTLEV(curqlevel);
state = LQPRS_WAITLEVEL;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITFNUM)
{
if (charlen == 1 && t_iseq(ptr, ','))
state = LQPRS_WAITSNUM;
else if (t_isdigit(ptr))
{
curqlevel->low = atoi(ptr);
state = LQPRS_WAITND;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITSNUM)
{
if (t_isdigit(ptr))
{
curqlevel->high = atoi(ptr);
state = LQPRS_WAITCLOSE;
}
else if (charlen == 1 && t_iseq(ptr, '}'))
{
curqlevel->high = 0xffff;
state = LQPRS_WAITEND;
}
else
UNCHAR;
}
else if (state == LQPRS_WAITCLOSE)
{
if (charlen == 1 && t_iseq(ptr, '}'))
state = LQPRS_WAITEND;
else if (!t_isdigit(ptr))
UNCHAR;
}
else if (state == LQPRS_WAITND)
{
if (charlen == 1 && t_iseq(ptr, '}'))
{
curqlevel->high = curqlevel->low;
state = LQPRS_WAITEND;
}
else if (charlen == 1 && t_iseq(ptr, ','))
state = LQPRS_WAITSNUM;
else if (!t_isdigit(ptr))
UNCHAR;
}
| 166,404 |
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_METHOD(Phar, offsetSet)
{
char *fname, *cont_str = NULL;
size_t fname_len, cont_len;
zval *zresource;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
return;
}
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "sr", &fname, &fname_len, &zresource) == FAILURE
&& zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) {
return;
}
if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname);
return;
}
if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname);
return;
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname);
return;
}
phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource);
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, offsetSet)
{
char *fname, *cont_str = NULL;
size_t fname_len, cont_len;
zval *zresource;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
return;
}
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "pr", &fname, &fname_len, &zresource) == FAILURE
&& zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) {
return;
}
if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname);
return;
}
if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname);
return;
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname);
return;
}
phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource);
}
| 165,067 |
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: EntrySync* EntrySync::copyTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->copy(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | EntrySync* EntrySync::copyTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create();
m_fileSystem->copy(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
| 171,420 |
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 NTPResourceCache::CreateNewTabHTML() {
DictionaryValue localized_strings;
localized_strings.SetString("bookmarkbarattached",
profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) ?
"true" : "false");
localized_strings.SetString("hasattribution",
ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage(
IDR_THEME_NTP_ATTRIBUTION) ?
"true" : "false");
localized_strings.SetString("title",
l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE));
localized_strings.SetString("mostvisited",
l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED));
localized_strings.SetString("restoreThumbnailsShort",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK));
localized_strings.SetString("recentlyclosed",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED));
localized_strings.SetString("closedwindowsingle",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE));
localized_strings.SetString("closedwindowmultiple",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE));
localized_strings.SetString("attributionintro",
l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO));
localized_strings.SetString("thumbnailremovednotification",
l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION));
localized_strings.SetString("undothumbnailremove",
l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE));
localized_strings.SetString("removethumbnailtooltip",
l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP));
localized_strings.SetString("appuninstall",
l10n_util::GetStringFUTF16(
IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
localized_strings.SetString("appoptions",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS));
localized_strings.SetString("appdisablenotifications",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DISABLE_NOTIFICATIONS));
localized_strings.SetString("appcreateshortcut",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT));
localized_strings.SetString("appDefaultPageName",
l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME));
localized_strings.SetString("applaunchtypepinned",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED));
localized_strings.SetString("applaunchtyperegular",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR));
localized_strings.SetString("applaunchtypewindow",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW));
localized_strings.SetString("applaunchtypefullscreen",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN));
localized_strings.SetString("syncpromotext",
l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL));
localized_strings.SetString("syncLinkText",
l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS));
#if defined(OS_CHROMEOS)
localized_strings.SetString("expandMenu",
l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND));
#endif
NewTabPageHandler::GetLocalizedValues(profile_, &localized_strings);
NTPLoginHandler::GetLocalizedValues(profile_, &localized_strings);
if (profile_->GetProfileSyncService())
localized_strings.SetString("syncispresent", "true");
else
localized_strings.SetString("syncispresent", "false");
ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings);
std::string anim =
ui::Animation::ShouldRenderRichAnimation() ? "true" : "false";
localized_strings.SetString("anim", anim);
int alignment;
ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_);
tp->GetDisplayProperty(ThemeService::NTP_BACKGROUND_ALIGNMENT, &alignment);
localized_strings.SetString("themegravity",
(alignment & ThemeService::ALIGN_RIGHT) ? "right" : "");
if (profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoStart) &&
profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoEnd)) {
localized_strings.SetString("customlogo",
InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoStart),
profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoEnd)) ?
"true" : "false");
} else {
localized_strings.SetString("customlogo", "false");
}
if (PromoResourceService::CanShowNotificationPromo(profile_)) {
localized_strings.SetString("serverpromo",
profile_->GetPrefs()->GetString(prefs::kNTPPromoLine));
}
std::string full_html;
base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_NEW_TAB_4_HTML));
full_html = jstemplate_builder::GetI18nTemplateHtml(new_tab_html,
&localized_strings);
new_tab_html_ = base::RefCountedString::TakeString(&full_html);
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void NTPResourceCache::CreateNewTabHTML() {
DictionaryValue localized_strings;
localized_strings.SetString("bookmarkbarattached",
profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) ?
"true" : "false");
localized_strings.SetString("hasattribution",
ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage(
IDR_THEME_NTP_ATTRIBUTION) ?
"true" : "false");
localized_strings.SetString("title",
l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE));
localized_strings.SetString("mostvisited",
l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED));
localized_strings.SetString("restoreThumbnailsShort",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK));
localized_strings.SetString("recentlyclosed",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED));
localized_strings.SetString("closedwindowsingle",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE));
localized_strings.SetString("closedwindowmultiple",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE));
localized_strings.SetString("attributionintro",
l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO));
localized_strings.SetString("thumbnailremovednotification",
l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION));
localized_strings.SetString("undothumbnailremove",
l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE));
localized_strings.SetString("removethumbnailtooltip",
l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP));
localized_strings.SetString("appuninstall",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
localized_strings.SetString("appoptions",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS));
localized_strings.SetString("appdisablenotifications",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DISABLE_NOTIFICATIONS));
localized_strings.SetString("appcreateshortcut",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT));
localized_strings.SetString("appDefaultPageName",
l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME));
localized_strings.SetString("applaunchtypepinned",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED));
localized_strings.SetString("applaunchtyperegular",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR));
localized_strings.SetString("applaunchtypewindow",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW));
localized_strings.SetString("applaunchtypefullscreen",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN));
localized_strings.SetString("syncpromotext",
l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL));
localized_strings.SetString("syncLinkText",
l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS));
#if defined(OS_CHROMEOS)
localized_strings.SetString("expandMenu",
l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND));
#endif
NewTabPageHandler::GetLocalizedValues(profile_, &localized_strings);
NTPLoginHandler::GetLocalizedValues(profile_, &localized_strings);
if (profile_->GetProfileSyncService())
localized_strings.SetString("syncispresent", "true");
else
localized_strings.SetString("syncispresent", "false");
ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings);
std::string anim =
ui::Animation::ShouldRenderRichAnimation() ? "true" : "false";
localized_strings.SetString("anim", anim);
int alignment;
ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_);
tp->GetDisplayProperty(ThemeService::NTP_BACKGROUND_ALIGNMENT, &alignment);
localized_strings.SetString("themegravity",
(alignment & ThemeService::ALIGN_RIGHT) ? "right" : "");
if (profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoStart) &&
profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoEnd)) {
localized_strings.SetString("customlogo",
InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoStart),
profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoEnd)) ?
"true" : "false");
} else {
localized_strings.SetString("customlogo", "false");
}
if (PromoResourceService::CanShowNotificationPromo(profile_)) {
localized_strings.SetString("serverpromo",
profile_->GetPrefs()->GetString(prefs::kNTPPromoLine));
}
std::string full_html;
base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_NEW_TAB_4_HTML));
full_html = jstemplate_builder::GetI18nTemplateHtml(new_tab_html,
&localized_strings);
new_tab_html_ = base::RefCountedString::TakeString(&full_html);
}
| 170,985 |
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: ft_bitmap_assure_buffer( FT_Memory memory,
FT_Bitmap* bitmap,
FT_UInt xpixels,
FT_UInt ypixels )
{
FT_Error error;
int pitch;
int new_pitch;
FT_UInt bpp;
FT_Int i, width, height;
unsigned char* buffer = NULL;
width = bitmap->width;
height = bitmap->rows;
pitch = bitmap->pitch;
if ( pitch < 0 )
pitch = -pitch;
switch ( bitmap->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
bpp = 1;
new_pitch = ( width + xpixels + 7 ) >> 3;
break;
case FT_PIXEL_MODE_GRAY2:
bpp = 2;
new_pitch = ( width + xpixels + 3 ) >> 2;
break;
case FT_PIXEL_MODE_GRAY4:
bpp = 4;
new_pitch = ( width + xpixels + 1 ) >> 1;
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
bpp = 8;
new_pitch = ( width + xpixels );
break;
default:
return FT_THROW( Invalid_Glyph_Format );
}
/* if no need to allocate memory */
if ( ypixels == 0 && new_pitch <= pitch )
{
/* zero the padding */
FT_Int bit_width = pitch * 8;
FT_Int bit_last = ( width + xpixels ) * bpp;
if ( bit_last < bit_width )
{
FT_Byte* line = bitmap->buffer + ( bit_last >> 3 );
FT_Byte* end = bitmap->buffer + pitch;
FT_Int shift = bit_last & 7;
FT_UInt mask = 0xFF00U >> shift;
FT_Int count = height;
for ( ; count > 0; count--, line += pitch, end += pitch )
{
FT_Byte* write = line;
if ( shift > 0 )
{
write[0] = (FT_Byte)( write[0] & mask );
write++;
}
if ( write < end )
FT_MEM_ZERO( write, end - write );
}
}
return FT_Err_Ok;
}
/* otherwise allocate new buffer */
if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) )
return error;
/* new rows get added at the top of the bitmap, */
/* thus take care of the flow direction */
if ( bitmap->pitch > 0 )
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ),
bitmap->buffer + pitch * i, len );
}
else
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * i,
bitmap->buffer + pitch * i, len );
}
FT_FREE( bitmap->buffer );
bitmap->buffer = buffer;
if ( bitmap->pitch < 0 )
new_pitch = -new_pitch;
/* set pitch only, width and height are left untouched */
bitmap->pitch = new_pitch;
return FT_Err_Ok;
}
Commit Message:
CWE ID: CWE-119 | ft_bitmap_assure_buffer( FT_Memory memory,
FT_Bitmap* bitmap,
FT_UInt xpixels,
FT_UInt ypixels )
{
FT_Error error;
int pitch;
int new_pitch;
FT_UInt bpp;
FT_UInt i, width, height;
unsigned char* buffer = NULL;
width = bitmap->width;
height = bitmap->rows;
pitch = bitmap->pitch;
if ( pitch < 0 )
pitch = -pitch;
switch ( bitmap->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
bpp = 1;
new_pitch = ( width + xpixels + 7 ) >> 3;
break;
case FT_PIXEL_MODE_GRAY2:
bpp = 2;
new_pitch = ( width + xpixels + 3 ) >> 2;
break;
case FT_PIXEL_MODE_GRAY4:
bpp = 4;
new_pitch = ( width + xpixels + 1 ) >> 1;
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
bpp = 8;
new_pitch = ( width + xpixels );
break;
default:
return FT_THROW( Invalid_Glyph_Format );
}
/* if no need to allocate memory */
if ( ypixels == 0 && new_pitch <= pitch )
{
/* zero the padding */
FT_UInt bit_width = pitch * 8;
FT_UInt bit_last = ( width + xpixels ) * bpp;
if ( bit_last < bit_width )
{
FT_Byte* line = bitmap->buffer + ( bit_last >> 3 );
FT_Byte* end = bitmap->buffer + pitch;
FT_UInt shift = bit_last & 7;
FT_UInt mask = 0xFF00U >> shift;
FT_UInt count = height;
for ( ; count > 0; count--, line += pitch, end += pitch )
{
FT_Byte* write = line;
if ( shift > 0 )
{
write[0] = (FT_Byte)( write[0] & mask );
write++;
}
if ( write < end )
FT_MEM_ZERO( write, end - write );
}
}
return FT_Err_Ok;
}
/* otherwise allocate new buffer */
if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) )
return error;
/* new rows get added at the top of the bitmap, */
/* thus take care of the flow direction */
if ( bitmap->pitch > 0 )
{
FT_UInt len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ),
bitmap->buffer + pitch * i, len );
}
else
{
FT_UInt len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * i,
bitmap->buffer + pitch * i, len );
}
FT_FREE( bitmap->buffer );
bitmap->buffer = buffer;
if ( bitmap->pitch < 0 )
new_pitch = -new_pitch;
/* set pitch only, width and height are left untouched */
bitmap->pitch = new_pitch;
return FT_Err_Ok;
}
| 164,850 |
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: status_t BnCrypto::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case INIT_CHECK:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(initCheck());
return OK;
}
case IS_CRYPTO_SUPPORTED:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
reply->writeInt32(isCryptoSchemeSupported(uuid));
return OK;
}
case CREATE_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
size_t opaqueSize = data.readInt32();
void *opaqueData = NULL;
if (opaqueSize > 0) {
opaqueData = malloc(opaqueSize);
data.read(opaqueData, opaqueSize);
}
reply->writeInt32(createPlugin(uuid, opaqueData, opaqueSize));
if (opaqueData != NULL) {
free(opaqueData);
opaqueData = NULL;
}
return OK;
}
case DESTROY_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(destroyPlugin());
return OK;
}
case REQUIRES_SECURE_COMPONENT:
{
CHECK_INTERFACE(ICrypto, data, reply);
const char *mime = data.readCString();
reply->writeInt32(requiresSecureDecoderComponent(mime));
return OK;
}
case DECRYPT:
{
CHECK_INTERFACE(ICrypto, data, reply);
bool secure = data.readInt32() != 0;
CryptoPlugin::Mode mode = (CryptoPlugin::Mode)data.readInt32();
uint8_t key[16];
data.read(key, sizeof(key));
uint8_t iv[16];
data.read(iv, sizeof(iv));
size_t totalSize = data.readInt32();
sp<IMemory> sharedBuffer =
interface_cast<IMemory>(data.readStrongBinder());
int32_t offset = data.readInt32();
int32_t numSubSamples = data.readInt32();
CryptoPlugin::SubSample *subSamples =
new CryptoPlugin::SubSample[numSubSamples];
data.read(
subSamples,
sizeof(CryptoPlugin::SubSample) * numSubSamples);
void *secureBufferId, *dstPtr;
if (secure) {
secureBufferId = reinterpret_cast<void *>(static_cast<uintptr_t>(data.readInt64()));
} else {
dstPtr = calloc(1, totalSize);
}
AString errorDetailMsg;
ssize_t result;
size_t sumSubsampleSizes = 0;
bool overflow = false;
for (int32_t i = 0; i < numSubSamples; ++i) {
CryptoPlugin::SubSample &ss = subSamples[i];
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfEncryptedData) {
sumSubsampleSizes += ss.mNumBytesOfEncryptedData;
} else {
overflow = true;
}
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfClearData) {
sumSubsampleSizes += ss.mNumBytesOfClearData;
} else {
overflow = true;
}
}
if (overflow || sumSubsampleSizes != totalSize) {
result = -EINVAL;
} else if (offset + totalSize > sharedBuffer->size()) {
result = -EINVAL;
} else {
result = decrypt(
secure,
key,
iv,
mode,
sharedBuffer, offset,
subSamples, numSubSamples,
secure ? secureBufferId : dstPtr,
&errorDetailMsg);
}
reply->writeInt32(result);
if (isCryptoError(result)) {
reply->writeCString(errorDetailMsg.c_str());
}
if (!secure) {
if (result >= 0) {
CHECK_LE(result, static_cast<ssize_t>(totalSize));
reply->write(dstPtr, result);
}
free(dstPtr);
dstPtr = NULL;
}
delete[] subSamples;
subSamples = NULL;
return OK;
}
case NOTIFY_RESOLUTION:
{
CHECK_INTERFACE(ICrypto, data, reply);
int32_t width = data.readInt32();
int32_t height = data.readInt32();
notifyResolution(width, height);
return OK;
}
case SET_MEDIADRM_SESSION:
{
CHECK_INTERFACE(IDrm, data, reply);
Vector<uint8_t> sessionId;
readVector(data, sessionId);
reply->writeInt32(setMediaDrmSession(sessionId));
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: Fix security vulnerability in ICrypto DO NOT MERGE
b/25800375
Change-Id: I03c9395f7c7de4ac5813a1207452aac57aa39484
CWE ID: CWE-200 | status_t BnCrypto::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case INIT_CHECK:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(initCheck());
return OK;
}
case IS_CRYPTO_SUPPORTED:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
reply->writeInt32(isCryptoSchemeSupported(uuid));
return OK;
}
case CREATE_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
size_t opaqueSize = data.readInt32();
void *opaqueData = NULL;
if (opaqueSize > 0) {
opaqueData = malloc(opaqueSize);
data.read(opaqueData, opaqueSize);
}
reply->writeInt32(createPlugin(uuid, opaqueData, opaqueSize));
if (opaqueData != NULL) {
free(opaqueData);
opaqueData = NULL;
}
return OK;
}
case DESTROY_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(destroyPlugin());
return OK;
}
case REQUIRES_SECURE_COMPONENT:
{
CHECK_INTERFACE(ICrypto, data, reply);
const char *mime = data.readCString();
reply->writeInt32(requiresSecureDecoderComponent(mime));
return OK;
}
case DECRYPT:
{
CHECK_INTERFACE(ICrypto, data, reply);
bool secure = data.readInt32() != 0;
CryptoPlugin::Mode mode = (CryptoPlugin::Mode)data.readInt32();
uint8_t key[16];
data.read(key, sizeof(key));
uint8_t iv[16];
data.read(iv, sizeof(iv));
size_t totalSize = data.readInt32();
sp<IMemory> sharedBuffer =
interface_cast<IMemory>(data.readStrongBinder());
int32_t offset = data.readInt32();
int32_t numSubSamples = data.readInt32();
CryptoPlugin::SubSample *subSamples =
new CryptoPlugin::SubSample[numSubSamples];
data.read(
subSamples,
sizeof(CryptoPlugin::SubSample) * numSubSamples);
void *secureBufferId, *dstPtr;
if (secure) {
secureBufferId = reinterpret_cast<void *>(static_cast<uintptr_t>(data.readInt64()));
} else {
dstPtr = calloc(1, totalSize);
}
AString errorDetailMsg;
ssize_t result;
size_t sumSubsampleSizes = 0;
bool overflow = false;
for (int32_t i = 0; i < numSubSamples; ++i) {
CryptoPlugin::SubSample &ss = subSamples[i];
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfEncryptedData) {
sumSubsampleSizes += ss.mNumBytesOfEncryptedData;
} else {
overflow = true;
}
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfClearData) {
sumSubsampleSizes += ss.mNumBytesOfClearData;
} else {
overflow = true;
}
}
if (overflow || sumSubsampleSizes != totalSize) {
result = -EINVAL;
} else if (totalSize > sharedBuffer->size()) {
result = -EINVAL;
} else if ((size_t)offset > sharedBuffer->size() - totalSize) {
result = -EINVAL;
} else {
result = decrypt(
secure,
key,
iv,
mode,
sharedBuffer, offset,
subSamples, numSubSamples,
secure ? secureBufferId : dstPtr,
&errorDetailMsg);
}
reply->writeInt32(result);
if (isCryptoError(result)) {
reply->writeCString(errorDetailMsg.c_str());
}
if (!secure) {
if (result >= 0) {
CHECK_LE(result, static_cast<ssize_t>(totalSize));
reply->write(dstPtr, result);
}
free(dstPtr);
dstPtr = NULL;
}
delete[] subSamples;
subSamples = NULL;
return OK;
}
case NOTIFY_RESOLUTION:
{
CHECK_INTERFACE(ICrypto, data, reply);
int32_t width = data.readInt32();
int32_t height = data.readInt32();
notifyResolution(width, height);
return OK;
}
case SET_MEDIADRM_SESSION:
{
CHECK_INTERFACE(IDrm, data, reply);
Vector<uint8_t> sessionId;
readVector(data, sessionId);
reply->writeInt32(setMediaDrmSession(sessionId));
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
| 173,959 |
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 DiceResponseHandler::OnTokenExchangeSuccess(
DiceTokenFetcher* token_fetcher,
const std::string& refresh_token,
bool is_under_advanced_protection) {
const std::string& email = token_fetcher->email();
const std::string& gaia_id = token_fetcher->gaia_id();
if (!CanGetTokenForAccount(gaia_id, email))
return;
VLOG(1) << "[Dice] OAuth success for email " << email;
bool should_enable_sync = token_fetcher->should_enable_sync();
std::string account_id =
account_tracker_service_->SeedAccountInfo(gaia_id, email);
account_tracker_service_->SetIsAdvancedProtectionAccount(
account_id, is_under_advanced_protection);
token_service_->UpdateCredentials(account_id, refresh_token);
about_signin_internals_->OnRefreshTokenReceived(
base::StringPrintf("Successful (%s)", account_id.c_str()));
if (should_enable_sync)
token_fetcher->delegate()->EnableSync(account_id);
DeleteTokenFetcher(token_fetcher);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void DiceResponseHandler::OnTokenExchangeSuccess(
DiceTokenFetcher* token_fetcher,
const std::string& refresh_token,
bool is_under_advanced_protection) {
const std::string& email = token_fetcher->email();
const std::string& gaia_id = token_fetcher->gaia_id();
if (!CanGetTokenForAccount(gaia_id, email))
return;
VLOG(1) << "[Dice] OAuth success for email " << email;
bool should_enable_sync = token_fetcher->should_enable_sync();
std::string account_id =
account_tracker_service_->SeedAccountInfo(gaia_id, email);
account_tracker_service_->SetIsAdvancedProtectionAccount(
account_id, is_under_advanced_protection);
token_service_->UpdateCredentials(
account_id, refresh_token,
signin_metrics::SourceForRefreshTokenOperation::
kDiceResponseHandler_Signin);
about_signin_internals_->OnRefreshTokenReceived(
base::StringPrintf("Successful (%s)", account_id.c_str()));
if (should_enable_sync)
token_fetcher->delegate()->EnableSync(account_id);
DeleteTokenFetcher(token_fetcher);
}
| 172,566 |
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: pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
{
g_return_if_fail (new_len >= 0);
while (new_len > string->space)
{
if (string->space == 0)
string->space = 1;
else
string->space *= 2;
if (string->space < 0)
{
g_warning ("glyph string length overflows maximum integer size, truncated");
new_len = string->space = G_MAXINT - 8;
}
}
string->glyphs = g_realloc (string->glyphs, string->space * sizeof (PangoGlyphInfo));
string->log_clusters = g_realloc (string->log_clusters, string->space * sizeof (gint));
string->num_glyphs = new_len;
}
Commit Message: [glyphstring] Handle overflow with very long glyphstrings
CWE ID: CWE-189 | pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
{
g_return_if_fail (new_len >= 0);
while (new_len > string->space)
{
if (string->space == 0)
{
string->space = 4;
}
else
{
const guint max_space =
MIN (G_MAXINT, G_MAXSIZE / MAX (sizeof(PangoGlyphInfo), sizeof(gint)));
guint more_space = (guint)string->space * 2;
if (more_space > max_space)
{
more_space = max_space;
if ((guint)new_len > max_space)
{
g_error ("%s: failed to allocate glyph string of length %i\n",
G_STRLOC, new_len);
}
}
string->space = more_space;
}
}
string->glyphs = g_realloc (string->glyphs, string->space * sizeof (PangoGlyphInfo));
string->log_clusters = g_realloc (string->log_clusters, string->space * sizeof (gint));
string->num_glyphs = new_len;
}
| 165,514 |
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 FFmpegVideoDecodeEngine::Initialize(
MessageLoop* message_loop,
VideoDecodeEngine::EventHandler* event_handler,
VideoDecodeContext* context,
const VideoDecoderConfig& config) {
static const int kDecodeThreads = 2;
static const int kMaxDecodeThreads = 16;
codec_context_ = avcodec_alloc_context();
codec_context_->pix_fmt = PIX_FMT_YUV420P;
codec_context_->codec_type = AVMEDIA_TYPE_VIDEO;
codec_context_->codec_id = VideoCodecToCodecID(config.codec());
codec_context_->coded_width = config.width();
codec_context_->coded_height = config.height();
frame_rate_numerator_ = config.frame_rate_numerator();
frame_rate_denominator_ = config.frame_rate_denominator();
if (config.extra_data() != NULL) {
codec_context_->extradata_size = config.extra_data_size();
codec_context_->extradata =
reinterpret_cast<uint8_t*>(av_malloc(config.extra_data_size()));
memcpy(codec_context_->extradata, config.extra_data(),
config.extra_data_size());
}
codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
codec_context_->error_recognition = FF_ER_CAREFUL;
AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ?
1 : kDecodeThreads;
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
if ((!threads.empty() &&
!base::StringToInt(threads, &decode_threads)) ||
decode_threads < 0 || decode_threads > kMaxDecodeThreads) {
decode_threads = kDecodeThreads;
}
av_frame_.reset(avcodec_alloc_frame());
VideoCodecInfo info;
info.success = false;
info.provides_buffers = true;
info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY;
info.stream_info.surface_format = GetSurfaceFormat();
info.stream_info.surface_width = config.surface_width();
info.stream_info.surface_height = config.surface_height();
bool buffer_allocated = true;
frame_queue_available_.clear();
for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) {
scoped_refptr<VideoFrame> video_frame;
VideoFrame::CreateFrame(VideoFrame::YV12,
config.width(),
config.height(),
kNoTimestamp,
kNoTimestamp,
&video_frame);
if (!video_frame.get()) {
buffer_allocated = false;
break;
}
frame_queue_available_.push_back(video_frame);
}
if (codec &&
avcodec_thread_init(codec_context_, decode_threads) >= 0 &&
avcodec_open(codec_context_, codec) >= 0 &&
av_frame_.get() &&
buffer_allocated) {
info.success = true;
}
event_handler_ = event_handler;
event_handler_->OnInitializeComplete(info);
}
Commit Message: Don't forget the ffmpeg input buffer padding when allocating a codec's
extradata buffer.
BUG=82438
Review URL: http://codereview.chromium.org/7137002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void FFmpegVideoDecodeEngine::Initialize(
MessageLoop* message_loop,
VideoDecodeEngine::EventHandler* event_handler,
VideoDecodeContext* context,
const VideoDecoderConfig& config) {
static const int kDecodeThreads = 2;
static const int kMaxDecodeThreads = 16;
codec_context_ = avcodec_alloc_context();
codec_context_->pix_fmt = PIX_FMT_YUV420P;
codec_context_->codec_type = AVMEDIA_TYPE_VIDEO;
codec_context_->codec_id = VideoCodecToCodecID(config.codec());
codec_context_->coded_width = config.width();
codec_context_->coded_height = config.height();
frame_rate_numerator_ = config.frame_rate_numerator();
frame_rate_denominator_ = config.frame_rate_denominator();
if (config.extra_data() != NULL) {
codec_context_->extradata_size = config.extra_data_size();
codec_context_->extradata = reinterpret_cast<uint8_t*>(
av_malloc(config.extra_data_size() + FF_INPUT_BUFFER_PADDING_SIZE));
memcpy(codec_context_->extradata, config.extra_data(),
config.extra_data_size());
memset(codec_context_->extradata + config.extra_data_size(), '\0',
FF_INPUT_BUFFER_PADDING_SIZE);
}
codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
codec_context_->error_recognition = FF_ER_CAREFUL;
AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ?
1 : kDecodeThreads;
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
if ((!threads.empty() &&
!base::StringToInt(threads, &decode_threads)) ||
decode_threads < 0 || decode_threads > kMaxDecodeThreads) {
decode_threads = kDecodeThreads;
}
av_frame_.reset(avcodec_alloc_frame());
VideoCodecInfo info;
info.success = false;
info.provides_buffers = true;
info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY;
info.stream_info.surface_format = GetSurfaceFormat();
info.stream_info.surface_width = config.surface_width();
info.stream_info.surface_height = config.surface_height();
bool buffer_allocated = true;
frame_queue_available_.clear();
for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) {
scoped_refptr<VideoFrame> video_frame;
VideoFrame::CreateFrame(VideoFrame::YV12,
config.width(),
config.height(),
kNoTimestamp,
kNoTimestamp,
&video_frame);
if (!video_frame.get()) {
buffer_allocated = false;
break;
}
frame_queue_available_.push_back(video_frame);
}
if (codec &&
avcodec_thread_init(codec_context_, decode_threads) >= 0 &&
avcodec_open(codec_context_, codec) >= 0 &&
av_frame_.get() &&
buffer_allocated) {
info.success = true;
}
event_handler_ = event_handler;
event_handler_->OnInitializeComplete(info);
}
| 170,304 |
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: error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM(
uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) {
GLuint count = c.count;
uint32 pnames_size;
if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) {
return error::kOutOfBounds;
}
const GLenum* pnames = GetSharedMemoryAs<const GLenum*>(
c.pnames_shm_id, c.pnames_shm_offset, pnames_size);
if (pnames == NULL) {
return error::kOutOfBounds;
}
scoped_array<GLenum> enums(new GLenum[count]);
memcpy(enums.get(), pnames, pnames_size);
uint32 num_results = 0;
for (GLuint ii = 0; ii < count; ++ii) {
uint32 num = util_.GLGetNumValuesReturned(enums[ii]);
if (num == 0) {
SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname");
return error::kNoError;
}
DCHECK_LE(num, 4u);
if (!SafeAdd(num_results, num, &num_results)) {
return error::kOutOfBounds;
}
}
uint32 result_size = 0;
if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) {
return error::kOutOfBounds;
}
if (result_size != static_cast<uint32>(c.size)) {
SetGLError(GL_INVALID_VALUE,
"glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE");
return error::kNoError;
}
GLint* results = GetSharedMemoryAs<GLint*>(
c.results_shm_id, c.results_shm_offset, result_size);
if (results == NULL) {
return error::kOutOfBounds;
}
for (uint32 ii = 0; ii < num_results; ++ii) {
if (results[ii]) {
return error::kInvalidArguments;
}
}
GLint* start = results;
for (GLuint ii = 0; ii < count; ++ii) {
GLsizei num_written = 0;
if (!GetHelper(enums[ii], results, &num_written)) {
glGetIntegerv(enums[ii], results);
}
results += num_written;
}
if (static_cast<uint32>(results - start) != num_results) {
return error::kOutOfBounds;
}
return error::kNoError;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM(
uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) {
GLuint count = c.count;
uint32 pnames_size;
if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) {
return error::kOutOfBounds;
}
const GLenum* pnames = GetSharedMemoryAs<const GLenum*>(
c.pnames_shm_id, c.pnames_shm_offset, pnames_size);
if (pnames == NULL) {
return error::kOutOfBounds;
}
scoped_array<GLenum> enums(new GLenum[count]);
memcpy(enums.get(), pnames, pnames_size);
uint32 num_results = 0;
for (GLuint ii = 0; ii < count; ++ii) {
uint32 num = util_.GLGetNumValuesReturned(enums[ii]);
if (num == 0) {
SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname");
return error::kNoError;
}
DCHECK_LE(num, 4u);
if (!SafeAddUint32(num_results, num, &num_results)) {
return error::kOutOfBounds;
}
}
uint32 result_size = 0;
if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) {
return error::kOutOfBounds;
}
if (result_size != static_cast<uint32>(c.size)) {
SetGLError(GL_INVALID_VALUE,
"glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE");
return error::kNoError;
}
GLint* results = GetSharedMemoryAs<GLint*>(
c.results_shm_id, c.results_shm_offset, result_size);
if (results == NULL) {
return error::kOutOfBounds;
}
for (uint32 ii = 0; ii < num_results; ++ii) {
if (results[ii]) {
return error::kInvalidArguments;
}
}
GLint* start = results;
for (GLuint ii = 0; ii < count; ++ii) {
GLsizei num_written = 0;
if (!GetHelper(enums[ii], results, &num_written)) {
glGetIntegerv(enums[ii], results);
}
results += num_written;
}
if (static_cast<uint32>(results - start) != num_results) {
return error::kOutOfBounds;
}
return error::kNoError;
}
| 170,748 |
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 ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
if (s->version < TLS1_2_VERSION && tls1_suiteb(s))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW);
goto err;
}
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format
* Client Hello, can we? Error condition should be
* '>' otherweise */
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
s->method = ssl23_get_server_method(s->version);
if (s->method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
Commit Message:
CWE ID: | int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
if (s->version < TLS1_2_VERSION && tls1_suiteb(s))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW);
goto err;
}
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format
* Client Hello, can we? Error condition should be
* '>' otherweise */
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
const SSL_METHOD *new_method;
new_method = ssl23_get_server_method(s->version);
if (new_method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
s->method = new_method;
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
| 165,153 |
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 qcow2_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVQcowState *s = bs->opaque;
unsigned int len, i;
int ret = 0;
QCowHeader header;
QemuOpts *opts;
Error *local_err = NULL;
uint64_t ext_end;
uint64_t l1_vm_state_index;
const char *opt_overlap_check;
int overlap_check_template = 0;
ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read qcow2 header");
goto fail;
}
be32_to_cpus(&header.magic);
be32_to_cpus(&header.version);
be64_to_cpus(&header.backing_file_offset);
be32_to_cpus(&header.backing_file_size);
be64_to_cpus(&header.size);
be32_to_cpus(&header.cluster_bits);
be32_to_cpus(&header.crypt_method);
be64_to_cpus(&header.l1_table_offset);
be32_to_cpus(&header.l1_size);
be64_to_cpus(&header.refcount_table_offset);
be32_to_cpus(&header.refcount_table_clusters);
be64_to_cpus(&header.snapshots_offset);
be32_to_cpus(&header.nb_snapshots);
if (header.magic != QCOW_MAGIC) {
error_setg(errp, "Image is not in qcow2 format");
ret = -EINVAL;
goto fail;
}
if (header.version < 2 || header.version > 3) {
report_unsupported(bs, errp, "QCOW version %d", header.version);
ret = -ENOTSUP;
goto fail;
}
s->qcow_version = header.version;
/* Initialise cluster size */
if (header.cluster_bits < MIN_CLUSTER_BITS ||
header.cluster_bits > MAX_CLUSTER_BITS) {
error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
ret = -EINVAL;
goto fail;
}
s->cluster_bits = header.cluster_bits;
s->cluster_size = 1 << s->cluster_bits;
s->cluster_sectors = 1 << (s->cluster_bits - 9);
/* Initialise version 3 header fields */
if (header.version == 2) {
header.incompatible_features = 0;
header.compatible_features = 0;
header.autoclear_features = 0;
header.refcount_order = 4;
header.header_length = 72;
} else {
be64_to_cpus(&header.incompatible_features);
be64_to_cpus(&header.compatible_features);
be64_to_cpus(&header.autoclear_features);
be32_to_cpus(&header.refcount_order);
be32_to_cpus(&header.header_length);
if (header.header_length < 104) {
error_setg(errp, "qcow2 header too short");
ret = -EINVAL;
goto fail;
}
}
if (header.header_length > s->cluster_size) {
error_setg(errp, "qcow2 header exceeds cluster size");
ret = -EINVAL;
goto fail;
}
if (header.header_length > sizeof(header)) {
s->unknown_header_fields_size = header.header_length - sizeof(header);
s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
s->unknown_header_fields_size);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
"fields");
goto fail;
}
}
if (header.backing_file_offset > s->cluster_size) {
error_setg(errp, "Invalid backing file offset");
ret = -EINVAL;
goto fail;
}
if (header.backing_file_offset) {
ext_end = header.backing_file_offset;
} else {
ext_end = 1 << header.cluster_bits;
}
/* Handle feature bits */
s->incompatible_features = header.incompatible_features;
s->compatible_features = header.compatible_features;
s->autoclear_features = header.autoclear_features;
if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
void *feature_table = NULL;
qcow2_read_extensions(bs, header.header_length, ext_end,
&feature_table, NULL);
report_unsupported_feature(bs, errp, feature_table,
s->incompatible_features &
~QCOW2_INCOMPAT_MASK);
ret = -ENOTSUP;
g_free(feature_table);
goto fail;
}
if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
/* Corrupt images may not be written to unless they are being repaired
*/
if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
"read/write");
ret = -EACCES;
goto fail;
}
}
/* Check support for various header values */
if (header.refcount_order != 4) {
report_unsupported(bs, errp, "%d bit reference counts",
1 << header.refcount_order);
ret = -ENOTSUP;
goto fail;
}
s->refcount_order = header.refcount_order;
if (header.crypt_method > QCOW_CRYPT_AES) {
error_setg(errp, "Unsupported encryption method: %i",
header.crypt_method);
ret = -EINVAL;
goto fail;
}
s->crypt_method_header = header.crypt_method;
if (s->crypt_method_header) {
bs->encrypted = 1;
}
s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
s->l2_size = 1 << s->l2_bits;
bs->total_sectors = header.size / 512;
s->csize_shift = (62 - (s->cluster_bits - 8));
s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
s->refcount_table_offset = header.refcount_table_offset;
s->refcount_table_size =
header.refcount_table_clusters << (s->cluster_bits - 3);
if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
error_setg(errp, "Reference count table too large");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, s->refcount_table_offset,
s->refcount_table_size, sizeof(uint64_t));
if (ret < 0) {
error_setg(errp, "Invalid reference count table offset");
goto fail;
}
/* Snapshot table offset/length */
if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
error_setg(errp, "Too many snapshots");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, header.snapshots_offset,
header.nb_snapshots,
sizeof(QCowSnapshotHeader));
if (ret < 0) {
error_setg(errp, "Invalid snapshot table offset");
goto fail;
}
/* read the level 1 table */
if (header.l1_size > 0x2000000) {
/* 32 MB L1 table is enough for 2 PB images at 64k cluster size
* (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
error_setg(errp, "Active L1 table too large");
ret = -EFBIG;
goto fail;
ret = -EFBIG;
goto fail;
}
s->l1_size = header.l1_size;
l1_vm_state_index = size_to_l1(s, header.size);
if (l1_vm_state_index > INT_MAX) {
error_setg(errp, "Image is too big");
ret = -EFBIG;
goto fail;
}
s->l1_vm_state_index = l1_vm_state_index;
/* the L1 table must contain at least enough entries to put
header.size bytes */
if (s->l1_size < s->l1_vm_state_index) {
error_setg(errp, "L1 table is too small");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, header.l1_table_offset,
header.l1_size, sizeof(uint64_t));
if (ret < 0) {
error_setg(errp, "Invalid L1 table offset");
goto fail;
}
s->l1_table_offset = header.l1_table_offset;
if (s->l1_size > 0) {
s->l1_table = g_malloc0(
align_offset(s->l1_size * sizeof(uint64_t), 512));
ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
s->l1_size * sizeof(uint64_t));
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read L1 table");
goto fail;
}
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
}
/* alloc L2 table/refcount block cache */
s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
s->cluster_cache = g_malloc(s->cluster_size);
/* one more sector for decompressed data alignment */
s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
+ 512);
s->cluster_cache_offset = -1;
s->flags = flags;
ret = qcow2_refcount_init(bs);
if (ret != 0) {
error_setg_errno(errp, -ret, "Could not initialize refcount handling");
goto fail;
}
QLIST_INIT(&s->cluster_allocs);
QTAILQ_INIT(&s->discards);
/* read qcow2 extensions */
if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
&local_err)) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail;
}
/* read the backing file name */
if (header.backing_file_offset != 0) {
len = header.backing_file_size;
if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
error_setg(errp, "Backing file name too long");
ret = -EINVAL;
goto fail;
}
ret = bdrv_pread(bs->file, header.backing_file_offset,
bs->backing_file, len);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read backing file name");
goto fail;
}
bs->backing_file[len] = '\0';
}
/* Internal snapshots */
s->snapshots_offset = header.snapshots_offset;
s->nb_snapshots = header.nb_snapshots;
ret = qcow2_read_snapshots(bs);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read snapshots");
goto fail;
}
/* Clear unknown autoclear feature bits */
if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
s->autoclear_features = 0;
ret = qcow2_update_header(bs);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not update qcow2 header");
goto fail;
}
}
/* Initialise locks */
qemu_co_mutex_init(&s->lock);
/* Repair image if dirty */
if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
(s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
BdrvCheckResult result = {0};
ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not repair dirty image");
goto fail;
}
}
/* Enable lazy_refcounts according to image and command line options */
opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail;
}
s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
(s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
flags & BDRV_O_UNMAP);
s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
s->discard_passthrough[QCOW2_DISCARD_OTHER] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
if (!strcmp(opt_overlap_check, "none")) {
overlap_check_template = 0;
} else if (!strcmp(opt_overlap_check, "constant")) {
overlap_check_template = QCOW2_OL_CONSTANT;
} else if (!strcmp(opt_overlap_check, "cached")) {
overlap_check_template = QCOW2_OL_CACHED;
} else if (!strcmp(opt_overlap_check, "all")) {
overlap_check_template = QCOW2_OL_ALL;
} else {
error_setg(errp, "Unsupported value '%s' for qcow2 option "
"'overlap-check'. Allowed are either of the following: "
"none, constant, cached, all", opt_overlap_check);
qemu_opts_del(opts);
ret = -EINVAL;
goto fail;
}
s->overlap_check = 0;
for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
/* overlap-check defines a template bitmask, but every flag may be
* overwritten through the associated boolean option */
s->overlap_check |=
qemu_opt_get_bool(opts, overlap_bool_option_names[i],
overlap_check_template & (1 << i)) << i;
}
qemu_opts_del(opts);
if (s->use_lazy_refcounts && s->qcow_version < 3) {
error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
"qemu 1.1 compatibility level");
ret = -EINVAL;
goto fail;
}
#ifdef DEBUG_ALLOC
{
BdrvCheckResult result = {0};
qcow2_check_refcounts(bs, &result, 0);
}
#endif
return ret;
fail:
g_free(s->unknown_header_fields);
cleanup_unknown_header_ext(bs);
qcow2_free_snapshots(bs);
qcow2_refcount_close(bs);
g_free(s->l1_table);
/* else pre-write overlap checks in cache_destroy may crash */
s->l1_table = NULL;
if (s->l2_table_cache) {
qcow2_cache_destroy(bs, s->l2_table_cache);
}
if (s->refcount_block_cache) {
qcow2_cache_destroy(bs, s->refcount_block_cache);
}
g_free(s->cluster_cache);
qemu_vfree(s->cluster_data);
return ret;
}
Commit Message:
CWE ID: CWE-190 | static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVQcowState *s = bs->opaque;
unsigned int len, i;
int ret = 0;
QCowHeader header;
QemuOpts *opts;
Error *local_err = NULL;
uint64_t ext_end;
uint64_t l1_vm_state_index;
const char *opt_overlap_check;
int overlap_check_template = 0;
ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read qcow2 header");
goto fail;
}
be32_to_cpus(&header.magic);
be32_to_cpus(&header.version);
be64_to_cpus(&header.backing_file_offset);
be32_to_cpus(&header.backing_file_size);
be64_to_cpus(&header.size);
be32_to_cpus(&header.cluster_bits);
be32_to_cpus(&header.crypt_method);
be64_to_cpus(&header.l1_table_offset);
be32_to_cpus(&header.l1_size);
be64_to_cpus(&header.refcount_table_offset);
be32_to_cpus(&header.refcount_table_clusters);
be64_to_cpus(&header.snapshots_offset);
be32_to_cpus(&header.nb_snapshots);
if (header.magic != QCOW_MAGIC) {
error_setg(errp, "Image is not in qcow2 format");
ret = -EINVAL;
goto fail;
}
if (header.version < 2 || header.version > 3) {
report_unsupported(bs, errp, "QCOW version %d", header.version);
ret = -ENOTSUP;
goto fail;
}
s->qcow_version = header.version;
/* Initialise cluster size */
if (header.cluster_bits < MIN_CLUSTER_BITS ||
header.cluster_bits > MAX_CLUSTER_BITS) {
error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
ret = -EINVAL;
goto fail;
}
s->cluster_bits = header.cluster_bits;
s->cluster_size = 1 << s->cluster_bits;
s->cluster_sectors = 1 << (s->cluster_bits - 9);
/* Initialise version 3 header fields */
if (header.version == 2) {
header.incompatible_features = 0;
header.compatible_features = 0;
header.autoclear_features = 0;
header.refcount_order = 4;
header.header_length = 72;
} else {
be64_to_cpus(&header.incompatible_features);
be64_to_cpus(&header.compatible_features);
be64_to_cpus(&header.autoclear_features);
be32_to_cpus(&header.refcount_order);
be32_to_cpus(&header.header_length);
if (header.header_length < 104) {
error_setg(errp, "qcow2 header too short");
ret = -EINVAL;
goto fail;
}
}
if (header.header_length > s->cluster_size) {
error_setg(errp, "qcow2 header exceeds cluster size");
ret = -EINVAL;
goto fail;
}
if (header.header_length > sizeof(header)) {
s->unknown_header_fields_size = header.header_length - sizeof(header);
s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
s->unknown_header_fields_size);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
"fields");
goto fail;
}
}
if (header.backing_file_offset > s->cluster_size) {
error_setg(errp, "Invalid backing file offset");
ret = -EINVAL;
goto fail;
}
if (header.backing_file_offset) {
ext_end = header.backing_file_offset;
} else {
ext_end = 1 << header.cluster_bits;
}
/* Handle feature bits */
s->incompatible_features = header.incompatible_features;
s->compatible_features = header.compatible_features;
s->autoclear_features = header.autoclear_features;
if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
void *feature_table = NULL;
qcow2_read_extensions(bs, header.header_length, ext_end,
&feature_table, NULL);
report_unsupported_feature(bs, errp, feature_table,
s->incompatible_features &
~QCOW2_INCOMPAT_MASK);
ret = -ENOTSUP;
g_free(feature_table);
goto fail;
}
if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
/* Corrupt images may not be written to unless they are being repaired
*/
if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
"read/write");
ret = -EACCES;
goto fail;
}
}
/* Check support for various header values */
if (header.refcount_order != 4) {
report_unsupported(bs, errp, "%d bit reference counts",
1 << header.refcount_order);
ret = -ENOTSUP;
goto fail;
}
s->refcount_order = header.refcount_order;
if (header.crypt_method > QCOW_CRYPT_AES) {
error_setg(errp, "Unsupported encryption method: %i",
header.crypt_method);
ret = -EINVAL;
goto fail;
}
s->crypt_method_header = header.crypt_method;
if (s->crypt_method_header) {
bs->encrypted = 1;
}
s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
s->l2_size = 1 << s->l2_bits;
bs->total_sectors = header.size / 512;
s->csize_shift = (62 - (s->cluster_bits - 8));
s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
s->refcount_table_offset = header.refcount_table_offset;
s->refcount_table_size =
header.refcount_table_clusters << (s->cluster_bits - 3);
if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
error_setg(errp, "Reference count table too large");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, s->refcount_table_offset,
s->refcount_table_size, sizeof(uint64_t));
if (ret < 0) {
error_setg(errp, "Invalid reference count table offset");
goto fail;
}
/* Snapshot table offset/length */
if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
error_setg(errp, "Too many snapshots");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, header.snapshots_offset,
header.nb_snapshots,
sizeof(QCowSnapshotHeader));
if (ret < 0) {
error_setg(errp, "Invalid snapshot table offset");
goto fail;
}
/* read the level 1 table */
if (header.l1_size > QCOW_MAX_L1_SIZE) {
error_setg(errp, "Active L1 table too large");
ret = -EFBIG;
goto fail;
ret = -EFBIG;
goto fail;
}
s->l1_size = header.l1_size;
l1_vm_state_index = size_to_l1(s, header.size);
if (l1_vm_state_index > INT_MAX) {
error_setg(errp, "Image is too big");
ret = -EFBIG;
goto fail;
}
s->l1_vm_state_index = l1_vm_state_index;
/* the L1 table must contain at least enough entries to put
header.size bytes */
if (s->l1_size < s->l1_vm_state_index) {
error_setg(errp, "L1 table is too small");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, header.l1_table_offset,
header.l1_size, sizeof(uint64_t));
if (ret < 0) {
error_setg(errp, "Invalid L1 table offset");
goto fail;
}
s->l1_table_offset = header.l1_table_offset;
if (s->l1_size > 0) {
s->l1_table = g_malloc0(
align_offset(s->l1_size * sizeof(uint64_t), 512));
ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
s->l1_size * sizeof(uint64_t));
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read L1 table");
goto fail;
}
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
}
/* alloc L2 table/refcount block cache */
s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
s->cluster_cache = g_malloc(s->cluster_size);
/* one more sector for decompressed data alignment */
s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
+ 512);
s->cluster_cache_offset = -1;
s->flags = flags;
ret = qcow2_refcount_init(bs);
if (ret != 0) {
error_setg_errno(errp, -ret, "Could not initialize refcount handling");
goto fail;
}
QLIST_INIT(&s->cluster_allocs);
QTAILQ_INIT(&s->discards);
/* read qcow2 extensions */
if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
&local_err)) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail;
}
/* read the backing file name */
if (header.backing_file_offset != 0) {
len = header.backing_file_size;
if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
error_setg(errp, "Backing file name too long");
ret = -EINVAL;
goto fail;
}
ret = bdrv_pread(bs->file, header.backing_file_offset,
bs->backing_file, len);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read backing file name");
goto fail;
}
bs->backing_file[len] = '\0';
}
/* Internal snapshots */
s->snapshots_offset = header.snapshots_offset;
s->nb_snapshots = header.nb_snapshots;
ret = qcow2_read_snapshots(bs);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read snapshots");
goto fail;
}
/* Clear unknown autoclear feature bits */
if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
s->autoclear_features = 0;
ret = qcow2_update_header(bs);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not update qcow2 header");
goto fail;
}
}
/* Initialise locks */
qemu_co_mutex_init(&s->lock);
/* Repair image if dirty */
if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
(s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
BdrvCheckResult result = {0};
ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not repair dirty image");
goto fail;
}
}
/* Enable lazy_refcounts according to image and command line options */
opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail;
}
s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
(s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
flags & BDRV_O_UNMAP);
s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
s->discard_passthrough[QCOW2_DISCARD_OTHER] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
if (!strcmp(opt_overlap_check, "none")) {
overlap_check_template = 0;
} else if (!strcmp(opt_overlap_check, "constant")) {
overlap_check_template = QCOW2_OL_CONSTANT;
} else if (!strcmp(opt_overlap_check, "cached")) {
overlap_check_template = QCOW2_OL_CACHED;
} else if (!strcmp(opt_overlap_check, "all")) {
overlap_check_template = QCOW2_OL_ALL;
} else {
error_setg(errp, "Unsupported value '%s' for qcow2 option "
"'overlap-check'. Allowed are either of the following: "
"none, constant, cached, all", opt_overlap_check);
qemu_opts_del(opts);
ret = -EINVAL;
goto fail;
}
s->overlap_check = 0;
for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
/* overlap-check defines a template bitmask, but every flag may be
* overwritten through the associated boolean option */
s->overlap_check |=
qemu_opt_get_bool(opts, overlap_bool_option_names[i],
overlap_check_template & (1 << i)) << i;
}
qemu_opts_del(opts);
if (s->use_lazy_refcounts && s->qcow_version < 3) {
error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
"qemu 1.1 compatibility level");
ret = -EINVAL;
goto fail;
}
#ifdef DEBUG_ALLOC
{
BdrvCheckResult result = {0};
qcow2_check_refcounts(bs, &result, 0);
}
#endif
return ret;
fail:
g_free(s->unknown_header_fields);
cleanup_unknown_header_ext(bs);
qcow2_free_snapshots(bs);
qcow2_refcount_close(bs);
g_free(s->l1_table);
/* else pre-write overlap checks in cache_destroy may crash */
s->l1_table = NULL;
if (s->l2_table_cache) {
qcow2_cache_destroy(bs, s->l2_table_cache);
}
if (s->refcount_block_cache) {
qcow2_cache_destroy(bs, s->refcount_block_cache);
}
g_free(s->cluster_cache);
qemu_vfree(s->cluster_data);
return ret;
}
| 165,407 |
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 __fpu__restore_sig(void __user *buf, void __user *buf_fx, int size)
{
int ia32_fxstate = (buf != buf_fx);
struct task_struct *tsk = current;
struct fpu *fpu = &tsk->thread.fpu;
int state_size = fpu_kernel_xstate_size;
u64 xfeatures = 0;
int fx_only = 0;
ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) ||
IS_ENABLED(CONFIG_IA32_EMULATION));
if (!buf) {
fpu__clear(fpu);
return 0;
}
if (!access_ok(VERIFY_READ, buf, size))
return -EACCES;
fpu__activate_curr(fpu);
if (!static_cpu_has(X86_FEATURE_FPU))
return fpregs_soft_set(current, NULL,
0, sizeof(struct user_i387_ia32_struct),
NULL, buf) != 0;
if (use_xsave()) {
struct _fpx_sw_bytes fx_sw_user;
if (unlikely(check_for_xstate(buf_fx, buf_fx, &fx_sw_user))) {
/*
* Couldn't find the extended state information in the
* memory layout. Restore just the FP/SSE and init all
* the other extended state.
*/
state_size = sizeof(struct fxregs_state);
fx_only = 1;
trace_x86_fpu_xstate_check_failed(fpu);
} else {
state_size = fx_sw_user.xstate_size;
xfeatures = fx_sw_user.xfeatures;
}
}
if (ia32_fxstate) {
/*
* For 32-bit frames with fxstate, copy the user state to the
* thread's fpu state, reconstruct fxstate from the fsave
* header. Sanitize the copied state etc.
*/
struct fpu *fpu = &tsk->thread.fpu;
struct user_i387_ia32_struct env;
int err = 0;
/*
* Drop the current fpu which clears fpu->fpstate_active. This ensures
* that any context-switch during the copy of the new state,
* avoids the intermediate state from getting restored/saved.
* Thus avoiding the new restored state from getting corrupted.
* We will be ready to restore/save the state only after
* fpu->fpstate_active is again set.
*/
fpu__drop(fpu);
if (using_compacted_format())
err = copy_user_to_xstate(&fpu->state.xsave, buf_fx);
else
err = __copy_from_user(&fpu->state.xsave, buf_fx, state_size);
if (err || __copy_from_user(&env, buf, sizeof(env))) {
fpstate_init(&fpu->state);
trace_x86_fpu_init_state(fpu);
err = -1;
} else {
sanitize_restored_xstate(tsk, &env, xfeatures, fx_only);
}
fpu->fpstate_active = 1;
preempt_disable();
fpu__restore(fpu);
preempt_enable();
return err;
} else {
/*
* For 64-bit frames and 32-bit fsave frames, restore the user
* state to the registers directly (with exceptions handled).
*/
user_fpu_begin();
if (copy_user_to_fpregs_zeroing(buf_fx, xfeatures, fx_only)) {
fpu__clear(fpu);
return -1;
}
}
return 0;
}
Commit Message: x86/fpu: Don't let userspace set bogus xcomp_bv
On x86, userspace can use the ptrace() or rt_sigreturn() system calls to
set a task's extended state (xstate) or "FPU" registers. ptrace() can
set them for another task using the PTRACE_SETREGSET request with
NT_X86_XSTATE, while rt_sigreturn() can set them for the current task.
In either case, registers can be set to any value, but the kernel
assumes that the XSAVE area itself remains valid in the sense that the
CPU can restore it.
However, in the case where the kernel is using the uncompacted xstate
format (which it does whenever the XSAVES instruction is unavailable),
it was possible for userspace to set the xcomp_bv field in the
xstate_header to an arbitrary value. However, all bits in that field
are reserved in the uncompacted case, so when switching to a task with
nonzero xcomp_bv, the XRSTOR instruction failed with a #GP fault. This
caused the WARN_ON_FPU(err) in copy_kernel_to_xregs() to be hit. In
addition, since the error is otherwise ignored, the FPU registers from
the task previously executing on the CPU were leaked.
Fix the bug by checking that the user-supplied value of xcomp_bv is 0 in
the uncompacted case, and returning an error otherwise.
The reason for validating xcomp_bv rather than simply overwriting it
with 0 is that we want userspace to see an error if it (incorrectly)
provides an XSAVE area in compacted format rather than in uncompacted
format.
Note that as before, in case of error we clear the task's FPU state.
This is perhaps non-ideal, especially for PTRACE_SETREGSET; it might be
better to return an error before changing anything. But it seems the
"clear on error" behavior is fine for now, and it's a little tricky to
do otherwise because it would mean we couldn't simply copy the full
userspace state into kernel memory in one __copy_from_user().
This bug was found by syzkaller, which hit the above-mentioned
WARN_ON_FPU():
WARNING: CPU: 1 PID: 0 at ./arch/x86/include/asm/fpu/internal.h:373 __switch_to+0x5b5/0x5d0
CPU: 1 PID: 0 Comm: swapper/1 Not tainted 4.13.0 #453
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff9ba2bc8e42c0 task.stack: ffffa78cc036c000
RIP: 0010:__switch_to+0x5b5/0x5d0
RSP: 0000:ffffa78cc08bbb88 EFLAGS: 00010082
RAX: 00000000fffffffe RBX: ffff9ba2b8bf2180 RCX: 00000000c0000100
RDX: 00000000ffffffff RSI: 000000005cb10700 RDI: ffff9ba2b8bf36c0
RBP: ffffa78cc08bbbd0 R08: 00000000929fdf46 R09: 0000000000000001
R10: 0000000000000000 R11: 0000000000000000 R12: ffff9ba2bc8e42c0
R13: 0000000000000000 R14: ffff9ba2b8bf3680 R15: ffff9ba2bf5d7b40
FS: 00007f7e5cb10700(0000) GS:ffff9ba2bf400000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000004005cc CR3: 0000000079fd5000 CR4: 00000000001406e0
Call Trace:
Code: 84 00 00 00 00 00 e9 11 fd ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 e7 fa ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 c2 fa ff ff <0f> ff 66 0f 1f 84 00 00 00 00 00 e9 d4 fc ff ff 66 66 2e 0f 1f
Here is a C reproducer. The expected behavior is that the program spin
forever with no output. However, on a buggy kernel running on a
processor with the "xsave" feature but without the "xsaves" feature
(e.g. Sandy Bridge through Broadwell for Intel), within a second or two
the program reports that the xmm registers were corrupted, i.e. were not
restored correctly. With CONFIG_X86_DEBUG_FPU=y it also hits the above
kernel warning.
#define _GNU_SOURCE
#include <stdbool.h>
#include <inttypes.h>
#include <linux/elf.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int pid = fork();
uint64_t xstate[512];
struct iovec iov = { .iov_base = xstate, .iov_len = sizeof(xstate) };
if (pid == 0) {
bool tracee = true;
for (int i = 0; i < sysconf(_SC_NPROCESSORS_ONLN) && tracee; i++)
tracee = (fork() != 0);
uint32_t xmm0[4] = { [0 ... 3] = tracee ? 0x00000000 : 0xDEADBEEF };
asm volatile(" movdqu %0, %%xmm0\n"
" mov %0, %%rbx\n"
"1: movdqu %%xmm0, %0\n"
" mov %0, %%rax\n"
" cmp %%rax, %%rbx\n"
" je 1b\n"
: "+m" (xmm0) : : "rax", "rbx", "xmm0");
printf("BUG: xmm registers corrupted! tracee=%d, xmm0=%08X%08X%08X%08X\n",
tracee, xmm0[0], xmm0[1], xmm0[2], xmm0[3]);
} else {
usleep(100000);
ptrace(PTRACE_ATTACH, pid, 0, 0);
wait(NULL);
ptrace(PTRACE_GETREGSET, pid, NT_X86_XSTATE, &iov);
xstate[65] = -1;
ptrace(PTRACE_SETREGSET, pid, NT_X86_XSTATE, &iov);
ptrace(PTRACE_CONT, pid, 0, 0);
wait(NULL);
}
return 1;
}
Note: the program only tests for the bug using the ptrace() system call.
The bug can also be reproduced using the rt_sigreturn() system call, but
only when called from a 32-bit program, since for 64-bit programs the
kernel restores the FPU state from the signal frame by doing XRSTOR
directly from userspace memory (with proper error checking).
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Biggers <[email protected]>
Reviewed-by: Kees Cook <[email protected]>
Reviewed-by: Rik van Riel <[email protected]>
Acked-by: Dave Hansen <[email protected]>
Cc: <[email protected]> [v3.17+]
Cc: Andrew Morton <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Borislav Petkov <[email protected]>
Cc: Eric Biggers <[email protected]>
Cc: Fenghua Yu <[email protected]>
Cc: Kevin Hao <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Michael Halcrow <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Wanpeng Li <[email protected]>
Cc: Yu-cheng Yu <[email protected]>
Cc: [email protected]
Fixes: 0b29643a5843 ("x86/xsaves: Change compacted format xsave area header")
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-200 | static int __fpu__restore_sig(void __user *buf, void __user *buf_fx, int size)
{
int ia32_fxstate = (buf != buf_fx);
struct task_struct *tsk = current;
struct fpu *fpu = &tsk->thread.fpu;
int state_size = fpu_kernel_xstate_size;
u64 xfeatures = 0;
int fx_only = 0;
ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) ||
IS_ENABLED(CONFIG_IA32_EMULATION));
if (!buf) {
fpu__clear(fpu);
return 0;
}
if (!access_ok(VERIFY_READ, buf, size))
return -EACCES;
fpu__activate_curr(fpu);
if (!static_cpu_has(X86_FEATURE_FPU))
return fpregs_soft_set(current, NULL,
0, sizeof(struct user_i387_ia32_struct),
NULL, buf) != 0;
if (use_xsave()) {
struct _fpx_sw_bytes fx_sw_user;
if (unlikely(check_for_xstate(buf_fx, buf_fx, &fx_sw_user))) {
/*
* Couldn't find the extended state information in the
* memory layout. Restore just the FP/SSE and init all
* the other extended state.
*/
state_size = sizeof(struct fxregs_state);
fx_only = 1;
trace_x86_fpu_xstate_check_failed(fpu);
} else {
state_size = fx_sw_user.xstate_size;
xfeatures = fx_sw_user.xfeatures;
}
}
if (ia32_fxstate) {
/*
* For 32-bit frames with fxstate, copy the user state to the
* thread's fpu state, reconstruct fxstate from the fsave
* header. Sanitize the copied state etc.
*/
struct fpu *fpu = &tsk->thread.fpu;
struct user_i387_ia32_struct env;
int err = 0;
/*
* Drop the current fpu which clears fpu->fpstate_active. This ensures
* that any context-switch during the copy of the new state,
* avoids the intermediate state from getting restored/saved.
* Thus avoiding the new restored state from getting corrupted.
* We will be ready to restore/save the state only after
* fpu->fpstate_active is again set.
*/
fpu__drop(fpu);
if (using_compacted_format()) {
err = copy_user_to_xstate(&fpu->state.xsave, buf_fx);
} else {
err = __copy_from_user(&fpu->state.xsave, buf_fx, state_size);
/* xcomp_bv must be 0 when using uncompacted format */
if (!err && state_size > offsetof(struct xregs_state, header) && fpu->state.xsave.header.xcomp_bv)
err = -EINVAL;
}
if (err || __copy_from_user(&env, buf, sizeof(env))) {
fpstate_init(&fpu->state);
trace_x86_fpu_init_state(fpu);
err = -1;
} else {
sanitize_restored_xstate(tsk, &env, xfeatures, fx_only);
}
fpu->fpstate_active = 1;
preempt_disable();
fpu__restore(fpu);
preempt_enable();
return err;
} else {
/*
* For 64-bit frames and 32-bit fsave frames, restore the user
* state to the registers directly (with exceptions handled).
*/
user_fpu_begin();
if (copy_user_to_fpregs_zeroing(buf_fx, xfeatures, fx_only)) {
fpu__clear(fpu);
return -1;
}
}
return 0;
}
| 167,719 |
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 fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
case PACKET_FANOUT_RND:
case PACKET_FANOUT_QM:
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
break;
default:
return -EINVAL;
}
if (!po->running)
return -EINVAL;
if (po->fanout)
return -EALREADY;
if (type == PACKET_FANOUT_ROLLOVER ||
(type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
po->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL);
if (!po->rollover)
return -ENOMEM;
atomic_long_set(&po->rollover->num, 0);
atomic_long_set(&po->rollover->num_huge, 0);
atomic_long_set(&po->rollover->num_failed, 0);
}
mutex_lock(&fanout_mutex);
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
atomic_set(&match->sk_ref, 0);
fanout_init_data(match);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
dev_add_pack(&match->prot_hook);
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
if (match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
atomic_inc(&match->sk_ref);
__fanout_link(sk, po);
err = 0;
}
}
out:
mutex_unlock(&fanout_mutex);
if (err) {
kfree(po->rollover);
po->rollover = NULL;
}
return err;
}
Commit Message: packet: fix races in fanout_add()
Multiple threads can call fanout_add() at the same time.
We need to grab fanout_mutex earlier to avoid races that could
lead to one thread freeing po->rollover that was set by another thread.
Do the same in fanout_release(), for peace of mind, and to help us
finding lockdep issues earlier.
Fixes: dc99f600698d ("packet: Add fanout support.")
Fixes: 0648ab70afe6 ("packet: rollover prepare: per-socket state")
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_rollover *rollover = NULL;
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
case PACKET_FANOUT_RND:
case PACKET_FANOUT_QM:
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
break;
default:
return -EINVAL;
}
mutex_lock(&fanout_mutex);
err = -EINVAL;
if (!po->running)
goto out;
err = -EALREADY;
if (po->fanout)
goto out;
if (type == PACKET_FANOUT_ROLLOVER ||
(type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
err = -ENOMEM;
rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
if (!rollover)
goto out;
atomic_long_set(&rollover->num, 0);
atomic_long_set(&rollover->num_huge, 0);
atomic_long_set(&rollover->num_failed, 0);
po->rollover = rollover;
}
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
atomic_set(&match->sk_ref, 0);
fanout_init_data(match);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
dev_add_pack(&match->prot_hook);
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
if (match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
atomic_inc(&match->sk_ref);
__fanout_link(sk, po);
err = 0;
}
}
out:
if (err && rollover) {
kfree(rollover);
po->rollover = NULL;
}
mutex_unlock(&fanout_mutex);
return err;
}
| 168,346 |
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 udf_read_inode(struct inode *inode, bool hidden_inode)
{
struct buffer_head *bh = NULL;
struct fileEntry *fe;
struct extendedFileEntry *efe;
uint16_t ident;
struct udf_inode_info *iinfo = UDF_I(inode);
struct udf_sb_info *sbi = UDF_SB(inode->i_sb);
struct kernel_lb_addr *iloc = &iinfo->i_location;
unsigned int link_count;
unsigned int indirections = 0;
int bs = inode->i_sb->s_blocksize;
int ret = -EIO;
reread:
if (iloc->logicalBlockNum >=
sbi->s_partmaps[iloc->partitionReferenceNum].s_partition_len) {
udf_debug("block=%d, partition=%d out of range\n",
iloc->logicalBlockNum, iloc->partitionReferenceNum);
return -EIO;
}
/*
* Set defaults, but the inode is still incomplete!
* Note: get_new_inode() sets the following on a new inode:
* i_sb = sb
* i_no = ino
* i_flags = sb->s_flags
* i_state = 0
* clean_inode(): zero fills and sets
* i_count = 1
* i_nlink = 1
* i_op = NULL;
*/
bh = udf_read_ptagged(inode->i_sb, iloc, 0, &ident);
if (!bh) {
udf_err(inode->i_sb, "(ino %ld) failed !bh\n", inode->i_ino);
return -EIO;
}
if (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE &&
ident != TAG_IDENT_USE) {
udf_err(inode->i_sb, "(ino %ld) failed ident=%d\n",
inode->i_ino, ident);
goto out;
}
fe = (struct fileEntry *)bh->b_data;
efe = (struct extendedFileEntry *)bh->b_data;
if (fe->icbTag.strategyType == cpu_to_le16(4096)) {
struct buffer_head *ibh;
ibh = udf_read_ptagged(inode->i_sb, iloc, 1, &ident);
if (ident == TAG_IDENT_IE && ibh) {
struct kernel_lb_addr loc;
struct indirectEntry *ie;
ie = (struct indirectEntry *)ibh->b_data;
loc = lelb_to_cpu(ie->indirectICB.extLocation);
if (ie->indirectICB.extLength) {
brelse(ibh);
memcpy(&iinfo->i_location, &loc,
sizeof(struct kernel_lb_addr));
if (++indirections > UDF_MAX_ICB_NESTING) {
udf_err(inode->i_sb,
"too many ICBs in ICB hierarchy"
" (max %d supported)\n",
UDF_MAX_ICB_NESTING);
goto out;
}
brelse(bh);
goto reread;
}
}
brelse(ibh);
} else if (fe->icbTag.strategyType != cpu_to_le16(4)) {
udf_err(inode->i_sb, "unsupported strategy type: %d\n",
le16_to_cpu(fe->icbTag.strategyType));
goto out;
}
if (fe->icbTag.strategyType == cpu_to_le16(4))
iinfo->i_strat4096 = 0;
else /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */
iinfo->i_strat4096 = 1;
iinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) &
ICBTAG_FLAG_AD_MASK;
iinfo->i_unique = 0;
iinfo->i_lenEAttr = 0;
iinfo->i_lenExtents = 0;
iinfo->i_lenAlloc = 0;
iinfo->i_next_alloc_block = 0;
iinfo->i_next_alloc_goal = 0;
if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) {
iinfo->i_efe = 1;
iinfo->i_use = 0;
ret = udf_alloc_i_data(inode, bs -
sizeof(struct extendedFileEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct extendedFileEntry),
bs - sizeof(struct extendedFileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) {
iinfo->i_efe = 0;
iinfo->i_use = 0;
ret = udf_alloc_i_data(inode, bs - sizeof(struct fileEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct fileEntry),
bs - sizeof(struct fileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) {
iinfo->i_efe = 0;
iinfo->i_use = 1;
iinfo->i_lenAlloc = le32_to_cpu(
((struct unallocSpaceEntry *)bh->b_data)->
lengthAllocDescs);
ret = udf_alloc_i_data(inode, bs -
sizeof(struct unallocSpaceEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct unallocSpaceEntry),
bs - sizeof(struct unallocSpaceEntry));
return 0;
}
ret = -EIO;
read_lock(&sbi->s_cred_lock);
i_uid_write(inode, le32_to_cpu(fe->uid));
if (!uid_valid(inode->i_uid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET))
inode->i_uid = UDF_SB(inode->i_sb)->s_uid;
i_gid_write(inode, le32_to_cpu(fe->gid));
if (!gid_valid(inode->i_gid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET))
inode->i_gid = UDF_SB(inode->i_sb)->s_gid;
if (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_fmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_fmode;
else if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_dmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_dmode;
else
inode->i_mode = udf_convert_permissions(fe);
inode->i_mode &= ~sbi->s_umask;
read_unlock(&sbi->s_cred_lock);
link_count = le16_to_cpu(fe->fileLinkCount);
if (!link_count) {
if (!hidden_inode) {
ret = -ESTALE;
goto out;
}
link_count = 1;
}
set_nlink(inode, link_count);
inode->i_size = le64_to_cpu(fe->informationLength);
iinfo->i_lenExtents = inode->i_size;
if (iinfo->i_efe == 0) {
inode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
fe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(fe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(fe->checkpoint);
} else {
inode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
efe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime))
iinfo->i_crtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(efe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(efe->checkpoint);
}
inode->i_generation = iinfo->i_unique;
/* Sanity checks for files in ICB so that we don't get confused later */
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
/*
* For file in ICB data is stored in allocation descriptor
* so sizes should match
*/
if (iinfo->i_lenAlloc != inode->i_size)
goto out;
/* File in ICB has to fit in there... */
if (inode->i_size > bs - udf_file_entry_alloc_offset(inode))
goto out;
}
switch (fe->icbTag.fileType) {
case ICBTAG_FILE_TYPE_DIRECTORY:
inode->i_op = &udf_dir_inode_operations;
inode->i_fop = &udf_dir_operations;
inode->i_mode |= S_IFDIR;
inc_nlink(inode);
break;
case ICBTAG_FILE_TYPE_REALTIME:
case ICBTAG_FILE_TYPE_REGULAR:
case ICBTAG_FILE_TYPE_UNDEF:
case ICBTAG_FILE_TYPE_VAT20:
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
inode->i_data.a_ops = &udf_adinicb_aops;
else
inode->i_data.a_ops = &udf_aops;
inode->i_op = &udf_file_inode_operations;
inode->i_fop = &udf_file_operations;
inode->i_mode |= S_IFREG;
break;
case ICBTAG_FILE_TYPE_BLOCK:
inode->i_mode |= S_IFBLK;
break;
case ICBTAG_FILE_TYPE_CHAR:
inode->i_mode |= S_IFCHR;
break;
case ICBTAG_FILE_TYPE_FIFO:
init_special_inode(inode, inode->i_mode | S_IFIFO, 0);
break;
case ICBTAG_FILE_TYPE_SOCKET:
init_special_inode(inode, inode->i_mode | S_IFSOCK, 0);
break;
case ICBTAG_FILE_TYPE_SYMLINK:
inode->i_data.a_ops = &udf_symlink_aops;
inode->i_op = &udf_symlink_inode_operations;
inode->i_mode = S_IFLNK | S_IRWXUGO;
break;
case ICBTAG_FILE_TYPE_MAIN:
udf_debug("METADATA FILE-----\n");
break;
case ICBTAG_FILE_TYPE_MIRROR:
udf_debug("METADATA MIRROR FILE-----\n");
break;
case ICBTAG_FILE_TYPE_BITMAP:
udf_debug("METADATA BITMAP FILE-----\n");
break;
default:
udf_err(inode->i_sb, "(ino %ld) failed unknown file type=%d\n",
inode->i_ino, fe->icbTag.fileType);
goto out;
}
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
struct deviceSpec *dsea =
(struct deviceSpec *)udf_get_extendedattr(inode, 12, 1);
if (dsea) {
init_special_inode(inode, inode->i_mode,
MKDEV(le32_to_cpu(dsea->majorDeviceIdent),
le32_to_cpu(dsea->minorDeviceIdent)));
/* Developer ID ??? */
} else
goto out;
}
ret = 0;
out:
brelse(bh);
return ret;
}
Commit Message: udf: Check length of extended attributes and allocation descriptors
Check length of extended attributes and allocation descriptors when
loading inodes from disk. Otherwise corrupted filesystems could confuse
the code and make the kernel oops.
Reported-by: Carl Henrik Lunde <[email protected]>
CC: [email protected]
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-189 | static int udf_read_inode(struct inode *inode, bool hidden_inode)
{
struct buffer_head *bh = NULL;
struct fileEntry *fe;
struct extendedFileEntry *efe;
uint16_t ident;
struct udf_inode_info *iinfo = UDF_I(inode);
struct udf_sb_info *sbi = UDF_SB(inode->i_sb);
struct kernel_lb_addr *iloc = &iinfo->i_location;
unsigned int link_count;
unsigned int indirections = 0;
int bs = inode->i_sb->s_blocksize;
int ret = -EIO;
reread:
if (iloc->logicalBlockNum >=
sbi->s_partmaps[iloc->partitionReferenceNum].s_partition_len) {
udf_debug("block=%d, partition=%d out of range\n",
iloc->logicalBlockNum, iloc->partitionReferenceNum);
return -EIO;
}
/*
* Set defaults, but the inode is still incomplete!
* Note: get_new_inode() sets the following on a new inode:
* i_sb = sb
* i_no = ino
* i_flags = sb->s_flags
* i_state = 0
* clean_inode(): zero fills and sets
* i_count = 1
* i_nlink = 1
* i_op = NULL;
*/
bh = udf_read_ptagged(inode->i_sb, iloc, 0, &ident);
if (!bh) {
udf_err(inode->i_sb, "(ino %ld) failed !bh\n", inode->i_ino);
return -EIO;
}
if (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE &&
ident != TAG_IDENT_USE) {
udf_err(inode->i_sb, "(ino %ld) failed ident=%d\n",
inode->i_ino, ident);
goto out;
}
fe = (struct fileEntry *)bh->b_data;
efe = (struct extendedFileEntry *)bh->b_data;
if (fe->icbTag.strategyType == cpu_to_le16(4096)) {
struct buffer_head *ibh;
ibh = udf_read_ptagged(inode->i_sb, iloc, 1, &ident);
if (ident == TAG_IDENT_IE && ibh) {
struct kernel_lb_addr loc;
struct indirectEntry *ie;
ie = (struct indirectEntry *)ibh->b_data;
loc = lelb_to_cpu(ie->indirectICB.extLocation);
if (ie->indirectICB.extLength) {
brelse(ibh);
memcpy(&iinfo->i_location, &loc,
sizeof(struct kernel_lb_addr));
if (++indirections > UDF_MAX_ICB_NESTING) {
udf_err(inode->i_sb,
"too many ICBs in ICB hierarchy"
" (max %d supported)\n",
UDF_MAX_ICB_NESTING);
goto out;
}
brelse(bh);
goto reread;
}
}
brelse(ibh);
} else if (fe->icbTag.strategyType != cpu_to_le16(4)) {
udf_err(inode->i_sb, "unsupported strategy type: %d\n",
le16_to_cpu(fe->icbTag.strategyType));
goto out;
}
if (fe->icbTag.strategyType == cpu_to_le16(4))
iinfo->i_strat4096 = 0;
else /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */
iinfo->i_strat4096 = 1;
iinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) &
ICBTAG_FLAG_AD_MASK;
iinfo->i_unique = 0;
iinfo->i_lenEAttr = 0;
iinfo->i_lenExtents = 0;
iinfo->i_lenAlloc = 0;
iinfo->i_next_alloc_block = 0;
iinfo->i_next_alloc_goal = 0;
if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) {
iinfo->i_efe = 1;
iinfo->i_use = 0;
ret = udf_alloc_i_data(inode, bs -
sizeof(struct extendedFileEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct extendedFileEntry),
bs - sizeof(struct extendedFileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) {
iinfo->i_efe = 0;
iinfo->i_use = 0;
ret = udf_alloc_i_data(inode, bs - sizeof(struct fileEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct fileEntry),
bs - sizeof(struct fileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) {
iinfo->i_efe = 0;
iinfo->i_use = 1;
iinfo->i_lenAlloc = le32_to_cpu(
((struct unallocSpaceEntry *)bh->b_data)->
lengthAllocDescs);
ret = udf_alloc_i_data(inode, bs -
sizeof(struct unallocSpaceEntry));
if (ret)
goto out;
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct unallocSpaceEntry),
bs - sizeof(struct unallocSpaceEntry));
return 0;
}
ret = -EIO;
read_lock(&sbi->s_cred_lock);
i_uid_write(inode, le32_to_cpu(fe->uid));
if (!uid_valid(inode->i_uid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET))
inode->i_uid = UDF_SB(inode->i_sb)->s_uid;
i_gid_write(inode, le32_to_cpu(fe->gid));
if (!gid_valid(inode->i_gid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET))
inode->i_gid = UDF_SB(inode->i_sb)->s_gid;
if (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_fmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_fmode;
else if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_dmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_dmode;
else
inode->i_mode = udf_convert_permissions(fe);
inode->i_mode &= ~sbi->s_umask;
read_unlock(&sbi->s_cred_lock);
link_count = le16_to_cpu(fe->fileLinkCount);
if (!link_count) {
if (!hidden_inode) {
ret = -ESTALE;
goto out;
}
link_count = 1;
}
set_nlink(inode, link_count);
inode->i_size = le64_to_cpu(fe->informationLength);
iinfo->i_lenExtents = inode->i_size;
if (iinfo->i_efe == 0) {
inode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
fe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(fe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(fe->checkpoint);
} else {
inode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
efe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime))
iinfo->i_crtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(efe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(efe->checkpoint);
}
inode->i_generation = iinfo->i_unique;
/*
* Sanity check length of allocation descriptors and extended attrs to
* avoid integer overflows
*/
if (iinfo->i_lenEAttr > bs || iinfo->i_lenAlloc > bs)
goto out;
/* Now do exact checks */
if (udf_file_entry_alloc_offset(inode) + iinfo->i_lenAlloc > bs)
goto out;
/* Sanity checks for files in ICB so that we don't get confused later */
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
/*
* For file in ICB data is stored in allocation descriptor
* so sizes should match
*/
if (iinfo->i_lenAlloc != inode->i_size)
goto out;
/* File in ICB has to fit in there... */
if (inode->i_size > bs - udf_file_entry_alloc_offset(inode))
goto out;
}
switch (fe->icbTag.fileType) {
case ICBTAG_FILE_TYPE_DIRECTORY:
inode->i_op = &udf_dir_inode_operations;
inode->i_fop = &udf_dir_operations;
inode->i_mode |= S_IFDIR;
inc_nlink(inode);
break;
case ICBTAG_FILE_TYPE_REALTIME:
case ICBTAG_FILE_TYPE_REGULAR:
case ICBTAG_FILE_TYPE_UNDEF:
case ICBTAG_FILE_TYPE_VAT20:
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
inode->i_data.a_ops = &udf_adinicb_aops;
else
inode->i_data.a_ops = &udf_aops;
inode->i_op = &udf_file_inode_operations;
inode->i_fop = &udf_file_operations;
inode->i_mode |= S_IFREG;
break;
case ICBTAG_FILE_TYPE_BLOCK:
inode->i_mode |= S_IFBLK;
break;
case ICBTAG_FILE_TYPE_CHAR:
inode->i_mode |= S_IFCHR;
break;
case ICBTAG_FILE_TYPE_FIFO:
init_special_inode(inode, inode->i_mode | S_IFIFO, 0);
break;
case ICBTAG_FILE_TYPE_SOCKET:
init_special_inode(inode, inode->i_mode | S_IFSOCK, 0);
break;
case ICBTAG_FILE_TYPE_SYMLINK:
inode->i_data.a_ops = &udf_symlink_aops;
inode->i_op = &udf_symlink_inode_operations;
inode->i_mode = S_IFLNK | S_IRWXUGO;
break;
case ICBTAG_FILE_TYPE_MAIN:
udf_debug("METADATA FILE-----\n");
break;
case ICBTAG_FILE_TYPE_MIRROR:
udf_debug("METADATA MIRROR FILE-----\n");
break;
case ICBTAG_FILE_TYPE_BITMAP:
udf_debug("METADATA BITMAP FILE-----\n");
break;
default:
udf_err(inode->i_sb, "(ino %ld) failed unknown file type=%d\n",
inode->i_ino, fe->icbTag.fileType);
goto out;
}
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
struct deviceSpec *dsea =
(struct deviceSpec *)udf_get_extendedattr(inode, 12, 1);
if (dsea) {
init_special_inode(inode, inode->i_mode,
MKDEV(le32_to_cpu(dsea->majorDeviceIdent),
le32_to_cpu(dsea->minorDeviceIdent)));
/* Developer ID ??? */
} else
goto out;
}
ret = 0;
out:
brelse(bh);
return ret;
}
| 166,614 |
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_xprt *svc_rdma_accept(struct svc_xprt *xprt)
{
struct svcxprt_rdma *listen_rdma;
struct svcxprt_rdma *newxprt = NULL;
struct rdma_conn_param conn_param;
struct rpcrdma_connect_private pmsg;
struct ib_qp_init_attr qp_attr;
struct ib_device *dev;
struct sockaddr *sap;
unsigned int i;
int ret = 0;
listen_rdma = container_of(xprt, struct svcxprt_rdma, sc_xprt);
clear_bit(XPT_CONN, &xprt->xpt_flags);
/* Get the next entry off the accept list */
spin_lock_bh(&listen_rdma->sc_lock);
if (!list_empty(&listen_rdma->sc_accept_q)) {
newxprt = list_entry(listen_rdma->sc_accept_q.next,
struct svcxprt_rdma, sc_accept_q);
list_del_init(&newxprt->sc_accept_q);
}
if (!list_empty(&listen_rdma->sc_accept_q))
set_bit(XPT_CONN, &listen_rdma->sc_xprt.xpt_flags);
spin_unlock_bh(&listen_rdma->sc_lock);
if (!newxprt)
return NULL;
dprintk("svcrdma: newxprt from accept queue = %p, cm_id=%p\n",
newxprt, newxprt->sc_cm_id);
dev = newxprt->sc_cm_id->device;
/* Qualify the transport resource defaults with the
* capabilities of this particular device */
newxprt->sc_max_sge = min((size_t)dev->attrs.max_sge,
(size_t)RPCSVC_MAXPAGES);
newxprt->sc_max_sge_rd = min_t(size_t, dev->attrs.max_sge_rd,
RPCSVC_MAXPAGES);
newxprt->sc_max_req_size = svcrdma_max_req_size;
newxprt->sc_max_requests = min_t(u32, dev->attrs.max_qp_wr,
svcrdma_max_requests);
newxprt->sc_fc_credits = cpu_to_be32(newxprt->sc_max_requests);
newxprt->sc_max_bc_requests = min_t(u32, dev->attrs.max_qp_wr,
svcrdma_max_bc_requests);
newxprt->sc_rq_depth = newxprt->sc_max_requests +
newxprt->sc_max_bc_requests;
newxprt->sc_sq_depth = RPCRDMA_SQ_DEPTH_MULT * newxprt->sc_rq_depth;
atomic_set(&newxprt->sc_sq_avail, newxprt->sc_sq_depth);
if (!svc_rdma_prealloc_ctxts(newxprt))
goto errout;
if (!svc_rdma_prealloc_maps(newxprt))
goto errout;
/*
* Limit ORD based on client limit, local device limit, and
* configured svcrdma limit.
*/
newxprt->sc_ord = min_t(size_t, dev->attrs.max_qp_rd_atom, newxprt->sc_ord);
newxprt->sc_ord = min_t(size_t, svcrdma_ord, newxprt->sc_ord);
newxprt->sc_pd = ib_alloc_pd(dev, 0);
if (IS_ERR(newxprt->sc_pd)) {
dprintk("svcrdma: error creating PD for connect request\n");
goto errout;
}
newxprt->sc_sq_cq = ib_alloc_cq(dev, newxprt, newxprt->sc_sq_depth,
0, IB_POLL_WORKQUEUE);
if (IS_ERR(newxprt->sc_sq_cq)) {
dprintk("svcrdma: error creating SQ CQ for connect request\n");
goto errout;
}
newxprt->sc_rq_cq = ib_alloc_cq(dev, newxprt, newxprt->sc_rq_depth,
0, IB_POLL_WORKQUEUE);
if (IS_ERR(newxprt->sc_rq_cq)) {
dprintk("svcrdma: error creating RQ CQ for connect request\n");
goto errout;
}
memset(&qp_attr, 0, sizeof qp_attr);
qp_attr.event_handler = qp_event_handler;
qp_attr.qp_context = &newxprt->sc_xprt;
qp_attr.cap.max_send_wr = newxprt->sc_sq_depth;
qp_attr.cap.max_recv_wr = newxprt->sc_rq_depth;
qp_attr.cap.max_send_sge = newxprt->sc_max_sge;
qp_attr.cap.max_recv_sge = newxprt->sc_max_sge;
qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
qp_attr.qp_type = IB_QPT_RC;
qp_attr.send_cq = newxprt->sc_sq_cq;
qp_attr.recv_cq = newxprt->sc_rq_cq;
dprintk("svcrdma: newxprt->sc_cm_id=%p, newxprt->sc_pd=%p\n",
newxprt->sc_cm_id, newxprt->sc_pd);
dprintk(" cap.max_send_wr = %d, cap.max_recv_wr = %d\n",
qp_attr.cap.max_send_wr, qp_attr.cap.max_recv_wr);
dprintk(" cap.max_send_sge = %d, cap.max_recv_sge = %d\n",
qp_attr.cap.max_send_sge, qp_attr.cap.max_recv_sge);
ret = rdma_create_qp(newxprt->sc_cm_id, newxprt->sc_pd, &qp_attr);
if (ret) {
dprintk("svcrdma: failed to create QP, ret=%d\n", ret);
goto errout;
}
newxprt->sc_qp = newxprt->sc_cm_id->qp;
/*
* Use the most secure set of MR resources based on the
* transport type and available memory management features in
* the device. Here's the table implemented below:
*
* Fast Global DMA Remote WR
* Reg LKEY MR Access
* Sup'd Sup'd Needed Needed
*
* IWARP N N Y Y
* N Y Y Y
* Y N Y N
* Y Y N -
*
* IB N N Y N
* N Y N -
* Y N Y N
* Y Y N -
*
* NB: iWARP requires remote write access for the data sink
* of an RDMA_READ. IB does not.
*/
newxprt->sc_reader = rdma_read_chunk_lcl;
if (dev->attrs.device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS) {
newxprt->sc_frmr_pg_list_len =
dev->attrs.max_fast_reg_page_list_len;
newxprt->sc_dev_caps |= SVCRDMA_DEVCAP_FAST_REG;
newxprt->sc_reader = rdma_read_chunk_frmr;
} else
newxprt->sc_snd_w_inv = false;
/*
* Determine if a DMA MR is required and if so, what privs are required
*/
if (!rdma_protocol_iwarp(dev, newxprt->sc_cm_id->port_num) &&
!rdma_ib_or_roce(dev, newxprt->sc_cm_id->port_num))
goto errout;
if (rdma_protocol_iwarp(dev, newxprt->sc_cm_id->port_num))
newxprt->sc_dev_caps |= SVCRDMA_DEVCAP_READ_W_INV;
/* Post receive buffers */
for (i = 0; i < newxprt->sc_max_requests; i++) {
ret = svc_rdma_post_recv(newxprt, GFP_KERNEL);
if (ret) {
dprintk("svcrdma: failure posting receive buffers\n");
goto errout;
}
}
/* Swap out the handler */
newxprt->sc_cm_id->event_handler = rdma_cma_handler;
/* Construct RDMA-CM private message */
pmsg.cp_magic = rpcrdma_cmp_magic;
pmsg.cp_version = RPCRDMA_CMP_VERSION;
pmsg.cp_flags = 0;
pmsg.cp_send_size = pmsg.cp_recv_size =
rpcrdma_encode_buffer_size(newxprt->sc_max_req_size);
/* Accept Connection */
set_bit(RDMAXPRT_CONN_PENDING, &newxprt->sc_flags);
memset(&conn_param, 0, sizeof conn_param);
conn_param.responder_resources = 0;
conn_param.initiator_depth = newxprt->sc_ord;
conn_param.private_data = &pmsg;
conn_param.private_data_len = sizeof(pmsg);
ret = rdma_accept(newxprt->sc_cm_id, &conn_param);
if (ret) {
dprintk("svcrdma: failed to accept new connection, ret=%d\n",
ret);
goto errout;
}
dprintk("svcrdma: new connection %p accepted:\n", newxprt);
sap = (struct sockaddr *)&newxprt->sc_cm_id->route.addr.src_addr;
dprintk(" local address : %pIS:%u\n", sap, rpc_get_port(sap));
sap = (struct sockaddr *)&newxprt->sc_cm_id->route.addr.dst_addr;
dprintk(" remote address : %pIS:%u\n", sap, rpc_get_port(sap));
dprintk(" max_sge : %d\n", newxprt->sc_max_sge);
dprintk(" max_sge_rd : %d\n", newxprt->sc_max_sge_rd);
dprintk(" sq_depth : %d\n", newxprt->sc_sq_depth);
dprintk(" max_requests : %d\n", newxprt->sc_max_requests);
dprintk(" ord : %d\n", newxprt->sc_ord);
return &newxprt->sc_xprt;
errout:
dprintk("svcrdma: failure accepting new connection rc=%d.\n", ret);
/* Take a reference in case the DTO handler runs */
svc_xprt_get(&newxprt->sc_xprt);
if (newxprt->sc_qp && !IS_ERR(newxprt->sc_qp))
ib_destroy_qp(newxprt->sc_qp);
rdma_destroy_id(newxprt->sc_cm_id);
/* This call to put will destroy the transport */
svc_xprt_put(&newxprt->sc_xprt);
return NULL;
}
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_xprt *svc_rdma_accept(struct svc_xprt *xprt)
{
struct svcxprt_rdma *listen_rdma;
struct svcxprt_rdma *newxprt = NULL;
struct rdma_conn_param conn_param;
struct rpcrdma_connect_private pmsg;
struct ib_qp_init_attr qp_attr;
struct ib_device *dev;
struct sockaddr *sap;
unsigned int i;
int ret = 0;
listen_rdma = container_of(xprt, struct svcxprt_rdma, sc_xprt);
clear_bit(XPT_CONN, &xprt->xpt_flags);
/* Get the next entry off the accept list */
spin_lock_bh(&listen_rdma->sc_lock);
if (!list_empty(&listen_rdma->sc_accept_q)) {
newxprt = list_entry(listen_rdma->sc_accept_q.next,
struct svcxprt_rdma, sc_accept_q);
list_del_init(&newxprt->sc_accept_q);
}
if (!list_empty(&listen_rdma->sc_accept_q))
set_bit(XPT_CONN, &listen_rdma->sc_xprt.xpt_flags);
spin_unlock_bh(&listen_rdma->sc_lock);
if (!newxprt)
return NULL;
dprintk("svcrdma: newxprt from accept queue = %p, cm_id=%p\n",
newxprt, newxprt->sc_cm_id);
dev = newxprt->sc_cm_id->device;
newxprt->sc_port_num = newxprt->sc_cm_id->port_num;
/* Qualify the transport resource defaults with the
* capabilities of this particular device */
newxprt->sc_max_sge = min((size_t)dev->attrs.max_sge,
(size_t)RPCSVC_MAXPAGES);
newxprt->sc_max_sge_rd = min_t(size_t, dev->attrs.max_sge_rd,
RPCSVC_MAXPAGES);
newxprt->sc_max_req_size = svcrdma_max_req_size;
newxprt->sc_max_requests = min_t(u32, dev->attrs.max_qp_wr,
svcrdma_max_requests);
newxprt->sc_fc_credits = cpu_to_be32(newxprt->sc_max_requests);
newxprt->sc_max_bc_requests = min_t(u32, dev->attrs.max_qp_wr,
svcrdma_max_bc_requests);
newxprt->sc_rq_depth = newxprt->sc_max_requests +
newxprt->sc_max_bc_requests;
newxprt->sc_sq_depth = newxprt->sc_rq_depth;
atomic_set(&newxprt->sc_sq_avail, newxprt->sc_sq_depth);
if (!svc_rdma_prealloc_ctxts(newxprt))
goto errout;
/*
* Limit ORD based on client limit, local device limit, and
* configured svcrdma limit.
*/
newxprt->sc_ord = min_t(size_t, dev->attrs.max_qp_rd_atom, newxprt->sc_ord);
newxprt->sc_ord = min_t(size_t, svcrdma_ord, newxprt->sc_ord);
newxprt->sc_pd = ib_alloc_pd(dev, 0);
if (IS_ERR(newxprt->sc_pd)) {
dprintk("svcrdma: error creating PD for connect request\n");
goto errout;
}
newxprt->sc_sq_cq = ib_alloc_cq(dev, newxprt, newxprt->sc_sq_depth,
0, IB_POLL_WORKQUEUE);
if (IS_ERR(newxprt->sc_sq_cq)) {
dprintk("svcrdma: error creating SQ CQ for connect request\n");
goto errout;
}
newxprt->sc_rq_cq = ib_alloc_cq(dev, newxprt, newxprt->sc_rq_depth,
0, IB_POLL_WORKQUEUE);
if (IS_ERR(newxprt->sc_rq_cq)) {
dprintk("svcrdma: error creating RQ CQ for connect request\n");
goto errout;
}
memset(&qp_attr, 0, sizeof qp_attr);
qp_attr.event_handler = qp_event_handler;
qp_attr.qp_context = &newxprt->sc_xprt;
qp_attr.port_num = newxprt->sc_cm_id->port_num;
qp_attr.cap.max_rdma_ctxs = newxprt->sc_max_requests;
qp_attr.cap.max_send_wr = newxprt->sc_sq_depth;
qp_attr.cap.max_recv_wr = newxprt->sc_rq_depth;
qp_attr.cap.max_send_sge = newxprt->sc_max_sge;
qp_attr.cap.max_recv_sge = newxprt->sc_max_sge;
qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
qp_attr.qp_type = IB_QPT_RC;
qp_attr.send_cq = newxprt->sc_sq_cq;
qp_attr.recv_cq = newxprt->sc_rq_cq;
dprintk("svcrdma: newxprt->sc_cm_id=%p, newxprt->sc_pd=%p\n",
newxprt->sc_cm_id, newxprt->sc_pd);
dprintk(" cap.max_send_wr = %d, cap.max_recv_wr = %d\n",
qp_attr.cap.max_send_wr, qp_attr.cap.max_recv_wr);
dprintk(" cap.max_send_sge = %d, cap.max_recv_sge = %d\n",
qp_attr.cap.max_send_sge, qp_attr.cap.max_recv_sge);
ret = rdma_create_qp(newxprt->sc_cm_id, newxprt->sc_pd, &qp_attr);
if (ret) {
dprintk("svcrdma: failed to create QP, ret=%d\n", ret);
goto errout;
}
newxprt->sc_qp = newxprt->sc_cm_id->qp;
/*
* Use the most secure set of MR resources based on the
* transport type and available memory management features in
* the device. Here's the table implemented below:
*
* Fast Global DMA Remote WR
* Reg LKEY MR Access
* Sup'd Sup'd Needed Needed
*
* IWARP N N Y Y
* N Y Y Y
* Y N Y N
* Y Y N -
*
* IB N N Y N
* N Y N -
* Y N Y N
* Y Y N -
*
* NB: iWARP requires remote write access for the data sink
* of an RDMA_READ. IB does not.
*/
newxprt->sc_reader = rdma_read_chunk_lcl;
if (dev->attrs.device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS) {
newxprt->sc_frmr_pg_list_len =
dev->attrs.max_fast_reg_page_list_len;
newxprt->sc_dev_caps |= SVCRDMA_DEVCAP_FAST_REG;
newxprt->sc_reader = rdma_read_chunk_frmr;
} else
newxprt->sc_snd_w_inv = false;
/*
* Determine if a DMA MR is required and if so, what privs are required
*/
if (!rdma_protocol_iwarp(dev, newxprt->sc_cm_id->port_num) &&
!rdma_ib_or_roce(dev, newxprt->sc_cm_id->port_num))
goto errout;
if (rdma_protocol_iwarp(dev, newxprt->sc_cm_id->port_num))
newxprt->sc_dev_caps |= SVCRDMA_DEVCAP_READ_W_INV;
/* Post receive buffers */
for (i = 0; i < newxprt->sc_max_requests; i++) {
ret = svc_rdma_post_recv(newxprt, GFP_KERNEL);
if (ret) {
dprintk("svcrdma: failure posting receive buffers\n");
goto errout;
}
}
/* Swap out the handler */
newxprt->sc_cm_id->event_handler = rdma_cma_handler;
/* Construct RDMA-CM private message */
pmsg.cp_magic = rpcrdma_cmp_magic;
pmsg.cp_version = RPCRDMA_CMP_VERSION;
pmsg.cp_flags = 0;
pmsg.cp_send_size = pmsg.cp_recv_size =
rpcrdma_encode_buffer_size(newxprt->sc_max_req_size);
/* Accept Connection */
set_bit(RDMAXPRT_CONN_PENDING, &newxprt->sc_flags);
memset(&conn_param, 0, sizeof conn_param);
conn_param.responder_resources = 0;
conn_param.initiator_depth = newxprt->sc_ord;
conn_param.private_data = &pmsg;
conn_param.private_data_len = sizeof(pmsg);
ret = rdma_accept(newxprt->sc_cm_id, &conn_param);
if (ret) {
dprintk("svcrdma: failed to accept new connection, ret=%d\n",
ret);
goto errout;
}
dprintk("svcrdma: new connection %p accepted:\n", newxprt);
sap = (struct sockaddr *)&newxprt->sc_cm_id->route.addr.src_addr;
dprintk(" local address : %pIS:%u\n", sap, rpc_get_port(sap));
sap = (struct sockaddr *)&newxprt->sc_cm_id->route.addr.dst_addr;
dprintk(" remote address : %pIS:%u\n", sap, rpc_get_port(sap));
dprintk(" max_sge : %d\n", newxprt->sc_max_sge);
dprintk(" max_sge_rd : %d\n", newxprt->sc_max_sge_rd);
dprintk(" sq_depth : %d\n", newxprt->sc_sq_depth);
dprintk(" max_requests : %d\n", newxprt->sc_max_requests);
dprintk(" ord : %d\n", newxprt->sc_ord);
return &newxprt->sc_xprt;
errout:
dprintk("svcrdma: failure accepting new connection rc=%d.\n", ret);
/* Take a reference in case the DTO handler runs */
svc_xprt_get(&newxprt->sc_xprt);
if (newxprt->sc_qp && !IS_ERR(newxprt->sc_qp))
ib_destroy_qp(newxprt->sc_qp);
rdma_destroy_id(newxprt->sc_cm_id);
/* This call to put will destroy the transport */
svc_xprt_put(&newxprt->sc_xprt);
return NULL;
}
| 168,179 |
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_CreateInt( int64_t num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
}
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_CreateInt( int64_t num )
| 167,274 |
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: datum_to_json(Datum val, bool is_null, StringInfo result,
JsonTypeCategory tcategory, Oid outfuncoid,
bool key_scalar)
{
char *outputstr;
text *jsontext;
/* callers are expected to ensure that null keys are not passed in */
char *outputstr;
text *jsontext;
/* callers are expected to ensure that null keys are not passed in */
Assert(!(key_scalar && is_null));
if (key_scalar &&
(tcategory == JSONTYPE_ARRAY ||
tcategory == JSONTYPE_COMPOSITE ||
tcategory == JSONTYPE_JSON ||
tcategory == JSONTYPE_CAST))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("key value must be scalar, not array, composite, or json")));
switch (tcategory)
{
case JSONTYPE_ARRAY:
array_to_json_internal(val, result, false);
break;
case JSONTYPE_COMPOSITE:
composite_to_json(val, result, false);
break;
case JSONTYPE_BOOL:
outputstr = DatumGetBool(val) ? "true" : "false";
if (key_scalar)
escape_json(result, outputstr);
else
appendStringInfoString(result, outputstr);
break;
case JSONTYPE_NUMERIC:
outputstr = OidOutputFunctionCall(outfuncoid, val);
/*
* Don't call escape_json for a non-key if it's a valid JSON
* number.
*/
if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
appendStringInfoString(result, outputstr);
else
escape_json(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_DATE:
{
DateADT date;
struct pg_tm tm;
char buf[MAXDATELEN + 1];
date = DatumGetDateADT(val);
if (DATE_NOT_FINITE(date))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else
{
j2date(date + POSTGRES_EPOCH_JDATE,
&(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
EncodeDateOnly(&tm, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
}
break;
case JSONTYPE_TIMESTAMP:
{
Timestamp timestamp;
struct pg_tm tm;
fsec_t fsec;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
{
EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_TIMESTAMPTZ:
{
TimestampTz timestamp;
struct pg_tm tm;
int tz;
fsec_t fsec;
const char *tzn = NULL;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
{
EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_JSON:
/* JSON and JSONB output will already be escaped */
outputstr = OidOutputFunctionCall(outfuncoid, val);
appendStringInfoString(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_CAST:
/* outfuncoid refers to a cast function, not an output function */
jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
outputstr = text_to_cstring(jsontext);
appendStringInfoString(result, outputstr);
pfree(outputstr);
pfree(jsontext);
break;
default:
outputstr = OidOutputFunctionCall(outfuncoid, val);
escape_json(result, outputstr);
pfree(outputstr);
break;
}
}
Commit Message:
CWE ID: CWE-119 | datum_to_json(Datum val, bool is_null, StringInfo result,
JsonTypeCategory tcategory, Oid outfuncoid,
bool key_scalar)
{
char *outputstr;
text *jsontext;
/* callers are expected to ensure that null keys are not passed in */
char *outputstr;
text *jsontext;
check_stack_depth();
/* callers are expected to ensure that null keys are not passed in */
Assert(!(key_scalar && is_null));
if (key_scalar &&
(tcategory == JSONTYPE_ARRAY ||
tcategory == JSONTYPE_COMPOSITE ||
tcategory == JSONTYPE_JSON ||
tcategory == JSONTYPE_CAST))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("key value must be scalar, not array, composite, or json")));
switch (tcategory)
{
case JSONTYPE_ARRAY:
array_to_json_internal(val, result, false);
break;
case JSONTYPE_COMPOSITE:
composite_to_json(val, result, false);
break;
case JSONTYPE_BOOL:
outputstr = DatumGetBool(val) ? "true" : "false";
if (key_scalar)
escape_json(result, outputstr);
else
appendStringInfoString(result, outputstr);
break;
case JSONTYPE_NUMERIC:
outputstr = OidOutputFunctionCall(outfuncoid, val);
/*
* Don't call escape_json for a non-key if it's a valid JSON
* number.
*/
if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
appendStringInfoString(result, outputstr);
else
escape_json(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_DATE:
{
DateADT date;
struct pg_tm tm;
char buf[MAXDATELEN + 1];
date = DatumGetDateADT(val);
if (DATE_NOT_FINITE(date))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else
{
j2date(date + POSTGRES_EPOCH_JDATE,
&(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
EncodeDateOnly(&tm, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
}
break;
case JSONTYPE_TIMESTAMP:
{
Timestamp timestamp;
struct pg_tm tm;
fsec_t fsec;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
{
EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_TIMESTAMPTZ:
{
TimestampTz timestamp;
struct pg_tm tm;
int tz;
fsec_t fsec;
const char *tzn = NULL;
char buf[MAXDATELEN + 1];
timestamp = DatumGetTimestamp(val);
if (TIMESTAMP_NOT_FINITE(timestamp))
{
/* we have to format infinity ourselves */
appendStringInfoString(result, DT_INFINITY);
}
else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
{
EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
appendStringInfo(result, "\"%s\"", buf);
}
else
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
break;
case JSONTYPE_JSON:
/* JSON and JSONB output will already be escaped */
outputstr = OidOutputFunctionCall(outfuncoid, val);
appendStringInfoString(result, outputstr);
pfree(outputstr);
break;
case JSONTYPE_CAST:
/* outfuncoid refers to a cast function, not an output function */
jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
outputstr = text_to_cstring(jsontext);
appendStringInfoString(result, outputstr);
pfree(outputstr);
pfree(jsontext);
break;
default:
outputstr = OidOutputFunctionCall(outfuncoid, val);
escape_json(result, outputstr);
pfree(outputstr);
break;
}
}
| 164,678 |
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 nsc_context_initialize_encode(NSC_CONTEXT* context)
{
int i;
UINT32 length;
UINT32 tempWidth;
UINT32 tempHeight;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
/* The maximum length a decoded plane can reach in all cases */
length = tempWidth * tempHeight + 16;
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
{
BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length);
if (!tmp)
goto fail;
context->priv->PlaneBuffers[i] = tmp;
}
context->priv->PlaneBuffersLength = length;
}
if (context->ChromaSubsamplingLevel)
{
context->OrgByteCount[0] = tempWidth * context->height;
context->OrgByteCount[1] = tempWidth * tempHeight / 4;
context->OrgByteCount[2] = tempWidth * tempHeight / 4;
context->OrgByteCount[3] = context->width * context->height;
}
else
{
context->OrgByteCount[0] = context->width * context->height;
context->OrgByteCount[1] = context->width * context->height;
context->OrgByteCount[2] = context->width * context->height;
context->OrgByteCount[3] = context->width * context->height;
}
return TRUE;
fail:
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
free(context->priv->PlaneBuffers[i]);
}
return FALSE;
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context)
{
int i;
UINT32 length;
UINT32 tempWidth;
UINT32 tempHeight;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
/* The maximum length a decoded plane can reach in all cases */
length = tempWidth * tempHeight + 16;
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
{
BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length);
if (!tmp)
goto fail;
context->priv->PlaneBuffers[i] = tmp;
}
context->priv->PlaneBuffersLength = length;
}
if (context->ChromaSubsamplingLevel)
{
context->OrgByteCount[0] = tempWidth * context->height;
context->OrgByteCount[1] = tempWidth * tempHeight / 4;
context->OrgByteCount[2] = tempWidth * tempHeight / 4;
context->OrgByteCount[3] = context->width * context->height;
}
else
{
context->OrgByteCount[0] = context->width * context->height;
context->OrgByteCount[1] = context->width * context->height;
context->OrgByteCount[2] = context->width * context->height;
context->OrgByteCount[3] = context->width * context->height;
}
return TRUE;
fail:
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
free(context->priv->PlaneBuffers[i]);
}
return FALSE;
}
| 169,286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.