{"idx": 194999, "project": "hhvm", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 1, "func": "String preg_quote(const String& str,\n const String& delimiter /* = null_string */) {\n const char* in_str = str.data();\n const char* in_str_end = in_str + str.size();\n\n /* Nothing to do if we got an empty string */\n if (in_str == in_str_end) {\n return str;\n }\n\n char delim_char = 0; /* Delimiter character to be quoted */\n bool quote_delim = false; /* Whether to quote additional delim char */\n if (!delimiter.empty()) {\n delim_char = delimiter.charAt(0);\n quote_delim = true;\n }\n\n /* Allocate enough memory so that even if each character\n is quoted, we won't run out of room */\n String ret(4 * str.size() + 1, ReserveString);\n char* out_str = ret.mutableData();\n\n /* Go through the string and quote necessary characters */\n const char* p;\n char* q;\n for (p = in_str, q = out_str; p != in_str_end; p++) {\n char c = *p;\n switch (c) {\n case '.': case '\\\\': case '+': case '*': case '?':\n case '[': case '^': case ']': case '$': case '(':\n case ')': case '{': case '}': case '=': case '!':\n case '>': case '<': case '|': case ':': case '-':\n case '#':\n *q++ = '\\\\';\n *q++ = c;\n break;\n\n case '\\0':\n *q++ = '\\\\';\n *q++ = '0';\n *q++ = '0';\n *q++ = '0';\n break;\n\n default:\n if (quote_delim && c == delim_char)\n *q++ = '\\\\';\n *q++ = c;\n break;\n }\n }\n *q = '\\0';\n\n return ret.setSize(q - out_str);\n}", "func_hash": 238223164532786533215583452209843695586, "file_name": "preg.cpp", "file_hash": 285507481464794574944910815142691250961, "cwe": ["CWE-190"], "cve": "CVE-2020-1918", "cve_desc": "In-memory file operations (ie: using fopen on a data URI) did not properly restrict negative seeking, allowing for the reading of memory prior to the in-memory buffer. This issue affects HHVM versions prior to 4.56.3, all versions between 4.57.0 and 4.80.1, all versions between 4.81.0 and 4.93.1, and versions 4.94.0, 4.95.0, 4.96.0, 4.97.0, 4.98.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1918"} {"idx": 219542, "project": "hhvm", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 0, "func": "String preg_quote(const String& str,\n const String& delimiter /* = null_string */) {\n const char* in_str = str.data();\n const char* in_str_end = in_str + str.size();\n\n /* Nothing to do if we got an empty string */\n if (in_str == in_str_end) {\n return str;\n }\n\n char delim_char = 0; /* Delimiter character to be quoted */\n bool quote_delim = false; /* Whether to quote additional delim char */\n if (!delimiter.empty()) {\n delim_char = delimiter.charAt(0);\n quote_delim = true;\n }\n\n /* Allocate enough memory so that even if each character\n is quoted, we won't run out of room */\n static_assert(\n (StringData::MaxSize * 4 + 1) < std::numeric_limits::max()\n );\n String ret(4 * str.size() + 1, ReserveString);\n char* out_str = ret.mutableData();\n\n /* Go through the string and quote necessary characters */\n const char* p;\n char* q;\n for (p = in_str, q = out_str; p != in_str_end; p++) {\n char c = *p;\n switch (c) {\n case '.': case '\\\\': case '+': case '*': case '?':\n case '[': case '^': case ']': case '$': case '(':\n case ')': case '{': case '}': case '=': case '!':\n case '>': case '<': case '|': case ':': case '-':\n case '#':\n *q++ = '\\\\';\n *q++ = c;\n break;\n\n case '\\0':\n *q++ = '\\\\';\n *q++ = '0';\n *q++ = '0';\n *q++ = '0';\n break;\n\n default:\n if (quote_delim && c == delim_char)\n *q++ = '\\\\';\n *q++ = c;\n break;\n }\n }\n *q = '\\0';\n\n return ret.setSize(q - out_str);\n}", "func_hash": 151686398596358025031627572249093000071, "file_name": "preg.cpp", "file_hash": 186958971386656040690242679271504836889, "cwe": ["CWE-190"], "cve": "CVE-2020-1918", "cve_desc": "In-memory file operations (ie: using fopen on a data URI) did not properly restrict negative seeking, allowing for the reading of memory prior to the in-memory buffer. This issue affects HHVM versions prior to 4.56.3, all versions between 4.57.0 and 4.80.1, all versions between 4.81.0 and 4.93.1, and versions 4.94.0, 4.95.0, 4.96.0, 4.97.0, 4.98.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1918"} {"idx": 195007, "project": "hhvm", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 1, "func": "static int xbuf_format_converter(char **outbuf, const char *fmt, va_list ap)\n{\n register char *s = nullptr;\n char *q;\n int s_len;\n\n register int min_width = 0;\n int precision = 0;\n enum {\n LEFT, RIGHT\n } adjust;\n char pad_char;\n char prefix_char;\n\n double fp_num;\n wide_int i_num = (wide_int) 0;\n u_wide_int ui_num;\n\n char num_buf[NUM_BUF_SIZE];\n char char_buf[2]; /* for printing %% and % */\n\n#ifdef HAVE_LOCALE_H\n struct lconv *lconv = nullptr;\n#endif\n\n /*\n * Flag variables\n */\n length_modifier_e modifier;\n boolean_e alternate_form;\n boolean_e print_sign;\n boolean_e print_blank;\n boolean_e adjust_precision;\n boolean_e adjust_width;\n int is_negative;\n\n int size = 240;\n char *result = (char *)malloc(size);\n int outpos = 0;\n\n while (*fmt) {\n if (*fmt != '%') {\n appendchar(&result, &outpos, &size, *fmt);\n } else {\n /*\n * Default variable settings\n */\n adjust = RIGHT;\n alternate_form = print_sign = print_blank = NO;\n pad_char = ' ';\n prefix_char = NUL;\n\n fmt++;\n\n /*\n * Try to avoid checking for flags, width or precision\n */\n if (isascii((int)*fmt) && !islower((int)*fmt)) {\n /*\n * Recognize flags: -, #, BLANK, +\n */\n for (;; fmt++) {\n if (*fmt == '-')\n adjust = LEFT;\n else if (*fmt == '+')\n print_sign = YES;\n else if (*fmt == '#')\n alternate_form = YES;\n else if (*fmt == ' ')\n print_blank = YES;\n else if (*fmt == '0')\n pad_char = '0';\n else\n break;\n }\n\n /*\n * Check if a width was specified\n */\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, min_width);\n adjust_width = YES;\n } else if (*fmt == '*') {\n min_width = va_arg(ap, int);\n fmt++;\n adjust_width = YES;\n if (min_width < 0) {\n adjust = LEFT;\n min_width = -min_width;\n }\n } else\n adjust_width = NO;\n\n /*\n * Check if a precision was specified\n *\n * XXX: an unreasonable amount of precision may be specified\n * resulting in overflow of num_buf. Currently we\n * ignore this possibility.\n */\n if (*fmt == '.') {\n adjust_precision = YES;\n fmt++;\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, precision);\n } else if (*fmt == '*') {\n precision = va_arg(ap, int);\n fmt++;\n if (precision < 0)\n precision = 0;\n } else\n precision = 0;\n } else\n adjust_precision = NO;\n } else\n adjust_precision = adjust_width = NO;\n\n /*\n * Modifier check\n */\n switch (*fmt) {\n case 'L':\n fmt++;\n modifier = LM_LONG_DOUBLE;\n break;\n case 'I':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == '6' && *(fmt+1) == '4') {\n fmt += 2;\n modifier = LM_LONG_LONG;\n } else\n#endif\n if (*fmt == '3' && *(fmt+1) == '2') {\n fmt += 2;\n modifier = LM_LONG;\n } else {\n#ifdef _WIN64\n modifier = LM_LONG_LONG;\n#else\n modifier = LM_LONG;\n#endif\n }\n break;\n case 'l':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == 'l') {\n fmt++;\n modifier = LM_LONG_LONG;\n } else\n#endif\n modifier = LM_LONG;\n break;\n case 'z':\n fmt++;\n modifier = LM_SIZE_T;\n break;\n case 'j':\n fmt++;\n#if SIZEOF_INTMAX_T\n modifier = LM_INTMAX_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 't':\n fmt++;\n#if SIZEOF_PTRDIFF_T\n modifier = LM_PTRDIFF_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 'h':\n fmt++;\n if (*fmt == 'h') {\n fmt++;\n }\n /* these are promoted to int, so no break */\n default:\n modifier = LM_STD;\n break;\n }\n\n /*\n * Argument extraction and printing.\n * First we determine the argument type.\n * Then, we convert the argument to a string.\n * On exit from the switch, s points to the string that\n * must be printed, s_len has the length of the string\n * The precision requirements, if any, are reflected in s_len.\n *\n * NOTE: pad_char may be set to '0' because of the 0 flag.\n * It is reset to ' ' by non-numeric formats\n */\n switch (*fmt) {\n case 'u':\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n i_num = (wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n /*\n * The rest also applies to other integer formats, so fall\n * into that case.\n */\n case 'd':\n case 'i':\n /*\n * Get the arg if we haven't already.\n */\n if ((*fmt) != 'u') {\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, long int);\n break;\n case LM_SIZE_T:\n#if SIZEOF_SSIZE_T\n i_num = (wide_int) va_arg(ap, ssize_t);\n#else\n i_num = (wide_int) va_arg(ap, size_t);\n#endif\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, intmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n }\n s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n\n if (*fmt != 'u') {\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'o':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 3, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && *s != '0') {\n *--s = '0';\n s_len++;\n }\n break;\n\n\n case 'x':\n case 'X':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 4, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && i_num != 0) {\n *--s = *fmt; /* 'x' or 'X' */\n *--s = '0';\n s_len += 2;\n }\n break;\n\n\n case 's':\n case 'v':\n s = va_arg(ap, char *);\n if (s != nullptr) {\n s_len = strlen(s);\n if (adjust_precision && precision < s_len)\n s_len = precision;\n } else {\n s = const_cast(s_null);\n s_len = S_NULL_LEN;\n }\n pad_char = ' ';\n break;\n\n\n case 'f':\n case 'F':\n case 'e':\n case 'E':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"nan\");\n s_len = 3;\n } else if (std::isinf(fp_num)) {\n s = const_cast(\"inf\");\n s_len = 3;\n } else {\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,\n (adjust_precision == NO) ? FLOAT_DIGITS : precision,\n (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',\n &is_negative, &num_buf[1], &s_len);\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'g':\n case 'k':\n case 'G':\n case 'H':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"NAN\");\n s_len = 3;\n break;\n } else if (std::isinf(fp_num)) {\n if (fp_num > 0) {\n s = const_cast(\"INF\");\n s_len = 3;\n } else {\n s = const_cast(\"-INF\");\n s_len = 4;\n }\n break;\n }\n\n if (adjust_precision == NO)\n precision = FLOAT_DIGITS;\n else if (precision == 0)\n precision = 1;\n /*\n * * We use &num_buf[ 1 ], so that we have room for the sign\n */\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_gcvt(fp_num, precision,\n (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT,\n (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);\n if (*s == '-')\n prefix_char = *s++;\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n\n s_len = strlen(s);\n\n if (alternate_form && (q = strchr(s, '.')) == nullptr)\n s[s_len++] = '.';\n break;\n\n\n case 'c':\n char_buf[0] = (char) (va_arg(ap, int));\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case '%':\n char_buf[0] = '%';\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case 'n':\n *(va_arg(ap, int *)) = outpos;\n goto skip_output;\n\n /*\n * Always extract the argument as a \"char *\" pointer. We\n * should be using \"void *\" but there are still machines\n * that don't understand it.\n * If the pointer size is equal to the size of an unsigned\n * integer we convert the pointer to a hex number, otherwise\n * we print \"%p\" to indicate that we don't handle \"%p\".\n */\n case 'p':\n if (sizeof(char *) <= sizeof(u_wide_int)) {\n ui_num = (u_wide_int)((size_t) va_arg(ap, char *));\n s = ap_php_conv_p2(ui_num, 4, 'x',\n &num_buf[NUM_BUF_SIZE], &s_len);\n if (ui_num != 0) {\n *--s = 'x';\n *--s = '0';\n s_len += 2;\n }\n } else {\n s = const_cast(\"%p\");\n s_len = 2;\n }\n pad_char = ' ';\n break;\n\n\n case NUL:\n /*\n * The last character of the format string was %.\n * We ignore it.\n */\n continue;\n\n\nfmt_error:\n throw Exception(\"Illegal length modifier specified '%c'\", *fmt);\n\n /*\n * The default case is for unrecognized %'s.\n * We print % to help the user identify what\n * option is not understood.\n * This is also useful in case the user wants to pass\n * the output of format_converter to another function\n * that understands some other % (like syslog).\n * Note that we can't point s inside fmt because the\n * unknown could be preceded by width etc.\n */\n default:\n char_buf[0] = '%';\n char_buf[1] = *fmt;\n s = char_buf;\n s_len = 2;\n pad_char = ' ';\n break;\n }\n\n if (prefix_char != NUL) {\n *--s = prefix_char;\n s_len++;\n }\n if (adjust_width && adjust == RIGHT && min_width > s_len) {\n if (pad_char == '0' && prefix_char != NUL) {\n appendchar(&result, &outpos, &size, *s);\n s++;\n s_len--;\n min_width--;\n }\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n /*\n * Print the (for now) non-null terminated string s.\n */\n appendsimplestring(&result, &outpos, &size, s, s_len);\n\n if (adjust_width && adjust == LEFT && min_width > s_len) {\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n }\nskip_output:\n fmt++;\n }\n /*\n * Add the terminating null here since it wasn't added incrementally above\n * once the whole string has been composed.\n */\n result[outpos] = NUL;\n *outbuf = result;\n return outpos;\n}", "func_hash": 123878033373043862530376781820859980563, "file_name": "zend-printf.cpp", "file_hash": 92196731070771540321178301198615589471, "cwe": ["CWE-190"], "cve": "CVE-2020-1918", "cve_desc": "In-memory file operations (ie: using fopen on a data URI) did not properly restrict negative seeking, allowing for the reading of memory prior to the in-memory buffer. This issue affects HHVM versions prior to 4.56.3, all versions between 4.57.0 and 4.80.1, all versions between 4.81.0 and 4.93.1, and versions 4.94.0, 4.95.0, 4.96.0, 4.97.0, 4.98.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1918"} {"idx": 219451, "project": "hhvm", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 0, "func": "static int xbuf_format_converter(char **outbuf, const char *fmt, va_list ap)\n{\n register char *s = nullptr;\n char *q;\n int s_len;\n\n register int min_width = 0;\n int precision = 0;\n enum {\n LEFT, RIGHT\n } adjust;\n char pad_char;\n char prefix_char;\n\n double fp_num;\n wide_int i_num = (wide_int) 0;\n u_wide_int ui_num;\n\n char num_buf[NUM_BUF_SIZE];\n char char_buf[2]; /* for printing %% and % */\n\n#ifdef HAVE_LOCALE_H\n struct lconv *lconv = nullptr;\n#endif\n\n /*\n * Flag variables\n */\n length_modifier_e modifier;\n boolean_e alternate_form;\n boolean_e print_sign;\n boolean_e print_blank;\n boolean_e adjust_precision;\n boolean_e adjust_width;\n int is_negative;\n\n int size = 240;\n char *result = (char *)malloc(size);\n int outpos = 0;\n\n while (*fmt) {\n if (*fmt != '%') {\n appendchar(&result, &outpos, &size, *fmt);\n } else {\n /*\n * Default variable settings\n */\n adjust = RIGHT;\n alternate_form = print_sign = print_blank = NO;\n pad_char = ' ';\n prefix_char = NUL;\n\n fmt++;\n\n /*\n * Try to avoid checking for flags, width or precision\n */\n if (isascii((int)*fmt) && !islower((int)*fmt)) {\n /*\n * Recognize flags: -, #, BLANK, +\n */\n for (;; fmt++) {\n if (*fmt == '-')\n adjust = LEFT;\n else if (*fmt == '+')\n print_sign = YES;\n else if (*fmt == '#')\n alternate_form = YES;\n else if (*fmt == ' ')\n print_blank = YES;\n else if (*fmt == '0')\n pad_char = '0';\n else\n break;\n }\n\n /*\n * Check if a width was specified\n */\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, min_width);\n adjust_width = YES;\n } else if (*fmt == '*') {\n min_width = va_arg(ap, int);\n fmt++;\n adjust_width = YES;\n if (min_width < 0) {\n adjust = LEFT;\n min_width = -min_width;\n }\n } else\n adjust_width = NO;\n\n /*\n * Check if a precision was specified\n *\n * XXX: an unreasonable amount of precision may be specified\n * resulting in overflow of num_buf. Currently we\n * ignore this possibility.\n */\n if (*fmt == '.') {\n adjust_precision = YES;\n fmt++;\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, precision);\n } else if (*fmt == '*') {\n precision = va_arg(ap, int);\n fmt++;\n if (precision < 0)\n precision = 0;\n } else\n precision = 0;\n } else\n adjust_precision = NO;\n } else\n adjust_precision = adjust_width = NO;\n\n /*\n * Modifier check\n */\n switch (*fmt) {\n case 'L':\n fmt++;\n modifier = LM_LONG_DOUBLE;\n break;\n case 'I':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == '6' && *(fmt+1) == '4') {\n fmt += 2;\n modifier = LM_LONG_LONG;\n } else\n#endif\n if (*fmt == '3' && *(fmt+1) == '2') {\n fmt += 2;\n modifier = LM_LONG;\n } else {\n#ifdef _WIN64\n modifier = LM_LONG_LONG;\n#else\n modifier = LM_LONG;\n#endif\n }\n break;\n case 'l':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == 'l') {\n fmt++;\n modifier = LM_LONG_LONG;\n } else\n#endif\n modifier = LM_LONG;\n break;\n case 'z':\n fmt++;\n modifier = LM_SIZE_T;\n break;\n case 'j':\n fmt++;\n#if SIZEOF_INTMAX_T\n modifier = LM_INTMAX_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 't':\n fmt++;\n#if SIZEOF_PTRDIFF_T\n modifier = LM_PTRDIFF_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 'h':\n fmt++;\n if (*fmt == 'h') {\n fmt++;\n }\n /* these are promoted to int, so no break */\n default:\n modifier = LM_STD;\n break;\n }\n\n /*\n * Argument extraction and printing.\n * First we determine the argument type.\n * Then, we convert the argument to a string.\n * On exit from the switch, s points to the string that\n * must be printed, s_len has the length of the string\n * The precision requirements, if any, are reflected in s_len.\n *\n * NOTE: pad_char may be set to '0' because of the 0 flag.\n * It is reset to ' ' by non-numeric formats\n */\n switch (*fmt) {\n case 'u':\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n i_num = (wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n /*\n * The rest also applies to other integer formats, so fall\n * into that case.\n */\n case 'd':\n case 'i':\n /*\n * Get the arg if we haven't already.\n */\n if ((*fmt) != 'u') {\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, long int);\n break;\n case LM_SIZE_T:\n#if SIZEOF_SSIZE_T\n i_num = (wide_int) va_arg(ap, ssize_t);\n#else\n i_num = (wide_int) va_arg(ap, size_t);\n#endif\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, intmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n }\n s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n\n if (*fmt != 'u') {\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'o':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 3, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && *s != '0') {\n *--s = '0';\n s_len++;\n }\n break;\n\n\n case 'x':\n case 'X':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 4, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && i_num != 0) {\n *--s = *fmt; /* 'x' or 'X' */\n *--s = '0';\n s_len += 2;\n }\n break;\n\n\n case 's':\n case 'v':\n s = va_arg(ap, char *);\n if (s != nullptr) {\n s_len = strlen(s);\n if (adjust_precision && precision < s_len)\n s_len = precision;\n } else {\n s = const_cast(s_null);\n s_len = S_NULL_LEN;\n }\n pad_char = ' ';\n break;\n\n\n case 'f':\n case 'F':\n case 'e':\n case 'E':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"nan\");\n s_len = 3;\n } else if (std::isinf(fp_num)) {\n s = const_cast(\"inf\");\n s_len = 3;\n } else {\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,\n (adjust_precision == NO) ? FLOAT_DIGITS : precision,\n (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',\n &is_negative, &num_buf[1], &s_len);\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'g':\n case 'k':\n case 'G':\n case 'H':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"NAN\");\n s_len = 3;\n break;\n } else if (std::isinf(fp_num)) {\n if (fp_num > 0) {\n s = const_cast(\"INF\");\n s_len = 3;\n } else {\n s = const_cast(\"-INF\");\n s_len = 4;\n }\n break;\n }\n\n if (adjust_precision == NO)\n precision = FLOAT_DIGITS;\n else if (precision == 0)\n precision = 1;\n /*\n * * We use &num_buf[ 1 ], so that we have room for the sign\n */\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_gcvt(fp_num, precision,\n (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT,\n (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);\n if (*s == '-')\n prefix_char = *s++;\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n\n s_len = strlen(s);\n\n if (alternate_form && (q = strchr(s, '.')) == nullptr)\n s[s_len++] = '.';\n break;\n\n\n case 'c':\n char_buf[0] = (char) (va_arg(ap, int));\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case '%':\n char_buf[0] = '%';\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case 'n':\n *(va_arg(ap, int *)) = outpos;\n goto skip_output;\n\n /*\n * Always extract the argument as a \"char *\" pointer. We\n * should be using \"void *\" but there are still machines\n * that don't understand it.\n * If the pointer size is equal to the size of an unsigned\n * integer we convert the pointer to a hex number, otherwise\n * we print \"%p\" to indicate that we don't handle \"%p\".\n */\n case 'p':\n if (sizeof(char *) <= sizeof(u_wide_int)) {\n ui_num = (u_wide_int)((size_t) va_arg(ap, char *));\n s = ap_php_conv_p2(ui_num, 4, 'x',\n &num_buf[NUM_BUF_SIZE], &s_len);\n if (ui_num != 0) {\n *--s = 'x';\n *--s = '0';\n s_len += 2;\n }\n } else {\n s = const_cast(\"%p\");\n s_len = 2;\n }\n pad_char = ' ';\n break;\n\n\n case NUL:\n /*\n * The last character of the format string was %.\n * We ignore it.\n */\n continue;\n\n\nfmt_error:\n throw Exception(\"Illegal length modifier specified '%c'\", *fmt);\n\n /*\n * The default case is for unrecognized %'s.\n * We print % to help the user identify what\n * option is not understood.\n * This is also useful in case the user wants to pass\n * the output of format_converter to another function\n * that understands some other % (like syslog).\n * Note that we can't point s inside fmt because the\n * unknown could be preceded by width etc.\n */\n default:\n char_buf[0] = '%';\n char_buf[1] = *fmt;\n s = char_buf;\n s_len = 2;\n pad_char = ' ';\n break;\n }\n\n if (prefix_char != NUL) {\n *--s = prefix_char;\n s_len++;\n }\n if (adjust_width && adjust == RIGHT && min_width > s_len) {\n if (pad_char == '0' && prefix_char != NUL) {\n appendchar(&result, &outpos, &size, *s);\n s++;\n s_len--;\n min_width--;\n }\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n /*\n * Print the (for now) non-null terminated string s.\n */\n appendsimplestring(&result, &outpos, &size, s, s_len);\n\n if (adjust_width && adjust == LEFT && min_width > s_len) {\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n }\nskip_output:\n fmt++;\n }\n /*\n * Add the terminating null here since it wasn't added incrementally above\n * once the whole string has been composed.\n */\n appendchar(&result, &outpos, &size, NUL);\n *outbuf = result;\n return outpos - 1;\n}", "func_hash": 185811107621985029487446489452053625714, "file_name": "zend-printf.cpp", "file_hash": 162953581506832129657446513284466352674, "cwe": ["CWE-190"], "cve": "CVE-2020-1918", "cve_desc": "In-memory file operations (ie: using fopen on a data URI) did not properly restrict negative seeking, allowing for the reading of memory prior to the in-memory buffer. This issue affects HHVM versions prior to 4.56.3, all versions between 4.57.0 and 4.80.1, all versions between 4.81.0 and 4.93.1, and versions 4.94.0, 4.95.0, 4.96.0, 4.97.0, 4.98.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1918"} {"idx": 195020, "project": "xbmc", "commit_id": "80c8138c09598e88b4ddb6dbb279fa193bbb3237", "project_url": "https://github.com/fuzzard/xbmc", "commit_url": "https://github.com/fuzzard/xbmc/commit/80c8138c09598e88b4ddb6dbb279fa193bbb3237", "commit_message": "[Playlist] dont use istream directly to a tinyxml structure\n\nTurn istream into a std::string to handle large buffers (#20305)", "target": 1, "func": "bool CPlayListASX::LoadData(std::istream& stream)\n{\n CLog::Log(LOGINFO, \"Parsing ASX\");\n\n if(stream.peek() == '[')\n {\n return LoadAsxIniInfo(stream);\n }\n else\n {\n CXBMCTinyXML xmlDoc;\n stream >> xmlDoc;\n\n if (xmlDoc.Error())\n {\n CLog::Log(LOGERROR, \"Unable to parse ASX info Error: {}\", xmlDoc.ErrorDesc());\n return false;\n }\n\n TiXmlElement *pRootElement = xmlDoc.RootElement();\n\n // lowercase every element\n TiXmlNode *pNode = pRootElement;\n TiXmlNode *pChild = NULL;\n std::string value;\n value = pNode->Value();\n StringUtils::ToLower(value);\n pNode->SetValue(value);\n while(pNode)\n {\n pChild = pNode->IterateChildren(pChild);\n if(pChild)\n {\n if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT)\n {\n value = pChild->Value();\n StringUtils::ToLower(value);\n pChild->SetValue(value);\n\n TiXmlAttribute* pAttr = pChild->ToElement()->FirstAttribute();\n while(pAttr)\n {\n value = pAttr->Name();\n StringUtils::ToLower(value);\n pAttr->SetName(value);\n pAttr = pAttr->Next();\n }\n }\n\n pNode = pChild;\n pChild = NULL;\n continue;\n }\n\n pChild = pNode;\n pNode = pNode->Parent();\n }\n std::string roottitle;\n TiXmlElement *pElement = pRootElement->FirstChildElement();\n while (pElement)\n {\n value = pElement->Value();\n if (value == \"title\" && !pElement->NoChildren())\n {\n roottitle = pElement->FirstChild()->ValueStr();\n }\n else if (value == \"entry\")\n {\n std::string title(roottitle);\n\n TiXmlElement *pRef = pElement->FirstChildElement(\"ref\");\n TiXmlElement *pTitle = pElement->FirstChildElement(\"title\");\n\n if(pTitle && !pTitle->NoChildren())\n title = pTitle->FirstChild()->ValueStr();\n\n while (pRef)\n { // multiple references may appear for one entry\n // duration may exist on this level too\n value = XMLUtils::GetAttribute(pRef, \"href\");\n if (!value.empty())\n {\n if(title.empty())\n title = value;\n\n CLog::Log(LOGINFO, \"Adding element {}, {}\", title, value);\n CFileItemPtr newItem(new CFileItem(title));\n newItem->SetPath(value);\n Add(newItem);\n }\n pRef = pRef->NextSiblingElement(\"ref\");\n }\n }\n else if (value == \"entryref\")\n {\n value = XMLUtils::GetAttribute(pElement, \"href\");\n if (!value.empty())\n { // found an entryref, let's try loading that url\n std::unique_ptr playlist(CPlayListFactory::Create(value));\n if (nullptr != playlist)\n if (playlist->Load(value))\n Add(*playlist);\n }\n }\n pElement = pElement->NextSiblingElement();\n }\n }\n\n return true;\n}", "func_hash": 129199039044343218280540573116603539534, "file_name": "PlayListPLS.cpp", "file_hash": 322007883831105198298453502916963773077, "cwe": ["CWE-120"], "cve": "CVE-2021-42917", "cve_desc": "Buffer overflow vulnerability in Kodi xbmc up to 19.0, allows attackers to cause a denial of service due to improper length of values passed to istream.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-42917"} {"idx": 219934, "project": "xbmc", "commit_id": "80c8138c09598e88b4ddb6dbb279fa193bbb3237", "project_url": "https://github.com/fuzzard/xbmc", "commit_url": "https://github.com/fuzzard/xbmc/commit/80c8138c09598e88b4ddb6dbb279fa193bbb3237", "commit_message": "[Playlist] dont use istream directly to a tinyxml structure\n\nTurn istream into a std::string to handle large buffers (#20305)", "target": 0, "func": "bool CPlayListASX::LoadData(std::istream& stream)\n{\n CLog::Log(LOGINFO, \"Parsing ASX\");\n\n if(stream.peek() == '[')\n {\n return LoadAsxIniInfo(stream);\n }\n else\n {\n std::string asxstream(std::istreambuf_iterator(stream), {});\n CXBMCTinyXML xmlDoc;\n xmlDoc.Parse(asxstream, TIXML_DEFAULT_ENCODING);\n\n if (xmlDoc.Error())\n {\n CLog::Log(LOGERROR, \"Unable to parse ASX info Error: {}\", xmlDoc.ErrorDesc());\n return false;\n }\n\n TiXmlElement *pRootElement = xmlDoc.RootElement();\n\n if (!pRootElement)\n return false;\n\n // lowercase every element\n TiXmlNode *pNode = pRootElement;\n TiXmlNode *pChild = NULL;\n std::string value;\n value = pNode->Value();\n StringUtils::ToLower(value);\n pNode->SetValue(value);\n while(pNode)\n {\n pChild = pNode->IterateChildren(pChild);\n if(pChild)\n {\n if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT)\n {\n value = pChild->Value();\n StringUtils::ToLower(value);\n pChild->SetValue(value);\n\n TiXmlAttribute* pAttr = pChild->ToElement()->FirstAttribute();\n while(pAttr)\n {\n value = pAttr->Name();\n StringUtils::ToLower(value);\n pAttr->SetName(value);\n pAttr = pAttr->Next();\n }\n }\n\n pNode = pChild;\n pChild = NULL;\n continue;\n }\n\n pChild = pNode;\n pNode = pNode->Parent();\n }\n std::string roottitle;\n TiXmlElement *pElement = pRootElement->FirstChildElement();\n while (pElement)\n {\n value = pElement->Value();\n if (value == \"title\" && !pElement->NoChildren())\n {\n roottitle = pElement->FirstChild()->ValueStr();\n }\n else if (value == \"entry\")\n {\n std::string title(roottitle);\n\n TiXmlElement *pRef = pElement->FirstChildElement(\"ref\");\n TiXmlElement *pTitle = pElement->FirstChildElement(\"title\");\n\n if(pTitle && !pTitle->NoChildren())\n title = pTitle->FirstChild()->ValueStr();\n\n while (pRef)\n { // multiple references may appear for one entry\n // duration may exist on this level too\n value = XMLUtils::GetAttribute(pRef, \"href\");\n if (!value.empty())\n {\n if(title.empty())\n title = value;\n\n CLog::Log(LOGINFO, \"Adding element {}, {}\", title, value);\n CFileItemPtr newItem(new CFileItem(title));\n newItem->SetPath(value);\n Add(newItem);\n }\n pRef = pRef->NextSiblingElement(\"ref\");\n }\n }\n else if (value == \"entryref\")\n {\n value = XMLUtils::GetAttribute(pElement, \"href\");\n if (!value.empty())\n { // found an entryref, let's try loading that url\n std::unique_ptr playlist(CPlayListFactory::Create(value));\n if (nullptr != playlist)\n if (playlist->Load(value))\n Add(*playlist);\n }\n }\n pElement = pElement->NextSiblingElement();\n }\n }\n\n return true;\n}", "func_hash": 334668239104120694213279500883580298304, "file_name": "PlayListPLS.cpp", "file_hash": 206557608263131641055685559774149729334, "cwe": ["CWE-120"], "cve": "CVE-2021-42917", "cve_desc": "Buffer overflow vulnerability in Kodi xbmc up to 19.0, allows attackers to cause a denial of service due to improper length of values passed to istream.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-42917"} {"idx": 195042, "project": "tensorflow", "commit_id": "6c0b2b70eeee588591680f5b7d5d38175fd7cdf6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/6c0b2b70eeee588591680f5b7d5d38175fd7cdf6", "commit_message": "[lite] add validation check for sparse fully connected\n\nPiperOrigin-RevId: 417629354\nChange-Id: If96171c4bd4f5fdb01d6368d6deab19d1c9beca7", "target": 1, "func": "TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node,\n TfLiteFullyConnectedParams* params, OpData* data,\n const TfLiteTensor* input, const TfLiteTensor* filter,\n const TfLiteTensor* bias, TfLiteTensor* output) {\n float output_activation_min, output_activation_max;\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n if (kernel_type == kReference) {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n reference_ops::FullyConnectedSparseWeight(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output));\n } else {\n reference_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output));\n }\n } else if (kernel_type == kLegacyPie) {\n return EvalPie(context, node, params, data, input, filter, bias, output);\n } else {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n if (!SupportedSparsityFormat(sparsity)) {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n\n if (sparsity.dim_metadata_size == kDimMetadataSizeRandomSparse) {\n // Random sparse.\n optimized_ops::FullyConnectedSparseWeight(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output));\n } else if (sparsity.dim_metadata_size == kDimMetadataSizeBlockSparse &&\n sparsity.dim_metadata[2].dense_size == 4) {\n // Block sparse with block size of 1x4.\n optimized_ops::FullyConnectedSparseWeight1x4(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n } else {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n\n } else {\n op_params.lhs_cacheable = IsConstantTensor(filter);\n op_params.rhs_cacheable = IsConstantTensor(input);\n optimized_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n }\n }\n\n return kTfLiteOk;\n}", "func_hash": 62355110582225554577873492287231441253, "file_name": "fully_connected.cc", "file_hash": 336723537786498894160827433697879115254, "cwe": ["CWE-787"], "cve": "CVE-2022-23561", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause a write outside of bounds of an array in TFLite. In fact, the attacker can override the linked list used by the memory allocator. This can be leveraged for an arbitrary write primitive under certain conditions. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23561"} {"idx": 220473, "project": "tensorflow", "commit_id": "6c0b2b70eeee588591680f5b7d5d38175fd7cdf6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/6c0b2b70eeee588591680f5b7d5d38175fd7cdf6", "commit_message": "[lite] add validation check for sparse fully connected\n\nPiperOrigin-RevId: 417629354\nChange-Id: If96171c4bd4f5fdb01d6368d6deab19d1c9beca7", "target": 0, "func": "TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node,\n TfLiteFullyConnectedParams* params, OpData* data,\n const TfLiteTensor* input, const TfLiteTensor* filter,\n const TfLiteTensor* bias, TfLiteTensor* output) {\n float output_activation_min, output_activation_max;\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n if (kernel_type == kReference) {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n reference_ops::FullyConnectedSparseWeight(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output));\n } else {\n reference_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output));\n }\n } else if (kernel_type == kLegacyPie) {\n return EvalPie(context, node, params, data, input, filter, bias, output);\n } else {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n if (!SupportedSparsityFormat(sparsity)) {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n const auto& input_shape = GetTensorShape(input);\n const auto& filter_shape = GetTensorShape(filter);\n const auto& output_shape = GetTensorShape(output);\n const auto& bias_shape = GetTensorShape(bias);\n if (!VerifySparsity(filter_shape, input_shape, output_shape, &sparsity)) {\n TF_LITE_KERNEL_LOG(context, \"Invalid sparse fully-connected format.\");\n return kTfLiteError;\n }\n\n if (sparsity.dim_metadata_size == kDimMetadataSizeRandomSparse) {\n // Random sparse.\n optimized_ops::FullyConnectedSparseWeight(\n sparsity, op_params, // Disable formatting\n input_shape, GetTensorData(input), // Disable formatting\n filter_shape, GetTensorData(filter), // Disable formatting\n bias_shape, GetTensorData(bias), // Disable formatting\n output_shape, GetTensorData(output));\n } else if (sparsity.dim_metadata_size == kDimMetadataSizeBlockSparse &&\n sparsity.dim_metadata[2].dense_size == 4) {\n // Block sparse with block size of 1x4.\n optimized_ops::FullyConnectedSparseWeight1x4(\n sparsity, op_params, // Disable formatting\n input_shape, GetTensorData(input), // Disable formatting\n filter_shape, GetTensorData(filter), // Disable formatting\n bias_shape, GetTensorData(bias), // Disable formatting\n output_shape, GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n } else {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n\n } else {\n op_params.lhs_cacheable = IsConstantTensor(filter);\n op_params.rhs_cacheable = IsConstantTensor(input);\n optimized_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n }\n }\n\n return kTfLiteOk;\n}", "func_hash": 286806067344740060941179911254835555382, "file_name": "fully_connected.cc", "file_hash": 95000589894742826497262957859775961687, "cwe": ["CWE-787"], "cve": "CVE-2022-23561", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause a write outside of bounds of an array in TFLite. In fact, the attacker can override the linked list used by the memory allocator. This can be leveraged for an arbitrary write primitive under certain conditions. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23561"} {"idx": 195057, "project": "keepkey-firmware", "commit_id": "e49d45594002d4d3fbc1f03488e6dfc0a0a65836", "project_url": "https://github.com/keepkey/keepkey-firmware", "commit_url": "https://github.com/keepkey/keepkey-firmware/commit/e49d45594002d4d3fbc1f03488e6dfc0a0a65836", "commit_message": "710 merge", "target": 1, "func": "uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg,\n char *buffer) {\n // Swap data begins 164 chars into data buffer:\n // offset = deposit function hash + address + address + uint256\n uint16_t offset = 4 + (5 * 32);\n int16_t len = msg->data_length - offset;\n if (msg->has_data_length && len > 0) {\n memcpy(buffer, msg->data_initial_chunk.bytes + offset, len);\n // String length must be < 255 characters\n return len < 256 ? (uint8_t)len : 0;\n }\n return 0;\n}", "func_hash": 62617281911012576687050684518892834758, "file_name": "ethereum.c", "file_hash": 270938923042963122350351912532736990905, "cwe": ["CWE-787"], "cve": "CVE-2021-31616", "cve_desc": "Insufficient length checks in the ShapeShift KeepKey hardware wallet firmware before 7.1.0 allow a stack buffer overflow via crafted messages. The overflow in ethereum_extractThorchainSwapData() in ethereum.c can circumvent stack protections and lead to code execution. The vulnerable interface is reachable remotely over WebUSB.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31616"} {"idx": 220894, "project": "keepkey-firmware", "commit_id": "e49d45594002d4d3fbc1f03488e6dfc0a0a65836", "project_url": "https://github.com/keepkey/keepkey-firmware", "commit_url": "https://github.com/keepkey/keepkey-firmware/commit/e49d45594002d4d3fbc1f03488e6dfc0a0a65836", "commit_message": "710 merge", "target": 0, "func": "uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg,\n char *buffer) {\n // Swap data begins 164 chars into data buffer:\n // offset = deposit function hash + address + address + uint256\n uint16_t offset = 4 + (5 * 32);\n int16_t len = msg->data_length - offset;\n if (msg->has_data_length && len > 0 && len < 256) {\n memcpy(buffer, msg->data_initial_chunk.bytes + offset, len);\n // String length must be < 255 characters\n return (uint8_t)len;\n }\n return 0;\n}", "func_hash": 223892848176218771120940238183522305923, "file_name": "ethereum.c", "file_hash": 63575726515717625139102233637299529983, "cwe": ["CWE-787"], "cve": "CVE-2021-31616", "cve_desc": "Insufficient length checks in the ShapeShift KeepKey hardware wallet firmware before 7.1.0 allow a stack buffer overflow via crafted messages. The overflow in ethereum_extractThorchainSwapData() in ethereum.c can circumvent stack protections and lead to code execution. The vulnerable interface is reachable remotely over WebUSB.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31616"} {"idx": 195084, "project": "faad2", "commit_id": "1b71a6ba963d131375f5e489b3b25e36f19f3f24", "project_url": "https://github.com/knik0/faad2", "commit_url": "https://github.com/knik0/faad2/commit/1b71a6ba963d131375f5e489b3b25e36f19f3f24", "commit_message": "fix heap-buffer-overflow in mp4read.c\n\nThis originated from an integer overflow: If mp4config.frame.ents\nwould be read-in with a value of (uint32t)(-1), it would overflow to 0\nin the size calculation for the allocation in the next line. The\nmalloc() function would then successfully return a pointer to a memory\nregion of size 0, which will cause a segfault when written to.\n\nFixes #57.", "target": 1, "func": "static int stszin(int size)\n{\n int cnt;\n uint32_t ofs;\n\n // version/flags\n u32in();\n // Sample size\n u32in();\n // Number of entries\n mp4config.frame.ents = u32in();\n // fixme: check atom size\n mp4config.frame.data = malloc(sizeof(*mp4config.frame.data)\n * (mp4config.frame.ents + 1));\n\n if (!mp4config.frame.data)\n return ERR_FAIL;\n\n ofs = 0;\n mp4config.frame.data[0] = ofs;\n for (cnt = 0; cnt < mp4config.frame.ents; cnt++)\n {\n uint32_t fsize = u32in();\n\n ofs += fsize;\n if (mp4config.frame.maxsize < fsize)\n mp4config.frame.maxsize = fsize;\n\n mp4config.frame.data[cnt + 1] = ofs;\n\n if (ofs < mp4config.frame.data[cnt])\n return ERR_FAIL;\n }\n\n return size;\n}", "func_hash": 182699574576129672282989775834999797945, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-32272", "cve_desc": "An issue was discovered in faad2 before 2.10.0. A heap-buffer-overflow exists in the function stszin located in mp4read.c. It allows an attacker to cause Code Execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32272"} {"idx": 221432, "project": "faad2", "commit_id": "1b71a6ba963d131375f5e489b3b25e36f19f3f24", "project_url": "https://github.com/knik0/faad2", "commit_url": "https://github.com/knik0/faad2/commit/1b71a6ba963d131375f5e489b3b25e36f19f3f24", "commit_message": "fix heap-buffer-overflow in mp4read.c\n\nThis originated from an integer overflow: If mp4config.frame.ents\nwould be read-in with a value of (uint32t)(-1), it would overflow to 0\nin the size calculation for the allocation in the next line. The\nmalloc() function would then successfully return a pointer to a memory\nregion of size 0, which will cause a segfault when written to.\n\nFixes #57.", "target": 0, "func": "static int stszin(int size)\n{\n int cnt;\n uint32_t ofs;\n\n // version/flags\n u32in();\n // Sample size\n u32in();\n // Number of entries\n mp4config.frame.ents = u32in();\n\n if (!(mp4config.frame.ents + 1))\n return ERR_FAIL;\n\n mp4config.frame.data = malloc(sizeof(*mp4config.frame.data)\n * (mp4config.frame.ents + 1));\n\n if (!mp4config.frame.data)\n return ERR_FAIL;\n\n ofs = 0;\n mp4config.frame.data[0] = ofs;\n for (cnt = 0; cnt < mp4config.frame.ents; cnt++)\n {\n uint32_t fsize = u32in();\n\n ofs += fsize;\n if (mp4config.frame.maxsize < fsize)\n mp4config.frame.maxsize = fsize;\n\n mp4config.frame.data[cnt + 1] = ofs;\n\n if (ofs < mp4config.frame.data[cnt])\n return ERR_FAIL;\n }\n\n return size;\n}", "func_hash": 307367588042083734156458028287764725262, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-32272", "cve_desc": "An issue was discovered in faad2 before 2.10.0. A heap-buffer-overflow exists in the function stszin located in mp4read.c. It allows an attacker to cause Code Execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32272"} {"idx": 195217, "project": "mruby", "commit_id": "28ccc664e5dcd3f9d55173e9afde77c4705a9ab6", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/28ccc664e5dcd3f9d55173e9afde77c4705a9ab6", "commit_message": "proc.c: should not reference `irep` when copying failed.\n\nIt may cause broken reference count numbers.", "target": 1, "func": "mrb_proc_copy(mrb_state *mrb, struct RProc *a, struct RProc *b)\n{\n if (a->body.irep) {\n /* already initialized proc */\n return;\n }\n a->flags = b->flags;\n a->body = b->body;\n a->upper = b->upper;\n if (!MRB_PROC_CFUNC_P(a) && a->body.irep) {\n mrb_irep_incref(mrb, (mrb_irep*)a->body.irep);\n }\n a->e.env = b->e.env;\n /* a->e.target_class = a->e.target_class; */\n}", "func_hash": 141188842630049204876287625075629935243, "file_name": "proc.c", "file_hash": 25312707254065398661522821980007315136, "cwe": ["CWE-122"], "cve": "CVE-2022-0080", "cve_desc": "mruby is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0080"} {"idx": 222586, "project": "mruby", "commit_id": "28ccc664e5dcd3f9d55173e9afde77c4705a9ab6", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/28ccc664e5dcd3f9d55173e9afde77c4705a9ab6", "commit_message": "proc.c: should not reference `irep` when copying failed.\n\nIt may cause broken reference count numbers.", "target": 0, "func": "mrb_proc_copy(mrb_state *mrb, struct RProc *a, struct RProc *b)\n{\n if (a->body.irep) {\n /* already initialized proc */\n return;\n }\n if (!MRB_PROC_CFUNC_P(b) && b->body.irep) {\n mrb_irep_incref(mrb, (mrb_irep*)b->body.irep);\n }\n a->flags = b->flags;\n a->body = b->body;\n a->upper = b->upper;\n a->e.env = b->e.env;\n /* a->e.target_class = a->e.target_class; */\n}", "func_hash": 280395994762246342247524448151502050394, "file_name": "proc.c", "file_hash": 167137142806523889442559298976618300314, "cwe": ["CWE-122"], "cve": "CVE-2022-0080", "cve_desc": "mruby is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0080"} {"idx": 195244, "project": "tensorflow", "commit_id": "c2426bba00a01de6913738df8fa78e0215fcce02", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c2426bba00a01de6913738df8fa78e0215fcce02", "commit_message": "Use `PartialTensorShape` instead of `TensorShape`.\n\n`TensorShape` constructor throws a CHECK-fail if shape is partial/overflows which the other doesn't. We are only determining the number of elements in the shape and partial shape should be used as it returns negative number when needed.\n\nPiperOrigin-RevId: 409205384\nChange-Id: Ia56542ff9ec758f2c9ffc7e4dcc9fa7eecd86e7b", "target": 1, "func": "int64_t TensorByteSize(const TensorProto& t) {\n // num_elements returns -1 if shape is not fully defined.\n int64_t num_elems = TensorShape(t.tensor_shape()).num_elements();\n return num_elems < 0 ? -1 : num_elems * DataTypeSize(t.dtype());\n}", "func_hash": 4480814010538664140540142741999865506, "file_name": "attr_value_util.cc", "file_hash": 86426759929974438313973525221473193689, "cwe": ["CWE-617"], "cve": "CVE-2022-23582", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a denial of service by altering a `SavedModel` such that `TensorByteSize` would trigger `CHECK` failures. `TensorShape` constructor throws a `CHECK`-fail if shape is partial or has a number of elements that would overflow the size of an `int`. The `PartialTensorShape` constructor instead does not cause a `CHECK`-abort if the shape is partial, which is exactly what this function needs to be able to return `-1`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23582"} {"idx": 223149, "project": "tensorflow", "commit_id": "c2426bba00a01de6913738df8fa78e0215fcce02", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c2426bba00a01de6913738df8fa78e0215fcce02", "commit_message": "Use `PartialTensorShape` instead of `TensorShape`.\n\n`TensorShape` constructor throws a CHECK-fail if shape is partial/overflows which the other doesn't. We are only determining the number of elements in the shape and partial shape should be used as it returns negative number when needed.\n\nPiperOrigin-RevId: 409205384\nChange-Id: Ia56542ff9ec758f2c9ffc7e4dcc9fa7eecd86e7b", "target": 0, "func": "int64_t TensorByteSize(const TensorProto& t) {\n // num_elements returns -1 if shape is not fully defined.\n int64_t num_elems = PartialTensorShape(t.tensor_shape()).num_elements();\n return num_elems < 0 ? -1 : num_elems * DataTypeSize(t.dtype());\n}", "func_hash": 61315629866685338581992436382236559668, "file_name": "attr_value_util.cc", "file_hash": 194187196296125870174960156454135885035, "cwe": ["CWE-617"], "cve": "CVE-2022-23582", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a denial of service by altering a `SavedModel` such that `TensorByteSize` would trigger `CHECK` failures. `TensorShape` constructor throws a `CHECK`-fail if shape is partial or has a number of elements that would overflow the size of an `int`. The `PartialTensorShape` constructor instead does not cause a `CHECK`-abort if the shape is partial, which is exactly what this function needs to be able to return `-1`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23582"} {"idx": 195247, "project": "tensorflow", "commit_id": "e5b0eec199c2d03de54fd6a7fd9275692218e2bc", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e5b0eec199c2d03de54fd6a7fd9275692218e2bc", "commit_message": "[lite] Add validation check for dilation height/width to be positive integers.\n\nPiperOrigin-RevId: 416429178\nChange-Id: If7cdcddca54486434d9b2f06e7e2b401d7c3ee25", "target": 1, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n bool has_bias = NumInputs(node) == 3;\n\n TF_LITE_ENSURE(context, has_bias || NumInputs(node) == 2);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* filter;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kFilterTensor, &filter));\n const TfLiteTensor* bias = nullptr;\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 4);\n\n const TfLiteType data_type = input->type;\n\n const TfLiteType filter_type = filter->type;\n const bool is_hybrid =\n data_type == kTfLiteFloat32 && filter_type == kTfLiteInt8;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt16);\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, data_type);\n if (!is_hybrid) {\n TF_LITE_ENSURE(context,\n filter->type == data_type || data_type == kTfLiteInt16);\n }\n\n if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n // Filter in DepthwiseConv is expected to be [1, H, W, O].\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 0), 1);\n\n if (has_bias) {\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBiasTensor, &bias));\n if (data_type == kTfLiteUInt8 || data_type == kTfLiteInt8) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt64);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, data_type);\n }\n TF_LITE_ENSURE_EQ(context, NumDimensions(bias), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 3),\n SizeOfDimension(bias, 0));\n }\n\n int channels_out = SizeOfDimension(filter, 3);\n int width = SizeOfDimension(input, 2);\n int height = SizeOfDimension(input, 1);\n int filter_width = SizeOfDimension(filter, 2);\n int filter_height = SizeOfDimension(filter, 1);\n int batches = SizeOfDimension(input, 0);\n\n // Matching GetWindowedOutputSize in TensorFlow.\n auto padding = params->padding;\n int out_width, out_height;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width,\n params->dilation_height_factor, params->dilation_width_factor, height,\n width, filter_height, filter_width, padding, &out_height, &out_width);\n\n // Note that quantized inference requires that all tensors have their\n // parameters set. This is usually done during quantized training or\n // calibration.\n if (data_type != kTfLiteFloat32) {\n TF_LITE_ENSURE_EQ(context, filter->quantization.type,\n kTfLiteAffineQuantization);\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE(context, (affine_quantization->scale->size == 1 ||\n affine_quantization->scale->size == channels_out));\n\n data->per_channel_output_multiplier.resize(channels_out);\n data->per_channel_output_shift.resize(channels_out);\n TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(\n context, input, filter, bias, output, params->activation,\n &data->output_multiplier, &data->output_shift,\n &data->output_activation_min, &data->output_activation_max,\n data->per_channel_output_multiplier.data(),\n data->per_channel_output_shift.data(), channels_out));\n }\n\n if (is_hybrid) {\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE_EQ(\n context, affine_quantization->scale->size,\n filter->dims->data[affine_quantization->quantized_dimension]);\n\n int temporaries_count = 0;\n data->input_quantized_index = temporaries_count;\n if (data->input_quantized_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_quantized_id));\n }\n ++temporaries_count;\n data->scaling_factors_index = temporaries_count;\n if (data->scaling_factors_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->scaling_factors_id));\n }\n ++temporaries_count;\n data->input_offset_index = temporaries_count;\n if (data->input_offset_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_offset_id));\n }\n ++temporaries_count;\n\n TfLiteIntArrayFree(node->temporaries);\n node->temporaries = TfLiteIntArrayCreate(temporaries_count);\n\n node->temporaries->data[data->input_quantized_index] =\n data->input_quantized_id;\n TfLiteTensor* input_quantized;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->input_quantized_index,\n &input_quantized));\n input_quantized->type = kTfLiteInt8;\n input_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n input_quantized_size));\n }\n node->temporaries->data[data->scaling_factors_index] =\n data->scaling_factors_id;\n TfLiteTensor* scaling_factors;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scaling_factors_index,\n &scaling_factors));\n scaling_factors->type = kTfLiteFloat32;\n scaling_factors->allocation_type = kTfLiteArenaRw;\n const int batch_size = SizeOfDimension(input, 0);\n int scaling_dims[1] = {batch_size};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n scaling_factors_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n scaling_factors_size));\n }\n node->temporaries->data[data->input_offset_index] = data->input_offset_id;\n TfLiteTensor* input_offsets;\n TF_LITE_ENSURE_OK(context,\n GetTemporarySafe(context, node, data->input_offset_index,\n &input_offsets));\n input_offsets->type = kTfLiteInt32;\n input_offsets->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1, scaling_dims)) {\n TfLiteIntArray* input_offsets_size = TfLiteIntArrayCreate(1);\n input_offsets_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_offsets,\n input_offsets_size));\n }\n }\n\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(4);\n outputSize->data[0] = batches;\n outputSize->data[1] = out_height;\n outputSize->data[2] = out_width;\n outputSize->data[3] = channels_out;\n return context->ResizeTensor(context, output, outputSize);\n}", "func_hash": 158191376502861052790903162927100796429, "file_name": "depthwise_conv.cc", "file_hash": 254210893506480532293472494017662319300, "cwe": ["CWE-369"], "cve": "CVE-2022-21741", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. ### Impact An attacker can craft a TFLite model that would trigger a division by zero in the implementation of depthwise convolutions. The parameters of the convolution can be user controlled and are also used within a division operation to determine the size of the padding that needs to be added before applying the convolution. There is no check before this division that the divisor is strictly positive. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21741"} {"idx": 223174, "project": "tensorflow", "commit_id": "e5b0eec199c2d03de54fd6a7fd9275692218e2bc", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e5b0eec199c2d03de54fd6a7fd9275692218e2bc", "commit_message": "[lite] Add validation check for dilation height/width to be positive integers.\n\nPiperOrigin-RevId: 416429178\nChange-Id: If7cdcddca54486434d9b2f06e7e2b401d7c3ee25", "target": 0, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n bool has_bias = NumInputs(node) == 3;\n\n TF_LITE_ENSURE(context, has_bias || NumInputs(node) == 2);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* filter;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kFilterTensor, &filter));\n const TfLiteTensor* bias = nullptr;\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 4);\n TF_LITE_ENSURE(context, params->dilation_height_factor > 0);\n TF_LITE_ENSURE(context, params->dilation_width_factor > 0);\n\n const TfLiteType data_type = input->type;\n\n const TfLiteType filter_type = filter->type;\n const bool is_hybrid =\n data_type == kTfLiteFloat32 && filter_type == kTfLiteInt8;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt16);\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, data_type);\n if (!is_hybrid) {\n TF_LITE_ENSURE(context,\n filter->type == data_type || data_type == kTfLiteInt16);\n }\n\n if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n // Filter in DepthwiseConv is expected to be [1, H, W, O].\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 0), 1);\n\n if (has_bias) {\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBiasTensor, &bias));\n if (data_type == kTfLiteUInt8 || data_type == kTfLiteInt8) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt64);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, data_type);\n }\n TF_LITE_ENSURE_EQ(context, NumDimensions(bias), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 3),\n SizeOfDimension(bias, 0));\n }\n\n int channels_out = SizeOfDimension(filter, 3);\n int width = SizeOfDimension(input, 2);\n int height = SizeOfDimension(input, 1);\n int filter_width = SizeOfDimension(filter, 2);\n int filter_height = SizeOfDimension(filter, 1);\n int batches = SizeOfDimension(input, 0);\n\n // Matching GetWindowedOutputSize in TensorFlow.\n auto padding = params->padding;\n int out_width, out_height;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width,\n params->dilation_height_factor, params->dilation_width_factor, height,\n width, filter_height, filter_width, padding, &out_height, &out_width);\n\n // Note that quantized inference requires that all tensors have their\n // parameters set. This is usually done during quantized training or\n // calibration.\n if (data_type != kTfLiteFloat32) {\n TF_LITE_ENSURE_EQ(context, filter->quantization.type,\n kTfLiteAffineQuantization);\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE(context, (affine_quantization->scale->size == 1 ||\n affine_quantization->scale->size == channels_out));\n\n data->per_channel_output_multiplier.resize(channels_out);\n data->per_channel_output_shift.resize(channels_out);\n TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(\n context, input, filter, bias, output, params->activation,\n &data->output_multiplier, &data->output_shift,\n &data->output_activation_min, &data->output_activation_max,\n data->per_channel_output_multiplier.data(),\n data->per_channel_output_shift.data(), channels_out));\n }\n\n if (is_hybrid) {\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE_EQ(\n context, affine_quantization->scale->size,\n filter->dims->data[affine_quantization->quantized_dimension]);\n\n int temporaries_count = 0;\n data->input_quantized_index = temporaries_count;\n if (data->input_quantized_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_quantized_id));\n }\n ++temporaries_count;\n data->scaling_factors_index = temporaries_count;\n if (data->scaling_factors_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->scaling_factors_id));\n }\n ++temporaries_count;\n data->input_offset_index = temporaries_count;\n if (data->input_offset_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_offset_id));\n }\n ++temporaries_count;\n\n TfLiteIntArrayFree(node->temporaries);\n node->temporaries = TfLiteIntArrayCreate(temporaries_count);\n\n node->temporaries->data[data->input_quantized_index] =\n data->input_quantized_id;\n TfLiteTensor* input_quantized;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->input_quantized_index,\n &input_quantized));\n input_quantized->type = kTfLiteInt8;\n input_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n input_quantized_size));\n }\n node->temporaries->data[data->scaling_factors_index] =\n data->scaling_factors_id;\n TfLiteTensor* scaling_factors;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scaling_factors_index,\n &scaling_factors));\n scaling_factors->type = kTfLiteFloat32;\n scaling_factors->allocation_type = kTfLiteArenaRw;\n const int batch_size = SizeOfDimension(input, 0);\n int scaling_dims[1] = {batch_size};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n scaling_factors_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n scaling_factors_size));\n }\n node->temporaries->data[data->input_offset_index] = data->input_offset_id;\n TfLiteTensor* input_offsets;\n TF_LITE_ENSURE_OK(context,\n GetTemporarySafe(context, node, data->input_offset_index,\n &input_offsets));\n input_offsets->type = kTfLiteInt32;\n input_offsets->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1, scaling_dims)) {\n TfLiteIntArray* input_offsets_size = TfLiteIntArrayCreate(1);\n input_offsets_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_offsets,\n input_offsets_size));\n }\n }\n\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(4);\n outputSize->data[0] = batches;\n outputSize->data[1] = out_height;\n outputSize->data[2] = out_width;\n outputSize->data[3] = channels_out;\n return context->ResizeTensor(context, output, outputSize);\n}", "func_hash": 258070939506441084913023936149672540254, "file_name": "depthwise_conv.cc", "file_hash": 209199614449658424010907866620463852951, "cwe": ["CWE-369"], "cve": "CVE-2022-21741", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. ### Impact An attacker can craft a TFLite model that would trigger a division by zero in the implementation of depthwise convolutions. The parameters of the convolution can be user controlled and are also used within a division operation to determine the size of the padding that needs to be added before applying the convolution. There is no check before this division that the divisor is strictly positive. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21741"} {"idx": 195337, "project": "linux", "commit_id": "bcd0f93353326954817a4f9fa55ec57fb38acbb0", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/bcd0f93353326954817a4f9fa55ec57fb38acbb0", "commit_message": "phonet: refcount leak in pep_sock_accep\n\nsock_hold(sk) is invoked in pep_sock_accept(), but __sock_put(sk) is not\ninvoked in subsequent failure branches(pep_accept_conn() != 0).\n\nSigned-off-by: Hangyu Hua \nLink: https://lore.kernel.org/r/20211209082839.33985-1-hbh25y@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 1, "func": "static struct sock *pep_sock_accept(struct sock *sk, int flags, int *errp,\n\t\t\t\t bool kern)\n{\n\tstruct pep_sock *pn = pep_sk(sk), *newpn;\n\tstruct sock *newsk = NULL;\n\tstruct sk_buff *skb;\n\tstruct pnpipehdr *hdr;\n\tstruct sockaddr_pn dst, src;\n\tint err;\n\tu16 peer_type;\n\tu8 pipe_handle, enabled, n_sb;\n\tu8 aligned = 0;\n\n\tskb = skb_recv_datagram(sk, 0, flags & O_NONBLOCK, errp);\n\tif (!skb)\n\t\treturn NULL;\n\n\tlock_sock(sk);\n\tif (sk->sk_state != TCP_LISTEN) {\n\t\terr = -EINVAL;\n\t\tgoto drop;\n\t}\n\tsk_acceptq_removed(sk);\n\n\terr = -EPROTO;\n\tif (!pskb_may_pull(skb, sizeof(*hdr) + 4))\n\t\tgoto drop;\n\n\thdr = pnp_hdr(skb);\n\tpipe_handle = hdr->pipe_handle;\n\tswitch (hdr->state_after_connect) {\n\tcase PN_PIPE_DISABLE:\n\t\tenabled = 0;\n\t\tbreak;\n\tcase PN_PIPE_ENABLE:\n\t\tenabled = 1;\n\t\tbreak;\n\tdefault:\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_INVALID_PARAM,\n\t\t\t\tGFP_KERNEL);\n\t\tgoto drop;\n\t}\n\tpeer_type = hdr->other_pep_type << 8;\n\n\t/* Parse sub-blocks (options) */\n\tn_sb = hdr->data[3];\n\twhile (n_sb > 0) {\n\t\tu8 type, buf[1], len = sizeof(buf);\n\t\tconst u8 *data = pep_get_sb(skb, &type, &len, buf);\n\n\t\tif (data == NULL)\n\t\t\tgoto drop;\n\t\tswitch (type) {\n\t\tcase PN_PIPE_SB_CONNECT_REQ_PEP_SUB_TYPE:\n\t\t\tif (len < 1)\n\t\t\t\tgoto drop;\n\t\t\tpeer_type = (peer_type & 0xff00) | data[0];\n\t\t\tbreak;\n\t\tcase PN_PIPE_SB_ALIGNED_DATA:\n\t\t\taligned = data[0] != 0;\n\t\t\tbreak;\n\t\t}\n\t\tn_sb--;\n\t}\n\n\t/* Check for duplicate pipe handle */\n\tnewsk = pep_find_pipe(&pn->hlist, &dst, pipe_handle);\n\tif (unlikely(newsk)) {\n\t\t__sock_put(newsk);\n\t\tnewsk = NULL;\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_PEP_IN_USE, GFP_KERNEL);\n\t\tgoto drop;\n\t}\n\n\t/* Create a new to-be-accepted sock */\n\tnewsk = sk_alloc(sock_net(sk), PF_PHONET, GFP_KERNEL, sk->sk_prot,\n\t\t\t kern);\n\tif (!newsk) {\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_OVERLOAD, GFP_KERNEL);\n\t\terr = -ENOBUFS;\n\t\tgoto drop;\n\t}\n\n\tsock_init_data(NULL, newsk);\n\tnewsk->sk_state = TCP_SYN_RECV;\n\tnewsk->sk_backlog_rcv = pipe_do_rcv;\n\tnewsk->sk_protocol = sk->sk_protocol;\n\tnewsk->sk_destruct = pipe_destruct;\n\n\tnewpn = pep_sk(newsk);\n\tpn_skb_get_dst_sockaddr(skb, &dst);\n\tpn_skb_get_src_sockaddr(skb, &src);\n\tnewpn->pn_sk.sobject = pn_sockaddr_get_object(&dst);\n\tnewpn->pn_sk.dobject = pn_sockaddr_get_object(&src);\n\tnewpn->pn_sk.resource = pn_sockaddr_get_resource(&dst);\n\tsock_hold(sk);\n\tnewpn->listener = sk;\n\tskb_queue_head_init(&newpn->ctrlreq_queue);\n\tnewpn->pipe_handle = pipe_handle;\n\tatomic_set(&newpn->tx_credits, 0);\n\tnewpn->ifindex = 0;\n\tnewpn->peer_type = peer_type;\n\tnewpn->rx_credits = 0;\n\tnewpn->rx_fc = newpn->tx_fc = PN_LEGACY_FLOW_CONTROL;\n\tnewpn->init_enable = enabled;\n\tnewpn->aligned = aligned;\n\n\terr = pep_accept_conn(newsk, skb);\n\tif (err) {\n\t\tsock_put(newsk);\n\t\tnewsk = NULL;\n\t\tgoto drop;\n\t}\n\tsk_add_node(newsk, &pn->hlist);\ndrop:\n\trelease_sock(sk);\n\tkfree_skb(skb);\n\t*errp = err;\n\treturn newsk;\n}", "func_hash": 98147170872893789319599497635563701391, "file_name": "pep.c", "file_hash": 271547007658605746827847008815001385986, "cwe": ["CWE-200"], "cve": "CVE-2021-45095", "cve_desc": "pep_sock_accept in net/phonet/pep.c in the Linux kernel through 5.15.8 has a refcount leak.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-45095"} {"idx": 224826, "project": "linux", "commit_id": "bcd0f93353326954817a4f9fa55ec57fb38acbb0", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/bcd0f93353326954817a4f9fa55ec57fb38acbb0", "commit_message": "phonet: refcount leak in pep_sock_accep\n\nsock_hold(sk) is invoked in pep_sock_accept(), but __sock_put(sk) is not\ninvoked in subsequent failure branches(pep_accept_conn() != 0).\n\nSigned-off-by: Hangyu Hua \nLink: https://lore.kernel.org/r/20211209082839.33985-1-hbh25y@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 0, "func": "static struct sock *pep_sock_accept(struct sock *sk, int flags, int *errp,\n\t\t\t\t bool kern)\n{\n\tstruct pep_sock *pn = pep_sk(sk), *newpn;\n\tstruct sock *newsk = NULL;\n\tstruct sk_buff *skb;\n\tstruct pnpipehdr *hdr;\n\tstruct sockaddr_pn dst, src;\n\tint err;\n\tu16 peer_type;\n\tu8 pipe_handle, enabled, n_sb;\n\tu8 aligned = 0;\n\n\tskb = skb_recv_datagram(sk, 0, flags & O_NONBLOCK, errp);\n\tif (!skb)\n\t\treturn NULL;\n\n\tlock_sock(sk);\n\tif (sk->sk_state != TCP_LISTEN) {\n\t\terr = -EINVAL;\n\t\tgoto drop;\n\t}\n\tsk_acceptq_removed(sk);\n\n\terr = -EPROTO;\n\tif (!pskb_may_pull(skb, sizeof(*hdr) + 4))\n\t\tgoto drop;\n\n\thdr = pnp_hdr(skb);\n\tpipe_handle = hdr->pipe_handle;\n\tswitch (hdr->state_after_connect) {\n\tcase PN_PIPE_DISABLE:\n\t\tenabled = 0;\n\t\tbreak;\n\tcase PN_PIPE_ENABLE:\n\t\tenabled = 1;\n\t\tbreak;\n\tdefault:\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_INVALID_PARAM,\n\t\t\t\tGFP_KERNEL);\n\t\tgoto drop;\n\t}\n\tpeer_type = hdr->other_pep_type << 8;\n\n\t/* Parse sub-blocks (options) */\n\tn_sb = hdr->data[3];\n\twhile (n_sb > 0) {\n\t\tu8 type, buf[1], len = sizeof(buf);\n\t\tconst u8 *data = pep_get_sb(skb, &type, &len, buf);\n\n\t\tif (data == NULL)\n\t\t\tgoto drop;\n\t\tswitch (type) {\n\t\tcase PN_PIPE_SB_CONNECT_REQ_PEP_SUB_TYPE:\n\t\t\tif (len < 1)\n\t\t\t\tgoto drop;\n\t\t\tpeer_type = (peer_type & 0xff00) | data[0];\n\t\t\tbreak;\n\t\tcase PN_PIPE_SB_ALIGNED_DATA:\n\t\t\taligned = data[0] != 0;\n\t\t\tbreak;\n\t\t}\n\t\tn_sb--;\n\t}\n\n\t/* Check for duplicate pipe handle */\n\tnewsk = pep_find_pipe(&pn->hlist, &dst, pipe_handle);\n\tif (unlikely(newsk)) {\n\t\t__sock_put(newsk);\n\t\tnewsk = NULL;\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_PEP_IN_USE, GFP_KERNEL);\n\t\tgoto drop;\n\t}\n\n\t/* Create a new to-be-accepted sock */\n\tnewsk = sk_alloc(sock_net(sk), PF_PHONET, GFP_KERNEL, sk->sk_prot,\n\t\t\t kern);\n\tif (!newsk) {\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_OVERLOAD, GFP_KERNEL);\n\t\terr = -ENOBUFS;\n\t\tgoto drop;\n\t}\n\n\tsock_init_data(NULL, newsk);\n\tnewsk->sk_state = TCP_SYN_RECV;\n\tnewsk->sk_backlog_rcv = pipe_do_rcv;\n\tnewsk->sk_protocol = sk->sk_protocol;\n\tnewsk->sk_destruct = pipe_destruct;\n\n\tnewpn = pep_sk(newsk);\n\tpn_skb_get_dst_sockaddr(skb, &dst);\n\tpn_skb_get_src_sockaddr(skb, &src);\n\tnewpn->pn_sk.sobject = pn_sockaddr_get_object(&dst);\n\tnewpn->pn_sk.dobject = pn_sockaddr_get_object(&src);\n\tnewpn->pn_sk.resource = pn_sockaddr_get_resource(&dst);\n\tsock_hold(sk);\n\tnewpn->listener = sk;\n\tskb_queue_head_init(&newpn->ctrlreq_queue);\n\tnewpn->pipe_handle = pipe_handle;\n\tatomic_set(&newpn->tx_credits, 0);\n\tnewpn->ifindex = 0;\n\tnewpn->peer_type = peer_type;\n\tnewpn->rx_credits = 0;\n\tnewpn->rx_fc = newpn->tx_fc = PN_LEGACY_FLOW_CONTROL;\n\tnewpn->init_enable = enabled;\n\tnewpn->aligned = aligned;\n\n\terr = pep_accept_conn(newsk, skb);\n\tif (err) {\n\t\t__sock_put(sk);\n\t\tsock_put(newsk);\n\t\tnewsk = NULL;\n\t\tgoto drop;\n\t}\n\tsk_add_node(newsk, &pn->hlist);\ndrop:\n\trelease_sock(sk);\n\tkfree_skb(skb);\n\t*errp = err;\n\treturn newsk;\n}", "func_hash": 215701636968607266341616799278763335053, "file_name": "pep.c", "file_hash": 306429533673285594557101295584314100863, "cwe": ["CWE-200"], "cve": "CVE-2021-45095", "cve_desc": "pep_sock_accept in net/phonet/pep.c in the Linux kernel through 5.15.8 has a refcount leak.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-45095"} {"idx": 195345, "project": "gpac", "commit_id": "8e585e623b1d666b4ef736ed609264639cb27701", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/8e585e623b1d666b4ef736ed609264639cb27701", "commit_message": "fixed potential crash - cf #1406", "target": 1, "func": "GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box)\n{\n\tu32 type, uuid_type, hdr_size;\n\tu64 size, start, payload_start, end;\n\tchar uuid[16];\n\tGF_Err e;\n\tGF_Box *newBox;\n\tBool skip_logs = gf_bs_get_cookie(bs) ? GF_TRUE : GF_FALSE;\n\tBool is_special = GF_TRUE;\n\n\tif ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM;\n\t*outBox = NULL;\n\tif (gf_bs_available(bs) < 8) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tstart = gf_bs_get_position(bs);\n\n\tuuid_type = 0;\n\tsize = (u64) gf_bs_read_u32(bs);\n\thdr_size = 4;\n\t/*fix for some boxes found in some old hinted files*/\n\tif ((size >= 2) && (size <= 4)) {\n\t\tsize = 4;\n\t\ttype = GF_ISOM_BOX_TYPE_VOID;\n\t} else {\n\t\ttype = gf_bs_read_u32(bs);\n\t\thdr_size += 4;\n\t\t/*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/\n\t\tif (type == GF_ISOM_BOX_TYPE_TOTL)\n\t\t\tsize = 12;\n\t\tif (!size) {\n\t\t\tif (is_root_box) {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\\n\", gf_4cc_to_str(type), type));\n\t\t\t\t}\n\t\t\t\tsize = gf_bs_available(bs) + 8;\n\t\t\t} else {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s (0x%08X) at position \"LLU\" has size 0 but is not at root/file level, skipping\\n\", gf_4cc_to_str(type), type, start));\n\t\t\t\t}\n\t\t\t\treturn GF_OK;\n//\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t}\n\t}\n\t/*handle uuid*/\n\tmemset(uuid, 0, 16);\n\tif (type == GF_ISOM_BOX_TYPE_UUID ) {\n\t\tif (gf_bs_available(bs) < 16) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tgf_bs_read_data(bs, uuid, 16);\n\t\thdr_size += 16;\n\t\tuuid_type = gf_isom_solve_uuid_box(uuid);\n\t}\n\n\t//handle large box\n\tif (size == 1) {\n\t\tif (gf_bs_available(bs) < 8) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tsize = gf_bs_read_u64(bs);\n\t\thdr_size += 8;\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s size \"LLD\" start \"LLD\"\\n\", gf_4cc_to_str(type), LLD_CAST size, LLD_CAST start));\n\n\tif ( size < hdr_size ) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Box size \"LLD\" less than box header size %d\\n\", LLD_CAST size, hdr_size));\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\t//some special boxes (references and track groups) are handled by a single generic box with an associated ref/group type\n\tif (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_ItemReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackGroupTypeBox*)newBox)->group_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type;\n\t} else {\n\t\t//OK, create the box based on the type\n\t\tis_special = GF_FALSE;\n\t\tnewBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t}\n\n\t//OK, init and read this box\n\tif (type==GF_ISOM_BOX_TYPE_UUID && !is_special) {\n\t\tmemcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16);\n\t\t((GF_UUIDBox *)newBox)->internal_4cc = uuid_type;\n\t}\n\n\tif (!newBox->type) newBox->type = type;\n\tpayload_start = gf_bs_get_position(bs);\n\nretry_unknown_box:\n\n\tend = gf_bs_available(bs);\n\tif (size - hdr_size > end ) {\n\t\tnewBox->size = size - hdr_size - end;\n\t\t*outBox = newBox;\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tnewBox->size = size - hdr_size;\n\n\tif (newBox->size) {\n\t\te = gf_isom_full_box_read(newBox, bs);\n\t\tif (!e) e = gf_isom_box_read(newBox, bs);\n\t\tnewBox->size = size;\n\t\tend = gf_bs_get_position(bs);\n\t} else {\n\t\tnewBox->size = size;\n\t\t//empty box\n\t\te = GF_OK;\n\t\tend = gf_bs_get_position(bs);\n\t}\n\n\tif (e && (e != GF_ISOM_INCOMPLETE_FILE)) {\n\t\tgf_isom_box_del(newBox);\n\t\t*outBox = NULL;\n\n\t\tif (parent_type==GF_ISOM_BOX_TYPE_STSD) {\n\t\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_UNKNOWN);\n\t\t\t((GF_UnknownBox *)newBox)->original_4cc = type;\n\t\t\tnewBox->size = size;\n\t\t\tgf_bs_seek(bs, payload_start);\n\t\t\tgoto retry_unknown_box;\n\t\t}\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box \\\"%s\\\" (start \"LLU\") failed (%s) - skipping\\n\", gf_4cc_to_str(type), start, gf_error_to_string(e)));\n\t\t}\n\t\t//we don't try to reparse known boxes that have been failing (too dangerous)\n\t\treturn e;\n\t}\n\n\tif (end-start > size) {\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" size \"LLU\" (start \"LLU\") invalid (read \"LLU\")\\n\", gf_4cc_to_str(type), LLU_CAST size, start, LLU_CAST (end-start) ));\n\t\t}\n\t\t/*let's still try to load the file since no error was notified*/\n\t\tgf_bs_seek(bs, start+size);\n\t} else if (end-start < size) {\n\t\tu32 to_skip = (u32) (size-(end-start));\n\t\tif (!skip_logs) {\n\t\t\tif ((to_skip!=4) || gf_bs_peek_bits(bs, 32, 0)) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" (start \"LLU\") has %u extra bytes\\n\", gf_4cc_to_str(type), start, to_skip));\n\t\t\t}\n\t\t}\n\t\tgf_bs_skip_bytes(bs, to_skip);\n\t}\n\t*outBox = newBox;\n\n\treturn e;\n}", "func_hash": 260911075280980343517308995497986880453, "file_name": "box_funcs.c", "file_hash": 168689251586511039942802087378905680110, "cwe": ["CWE-476"], "cve": "CVE-2020-25427", "cve_desc": "A Null pointer dereference vulnerability exits in MP4Box - GPAC version 0.8.0-rev177-g51a8ef874-master via the gf_isom_get_track_id function, which causes a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25427"} {"idx": 224922, "project": "gpac", "commit_id": "8e585e623b1d666b4ef736ed609264639cb27701", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/8e585e623b1d666b4ef736ed609264639cb27701", "commit_message": "fixed potential crash - cf #1406", "target": 0, "func": "GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box)\n{\n\tu32 type, uuid_type, hdr_size;\n\tu64 size, start, payload_start, end;\n\tchar uuid[16];\n\tGF_Err e;\n\tGF_Box *newBox;\n\tBool skip_logs = gf_bs_get_cookie(bs) ? GF_TRUE : GF_FALSE;\n\tBool is_special = GF_TRUE;\n\n\tif ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM;\n\t*outBox = NULL;\n\tif (gf_bs_available(bs) < 8) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tstart = gf_bs_get_position(bs);\n\n\tuuid_type = 0;\n\tsize = (u64) gf_bs_read_u32(bs);\n\thdr_size = 4;\n\t/*fix for some boxes found in some old hinted files*/\n\tif ((size >= 2) && (size <= 4)) {\n\t\tsize = 4;\n\t\ttype = GF_ISOM_BOX_TYPE_VOID;\n\t} else {\n\t\ttype = gf_bs_read_u32(bs);\n\t\thdr_size += 4;\n\t\t/*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/\n\t\tif (type == GF_ISOM_BOX_TYPE_TOTL)\n\t\t\tsize = 12;\n\t\tif (!size) {\n\t\t\tif (is_root_box) {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\\n\", gf_4cc_to_str(type), type));\n\t\t\t\t}\n\t\t\t\tsize = gf_bs_available(bs) + 8;\n\t\t\t} else {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s (0x%08X) at position \"LLU\" has size 0 but is not at root/file level, skipping\\n\", gf_4cc_to_str(type), type, start));\n\t\t\t\t}\n\t\t\t\treturn GF_OK;\n//\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t}\n\t}\n\t/*handle uuid*/\n\tmemset(uuid, 0, 16);\n\tif (type == GF_ISOM_BOX_TYPE_UUID ) {\n\t\tif (gf_bs_available(bs) < 16) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tgf_bs_read_data(bs, uuid, 16);\n\t\thdr_size += 16;\n\t\tuuid_type = gf_isom_solve_uuid_box(uuid);\n\t}\n\n\t//handle large box\n\tif (size == 1) {\n\t\tif (gf_bs_available(bs) < 8) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tsize = gf_bs_read_u64(bs);\n\t\thdr_size += 8;\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s size \"LLD\" start \"LLD\"\\n\", gf_4cc_to_str(type), LLD_CAST size, LLD_CAST start));\n\n\tif ( size < hdr_size ) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Box size \"LLD\" less than box header size %d\\n\", LLD_CAST size, hdr_size));\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\t//some special boxes (references and track groups) are handled by a single generic box with an associated ref/group type\n\tif (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_ItemReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackGroupTypeBox*)newBox)->group_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type;\n\t} else {\n\t\t//OK, create the box based on the type\n\t\tis_special = GF_FALSE;\n\t\tnewBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t}\n\n\t//OK, init and read this box\n\tif (type==GF_ISOM_BOX_TYPE_UUID && !is_special) {\n\t\tmemcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16);\n\t\t((GF_UUIDBox *)newBox)->internal_4cc = uuid_type;\n\t}\n\n\tif (!newBox->type) newBox->type = type;\n\tpayload_start = gf_bs_get_position(bs);\n\nretry_unknown_box:\n\n\tend = gf_bs_available(bs);\n\tif (size - hdr_size > end ) {\n\t\tnewBox->size = size - hdr_size - end;\n\t\t*outBox = newBox;\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tnewBox->size = size - hdr_size;\n\n\t//parse even if size is 0 - this makes sure that we perform box parsing (usually in box->read)\n\te = gf_isom_full_box_read(newBox, bs);\n\tif (!e) e = gf_isom_box_read(newBox, bs);\n\tnewBox->size = size;\n\tend = gf_bs_get_position(bs);\n\n\tif (e && (e != GF_ISOM_INCOMPLETE_FILE)) {\n\t\tgf_isom_box_del(newBox);\n\t\t*outBox = NULL;\n\n\t\tif (parent_type==GF_ISOM_BOX_TYPE_STSD) {\n\t\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_UNKNOWN);\n\t\t\t((GF_UnknownBox *)newBox)->original_4cc = type;\n\t\t\tnewBox->size = size;\n\t\t\tgf_bs_seek(bs, payload_start);\n\t\t\tgoto retry_unknown_box;\n\t\t}\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box \\\"%s\\\" (start \"LLU\") failed (%s) - skipping\\n\", gf_4cc_to_str(type), start, gf_error_to_string(e)));\n\t\t}\n\t\t//we don't try to reparse known boxes that have been failing (too dangerous)\n\t\treturn e;\n\t}\n\n\tif (end-start > size) {\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" size \"LLU\" (start \"LLU\") invalid (read \"LLU\")\\n\", gf_4cc_to_str(type), LLU_CAST size, start, LLU_CAST (end-start) ));\n\t\t}\n\t\t/*let's still try to load the file since no error was notified*/\n\t\tgf_bs_seek(bs, start+size);\n\t} else if (end-start < size) {\n\t\tu32 to_skip = (u32) (size-(end-start));\n\t\tif (!skip_logs) {\n\t\t\tif ((to_skip!=4) || gf_bs_peek_bits(bs, 32, 0)) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" (start \"LLU\") has %u extra bytes\\n\", gf_4cc_to_str(type), start, to_skip));\n\t\t\t}\n\t\t}\n\t\tgf_bs_skip_bytes(bs, to_skip);\n\t}\n\t*outBox = newBox;\n\n\treturn e;\n}", "func_hash": 98584238472621076061917957347416198784, "file_name": "box_funcs.c", "file_hash": 19050742673505602409695289794684763861, "cwe": ["CWE-476"], "cve": "CVE-2020-25427", "cve_desc": "A Null pointer dereference vulnerability exits in MP4Box - GPAC version 0.8.0-rev177-g51a8ef874-master via the gf_isom_get_track_id function, which causes a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25427"} {"idx": 195362, "project": "contiki-ng", "commit_id": "12c824386ab60de757de5001974d73b32e19ad71", "project_url": "https://github.com/contiki-ng/contiki-ng", "commit_url": "https://github.com/contiki-ng/contiki-ng/commit/12c824386ab60de757de5001974d73b32e19ad71", "commit_message": "Refactored SNMP engine after vulnerabilities", "target": 1, "func": "snmp_ber_decode_string_len_buffer(unsigned char *buf, uint32_t *buff_len, const char **str, uint32_t *length)\n{\n uint8_t type, i, length_bytes;\n\n buf = snmp_ber_decode_type(buf, buff_len, &type);\n\n if(buf == NULL || type != BER_DATA_TYPE_OCTET_STRING) {\n /*\n * Sanity check\n * Invalid type in buffer\n */\n return NULL;\n }\n\n if((*buf & 0x80) == 0) {\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n } else {\n\n length_bytes = (uint8_t)(*buf++ & 0x7F);\n (*buff_len)--;\n if(length_bytes > 4) {\n /*\n * Sanity check\n * It will not fit in the uint32_t\n */\n return NULL;\n }\n\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n for(i = 1; i < length_bytes; ++i) {\n *length <<= 8;\n *length |= *buf++;\n (*buff_len)--;\n }\n }\n\n *str = (const char *)buf;\n *buff_len -= *length;\n\n return buf + *length;\n}", "func_hash": 22253653741917009457343936172115657543, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-12141", "cve_desc": "An out-of-bounds read in the SNMP stack in Contiki-NG 4.4 and earlier allows an attacker to cause a denial of service and potentially disclose information via crafted SNMP packets to snmp_ber_decode_string_len_buffer in os/net/app-layer/snmp/snmp-ber.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12141"} {"idx": 224950, "project": "contiki-ng", "commit_id": "12c824386ab60de757de5001974d73b32e19ad71", "project_url": "https://github.com/contiki-ng/contiki-ng", "commit_url": "https://github.com/contiki-ng/contiki-ng/commit/12c824386ab60de757de5001974d73b32e19ad71", "commit_message": "Refactored SNMP engine after vulnerabilities", "target": 0, "func": "snmp_ber_decode_string_len_buffer(snmp_packet_t *snmp_packet, const char **str, uint32_t *length)\n{\n uint8_t type, i, length_bytes;\n\n if(!snmp_ber_decode_type(snmp_packet, &type)) {\n return 0;\n }\n\n if(type != BER_DATA_TYPE_OCTET_STRING) {\n /*\n * Sanity check\n * Invalid type in buffer\n */\n return 0;\n }\n\n if((*snmp_packet->in & 0x80) == 0) {\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n *length = (uint32_t)*snmp_packet->in++;\n snmp_packet->used--;\n } else {\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n length_bytes = (uint8_t)(*snmp_packet->in++ & 0x7F);\n snmp_packet->used--;\n\n if(length_bytes > 4) {\n /*\n * Sanity check\n * It will not fit in the uint32_t\n */\n return 0;\n }\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n *length = (uint32_t)*snmp_packet->in++;\n snmp_packet->used--;\n\n for(i = 1; i < length_bytes; ++i) {\n *length <<= 8;\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n *length |= *snmp_packet->in++;\n snmp_packet->used--;\n }\n }\n\n *str = (const char *)snmp_packet->in;\n\n if(snmp_packet->used == 0 || snmp_packet->used - *length <= 0) {\n return 0;\n }\n\n snmp_packet->used -= *length;\n snmp_packet->in += *length;\n\n return 1;\n}", "func_hash": 219339813812981517466318844695929060846, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-12141", "cve_desc": "An out-of-bounds read in the SNMP stack in Contiki-NG 4.4 and earlier allows an attacker to cause a denial of service and potentially disclose information via crafted SNMP packets to snmp_ber_decode_string_len_buffer in os/net/app-layer/snmp/snmp-ber.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12141"} {"idx": 195486, "project": "hhvm", "commit_id": "b3679121bb3c7017ff04b4c08402ffff5cf59b13", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/b3679121bb3c7017ff04b4c08402ffff5cf59b13", "commit_message": "Fix buffer overrun in SimpleParser::handleBackslash\n\nSummary:\nIt read 4 chars, then checked for validity, but any of them could have\nbeen the end of the string, so check after each one instead.\n\nReviewed By: oulgen\n\nDifferential Revision: D19611163\n\nfbshipit-source-id: 3da0a39555cb85a93f4fd98048368f17cf37e2e4", "target": 1, "func": " bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n auto const ch2 = *p++;\n auto const dch3 = dehexchar(*p++);\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n return false;\n }\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }", "func_hash": 138603020136049044878395293534036432832, "file_name": "JSON_parser.cpp", "file_hash": 15110771764883296817845189962166490807, "cwe": ["CWE-125"], "cve": "CVE-2020-1888", "cve_desc": "Insufficient boundary checks when decoding JSON in handleBackslash reads out of bounds memory, potentially leading to DOS. This issue affects HHVM 4.45.0, 4.44.0, 4.43.0, 4.42.0, 4.41.0, 4.40.0, 4.39.0, versions between 4.33.0 and 4.38.0 (inclusive), versions between 4.9.0 and 4.32.0 (inclusive), and versions prior to 4.8.7.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1888"} {"idx": 227282, "project": "hhvm", "commit_id": "b3679121bb3c7017ff04b4c08402ffff5cf59b13", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/b3679121bb3c7017ff04b4c08402ffff5cf59b13", "commit_message": "Fix buffer overrun in SimpleParser::handleBackslash\n\nSummary:\nIt read 4 chars, then checked for validity, but any of them could have\nbeen the end of the string, so check after each one instead.\n\nReviewed By: oulgen\n\nDifferential Revision: D19611163\n\nfbshipit-source-id: 3da0a39555cb85a93f4fd98048368f17cf37e2e4", "target": 0, "func": " bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n if (UNLIKELY(ch1 != '0')) return false;\n auto const ch2 = *p++;\n if (UNLIKELY(ch2 != '0')) return false;\n auto const dch3 = dehexchar(*p++);\n if (UNLIKELY(dch3 < 0)) return false;\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(dch4 < 0)) return false;\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }", "func_hash": 164664689504516599984462784447993143601, "file_name": "JSON_parser.cpp", "file_hash": 327538819431907468445610924515627091549, "cwe": ["CWE-125"], "cve": "CVE-2020-1888", "cve_desc": "Insufficient boundary checks when decoding JSON in handleBackslash reads out of bounds memory, potentially leading to DOS. This issue affects HHVM 4.45.0, 4.44.0, 4.43.0, 4.42.0, 4.41.0, 4.40.0, 4.39.0, versions between 4.33.0 and 4.38.0 (inclusive), versions between 4.9.0 and 4.32.0 (inclusive), and versions prior to 4.8.7.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1888"} {"idx": 195488, "project": "kdeconnect-kde", "commit_id": "542d94a70c56aa386c8d4d793481ce181b0422e8", "project_url": "https://github.com/KDE/kdeconnect-kde", "commit_url": "https://github.com/KDE/kdeconnect-kde/commit/542d94a70c56aa386c8d4d793481ce181b0422e8", "commit_message": "Limit number of connected sockets from unpaired devices\n\nThanks Matthias Gerstner for reporting this.", "target": 1, "func": "void LanLinkProvider::addLink(const QString& deviceId, QSslSocket* socket, NetworkPacket* receivedPacket, LanDeviceLink::ConnectionStarted connectionOrigin)\n{\n // Socket disconnection will now be handled by LanDeviceLink\n disconnect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater);\n\n LanDeviceLink* deviceLink;\n //Do we have a link for this device already?\n QMap< QString, LanDeviceLink* >::iterator linkIterator = m_links.find(deviceId);\n if (linkIterator != m_links.end()) {\n //qCDebug(KDECONNECT_CORE) << \"Reusing link to\" << deviceId;\n deviceLink = linkIterator.value();\n deviceLink->reset(socket, connectionOrigin);\n } else {\n deviceLink = new LanDeviceLink(deviceId, this, socket, connectionOrigin);\n connect(deviceLink, &QObject::destroyed, this, &LanLinkProvider::deviceLinkDestroyed);\n m_links[deviceId] = deviceLink;\n if (m_pairingHandlers.contains(deviceId)) {\n //We shouldn't have a pairinghandler if we didn't have a link.\n //Crash if debug, recover if release (by setting the new devicelink to the old pairinghandler)\n Q_ASSERT(m_pairingHandlers.contains(deviceId));\n m_pairingHandlers[deviceId]->setDeviceLink(deviceLink);\n }\n }\n Q_EMIT onConnectionReceived(*receivedPacket, deviceLink);\n}", "func_hash": 334035650856713652635853094501219568844, "file_name": "lanlinkprovider.cpp", "file_hash": 239070225289591185607367891791368728465, "cwe": ["CWE-400"], "cve": "CVE-2020-26164", "cve_desc": "In kdeconnect-kde (aka KDE Connect) before 20.08.2, an attacker on the local network could send crafted packets that trigger use of large amounts of CPU, memory, or network connection slots, aka a Denial of Service attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-26164"} {"idx": 227355, "project": "kdeconnect-kde", "commit_id": "542d94a70c56aa386c8d4d793481ce181b0422e8", "project_url": "https://github.com/KDE/kdeconnect-kde", "commit_url": "https://github.com/KDE/kdeconnect-kde/commit/542d94a70c56aa386c8d4d793481ce181b0422e8", "commit_message": "Limit number of connected sockets from unpaired devices\n\nThanks Matthias Gerstner for reporting this.", "target": 0, "func": "void LanLinkProvider::addLink(const QString& deviceId, QSslSocket* socket, NetworkPacket* receivedPacket, LanDeviceLink::ConnectionStarted connectionOrigin)\n{\n // Socket disconnection will now be handled by LanDeviceLink\n disconnect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater);\n\n LanDeviceLink* deviceLink;\n //Do we have a link for this device already?\n QMap< QString, LanDeviceLink* >::iterator linkIterator = m_links.find(deviceId);\n if (linkIterator != m_links.end()) {\n //qCDebug(KDECONNECT_CORE) << \"Reusing link to\" << deviceId;\n deviceLink = linkIterator.value();\n deviceLink->reset(socket, connectionOrigin);\n } else {\n deviceLink = new LanDeviceLink(deviceId, this, socket, connectionOrigin);\n // Socket disconnection will now be handled by LanDeviceLink\n disconnect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater);\n bool isDeviceTrusted = KdeConnectConfig::instance().trustedDevices().contains(deviceId);\n if (!isDeviceTrusted && m_links.size() > MAX_UNPAIRED_CONNECTIONS) {\n qCWarning(KDECONNECT_CORE) << \"Too many unpaired devices to remember them all. Ignoring \" << deviceId;\n socket->disconnectFromHost();\n socket->deleteLater();\n return;\n }\n connect(deviceLink, &QObject::destroyed, this, &LanLinkProvider::deviceLinkDestroyed);\n m_links[deviceId] = deviceLink;\n if (m_pairingHandlers.contains(deviceId)) {\n //We shouldn't have a pairinghandler if we didn't have a link.\n //Crash if debug, recover if release (by setting the new devicelink to the old pairinghandler)\n Q_ASSERT(m_pairingHandlers.contains(deviceId));\n m_pairingHandlers[deviceId]->setDeviceLink(deviceLink);\n }\n }\n Q_EMIT onConnectionReceived(*receivedPacket, deviceLink);\n}", "func_hash": 137088549749552213541487710644083599588, "file_name": "lanlinkprovider.cpp", "file_hash": 122426479794157688895885193734571798156, "cwe": ["CWE-400"], "cve": "CVE-2020-26164", "cve_desc": "In kdeconnect-kde (aka KDE Connect) before 20.08.2, an attacker on the local network could send crafted packets that trigger use of large amounts of CPU, memory, or network connection slots, aka a Denial of Service attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-26164"} {"idx": 195648, "project": "libssh2", "commit_id": "dedcbd106f8e52d5586b0205bc7677e4c9868f9c", "project_url": "https://github.com/libssh2/libssh2", "commit_url": "https://github.com/libssh2/libssh2/commit/dedcbd106f8e52d5586b0205bc7677e4c9868f9c", "commit_message": "packet.c: improve message parsing (#402)\n\n* packet.c: improve parsing of packets\n\nfile: packet.c\n\nnotes:\nUse _libssh2_get_string API in SSH_MSG_DEBUG/SSH_MSG_DISCONNECT. Additional uint32 bounds check in SSH_MSG_GLOBAL_REQUEST.", "target": 1, "func": "_libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,\n size_t datalen, int macstate)\n{\n int rc = 0;\n char *message = NULL;\n char *language = NULL;\n size_t message_len = 0;\n size_t language_len = 0;\n LIBSSH2_CHANNEL *channelp = NULL;\n size_t data_head = 0;\n unsigned char msg = data[0];\n\n switch(session->packAdd_state) {\n case libssh2_NB_state_idle:\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Packet type %d received, length=%d\",\n (int) msg, (int) datalen);\n\n if((macstate == LIBSSH2_MAC_INVALID) &&\n (!session->macerror ||\n LIBSSH2_MACERROR(session, (char *) data, datalen))) {\n /* Bad MAC input, but no callback set or non-zero return from the\n callback */\n\n LIBSSH2_FREE(session, data);\n return _libssh2_error(session, LIBSSH2_ERROR_INVALID_MAC,\n \"Invalid MAC received\");\n }\n session->packAdd_state = libssh2_NB_state_allocated;\n break;\n case libssh2_NB_state_jump1:\n goto libssh2_packet_add_jump_point1;\n case libssh2_NB_state_jump2:\n goto libssh2_packet_add_jump_point2;\n case libssh2_NB_state_jump3:\n goto libssh2_packet_add_jump_point3;\n case libssh2_NB_state_jump4:\n goto libssh2_packet_add_jump_point4;\n case libssh2_NB_state_jump5:\n goto libssh2_packet_add_jump_point5;\n default: /* nothing to do */\n break;\n }\n\n if(session->packAdd_state == libssh2_NB_state_allocated) {\n /* A couple exceptions to the packet adding rule: */\n switch(msg) {\n\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DISCONNECT:\n if(datalen >= 5) {\n size_t reason = _libssh2_ntohu32(data + 1);\n\n if(datalen >= 9) {\n message_len = _libssh2_ntohu32(data + 5);\n\n if(message_len < datalen-13) {\n /* 9 = packet_type(1) + reason(4) + message_len(4) */\n message = (char *) data + 9;\n\n language_len =\n _libssh2_ntohu32(data + 9 + message_len);\n language = (char *) data + 9 + message_len + 4;\n\n if(language_len > (datalen-13-message_len)) {\n /* bad input, clear info */\n language = message = NULL;\n language_len = message_len = 0;\n }\n }\n else\n /* bad size, clear it */\n message_len = 0;\n }\n if(session->ssh_msg_disconnect) {\n LIBSSH2_DISCONNECT(session, reason, message,\n message_len, language, language_len);\n }\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Disconnect(%d): %s(%s)\", reason,\n message, language);\n }\n\n LIBSSH2_FREE(session, data);\n session->socket_state = LIBSSH2_SOCKET_DISCONNECTED;\n session->packAdd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_DISCONNECT,\n \"socket disconnect\");\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n\n case SSH_MSG_IGNORE:\n if(datalen >= 2) {\n if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, (char *) data + 1, datalen - 1);\n }\n }\n else if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, \"\", 0);\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DEBUG:\n if(datalen >= 2) {\n int always_display = data[1];\n\n if(datalen >= 6) {\n message_len = _libssh2_ntohu32(data + 2);\n\n if(message_len <= (datalen - 10)) {\n /* 6 = packet_type(1) + display(1) + message_len(4) */\n message = (char *) data + 6;\n language_len = _libssh2_ntohu32(data + 6 +\n message_len);\n\n if(language_len <= (datalen - 10 - message_len))\n language = (char *) data + 10 + message_len;\n }\n }\n\n if(session->ssh_msg_debug) {\n LIBSSH2_DEBUG(session, always_display, message,\n message_len, language, language_len);\n }\n }\n /*\n * _libssh2_debug will actually truncate this for us so\n * that it's not an inordinate about of data\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Debug Packet: %s\", message);\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n\n case SSH_MSG_GLOBAL_REQUEST:\n if(datalen >= 5) {\n uint32_t len = 0;\n unsigned char want_reply = 0;\n len = _libssh2_ntohu32(data + 1);\n if(datalen >= (6 + len)) {\n want_reply = data[5 + len];\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Received global request type %.*s (wr %X)\",\n len, data + 5, want_reply);\n }\n\n\n if(want_reply) {\n static const unsigned char packet =\n SSH_MSG_REQUEST_FAILURE;\n libssh2_packet_add_jump_point5:\n session->packAdd_state = libssh2_NB_state_jump5;\n rc = _libssh2_transport_send(session, &packet, 1, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n\n case SSH_MSG_CHANNEL_EXTENDED_DATA:\n /* streamid(4) */\n data_head += 4;\n\n /* fall-through */\n\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n\n case SSH_MSG_CHANNEL_DATA:\n /* packet_type(1) + channelno(4) + datalen(4) */\n data_head += 9;\n\n if(datalen >= data_head)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n\n if(!channelp) {\n _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_UNKNOWN,\n \"Packet received for unknown channel\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n#ifdef LIBSSH2DEBUG\n {\n uint32_t stream_id = 0;\n if(msg == SSH_MSG_CHANNEL_EXTENDED_DATA)\n stream_id = _libssh2_ntohu32(data + 5);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"%d bytes packet_add() for %lu/%lu/%lu\",\n (int) (datalen - data_head),\n channelp->local.id,\n channelp->remote.id,\n stream_id);\n }\n#endif\n if((channelp->remote.extended_data_ignore_mode ==\n LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE) &&\n (msg == SSH_MSG_CHANNEL_EXTENDED_DATA)) {\n /* Pretend we didn't receive this */\n LIBSSH2_FREE(session, data);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Ignoring extended data and refunding %d bytes\",\n (int) (datalen - 13));\n if(channelp->read_avail + datalen - data_head >=\n channelp->remote.window_size)\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n\n channelp->remote.window_size -= datalen - data_head;\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"shrinking window size by %lu bytes to %lu, \"\n \"read_avail %lu\",\n datalen - data_head,\n channelp->remote.window_size,\n channelp->read_avail);\n\n session->packAdd_channelp = channelp;\n\n /* Adjust the window based on the block we just freed */\n libssh2_packet_add_jump_point1:\n session->packAdd_state = libssh2_NB_state_jump1;\n rc = _libssh2_channel_receive_window_adjust(session->\n packAdd_channelp,\n datalen - 13,\n 1, NULL);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n\n /*\n * REMEMBER! remote means remote as source of data,\n * NOT remote window!\n */\n if(channelp->remote.packet_size < (datalen - data_head)) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * packet_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED,\n \"Packet contains more data than we offered\"\n \" to receive, truncating\");\n datalen = channelp->remote.packet_size + data_head;\n }\n if(channelp->remote.window_size <= channelp->read_avail) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * window_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"The current receive window is full,\"\n \" data ignored\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n /* Reset EOF status */\n channelp->remote.eof = 0;\n\n if(channelp->read_avail + datalen - data_head >\n channelp->remote.window_size) {\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"Remote sent more data than current \"\n \"window allows, truncating\");\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n }\n\n /* Update the read_avail counter. The window size will be\n * updated once the data is actually read from the queue\n * from an upper layer */\n channelp->read_avail += datalen - data_head;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"increasing read_avail by %lu bytes to %lu/%lu\",\n (long)(datalen - data_head),\n (long)channelp->read_avail,\n (long)channelp->remote.window_size);\n\n break;\n\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_EOF:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp)\n /* We may have freed already, just quietly ignore this... */\n ;\n else {\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"EOF received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n channelp->remote.eof = 1;\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n\n case SSH_MSG_CHANNEL_REQUEST:\n if(datalen >= 9) {\n uint32_t channel = _libssh2_ntohu32(data + 1);\n uint32_t len = _libssh2_ntohu32(data + 5);\n unsigned char want_reply = 1;\n\n if((len + 9) < datalen)\n want_reply = data[len + 9];\n\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Channel %d received request type %.*s (wr %X)\",\n channel, len, data + 9, want_reply);\n\n if(len == sizeof(\"exit-status\") - 1\n && (sizeof(\"exit-status\") - 1 + 9) <= datalen\n && !memcmp(\"exit-status\", data + 9,\n sizeof(\"exit-status\") - 1)) {\n\n /* we've got \"exit-status\" packet. Set the session value */\n if(datalen >= 20)\n channelp =\n _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-status\") + 13) <= datalen) {\n channelp->exit_status =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-status\"));\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit status %lu received for \"\n \"channel %lu/%lu\",\n channelp->exit_status,\n channelp->local.id,\n channelp->remote.id);\n }\n\n }\n else if(len == sizeof(\"exit-signal\") - 1\n && (sizeof(\"exit-signal\") - 1 + 9) <= datalen\n && !memcmp(\"exit-signal\", data + 9,\n sizeof(\"exit-signal\") - 1)) {\n /* command terminated due to signal */\n if(datalen >= 20)\n channelp = _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-signal\") + 13) <= datalen) {\n /* set signal name (without SIG prefix) */\n uint32_t namelen =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-signal\"));\n\n if(namelen <= UINT_MAX - 1) {\n channelp->exit_signal =\n LIBSSH2_ALLOC(session, namelen + 1);\n }\n else {\n channelp->exit_signal = NULL;\n }\n\n if(!channelp->exit_signal)\n rc = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"memory for signal name\");\n else if((sizeof(\"exit-signal\") + 13 + namelen <=\n datalen)) {\n memcpy(channelp->exit_signal,\n data + 13 + sizeof(\"exit-signal\"), namelen);\n channelp->exit_signal[namelen] = '\\0';\n /* TODO: save error message and language tag */\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit signal %s received for \"\n \"channel %lu/%lu\",\n channelp->exit_signal,\n channelp->local.id,\n channelp->remote.id);\n }\n }\n }\n\n\n if(want_reply) {\n unsigned char packet[5];\n libssh2_packet_add_jump_point4:\n session->packAdd_state = libssh2_NB_state_jump4;\n packet[0] = SSH_MSG_CHANNEL_FAILURE;\n memcpy(&packet[1], data + 1, 4);\n rc = _libssh2_transport_send(session, packet, 5, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_CLOSE:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp) {\n /* We may have freed already, just quietly ignore this... */\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Close received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n\n channelp->remote.close = 1;\n channelp->remote.eof = 1;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string \"session\"\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n */\n\n case SSH_MSG_CHANNEL_OPEN:\n if(datalen < 17)\n ;\n else if((datalen >= (sizeof(\"forwarded-tcpip\") + 4)) &&\n ((sizeof(\"forwarded-tcpip\") - 1) ==\n _libssh2_ntohu32(data + 1))\n &&\n (memcmp(data + 5, \"forwarded-tcpip\",\n sizeof(\"forwarded-tcpip\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_Qlstn_state, 0,\n sizeof(session->packAdd_Qlstn_state));\n\n libssh2_packet_add_jump_point2:\n session->packAdd_state = libssh2_NB_state_jump2;\n rc = packet_queue_listener(session, data, datalen,\n &session->packAdd_Qlstn_state);\n }\n else if((datalen >= (sizeof(\"x11\") + 4)) &&\n ((sizeof(\"x11\") - 1) == _libssh2_ntohu32(data + 1)) &&\n (memcmp(data + 5, \"x11\", sizeof(\"x11\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_x11open_state, 0,\n sizeof(session->packAdd_x11open_state));\n\n libssh2_packet_add_jump_point3:\n session->packAdd_state = libssh2_NB_state_jump3;\n rc = packet_x11_open(session, data, datalen,\n &session->packAdd_x11open_state);\n }\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n case SSH_MSG_CHANNEL_WINDOW_ADJUST:\n if(datalen < 9)\n ;\n else {\n uint32_t bytestoadd = _libssh2_ntohu32(data + 5);\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(channelp) {\n channelp->local.window_size += bytestoadd;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Window adjust for channel %lu/%lu, \"\n \"adding %lu bytes, new window_size=%lu\",\n channelp->local.id,\n channelp->remote.id,\n bytestoadd,\n channelp->local.window_size);\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n default:\n break;\n }\n\n session->packAdd_state = libssh2_NB_state_sent;\n }\n\n if(session->packAdd_state == libssh2_NB_state_sent) {\n LIBSSH2_PACKET *packetp =\n LIBSSH2_ALLOC(session, sizeof(LIBSSH2_PACKET));\n if(!packetp) {\n _libssh2_debug(session, LIBSSH2_ERROR_ALLOC,\n \"memory for packet\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return LIBSSH2_ERROR_ALLOC;\n }\n packetp->data = data;\n packetp->data_len = datalen;\n packetp->data_head = data_head;\n\n _libssh2_list_add(&session->packets, &packetp->node);\n\n session->packAdd_state = libssh2_NB_state_sent1;\n }\n\n if((msg == SSH_MSG_KEXINIT &&\n !(session->state & LIBSSH2_STATE_EXCHANGING_KEYS)) ||\n (session->packAdd_state == libssh2_NB_state_sent2)) {\n if(session->packAdd_state == libssh2_NB_state_sent1) {\n /*\n * Remote wants new keys\n * Well, it's already in the brigade,\n * let's just call back into ourselves\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS, \"Renegotiating Keys\");\n\n session->packAdd_state = libssh2_NB_state_sent2;\n }\n\n /*\n * The KEXINIT message has been added to the queue. The packAdd and\n * readPack states need to be reset because _libssh2_kex_exchange\n * (eventually) calls upon _libssh2_transport_read to read the rest of\n * the key exchange conversation.\n */\n session->readPack_state = libssh2_NB_state_idle;\n session->packet.total_num = 0;\n session->packAdd_state = libssh2_NB_state_idle;\n session->fullpacket_state = libssh2_NB_state_idle;\n\n memset(&session->startup_key_state, 0, sizeof(key_exchange_state_t));\n\n /*\n * If there was a key reexchange failure, let's just hope we didn't\n * send NEWKEYS yet, otherwise remote will drop us like a rock\n */\n rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n}", "func_hash": 227905321649790343282736099785294686330, "file_name": "packet.c", "file_hash": 324054415871954142320000021425223095177, "cwe": ["CWE-703"], "cve": "CVE-2019-17498", "cve_desc": "In libssh2 v1.9.0 and earlier versions, the SSH_MSG_DISCONNECT logic in packet.c has an integer overflow in a bounds check, enabling an attacker to specify an arbitrary (out-of-bounds) offset for a subsequent memory read. A crafted SSH server may be able to disclose sensitive information or cause a denial of service condition on the client system when a user connects to the server.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-17498"} {"idx": 229853, "project": "libssh2", "commit_id": "dedcbd106f8e52d5586b0205bc7677e4c9868f9c", "project_url": "https://github.com/libssh2/libssh2", "commit_url": "https://github.com/libssh2/libssh2/commit/dedcbd106f8e52d5586b0205bc7677e4c9868f9c", "commit_message": "packet.c: improve message parsing (#402)\n\n* packet.c: improve parsing of packets\n\nfile: packet.c\n\nnotes:\nUse _libssh2_get_string API in SSH_MSG_DEBUG/SSH_MSG_DISCONNECT. Additional uint32 bounds check in SSH_MSG_GLOBAL_REQUEST.", "target": 0, "func": "_libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,\n size_t datalen, int macstate)\n{\n int rc = 0;\n unsigned char *message = NULL;\n unsigned char *language = NULL;\n size_t message_len = 0;\n size_t language_len = 0;\n LIBSSH2_CHANNEL *channelp = NULL;\n size_t data_head = 0;\n unsigned char msg = data[0];\n\n switch(session->packAdd_state) {\n case libssh2_NB_state_idle:\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Packet type %d received, length=%d\",\n (int) msg, (int) datalen);\n\n if((macstate == LIBSSH2_MAC_INVALID) &&\n (!session->macerror ||\n LIBSSH2_MACERROR(session, (char *) data, datalen))) {\n /* Bad MAC input, but no callback set or non-zero return from the\n callback */\n\n LIBSSH2_FREE(session, data);\n return _libssh2_error(session, LIBSSH2_ERROR_INVALID_MAC,\n \"Invalid MAC received\");\n }\n session->packAdd_state = libssh2_NB_state_allocated;\n break;\n case libssh2_NB_state_jump1:\n goto libssh2_packet_add_jump_point1;\n case libssh2_NB_state_jump2:\n goto libssh2_packet_add_jump_point2;\n case libssh2_NB_state_jump3:\n goto libssh2_packet_add_jump_point3;\n case libssh2_NB_state_jump4:\n goto libssh2_packet_add_jump_point4;\n case libssh2_NB_state_jump5:\n goto libssh2_packet_add_jump_point5;\n default: /* nothing to do */\n break;\n }\n\n if(session->packAdd_state == libssh2_NB_state_allocated) {\n /* A couple exceptions to the packet adding rule: */\n switch(msg) {\n\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DISCONNECT:\n if(datalen >= 5) {\n uint32_t reason = 0;\n struct string_buf buf;\n buf.data = (unsigned char *)data;\n buf.dataptr = buf.data;\n buf.len = datalen;\n buf.dataptr++; /* advance past type */\n\n _libssh2_get_u32(&buf, &reason);\n _libssh2_get_string(&buf, &message, &message_len);\n _libssh2_get_string(&buf, &language, &language_len);\n\n if(session->ssh_msg_disconnect) {\n LIBSSH2_DISCONNECT(session, reason, (const char *)message,\n message_len, (const char *)language,\n language_len);\n }\n\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Disconnect(%d): %s(%s)\", reason,\n message, language);\n }\n\n LIBSSH2_FREE(session, data);\n session->socket_state = LIBSSH2_SOCKET_DISCONNECTED;\n session->packAdd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_DISCONNECT,\n \"socket disconnect\");\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n\n case SSH_MSG_IGNORE:\n if(datalen >= 2) {\n if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, (char *) data + 1, datalen - 1);\n }\n }\n else if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, \"\", 0);\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DEBUG:\n if(datalen >= 2) {\n int always_display = data[1];\n\n if(datalen >= 6) {\n struct string_buf buf;\n buf.data = (unsigned char *)data;\n buf.dataptr = buf.data;\n buf.len = datalen;\n buf.dataptr += 2; /* advance past type & always display */\n\n _libssh2_get_string(&buf, &message, &message_len);\n _libssh2_get_string(&buf, &language, &language_len);\n }\n\n if(session->ssh_msg_debug) {\n LIBSSH2_DEBUG(session, always_display,\n (const char *)message,\n message_len, (const char *)language,\n language_len);\n }\n }\n\n /*\n * _libssh2_debug will actually truncate this for us so\n * that it's not an inordinate about of data\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Debug Packet: %s\", message);\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n\n case SSH_MSG_GLOBAL_REQUEST:\n if(datalen >= 5) {\n uint32_t len = 0;\n unsigned char want_reply = 0;\n len = _libssh2_ntohu32(data + 1);\n if((len <= (UINT_MAX - 6)) && (datalen >= (6 + len))) {\n want_reply = data[5 + len];\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Received global request type %.*s (wr %X)\",\n len, data + 5, want_reply);\n }\n\n\n if(want_reply) {\n static const unsigned char packet =\n SSH_MSG_REQUEST_FAILURE;\n libssh2_packet_add_jump_point5:\n session->packAdd_state = libssh2_NB_state_jump5;\n rc = _libssh2_transport_send(session, &packet, 1, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n\n case SSH_MSG_CHANNEL_EXTENDED_DATA:\n /* streamid(4) */\n data_head += 4;\n\n /* fall-through */\n\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n\n case SSH_MSG_CHANNEL_DATA:\n /* packet_type(1) + channelno(4) + datalen(4) */\n data_head += 9;\n\n if(datalen >= data_head)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n\n if(!channelp) {\n _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_UNKNOWN,\n \"Packet received for unknown channel\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n#ifdef LIBSSH2DEBUG\n {\n uint32_t stream_id = 0;\n if(msg == SSH_MSG_CHANNEL_EXTENDED_DATA)\n stream_id = _libssh2_ntohu32(data + 5);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"%d bytes packet_add() for %lu/%lu/%lu\",\n (int) (datalen - data_head),\n channelp->local.id,\n channelp->remote.id,\n stream_id);\n }\n#endif\n if((channelp->remote.extended_data_ignore_mode ==\n LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE) &&\n (msg == SSH_MSG_CHANNEL_EXTENDED_DATA)) {\n /* Pretend we didn't receive this */\n LIBSSH2_FREE(session, data);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Ignoring extended data and refunding %d bytes\",\n (int) (datalen - 13));\n if(channelp->read_avail + datalen - data_head >=\n channelp->remote.window_size)\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n\n channelp->remote.window_size -= datalen - data_head;\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"shrinking window size by %lu bytes to %lu, \"\n \"read_avail %lu\",\n datalen - data_head,\n channelp->remote.window_size,\n channelp->read_avail);\n\n session->packAdd_channelp = channelp;\n\n /* Adjust the window based on the block we just freed */\n libssh2_packet_add_jump_point1:\n session->packAdd_state = libssh2_NB_state_jump1;\n rc = _libssh2_channel_receive_window_adjust(session->\n packAdd_channelp,\n datalen - 13,\n 1, NULL);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n\n /*\n * REMEMBER! remote means remote as source of data,\n * NOT remote window!\n */\n if(channelp->remote.packet_size < (datalen - data_head)) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * packet_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED,\n \"Packet contains more data than we offered\"\n \" to receive, truncating\");\n datalen = channelp->remote.packet_size + data_head;\n }\n if(channelp->remote.window_size <= channelp->read_avail) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * window_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"The current receive window is full,\"\n \" data ignored\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n /* Reset EOF status */\n channelp->remote.eof = 0;\n\n if(channelp->read_avail + datalen - data_head >\n channelp->remote.window_size) {\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"Remote sent more data than current \"\n \"window allows, truncating\");\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n }\n\n /* Update the read_avail counter. The window size will be\n * updated once the data is actually read from the queue\n * from an upper layer */\n channelp->read_avail += datalen - data_head;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"increasing read_avail by %lu bytes to %lu/%lu\",\n (long)(datalen - data_head),\n (long)channelp->read_avail,\n (long)channelp->remote.window_size);\n\n break;\n\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_EOF:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp)\n /* We may have freed already, just quietly ignore this... */\n ;\n else {\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"EOF received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n channelp->remote.eof = 1;\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n\n case SSH_MSG_CHANNEL_REQUEST:\n if(datalen >= 9) {\n uint32_t channel = _libssh2_ntohu32(data + 1);\n uint32_t len = _libssh2_ntohu32(data + 5);\n unsigned char want_reply = 1;\n\n if((len + 9) < datalen)\n want_reply = data[len + 9];\n\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Channel %d received request type %.*s (wr %X)\",\n channel, len, data + 9, want_reply);\n\n if(len == sizeof(\"exit-status\") - 1\n && (sizeof(\"exit-status\") - 1 + 9) <= datalen\n && !memcmp(\"exit-status\", data + 9,\n sizeof(\"exit-status\") - 1)) {\n\n /* we've got \"exit-status\" packet. Set the session value */\n if(datalen >= 20)\n channelp =\n _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-status\") + 13) <= datalen) {\n channelp->exit_status =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-status\"));\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit status %lu received for \"\n \"channel %lu/%lu\",\n channelp->exit_status,\n channelp->local.id,\n channelp->remote.id);\n }\n\n }\n else if(len == sizeof(\"exit-signal\") - 1\n && (sizeof(\"exit-signal\") - 1 + 9) <= datalen\n && !memcmp(\"exit-signal\", data + 9,\n sizeof(\"exit-signal\") - 1)) {\n /* command terminated due to signal */\n if(datalen >= 20)\n channelp = _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-signal\") + 13) <= datalen) {\n /* set signal name (without SIG prefix) */\n uint32_t namelen =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-signal\"));\n\n if(namelen <= UINT_MAX - 1) {\n channelp->exit_signal =\n LIBSSH2_ALLOC(session, namelen + 1);\n }\n else {\n channelp->exit_signal = NULL;\n }\n\n if(!channelp->exit_signal)\n rc = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"memory for signal name\");\n else if((sizeof(\"exit-signal\") + 13 + namelen <=\n datalen)) {\n memcpy(channelp->exit_signal,\n data + 13 + sizeof(\"exit-signal\"), namelen);\n channelp->exit_signal[namelen] = '\\0';\n /* TODO: save error message and language tag */\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit signal %s received for \"\n \"channel %lu/%lu\",\n channelp->exit_signal,\n channelp->local.id,\n channelp->remote.id);\n }\n }\n }\n\n\n if(want_reply) {\n unsigned char packet[5];\n libssh2_packet_add_jump_point4:\n session->packAdd_state = libssh2_NB_state_jump4;\n packet[0] = SSH_MSG_CHANNEL_FAILURE;\n memcpy(&packet[1], data + 1, 4);\n rc = _libssh2_transport_send(session, packet, 5, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_CLOSE:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp) {\n /* We may have freed already, just quietly ignore this... */\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Close received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n\n channelp->remote.close = 1;\n channelp->remote.eof = 1;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string \"session\"\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n */\n\n case SSH_MSG_CHANNEL_OPEN:\n if(datalen < 17)\n ;\n else if((datalen >= (sizeof(\"forwarded-tcpip\") + 4)) &&\n ((sizeof(\"forwarded-tcpip\") - 1) ==\n _libssh2_ntohu32(data + 1))\n &&\n (memcmp(data + 5, \"forwarded-tcpip\",\n sizeof(\"forwarded-tcpip\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_Qlstn_state, 0,\n sizeof(session->packAdd_Qlstn_state));\n\n libssh2_packet_add_jump_point2:\n session->packAdd_state = libssh2_NB_state_jump2;\n rc = packet_queue_listener(session, data, datalen,\n &session->packAdd_Qlstn_state);\n }\n else if((datalen >= (sizeof(\"x11\") + 4)) &&\n ((sizeof(\"x11\") - 1) == _libssh2_ntohu32(data + 1)) &&\n (memcmp(data + 5, \"x11\", sizeof(\"x11\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_x11open_state, 0,\n sizeof(session->packAdd_x11open_state));\n\n libssh2_packet_add_jump_point3:\n session->packAdd_state = libssh2_NB_state_jump3;\n rc = packet_x11_open(session, data, datalen,\n &session->packAdd_x11open_state);\n }\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n case SSH_MSG_CHANNEL_WINDOW_ADJUST:\n if(datalen < 9)\n ;\n else {\n uint32_t bytestoadd = _libssh2_ntohu32(data + 5);\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(channelp) {\n channelp->local.window_size += bytestoadd;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Window adjust for channel %lu/%lu, \"\n \"adding %lu bytes, new window_size=%lu\",\n channelp->local.id,\n channelp->remote.id,\n bytestoadd,\n channelp->local.window_size);\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n default:\n break;\n }\n\n session->packAdd_state = libssh2_NB_state_sent;\n }\n\n if(session->packAdd_state == libssh2_NB_state_sent) {\n LIBSSH2_PACKET *packetp =\n LIBSSH2_ALLOC(session, sizeof(LIBSSH2_PACKET));\n if(!packetp) {\n _libssh2_debug(session, LIBSSH2_ERROR_ALLOC,\n \"memory for packet\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return LIBSSH2_ERROR_ALLOC;\n }\n packetp->data = data;\n packetp->data_len = datalen;\n packetp->data_head = data_head;\n\n _libssh2_list_add(&session->packets, &packetp->node);\n\n session->packAdd_state = libssh2_NB_state_sent1;\n }\n\n if((msg == SSH_MSG_KEXINIT &&\n !(session->state & LIBSSH2_STATE_EXCHANGING_KEYS)) ||\n (session->packAdd_state == libssh2_NB_state_sent2)) {\n if(session->packAdd_state == libssh2_NB_state_sent1) {\n /*\n * Remote wants new keys\n * Well, it's already in the brigade,\n * let's just call back into ourselves\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS, \"Renegotiating Keys\");\n\n session->packAdd_state = libssh2_NB_state_sent2;\n }\n\n /*\n * The KEXINIT message has been added to the queue. The packAdd and\n * readPack states need to be reset because _libssh2_kex_exchange\n * (eventually) calls upon _libssh2_transport_read to read the rest of\n * the key exchange conversation.\n */\n session->readPack_state = libssh2_NB_state_idle;\n session->packet.total_num = 0;\n session->packAdd_state = libssh2_NB_state_idle;\n session->fullpacket_state = libssh2_NB_state_idle;\n\n memset(&session->startup_key_state, 0, sizeof(key_exchange_state_t));\n\n /*\n * If there was a key reexchange failure, let's just hope we didn't\n * send NEWKEYS yet, otherwise remote will drop us like a rock\n */\n rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n}", "func_hash": 205050172228418240851320201480603708257, "file_name": "packet.c", "file_hash": 106788702686469656299333993960760040662, "cwe": ["CWE-703"], "cve": "CVE-2019-17498", "cve_desc": "In libssh2 v1.9.0 and earlier versions, the SSH_MSG_DISCONNECT logic in packet.c has an integer overflow in a bounds check, enabling an attacker to specify an arbitrary (out-of-bounds) offset for a subsequent memory read. A crafted SSH server may be able to disclose sensitive information or cause a denial of service condition on the client system when a user connects to the server.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-17498"} {"idx": 195649, "project": "tensorflow", "commit_id": "4d74d8a00b07441cba090a02e0dd9ed385145bf4", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4d74d8a00b07441cba090a02e0dd9ed385145bf4", "commit_message": "Fix crash in softmax-xent when some input dimensions are 1.\n\nBefore, tf.nn.softmax_cross_entropy_with_logits would fail a CHECK if one input tensor had shape (1, 1) and the other did not.\n\nIn particular, the call to ToIndexArray<2> here https://github.com/tensorflow/tensorflow/blob/1f3da84a89702d3b4f234ee83762d738caffe098/tensorflow/core/kernels/xent_op.cc#L99 would fail, since the call assumed the array had two dimensions. If both dimensions were 1, BCast would merge the two dimensions into a single dimension. Passing fewer_dims_optimization=false stops this optimization\n\nPiperOrigin-RevId: 384844496\nChange-Id: Ifb02dc74964132c3ed3f3bc98b0858dbe4e258b7", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& logits_in = context->input(0);\n const Tensor& labels_in = context->input(1);\n\n TensorShape shape_in = logits_in.shape();\n\n BCast bcast(BCast::FromShape(logits_in.shape()),\n BCast::FromShape(labels_in.shape()));\n if (!logits_in.IsSameSize(labels_in)) {\n OP_REQUIRES(context, bcast.IsValid(),\n errors::InvalidArgument(\n \"logits and labels must be broadcastable: logits_size=\",\n logits_in.shape().DebugString(),\n \" labels_size=\", labels_in.shape().DebugString()));\n shape_in = BCast::ToShape(bcast.output_shape());\n }\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(shape_in),\n errors::InvalidArgument(\"logits and labels must be either \"\n \"2-dimensional, or broadcasted to be \"\n \"2-dimensional\"));\n\n if (std::is_same::value) {\n OP_REQUIRES(context, !OpDeterminismRequired(),\n errors::Unimplemented(\n \"The GPU implementation of SoftmaxCrossEntropyWithLogits\"\n \" that would have been executed is not deterministic.\"\n \" Note that the Python API uses an alternative,\"\n \" deterministic, GPU-accelerated path when determinism is\"\n \" enabled.\"));\n }\n\n // loss is 1-D (one per example), and size is batch_size.\n\n Tensor scratch;\n OP_REQUIRES_OK(\n context, context->allocate_temp(DataTypeToEnum::value,\n TensorShape({shape_in.dim_size(0), 1}),\n &scratch));\n\n Tensor* loss_out = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 0, TensorShape({shape_in.dim_size(0)}), &loss_out));\n Tensor* back_out = nullptr;\n // Try to reuse the logits_in buffer for the backprop output.\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 1, shape_in, &back_out));\n if (shape_in.dim_size(0) > 0) {\n functor::XentFunctor functor;\n if (logits_in.IsSameSize(labels_in)) {\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n Eigen::array{1, 1},\n Eigen::array{1, 1}, logits_in.matrix(),\n labels_in.matrix(), scratch.matrix(), loss_out->vec(),\n back_out->matrix());\n } else {\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n BCast::ToIndexArray<2>(bcast.x_bcast()),\n BCast::ToIndexArray<2>(bcast.y_bcast()),\n logits_in.template shaped(bcast.x_reshape()),\n labels_in.template shaped(bcast.y_reshape()),\n scratch.matrix(), loss_out->vec(), back_out->matrix());\n }\n }\n }", "func_hash": 37442547035777739248678795250559616711, "file_name": "xent_op.cc", "file_hash": 333794670073850746351211159540008599642, "cwe": ["CWE-354"], "cve": "CVE-2021-41206", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions several TensorFlow operations are missing validation for the shapes of the tensor arguments involved in the call. Depending on the API, this can result in undefined behavior and segfault or `CHECK`-fail related crashes but in some scenarios writes and reads from heap populated arrays are also possible. We have discovered these issues internally via tooling while working on improving/testing GPU op determinism. As such, we don't have reproducers and there will be multiple fixes for these issues. These fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41206"} {"idx": 229858, "project": "tensorflow", "commit_id": "4d74d8a00b07441cba090a02e0dd9ed385145bf4", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4d74d8a00b07441cba090a02e0dd9ed385145bf4", "commit_message": "Fix crash in softmax-xent when some input dimensions are 1.\n\nBefore, tf.nn.softmax_cross_entropy_with_logits would fail a CHECK if one input tensor had shape (1, 1) and the other did not.\n\nIn particular, the call to ToIndexArray<2> here https://github.com/tensorflow/tensorflow/blob/1f3da84a89702d3b4f234ee83762d738caffe098/tensorflow/core/kernels/xent_op.cc#L99 would fail, since the call assumed the array had two dimensions. If both dimensions were 1, BCast would merge the two dimensions into a single dimension. Passing fewer_dims_optimization=false stops this optimization\n\nPiperOrigin-RevId: 384844496\nChange-Id: Ifb02dc74964132c3ed3f3bc98b0858dbe4e258b7", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& logits_in = context->input(0);\n const Tensor& labels_in = context->input(1);\n\n TensorShape shape_in = logits_in.shape();\n\n BCast bcast(BCast::FromShape(logits_in.shape()),\n BCast::FromShape(labels_in.shape()),\n /*fewer_dims_optimization=*/false);\n if (!logits_in.IsSameSize(labels_in)) {\n OP_REQUIRES(context, bcast.IsValid(),\n errors::InvalidArgument(\n \"logits and labels must be broadcastable: logits_size=\",\n logits_in.shape().DebugString(),\n \" labels_size=\", labels_in.shape().DebugString()));\n shape_in = BCast::ToShape(bcast.output_shape());\n }\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(shape_in),\n errors::InvalidArgument(\"logits and labels must be either \"\n \"2-dimensional, or broadcasted to be \"\n \"2-dimensional\"));\n\n if (std::is_same::value) {\n OP_REQUIRES(context, !OpDeterminismRequired(),\n errors::Unimplemented(\n \"The GPU implementation of SoftmaxCrossEntropyWithLogits\"\n \" that would have been executed is not deterministic.\"\n \" Note that the Python API uses an alternative,\"\n \" deterministic, GPU-accelerated path when determinism is\"\n \" enabled.\"));\n }\n\n // loss is 1-D (one per example), and size is batch_size.\n\n Tensor scratch;\n OP_REQUIRES_OK(\n context, context->allocate_temp(DataTypeToEnum::value,\n TensorShape({shape_in.dim_size(0), 1}),\n &scratch));\n\n Tensor* loss_out = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 0, TensorShape({shape_in.dim_size(0)}), &loss_out));\n Tensor* back_out = nullptr;\n // Try to reuse the logits_in buffer for the backprop output.\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 1, shape_in, &back_out));\n if (shape_in.dim_size(0) > 0) {\n functor::XentFunctor functor;\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n BCast::ToIndexArray<2>(bcast.x_bcast()),\n BCast::ToIndexArray<2>(bcast.y_bcast()),\n logits_in.template shaped(bcast.x_reshape()),\n labels_in.template shaped(bcast.y_reshape()),\n scratch.matrix(), loss_out->vec(), back_out->matrix());\n }\n }", "func_hash": 108868858390902996209513347534757157981, "file_name": "xent_op.cc", "file_hash": 226968860987690083919878482597780161031, "cwe": ["CWE-354"], "cve": "CVE-2021-41206", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions several TensorFlow operations are missing validation for the shapes of the tensor arguments involved in the call. Depending on the API, this can result in undefined behavior and segfault or `CHECK`-fail related crashes but in some scenarios writes and reads from heap populated arrays are also possible. We have discovered these issues internally via tooling while working on improving/testing GPU op determinism. As such, we don't have reproducers and there will be multiple fixes for these issues. These fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41206"} {"idx": 195659, "project": "tensorflow", "commit_id": "44b7f486c0143f68b56c34e2d01e146ee445134a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/44b7f486c0143f68b56c34e2d01e146ee445134a", "commit_message": "Fix out of bounds read in `ragged_cross_op.cc`.\n\nPiperOrigin-RevId: 369757702\nChange-Id: Ie6e5d2c21513a8d56bf41fcf35960caf76e890f9", "target": 1, "func": " Status BuildFeatureReaders(const OpInputList& ragged_values_list,\n const OpInputList& ragged_splits_list,\n const OpInputList& sparse_indices_list,\n const OpInputList& sparse_values_list,\n const OpInputList& dense_list, int64 batch_size,\n FeatureReaders* features) {\n features->reserve(input_order_.size());\n\n int next_ragged = 0;\n int next_sparse = 0;\n int next_dense = 0;\n for (char c : input_order_) {\n if (c == 'R') {\n TF_RETURN_IF_ERROR(BuildRaggedFeatureReader(\n ragged_values_list[next_ragged], ragged_splits_list[next_ragged],\n features));\n next_ragged++;\n } else if (c == 'S') {\n TF_RETURN_IF_ERROR(BuildSparseFeatureReader(\n sparse_indices_list[next_sparse], sparse_values_list[next_sparse],\n batch_size, features));\n next_sparse++;\n } else if (c == 'D') {\n TF_RETURN_IF_ERROR(\n BuildDenseFeatureReader(dense_list[next_dense++], features));\n } else {\n return errors::InvalidArgument(\"Unexpected input_order value.\");\n }\n }\n\n return Status::OK();\n }", "func_hash": 255265430266183173573561188514079315837, "file_name": "ragged_cross_op.cc", "file_hash": 174789727505400899326647043848603483988, "cwe": ["CWE-369"], "cve": "CVE-2021-29532", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can force accesses outside the bounds of heap allocated arrays by passing in invalid tensor values to `tf.raw_ops.RaggedCross`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/efea03b38fb8d3b81762237dc85e579cc5fc6e87/tensorflow/core/kernels/ragged_cross_op.cc#L456-L487) lacks validation for the user supplied arguments. Each of the above branches call a helper function after accessing array elements via a `*_list[next_*]` pattern, followed by incrementing the `next_*` index. However, as there is no validation that the `next_*` values are in the valid range for the corresponding `*_list` arrays, this results in heap OOB reads. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29532"} {"idx": 230086, "project": "tensorflow", "commit_id": "44b7f486c0143f68b56c34e2d01e146ee445134a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/44b7f486c0143f68b56c34e2d01e146ee445134a", "commit_message": "Fix out of bounds read in `ragged_cross_op.cc`.\n\nPiperOrigin-RevId: 369757702\nChange-Id: Ie6e5d2c21513a8d56bf41fcf35960caf76e890f9", "target": 0, "func": " Status BuildFeatureReaders(const OpInputList& ragged_values_list,\n const OpInputList& ragged_splits_list,\n const OpInputList& sparse_indices_list,\n const OpInputList& sparse_values_list,\n const OpInputList& dense_list, int64 batch_size,\n FeatureReaders* features) {\n features->reserve(input_order_.size());\n\n int next_ragged = 0;\n int next_sparse = 0;\n int next_dense = 0;\n for (char c : input_order_) {\n if (c == 'R') {\n if (next_ragged >= ragged_values_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a ragged tensor value at index \",\n next_ragged, \" from a list of \", ragged_values_list.size(),\n \" values.\");\n if (next_ragged >= ragged_splits_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a ragged tensor split at index \",\n next_ragged, \" from a list of \", ragged_splits_list.size(),\n \" splits.\");\n TF_RETURN_IF_ERROR(BuildRaggedFeatureReader(\n ragged_values_list[next_ragged], ragged_splits_list[next_ragged],\n features));\n next_ragged++;\n } else if (c == 'S') {\n if (next_sparse >= sparse_values_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a sparse tensor value at index \",\n next_sparse, \" from a list of \", sparse_values_list.size(),\n \" values.\");\n if (next_sparse >= sparse_indices_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a sparse tensor index at index \",\n next_sparse, \" from a list of \", sparse_indices_list.size(),\n \" indices.\");\n TF_RETURN_IF_ERROR(BuildSparseFeatureReader(\n sparse_indices_list[next_sparse], sparse_values_list[next_sparse],\n batch_size, features));\n next_sparse++;\n } else if (c == 'D') {\n if (next_dense >= dense_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a dense tensor at index \", next_dense,\n \" from a list of \", dense_list.size(), \" tensors.\");\n TF_RETURN_IF_ERROR(\n BuildDenseFeatureReader(dense_list[next_dense++], features));\n } else {\n return errors::InvalidArgument(\"Unexpected input_order value.\");\n }\n }\n\n return Status::OK();\n }", "func_hash": 89445084726165738251473258231592887879, "file_name": "ragged_cross_op.cc", "file_hash": 3609436573878159009750866827766812953, "cwe": ["CWE-369"], "cve": "CVE-2021-29532", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can force accesses outside the bounds of heap allocated arrays by passing in invalid tensor values to `tf.raw_ops.RaggedCross`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/efea03b38fb8d3b81762237dc85e579cc5fc6e87/tensorflow/core/kernels/ragged_cross_op.cc#L456-L487) lacks validation for the user supplied arguments. Each of the above branches call a helper function after accessing array elements via a `*_list[next_*]` pattern, followed by incrementing the `next_*` index. However, as there is no validation that the `next_*` values are in the valid range for the corresponding `*_list` arrays, this results in heap OOB reads. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29532"} {"idx": 195663, "project": "tensorflow", "commit_id": "5899741d0421391ca878da47907b1452f06aaf1b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5899741d0421391ca878da47907b1452f06aaf1b", "commit_message": "Fix heap OOB read in dequantize op.\n\nAlso fixes SEGV in same op\n\nPiperOrigin-RevId: 372437896\nChange-Id: I135e94d360c2a1ce374c10f7e0fed1af603dbc02", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const Tensor& input_min_tensor = ctx->input(1);\n const Tensor& input_max_tensor = ctx->input(2);\n\n int num_slices = 1;\n if (axis_ > -1) {\n num_slices = input.dim_size(axis_);\n }\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n Tensor float_output =\n need_cast_ ? tensorflow::Tensor(DT_FLOAT, input.shape()) : *output;\n if (num_slices == 1) {\n const float min_range = input_min_tensor.flat()(0);\n const float max_range = input_max_tensor.flat()(0);\n DequantizeTensor(ctx, input, min_range, max_range, &float_output);\n } else {\n OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n \"Dequantize with axis != -1.\"));\n\n int64 pre_dim = 1, post_dim = 1;\n for (int i = 0; i < axis_; ++i) {\n pre_dim *= float_output.dim_size(i);\n }\n for (int i = axis_ + 1; i < float_output.dims(); ++i) {\n post_dim *= float_output.dim_size(i);\n }\n auto input_tensor = input.template bit_casted_shaped(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims(axis_ - 1);\n auto min_ranges = input_min_tensor.vec();\n auto max_ranges = input_max_tensor.vec();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device(), ctx,\n input_tensor.template chip<1>(i), min_ranges(i),\n max_ranges(i), output_tensor.template chip<1>(i));\n }\n }\n if (need_cast_) {\n S* out_ptr = output->flat().data();\n float* in_ptr = float_output.flat().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast(in_ptr[i]);\n }\n }\n }", "func_hash": 56918695572769572707799862481332670073, "file_name": "dequantize_op.cc", "file_hash": 123134243221665449556186698409671209791, "cwe": ["CWE-20"], "cve": "CVE-2021-29582", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Due to lack of validation in `tf.raw_ops.Dequantize`, an attacker can trigger a read from outside of bounds of heap allocated data. The implementation(https://github.com/tensorflow/tensorflow/blob/26003593aa94b1742f34dc22ce88a1e17776a67d/tensorflow/core/kernels/dequantize_op.cc#L106-L131) accesses the `min_range` and `max_range` tensors in parallel but fails to check that they have the same shape. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29582"} {"idx": 230153, "project": "tensorflow", "commit_id": "5899741d0421391ca878da47907b1452f06aaf1b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5899741d0421391ca878da47907b1452f06aaf1b", "commit_message": "Fix heap OOB read in dequantize op.\n\nAlso fixes SEGV in same op\n\nPiperOrigin-RevId: 372437896\nChange-Id: I135e94d360c2a1ce374c10f7e0fed1af603dbc02", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const Tensor& input_min_tensor = ctx->input(1);\n const Tensor& input_max_tensor = ctx->input(2);\n\n int num_slices = 1;\n if (axis_ > -1) {\n num_slices = input.dim_size(axis_);\n }\n OP_REQUIRES(ctx, input_min_tensor.NumElements() == num_slices,\n errors::InvalidArgument(\n \"input_min_tensor must have as many elements as input on \"\n \"the dequantization axis (\",\n axis_, \"), got \", input_min_tensor.NumElements(),\n \", expected \", num_slices));\n OP_REQUIRES(ctx, input_max_tensor.NumElements() == num_slices,\n errors::InvalidArgument(\n \"input_max_tensor must have as many elements as input on \"\n \"the dequantization axis (\",\n axis_, \"), got \", input_max_tensor.NumElements(),\n \", expected \", num_slices));\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n Tensor float_output =\n need_cast_ ? tensorflow::Tensor(DT_FLOAT, input.shape()) : *output;\n if (num_slices == 1) {\n const float min_range = input_min_tensor.flat()(0);\n const float max_range = input_max_tensor.flat()(0);\n DequantizeTensor(ctx, input, min_range, max_range, &float_output);\n } else {\n OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n \"Dequantize with axis != -1.\"));\n\n int64 pre_dim = 1, post_dim = 1;\n for (int i = 0; i < axis_; ++i) {\n pre_dim *= float_output.dim_size(i);\n }\n for (int i = axis_ + 1; i < float_output.dims(); ++i) {\n post_dim *= float_output.dim_size(i);\n }\n auto input_tensor = input.template bit_casted_shaped(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims(axis_ - 1);\n auto min_ranges = input_min_tensor.vec();\n auto max_ranges = input_max_tensor.vec();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device(), ctx,\n input_tensor.template chip<1>(i), min_ranges(i),\n max_ranges(i), output_tensor.template chip<1>(i));\n }\n }\n if (need_cast_) {\n S* out_ptr = output->flat().data();\n float* in_ptr = float_output.flat().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast(in_ptr[i]);\n }\n }\n }", "func_hash": 106430857941452709559984336653597922117, "file_name": "dequantize_op.cc", "file_hash": 23297542649632383909356494944323211224, "cwe": ["CWE-20"], "cve": "CVE-2021-29582", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Due to lack of validation in `tf.raw_ops.Dequantize`, an attacker can trigger a read from outside of bounds of heap allocated data. The implementation(https://github.com/tensorflow/tensorflow/blob/26003593aa94b1742f34dc22ce88a1e17776a67d/tensorflow/core/kernels/dequantize_op.cc#L106-L131) accesses the `min_range` and `max_range` tensors in parallel but fails to check that they have the same shape. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29582"} {"idx": 195664, "project": "hermes", "commit_id": "fe52854cdf6725c2eaa9e125995da76e6ceb27da", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da", "commit_message": "[CVE-2020-1911] Look up HostObject computed properties on the right object in the prototype chain.\n\nSummary:\nThe change in the hermes repository fixes the security vulnerability\nCVE-2020-1911. This vulnerability only affects applications which\nallow evaluation of uncontrolled, untrusted JavaScript code not\nshipped with the app, so React Native apps will generally not be affected.\n\nThis revision includes a test for the bug. The test is generic JSI\ncode, so it is included in the hermes and react-native repositories.\n\nChangelog: [Internal]\n\nReviewed By: tmikov\n\nDifferential Revision: D23322992\n\nfbshipit-source-id: 4e88c974afe1ad33a263f9cac03e9dc98d33649a", "target": 1, "func": "CallResult> JSObject::getComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> receiver) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return it.\n PseudoHandle<> ourValue = createPseudoHandle(\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex));\n if (LLVM_LIKELY(!ourValue->isEmpty()))\n return ourValue;\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n if (!propObj)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n if (desc.flags.accessor) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n auto propRes = vmcast(selfHandle.get())->get(id);\n if (propRes == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return createPseudoHandle(*propRes);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::getComputed(propObj, runtime, *key, receiver);\n }\n}", "func_hash": 134944455041353102507225738173774547558, "file_name": "JSObject.cpp", "file_hash": 141228325056694021860942262927204985220, "cwe": ["CWE-125"], "cve": "CVE-2020-1911", "cve_desc": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1911"} {"idx": 230182, "project": "hermes", "commit_id": "fe52854cdf6725c2eaa9e125995da76e6ceb27da", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da", "commit_message": "[CVE-2020-1911] Look up HostObject computed properties on the right object in the prototype chain.\n\nSummary:\nThe change in the hermes repository fixes the security vulnerability\nCVE-2020-1911. This vulnerability only affects applications which\nallow evaluation of uncontrolled, untrusted JavaScript code not\nshipped with the app, so React Native apps will generally not be affected.\n\nThis revision includes a test for the bug. The test is generic JSI\ncode, so it is included in the hermes and react-native repositories.\n\nChangelog: [Internal]\n\nReviewed By: tmikov\n\nDifferential Revision: D23322992\n\nfbshipit-source-id: 4e88c974afe1ad33a263f9cac03e9dc98d33649a", "target": 0, "func": "CallResult> JSObject::getComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> receiver) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return it.\n PseudoHandle<> ourValue = createPseudoHandle(\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex));\n if (LLVM_LIKELY(!ourValue->isEmpty()))\n return ourValue;\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n if (!propObj)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n if (desc.flags.accessor) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n auto propRes = vmcast(propObj.get())->get(id);\n if (propRes == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return createPseudoHandle(*propRes);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::getComputed(propObj, runtime, *key, receiver);\n }\n}", "func_hash": 61064786264698092535168356727202825049, "file_name": "JSObject.cpp", "file_hash": 313398634736354939038310130415553970557, "cwe": ["CWE-125"], "cve": "CVE-2020-1911", "cve_desc": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1911"} {"idx": 195679, "project": "gpac", "commit_id": "e74be5976a6fee059c638050a237893f7e9a3b23", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/e74be5976a6fee059c638050a237893f7e9a3b23", "commit_message": "fixed #1753", "target": 1, "func": "GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;\n\tint i;\n\tu32 tmp_strsize;\n\tchar *tmp_str;\n\tBool zfound=GF_FALSE;\n\tGF_Err e;\n\n\tISOM_DECREASE_SIZE(ptr, 25)\n\tptr->bootstrapinfo_version = gf_bs_read_u32(bs);\n\tptr->profile = gf_bs_read_int(bs, 2);\n\tptr->live = gf_bs_read_int(bs, 1);\n\tptr->update = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 4);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\tptr->current_media_time = gf_bs_read_u64(bs);\n\tptr->smpte_time_code_offset = gf_bs_read_u64(bs);\n\n\ti=0;\n\tif (ptr->size<8) return GF_ISOM_INVALID_FILE;\n\ttmp_strsize =(u32)ptr->size;\n\ttmp_str = gf_malloc(sizeof(char)*tmp_strsize);\n\tif (!tmp_str) return GF_OUT_OF_MEM;\n\tmemset(tmp_str, 0, sizeof(char)*tmp_strsize);\n\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound)\n\t\treturn GF_ISOM_INVALID_FILE;\n\tif (i) {\n\t\tptr->movie_identifier = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->server_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iserver_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\tif (!zfound)\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->quality_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iquality_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\n\t\tif (!zfound)\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound)\n\t\treturn GF_ISOM_INVALID_FILE;\n\tif (i) {\n\t\tptr->drm_data = gf_strdup(tmp_str);\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound)\n\t\treturn GF_ISOM_INVALID_FILE;\n\tif (i) {\n\t\tptr->meta_data = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->segment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; isegment_run_table_count; i++) {\n\t\tGF_AdobeSegmentRunTableBox *asrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&asrt, bs);\n\t\tif (e) {\n\t\t\tif (asrt) gf_isom_box_del((GF_Box*)asrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->segment_run_table_entries, asrt);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->fragment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; ifragment_run_table_count; i++) {\n\t\tGF_AdobeFragmentRunTableBox *afrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&afrt, bs);\n\t\tif (e) {\n\t\t\tif (afrt) gf_isom_box_del((GF_Box*)afrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->fragment_run_table_entries, afrt);\n\t}\n\n\tgf_free(tmp_str);\n\n\treturn GF_OK;\n}", "func_hash": 145982444001010334957896971013304902640, "file_name": "box_code_adobe.c", "file_hash": 336891594641295561052709505822469576706, "cwe": ["CWE-476"], "cve": "CVE-2021-32132", "cve_desc": "The abst_box_size function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32132"} {"idx": 230580, "project": "gpac", "commit_id": "e74be5976a6fee059c638050a237893f7e9a3b23", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/e74be5976a6fee059c638050a237893f7e9a3b23", "commit_message": "fixed #1753", "target": 0, "func": "GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;\n\tint i;\n\tu32 tmp_strsize;\n\tchar *tmp_str;\n\tBool zfound=GF_FALSE;\n\tGF_Err e = GF_OK;\n\n\tISOM_DECREASE_SIZE(ptr, 25)\n\tptr->bootstrapinfo_version = gf_bs_read_u32(bs);\n\tptr->profile = gf_bs_read_int(bs, 2);\n\tptr->live = gf_bs_read_int(bs, 1);\n\tptr->update = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 4);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\tptr->current_media_time = gf_bs_read_u64(bs);\n\tptr->smpte_time_code_offset = gf_bs_read_u64(bs);\n\n\ti=0;\n\tif (ptr->size<8) return GF_ISOM_INVALID_FILE;\n\ttmp_strsize =(u32)ptr->size;\n\ttmp_str = gf_malloc(sizeof(char)*tmp_strsize);\n\tif (!tmp_str) return GF_OUT_OF_MEM;\n\tmemset(tmp_str, 0, sizeof(char)*tmp_strsize);\n\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\tif (i) {\n\t\tptr->movie_identifier = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->server_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iserver_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\tif (!zfound) {\n\t\t\te = GF_ISOM_INVALID_FILE;\n\t\t\tgoto exit;\n\t\t}\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\tif (ptr->server_entry_count != gf_list_count(ptr->server_entry_table)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->quality_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iquality_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\n\t\tif (!zfound) {\n\t\t\te = GF_ISOM_INVALID_FILE;\n\t\t\tgoto exit;\n\t\t}\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\tif (ptr->quality_entry_count != gf_list_count(ptr->quality_entry_table)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tif (i) {\n\t\tptr->drm_data = gf_strdup(tmp_str);\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tif (i) {\n\t\tptr->meta_data = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->segment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; isegment_run_table_count; i++) {\n\t\tGF_AdobeSegmentRunTableBox *asrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&asrt, bs);\n\t\tif (e) {\n\t\t\tif (asrt) gf_isom_box_del((GF_Box*)asrt);\n\t\t\tgoto exit;\n\t\t}\n\t\tgf_list_add(ptr->segment_run_table_entries, asrt);\n\t}\n\tif (ptr->segment_run_table_count != gf_list_count(ptr->segment_run_table_entries)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->fragment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; ifragment_run_table_count; i++) {\n\t\tGF_AdobeFragmentRunTableBox *afrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&afrt, bs);\n\t\tif (e) {\n\t\t\tif (afrt) gf_isom_box_del((GF_Box*)afrt);\n\t\t\tgoto exit;\n\t\t}\n\t\tgf_list_add(ptr->fragment_run_table_entries, afrt);\n\t}\n\tif (ptr->fragment_run_table_count != gf_list_count(ptr->fragment_run_table_entries)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\nexit:\n\tgf_free(tmp_str);\n\treturn e;\n}", "func_hash": 254435704674613253928330117090177689062, "file_name": "box_code_adobe.c", "file_hash": 171065027599064831276505048522260563365, "cwe": ["CWE-476"], "cve": "CVE-2021-32132", "cve_desc": "The abst_box_size function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32132"} {"idx": 195680, "project": "sqlite", "commit_id": "d1d43efa4fb0f2098c0e2c5bf2e807c58d5ec05b", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/d1d43efa4fb0f2098c0e2c5bf2e807c58d5ec05b", "commit_message": "Prevent fts5 tokenizer unicode61 from considering '\\0' to be a token characters, even if other characters of class \"Cc\" are.\n\nFossilOrigin-Name: b7b7bde9b7a03665e3691c6d51118965f216d2dfb1617f138b9f9e60e418ed2f", "target": 1, "func": "void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){\n int i = 0;\n int iTbl = 0;\n while( i<128 ){\n int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];\n int n = (aFts5UnicodeData[iTbl] >> 5) + i;\n for(; i<128 && i> 5) + i;\n for(; i<128 && i(sizeof(int32_t));\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_create_wait_queue\",\n 2);\n int32_t *queue = reinterpret_cast(output.next());\n int klinux_errno = output.next();\n if (queue == nullptr) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n }\n enc_untrusted_disable_waiting(queue);\n return queue;\n}", "func_hash": 321139250050019627755973874307735895479, "file_name": "concurrency.cc", "file_hash": 101646655188072928637890612144395472284, "cwe": ["CWE-787"], "cve": "CVE-2020-8937", "cve_desc": "An arbitrary memory overwrite vulnerability in Asylo versions up to 0.6.0 allows an attacker to make a host call to enc_untrusted_create_wait_queue that uses a pointer queue that relies on UntrustedLocalMemcpy, which fails to validate where the pointer is located. This allows an attacker to write memory values from within the enclave. We recommend upgrading past commit a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8937"} {"idx": 231074, "project": "asylo", "commit_id": "a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "commit_message": "Check untrusted queue is in outside enclave\n\nPiperOrigin-RevId: 333370935\nChange-Id: Ic3f15d5db1302d95c7cb199b44172474fecb81ca", "target": 0, "func": "int32_t *enc_untrusted_create_wait_queue() {\n MessageWriter input;\n MessageReader output;\n input.Push(sizeof(int32_t));\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_create_wait_queue\",\n 2);\n int32_t *queue = reinterpret_cast(output.next());\n if (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {\n TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_create_wait_queue: queue should be in untrusted memory\");\n }\n int klinux_errno = output.next();\n if (queue == nullptr) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n }\n enc_untrusted_disable_waiting(queue);\n return queue;\n}", "func_hash": 202891016846715318548961317598270526556, "file_name": "concurrency.cc", "file_hash": 331268857578070434275493364889372506093, "cwe": ["CWE-787"], "cve": "CVE-2020-8937", "cve_desc": "An arbitrary memory overwrite vulnerability in Asylo versions up to 0.6.0 allows an attacker to make a host call to enc_untrusted_create_wait_queue that uses a pointer queue that relies on UntrustedLocalMemcpy, which fails to validate where the pointer is located. This allows an attacker to write memory values from within the enclave. We recommend upgrading past commit a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8937"} {"idx": 195717, "project": "znc", "commit_id": "d229761821da38d984a9e4098ad96842490dc001", "project_url": "https://github.com/znc/znc", "commit_url": "https://github.com/znc/znc/commit/d229761821da38d984a9e4098ad96842490dc001", "commit_message": "Fix echo-message for *status\n\nClose #1705", "target": 1, "func": "bool CClient::OnTextMessage(CTextMessage& Message) {\n CString sTargets = Message.GetTarget();\n\n VCString vTargets;\n sTargets.Split(\",\", vTargets, false);\n\n for (CString& sTarget : vTargets) {\n Message.SetTarget(sTarget);\n if (m_pNetwork) {\n // May be nullptr.\n Message.SetChan(m_pNetwork->FindChan(sTarget));\n }\n\n if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {\n if (sTarget.Equals(\"status\")) {\n CString sMsg = Message.GetText();\n UserCommand(sMsg);\n } else {\n CALLMOD(sTarget, this, m_pUser, m_pNetwork,\n OnModCommand(Message.GetText()));\n }\n continue;\n }\n\n bool bContinue = false;\n NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,\n &bContinue);\n if (bContinue) continue;\n\n if (!GetIRCSock()) {\n // Some lagmeters do a PRIVMSG to their own nick, ignore those.\n if (!sTarget.Equals(m_sNick))\n PutStatus(\n t_f(\"Your message to {1} got lost, you are not connected \"\n \"to IRC!\")(Message.GetTarget()));\n continue;\n }\n\n if (m_pNetwork) {\n AddBuffer(Message);\n EchoMessage(Message);\n PutIRC(Message.ToString(CMessage::ExcludePrefix |\n CMessage::ExcludeTags));\n }\n }\n\n return true;\n}", "func_hash": 232384283134032566279923809505761358676, "file_name": "Client.cpp", "file_hash": 222230044302101519694734473074797602668, "cwe": ["CWE-476"], "cve": "CVE-2020-13775", "cve_desc": "ZNC 1.8.0 up to 1.8.1-rc1 allows authenticated users to trigger an application crash (with a NULL pointer dereference) if echo-message is not enabled and there is no network.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13775"} {"idx": 231582, "project": "znc", "commit_id": "d229761821da38d984a9e4098ad96842490dc001", "project_url": "https://github.com/znc/znc", "commit_url": "https://github.com/znc/znc/commit/d229761821da38d984a9e4098ad96842490dc001", "commit_message": "Fix echo-message for *status\n\nClose #1705", "target": 0, "func": "bool CClient::OnTextMessage(CTextMessage& Message) {\n CString sTargets = Message.GetTarget();\n\n VCString vTargets;\n sTargets.Split(\",\", vTargets, false);\n\n for (CString& sTarget : vTargets) {\n Message.SetTarget(sTarget);\n if (m_pNetwork) {\n // May be nullptr.\n Message.SetChan(m_pNetwork->FindChan(sTarget));\n }\n\n if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {\n EchoMessage(Message);\n\n if (sTarget.Equals(\"status\")) {\n CString sMsg = Message.GetText();\n UserCommand(sMsg);\n } else {\n CALLMOD(sTarget, this, m_pUser, m_pNetwork,\n OnModCommand(Message.GetText()));\n }\n continue;\n }\n\n bool bContinue = false;\n NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,\n &bContinue);\n if (bContinue) continue;\n\n if (!GetIRCSock()) {\n // Some lagmeters do a PRIVMSG to their own nick, ignore those.\n if (!sTarget.Equals(m_sNick))\n PutStatus(\n t_f(\"Your message to {1} got lost, you are not connected \"\n \"to IRC!\")(Message.GetTarget()));\n continue;\n }\n\n if (m_pNetwork) {\n AddBuffer(Message);\n EchoMessage(Message);\n PutIRC(Message.ToString(CMessage::ExcludePrefix |\n CMessage::ExcludeTags));\n }\n }\n\n return true;\n}", "func_hash": 235707861974033394560550673811043529161, "file_name": "Client.cpp", "file_hash": 99064157913385303033419643985333647670, "cwe": ["CWE-476"], "cve": "CVE-2020-13775", "cve_desc": "ZNC 1.8.0 up to 1.8.1-rc1 allows authenticated users to trigger an application crash (with a NULL pointer dereference) if echo-message is not enabled and there is no network.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13775"} {"idx": 195719, "project": "gpac", "commit_id": "328def7d3b93847d64ecb6e9e0399684e57c3eca", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/328def7d3b93847d64ecb6e9e0399684e57c3eca", "commit_message": "fixed #1766 (fuzz)", "target": 1, "func": "GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n{\n\n\tGF_DataEntryURLBox *entry;\n\tGF_DataMap *map;\n\tGF_Err e;\n\tif (!mdia || !dataEntryIndex || dataEntryIndex > gf_list_count(mdia->information->dataInformation->dref->child_boxes)) return GF_BAD_PARAM;\n\n\tentry = (GF_DataEntryURLBox*)gf_list_get(mdia->information->dataInformation->dref->child_boxes, dataEntryIndex - 1);\n\tif (!entry) return GF_ISOM_INVALID_FILE;\n\tif (entry->flags == 1) return GF_OK;\n\n\t//ok, not self contained, let's go for it...\n\t//we don't know what's a URN yet\n\tif (entry->type == GF_ISOM_BOX_TYPE_URN) return GF_NOT_SUPPORTED;\n\tif (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) {\n\t\te = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map);\n\t} else {\n\t\te = gf_isom_datamap_new(entry->location, mdia->mediaTrack->moov->mov->fileName, GF_ISOM_DATA_MAP_READ, &map);\n\t}\n\tif (e) return e;\n\tgf_isom_datamap_del(map);\n\treturn GF_OK;\n}", "func_hash": 104680146375696834221793645961764450131, "file_name": "media.c", "file_hash": 229120145651367727707019056428777606332, "cwe": ["CWE-787"], "cve": "CVE-2021-32137", "cve_desc": "Heap buffer overflow in the URL_GetProtocolType function in MP4Box in GPAC 1.0.1 allows attackers to cause a denial of service or execute arbitrary code via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32137"} {"idx": 231612, "project": "gpac", "commit_id": "328def7d3b93847d64ecb6e9e0399684e57c3eca", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/328def7d3b93847d64ecb6e9e0399684e57c3eca", "commit_message": "fixed #1766 (fuzz)", "target": 0, "func": "GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n{\n\tGF_DataEntryURLBox *entry;\n\tGF_DataMap *map;\n\tGF_Err e;\n\tif (!mdia || !dataEntryIndex || dataEntryIndex > gf_list_count(mdia->information->dataInformation->dref->child_boxes)) return GF_BAD_PARAM;\n\n\tentry = (GF_DataEntryURLBox*)gf_list_get(mdia->information->dataInformation->dref->child_boxes, dataEntryIndex - 1);\n\tif (!entry) return GF_ISOM_INVALID_FILE;\n\tif (entry->flags == 1) return GF_OK;\n\n\t//ok, not self contained, let's go for it...\n\t//we only support alias and URL boxes\n\tif ((entry->type != GF_ISOM_BOX_TYPE_URL) && (entry->type != GF_QT_BOX_TYPE_ALIS) )\n\t\treturn GF_NOT_SUPPORTED;\n\n\tif (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) {\n\t\te = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map);\n\t} else {\n\t\te = gf_isom_datamap_new(entry->location, mdia->mediaTrack->moov->mov->fileName, GF_ISOM_DATA_MAP_READ, &map);\n\t}\n\tif (e) return e;\n\tgf_isom_datamap_del(map);\n\treturn GF_OK;\n}", "func_hash": 137559700086627375950727413326113028509, "file_name": "media.c", "file_hash": 335136212064795241837127636851600580089, "cwe": ["CWE-787"], "cve": "CVE-2021-32137", "cve_desc": "Heap buffer overflow in the URL_GetProtocolType function in MP4Box in GPAC 1.0.1 allows attackers to cause a denial of service or execute arbitrary code via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32137"} {"idx": 195727, "project": "radare2", "commit_id": "cb8b683758edddae2d2f62e8e63a738c39f92683", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/cb8b683758edddae2d2f62e8e63a738c39f92683", "commit_message": "Fix #16303 - c->table_query double free (#16318)", "target": 1, "func": "R_API void r_core_fini(RCore *c) {\n\tif (!c) {\n\t\treturn;\n\t}\n\tr_core_task_break_all (&c->tasks);\n\tr_core_task_join (&c->tasks, NULL, -1);\n\tr_core_wait (c);\n\t/* TODO: it leaks as shit */\n\t//update_sdb (c);\n\t// avoid double free\n\tr_list_free (c->ropchain);\n\tr_event_free (c->ev);\n\tfree (c->cmdlog);\n\tfree (c->lastsearch);\n\tR_FREE (c->cons->pager);\n\tfree (c->cmdqueue);\n\tfree (c->lastcmd);\n\tfree (c->stkcmd);\n\tr_list_free (c->visual.tabs);\n\tfree (c->block);\n\tr_core_autocomplete_free (c->autocomplete);\n\n\tr_list_free (c->gadgets);\n\tr_list_free (c->undos);\n\tr_num_free (c->num);\n\t// TODO: sync or not? sdb_sync (c->sdb);\n\t// TODO: sync all dbs?\n\t//r_core_file_free (c->file);\n\t//c->file = NULL;\n\tfree (c->table_query);\n\tr_list_free (c->files);\n\tr_list_free (c->watchers);\n\tr_list_free (c->scriptstack);\n\tr_core_task_scheduler_fini (&c->tasks);\n\tc->rcmd = r_cmd_free (c->rcmd);\n\tr_list_free (c->cmd_descriptors);\n\tc->anal = r_anal_free (c->anal);\n\tr_asm_free (c->assembler);\n\tc->assembler = NULL;\n\tc->print = r_print_free (c->print);\n\tc->bin = (r_bin_free (c->bin), NULL);\n\tc->lang = (r_lang_free (c->lang), NULL);\n\tc->dbg = (r_debug_free (c->dbg), NULL);\n\tr_io_free (c->io);\n\tr_config_free (c->config);\n\t/* after r_config_free, the value of I.teefile is trashed */\n\t/* rconfig doesnt knows how to deinitialize vars, so we\n\tshould probably need to add a r_config_free_payload callback */\n\tr_cons_free ();\n\tr_cons_singleton ()->teefile = NULL; // HACK\n\tr_search_free (c->search);\n\tr_flag_free (c->flags);\n\tr_fs_free (c->fs);\n\tr_egg_free (c->egg);\n\tr_lib_free (c->lib);\n\tr_buf_free (c->yank_buf);\n\tr_agraph_free (c->graph);\n\tfree (c->asmqjmps);\n\tsdb_free (c->sdb);\n\tr_core_log_free (c->log);\n\tr_parse_free (c->parser);\n\tfree (c->times);\n}", "func_hash": 232638784798389304601427809897539323057, "file_name": "core.c", "file_hash": 72831698883468812438171259794281816832, "cwe": ["CWE-703"], "cve": "CVE-2020-27794", "cve_desc": "A double free issue was discovered in radare2 in cmd_info.c:cmd_info(). Successful exploitation could lead to modification of unexpected memory locations and potentially causing a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27794"} {"idx": 232153, "project": "radare2", "commit_id": "cb8b683758edddae2d2f62e8e63a738c39f92683", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/cb8b683758edddae2d2f62e8e63a738c39f92683", "commit_message": "Fix #16303 - c->table_query double free (#16318)", "target": 0, "func": "R_API void r_core_fini(RCore *c) {\n\tif (!c) {\n\t\treturn;\n\t}\n\tr_core_task_break_all (&c->tasks);\n\tr_core_task_join (&c->tasks, NULL, -1);\n\tr_core_wait (c);\n\t/* TODO: it leaks as shit */\n\t//update_sdb (c);\n\t// avoid double free\n\tr_list_free (c->ropchain);\n\tr_event_free (c->ev);\n\tfree (c->cmdlog);\n\tfree (c->lastsearch);\n\tR_FREE (c->cons->pager);\n\tfree (c->cmdqueue);\n\tfree (c->lastcmd);\n\tfree (c->stkcmd);\n\tr_list_free (c->visual.tabs);\n\tfree (c->block);\n\tr_core_autocomplete_free (c->autocomplete);\n\n\tr_list_free (c->gadgets);\n\tr_list_free (c->undos);\n\tr_num_free (c->num);\n\t// TODO: sync or not? sdb_sync (c->sdb);\n\t// TODO: sync all dbs?\n\t//r_core_file_free (c->file);\n\t//c->file = NULL;\n\tR_FREE (c->table_query);\n\tr_list_free (c->files);\n\tr_list_free (c->watchers);\n\tr_list_free (c->scriptstack);\n\tr_core_task_scheduler_fini (&c->tasks);\n\tc->rcmd = r_cmd_free (c->rcmd);\n\tr_list_free (c->cmd_descriptors);\n\tc->anal = r_anal_free (c->anal);\n\tr_asm_free (c->assembler);\n\tc->assembler = NULL;\n\tc->print = r_print_free (c->print);\n\tc->bin = (r_bin_free (c->bin), NULL);\n\tc->lang = (r_lang_free (c->lang), NULL);\n\tc->dbg = (r_debug_free (c->dbg), NULL);\n\tr_io_free (c->io);\n\tr_config_free (c->config);\n\t/* after r_config_free, the value of I.teefile is trashed */\n\t/* rconfig doesnt knows how to deinitialize vars, so we\n\tshould probably need to add a r_config_free_payload callback */\n\tr_cons_free ();\n\tr_cons_singleton ()->teefile = NULL; // HACK\n\tr_search_free (c->search);\n\tr_flag_free (c->flags);\n\tr_fs_free (c->fs);\n\tr_egg_free (c->egg);\n\tr_lib_free (c->lib);\n\tr_buf_free (c->yank_buf);\n\tr_agraph_free (c->graph);\n\tfree (c->asmqjmps);\n\tsdb_free (c->sdb);\n\tr_core_log_free (c->log);\n\tr_parse_free (c->parser);\n\tfree (c->times);\n}", "func_hash": 187957792462091275484171135720464463100, "file_name": "core.c", "file_hash": 68801096486314909650938410377725370677, "cwe": ["CWE-703"], "cve": "CVE-2020-27794", "cve_desc": "A double free issue was discovered in radare2 in cmd_info.c:cmd_info(). Successful exploitation could lead to modification of unexpected memory locations and potentially causing a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27794"} {"idx": 195747, "project": "tensorflow", "commit_id": "f851613f8f0fb0c838d160ced13c134f778e3ce7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f851613f8f0fb0c838d160ced13c134f778e3ce7", "commit_message": "Fix heap buffer overflow caused by rounding.\n\nThis was hard to fix. Due to the way we compute the pixels that influence an output pixel in resized images, for certain input configuration we might have issued a read to a pixel that is outside of boundary of the original image. This is because of floating errors that affected truncation results.\n\nPiperOrigin-RevId: 369757871\nChange-Id: If89425fff930983829a2168203c11858883eebc9", "target": 1, "func": "inline void ComputeInterpolationWeights(\n const int64 out_size, const int64 in_size, const float scale,\n const int resolution, InterpolationCache* interpolation) {\n const Scaler scaler;\n interpolation->lower.resize(out_size + 1);\n interpolation->upper.resize(out_size + 1);\n interpolation->lerp.resize(out_size + 1);\n interpolation->ilerp.resize(out_size + 1);\n\n interpolation->lower[out_size] = 0;\n interpolation->upper[out_size] = 0;\n for (int64 i = out_size - 1; i >= 0; --i) {\n const float in = scaler(i, scale);\n const float in_f = std::floor(in);\n interpolation->lower[i] =\n std::max(static_cast(in_f), static_cast(0));\n interpolation->upper[i] =\n std::min(static_cast(std::ceil(in)), in_size - 1);\n interpolation->lerp[i] = in - in_f;\n interpolation->ilerp[i] =\n static_cast((in - in_f) * (1 << resolution));\n }\n}", "func_hash": 199494613959710923477058431484252066334, "file_name": "quantized_resize_bilinear_op.cc", "file_hash": 193155769702860773247480925816393199754, "cwe": ["CWE-369"], "cve": "CVE-2021-29529", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a heap buffer overflow in `tf.raw_ops.QuantizedResizeBilinear` by manipulating input values so that float rounding results in off-by-one error in accessing image elements. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/44b7f486c0143f68b56c34e2d01e146ee445134a/tensorflow/core/kernels/quantized_resize_bilinear_op.cc#L62-L66) computes two integers (representing the upper and lower bounds for interpolation) by ceiling and flooring a floating point value. For some values of `in`, `interpolation->upper[i]` might be smaller than `interpolation->lower[i]`. This is an issue if `interpolation->upper[i]` is capped at `in_size-1` as it means that `interpolation->lower[i]` points outside of the image. Then, in the interpolation code(https://github.com/tensorflow/tensorflow/blob/44b7f486c0143f68b56c34e2d01e146ee445134a/tensorflow/core/kernels/quantized_resize_bilinear_op.cc#L245-L264), this would result in heap buffer overflow. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29529"} {"idx": 232376, "project": "tensorflow", "commit_id": "f851613f8f0fb0c838d160ced13c134f778e3ce7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f851613f8f0fb0c838d160ced13c134f778e3ce7", "commit_message": "Fix heap buffer overflow caused by rounding.\n\nThis was hard to fix. Due to the way we compute the pixels that influence an output pixel in resized images, for certain input configuration we might have issued a read to a pixel that is outside of boundary of the original image. This is because of floating errors that affected truncation results.\n\nPiperOrigin-RevId: 369757871\nChange-Id: If89425fff930983829a2168203c11858883eebc9", "target": 0, "func": "inline void ComputeInterpolationWeights(\n const int64 out_size, const int64 in_size, const float scale,\n const int resolution, InterpolationCache* interpolation) {\n const Scaler scaler;\n interpolation->lower.resize(out_size + 1);\n interpolation->upper.resize(out_size + 1);\n interpolation->lerp.resize(out_size + 1);\n interpolation->ilerp.resize(out_size + 1);\n\n interpolation->lower[out_size] = 0;\n interpolation->upper[out_size] = 0;\n for (int64 i = out_size - 1; i >= 0; --i) {\n const float in = scaler(i, scale);\n const float in_f = std::floor(in);\n interpolation->lower[i] =\n std::max(static_cast(in_f), static_cast(0));\n interpolation->upper[i] =\n std::min(static_cast(std::ceil(in)), in_size - 1);\n interpolation->lower[i] =\n std::min(interpolation->lower[i], interpolation->upper[i]);\n interpolation->lerp[i] = in - in_f;\n interpolation->ilerp[i] =\n static_cast((in - in_f) * (1 << resolution));\n }\n}", "func_hash": 109394558633497281262382694809408606063, "file_name": "quantized_resize_bilinear_op.cc", "file_hash": 207987506164343488757189036768001101755, "cwe": ["CWE-369"], "cve": "CVE-2021-29529", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a heap buffer overflow in `tf.raw_ops.QuantizedResizeBilinear` by manipulating input values so that float rounding results in off-by-one error in accessing image elements. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/44b7f486c0143f68b56c34e2d01e146ee445134a/tensorflow/core/kernels/quantized_resize_bilinear_op.cc#L62-L66) computes two integers (representing the upper and lower bounds for interpolation) by ceiling and flooring a floating point value. For some values of `in`, `interpolation->upper[i]` might be smaller than `interpolation->lower[i]`. This is an issue if `interpolation->upper[i]` is capped at `in_size-1` as it means that `interpolation->lower[i]` points outside of the image. Then, in the interpolation code(https://github.com/tensorflow/tensorflow/blob/44b7f486c0143f68b56c34e2d01e146ee445134a/tensorflow/core/kernels/quantized_resize_bilinear_op.cc#L245-L264), this would result in heap buffer overflow. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29529"} {"idx": 195754, "project": "tensorflow", "commit_id": "0ab290774f91a23bebe30a358fde4e53ab4876a0", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0ab290774f91a23bebe30a358fde4e53ab4876a0", "commit_message": "Ensure validation sticks in banded_triangular_solve_op\n\nPiperOrigin-RevId: 373275480\nChange-Id: Id7717cf275b2d6fdb9441fbbe166d555182d2e79", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& in0 = ctx->input(0);\n const Tensor& in1 = ctx->input(1);\n\n ValidateInputTensors(ctx, in0, in1);\n\n MatMulBCast bcast(in0.shape().dim_sizes(), in1.shape().dim_sizes());\n OP_REQUIRES(\n ctx, bcast.IsValid(),\n errors::InvalidArgument(\n \"In[0] and In[1] must have compatible batch dimensions: \",\n in0.shape().DebugString(), \" vs. \", in1.shape().DebugString()));\n\n TensorShape out_shape = bcast.output_batch_shape();\n auto batch_size = bcast.output_batch_size();\n auto d0 = in0.dim_size(in0.dims() - 2); // Band size.\n auto d1 = in0.dim_size(in0.dims() - 1);\n Tensor in0_reshaped;\n OP_REQUIRES(\n ctx,\n in0_reshaped.CopyFrom(in0, TensorShape({bcast.x_batch_size(), d0, d1})),\n errors::Internal(\"Failed to reshape In[0] from \",\n in0.shape().DebugString()));\n auto d2 = in1.dim_size(in1.dims() - 2);\n auto d3 = in1.dim_size(in1.dims() - 1);\n Tensor in1_reshaped;\n OP_REQUIRES(\n ctx,\n in1_reshaped.CopyFrom(in1, TensorShape({bcast.y_batch_size(), d2, d3})),\n errors::Internal(\"Failed to reshape In[1] from \",\n in1.shape().DebugString()));\n OP_REQUIRES(ctx, d1 == d2,\n errors::InvalidArgument(\n \"In[0] mismatch In[1] shape: \", d1, \" vs. \", d2, \": \",\n in0.shape().DebugString(), \" \", in1.shape().DebugString(),\n \" \", lower_, \" \", adjoint_));\n out_shape.AddDim(d1);\n out_shape.AddDim(d3);\n Tensor* out = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));\n if (out->NumElements() == 0) {\n return;\n }\n Tensor out_reshaped;\n OP_REQUIRES(ctx,\n out_reshaped.CopyFrom(*out, TensorShape({batch_size, d1, d3})),\n errors::Internal(\"Failed to reshape output from \",\n out->shape().DebugString()));\n LaunchBatchBandedTriangularSolve::Launch(\n ctx, in0_reshaped, in1_reshaped, adjoint_, lower_, bcast,\n &out_reshaped);\n }", "func_hash": 26087441008873390615001446022081926061, "file_name": "banded_triangular_solve_op.cc", "file_hash": 129902469995516118053406884500316657482, "cwe": ["CWE-787"], "cve": "CVE-2021-29612", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a heap buffer overflow in Eigen implementation of `tf.raw_ops.BandedTriangularSolve`. The implementation(https://github.com/tensorflow/tensorflow/blob/eccb7ec454e6617738554a255d77f08e60ee0808/tensorflow/core/kernels/linalg/banded_triangular_solve_op.cc#L269-L278) calls `ValidateInputTensors` for input validation but fails to validate that the two tensors are not empty. Furthermore, since `OP_REQUIRES` macro only stops execution of current function after setting `ctx->status()` to a non-OK value, callers of helper functions that use `OP_REQUIRES` must check value of `ctx->status()` before continuing. This doesn't happen in this op's implementation(https://github.com/tensorflow/tensorflow/blob/eccb7ec454e6617738554a255d77f08e60ee0808/tensorflow/core/kernels/linalg/banded_triangular_solve_op.cc#L219), hence the validation that is present is also not effective. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29612"} {"idx": 232648, "project": "tensorflow", "commit_id": "0ab290774f91a23bebe30a358fde4e53ab4876a0", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0ab290774f91a23bebe30a358fde4e53ab4876a0", "commit_message": "Ensure validation sticks in banded_triangular_solve_op\n\nPiperOrigin-RevId: 373275480\nChange-Id: Id7717cf275b2d6fdb9441fbbe166d555182d2e79", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& in0 = ctx->input(0);\n const Tensor& in1 = ctx->input(1);\n\n ValidateInputTensors(ctx, in0, in1);\n if (!ctx->status().ok()) return;\n\n MatMulBCast bcast(in0.shape().dim_sizes(), in1.shape().dim_sizes());\n OP_REQUIRES(\n ctx, bcast.IsValid(),\n errors::InvalidArgument(\n \"In[0] and In[1] must have compatible batch dimensions: \",\n in0.shape().DebugString(), \" vs. \", in1.shape().DebugString()));\n\n TensorShape out_shape = bcast.output_batch_shape();\n auto batch_size = bcast.output_batch_size();\n auto d0 = in0.dim_size(in0.dims() - 2); // Band size.\n auto d1 = in0.dim_size(in0.dims() - 1);\n Tensor in0_reshaped;\n OP_REQUIRES(\n ctx,\n in0_reshaped.CopyFrom(in0, TensorShape({bcast.x_batch_size(), d0, d1})),\n errors::Internal(\"Failed to reshape In[0] from \",\n in0.shape().DebugString()));\n auto d2 = in1.dim_size(in1.dims() - 2);\n auto d3 = in1.dim_size(in1.dims() - 1);\n Tensor in1_reshaped;\n OP_REQUIRES(\n ctx,\n in1_reshaped.CopyFrom(in1, TensorShape({bcast.y_batch_size(), d2, d3})),\n errors::Internal(\"Failed to reshape In[1] from \",\n in1.shape().DebugString()));\n OP_REQUIRES(ctx, d1 == d2,\n errors::InvalidArgument(\n \"In[0] mismatch In[1] shape: \", d1, \" vs. \", d2, \": \",\n in0.shape().DebugString(), \" \", in1.shape().DebugString(),\n \" \", lower_, \" \", adjoint_));\n out_shape.AddDim(d1);\n out_shape.AddDim(d3);\n Tensor* out = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));\n if (out->NumElements() == 0) {\n return;\n }\n Tensor out_reshaped;\n OP_REQUIRES(ctx,\n out_reshaped.CopyFrom(*out, TensorShape({batch_size, d1, d3})),\n errors::Internal(\"Failed to reshape output from \",\n out->shape().DebugString()));\n LaunchBatchBandedTriangularSolve::Launch(\n ctx, in0_reshaped, in1_reshaped, adjoint_, lower_, bcast,\n &out_reshaped);\n }", "func_hash": 129209172420096772371263993804412563590, "file_name": "banded_triangular_solve_op.cc", "file_hash": 94453818838766291386903631468275951111, "cwe": ["CWE-787"], "cve": "CVE-2021-29612", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a heap buffer overflow in Eigen implementation of `tf.raw_ops.BandedTriangularSolve`. The implementation(https://github.com/tensorflow/tensorflow/blob/eccb7ec454e6617738554a255d77f08e60ee0808/tensorflow/core/kernels/linalg/banded_triangular_solve_op.cc#L269-L278) calls `ValidateInputTensors` for input validation but fails to validate that the two tensors are not empty. Furthermore, since `OP_REQUIRES` macro only stops execution of current function after setting `ctx->status()` to a non-OK value, callers of helper functions that use `OP_REQUIRES` must check value of `ctx->status()` before continuing. This doesn't happen in this op's implementation(https://github.com/tensorflow/tensorflow/blob/eccb7ec454e6617738554a255d77f08e60ee0808/tensorflow/core/kernels/linalg/banded_triangular_solve_op.cc#L219), hence the validation that is present is also not effective. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29612"} {"idx": 195755, "project": "tensorflow", "commit_id": "030af767d357d1b4088c4a25c72cb3906abac489", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/030af767d357d1b4088c4a25c72cb3906abac489", "commit_message": "Fix `tf.raw_ops.ResourceCountUpTo` null pointer dereference.\n\nPiperOrigin-RevId: 368294347\nChange-Id: I2c16fbfc9b4966c402c3d8e311f0d665a9c852d8", "target": 1, "func": "Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,\n TF_DataType* out_tf_datatype) {\n PyObject* key;\n PyObject* value;\n Py_ssize_t pos = 0;\n if (PyDict_Next(descr->fields, &pos, &key, &value)) {\n // In Python 3, the keys of numpy custom struct types are unicode, unlike\n // Python 2, where the keys are bytes.\n const char* key_string =\n PyBytes_Check(key) ? PyBytes_AsString(key)\n : PyBytes_AsString(PyUnicode_AsASCIIString(key));\n if (!key_string) {\n return errors::Internal(\"Corrupt numpy type descriptor\");\n }\n tensorflow::string key = key_string;\n // The typenames here should match the field names in the custom struct\n // types constructed in test_util.py.\n // TODO(mrry,keveman): Investigate Numpy type registration to replace this\n // hard-coding of names.\n if (key == \"quint8\") {\n *out_tf_datatype = TF_QUINT8;\n } else if (key == \"qint8\") {\n *out_tf_datatype = TF_QINT8;\n } else if (key == \"qint16\") {\n *out_tf_datatype = TF_QINT16;\n } else if (key == \"quint16\") {\n *out_tf_datatype = TF_QUINT16;\n } else if (key == \"qint32\") {\n *out_tf_datatype = TF_QINT32;\n } else if (key == \"resource\") {\n *out_tf_datatype = TF_RESOURCE;\n } else {\n return errors::Internal(\"Unsupported numpy data type\");\n }\n return Status::OK();\n }\n return errors::Internal(\"Unsupported numpy data type\");\n}", "func_hash": 17996250235540502107269859138822230500, "file_name": "ndarray_tensor.cc", "file_hash": 221667263635400902606075155620670700681, "cwe": ["CWE-476"], "cve": "CVE-2021-29513", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Calling TF operations with tensors of non-numeric types when the operations expect numeric tensors result in null pointer dereferences. The conversion from Python array to C++ array(https://github.com/tensorflow/tensorflow/blob/ff70c47a396ef1e3cb73c90513da4f5cb71bebba/tensorflow/python/lib/core/ndarray_tensor.cc#L113-L169) is vulnerable to a type confusion. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29513"} {"idx": 232661, "project": "tensorflow", "commit_id": "030af767d357d1b4088c4a25c72cb3906abac489", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/030af767d357d1b4088c4a25c72cb3906abac489", "commit_message": "Fix `tf.raw_ops.ResourceCountUpTo` null pointer dereference.\n\nPiperOrigin-RevId: 368294347\nChange-Id: I2c16fbfc9b4966c402c3d8e311f0d665a9c852d8", "target": 0, "func": "Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,\n TF_DataType* out_tf_datatype) {\n PyObject* key;\n PyObject* value;\n Py_ssize_t pos = 0;\n\n // Return an error if the fields attribute is null.\n // Occurs with an improper conversion attempt to resource.\n if (descr->fields == nullptr) {\n return errors::Internal(\"Unexpected numpy data type\");\n }\n\n if (PyDict_Next(descr->fields, &pos, &key, &value)) {\n // In Python 3, the keys of numpy custom struct types are unicode, unlike\n // Python 2, where the keys are bytes.\n const char* key_string =\n PyBytes_Check(key) ? PyBytes_AsString(key)\n : PyBytes_AsString(PyUnicode_AsASCIIString(key));\n if (!key_string) {\n return errors::Internal(\"Corrupt numpy type descriptor\");\n }\n tensorflow::string key = key_string;\n // The typenames here should match the field names in the custom struct\n // types constructed in test_util.py.\n // TODO(mrry,keveman): Investigate Numpy type registration to replace this\n // hard-coding of names.\n if (key == \"quint8\") {\n *out_tf_datatype = TF_QUINT8;\n } else if (key == \"qint8\") {\n *out_tf_datatype = TF_QINT8;\n } else if (key == \"qint16\") {\n *out_tf_datatype = TF_QINT16;\n } else if (key == \"quint16\") {\n *out_tf_datatype = TF_QUINT16;\n } else if (key == \"qint32\") {\n *out_tf_datatype = TF_QINT32;\n } else if (key == \"resource\") {\n *out_tf_datatype = TF_RESOURCE;\n } else {\n return errors::Internal(\"Unsupported numpy data type\");\n }\n return Status::OK();\n }\n return errors::Internal(\"Unsupported numpy data type\");\n}", "func_hash": 88095966287032090335113257933180254176, "file_name": "ndarray_tensor.cc", "file_hash": 129591898093676470814698556918431542538, "cwe": ["CWE-476"], "cve": "CVE-2021-29513", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Calling TF operations with tensors of non-numeric types when the operations expect numeric tensors result in null pointer dereferences. The conversion from Python array to C++ array(https://github.com/tensorflow/tensorflow/blob/ff70c47a396ef1e3cb73c90513da4f5cb71bebba/tensorflow/python/lib/core/ndarray_tensor.cc#L113-L169) is vulnerable to a type confusion. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29513"} {"idx": 195776, "project": "acrn-hypervisor", "commit_id": "154fe59531c12b82e26d1b24b5531f5066d224f5", "project_url": "https://github.com/projectacrn/acrn-hypervisor", "commit_url": "https://github.com/projectacrn/acrn-hypervisor/commit/154fe59531c12b82e26d1b24b5531f5066d224f5", "commit_message": "dm: validate inputs in vq_endchains\n\n inputs shall be validated to avoid NULL pointer access.\n\nTracked-On: #6129\nSigned-off-by: Yonghua Huang ", "target": 1, "func": "vq_endchains(struct virtio_vq_info *vq, int used_all_avail)\n{\n\tstruct virtio_base *base;\n\tuint16_t event_idx, new_idx, old_idx;\n\tint intr;\n\n\t/*\n\t * Interrupt generation: if we're using EVENT_IDX,\n\t * interrupt if we've crossed the event threshold.\n\t * Otherwise interrupt is generated if we added \"used\" entries,\n\t * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.\n\t *\n\t * In any case, though, if NOTIFY_ON_EMPTY is set and the\n\t * entire avail was processed, we need to interrupt always.\n\t */\n\n\tatomic_thread_fence();\n\n\tbase = vq->base;\n\told_idx = vq->save_used;\n\tvq->save_used = new_idx = vq->used->idx;\n\tif (used_all_avail &&\n\t (base->negotiated_caps & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)))\n\t\tintr = 1;\n\telse if (base->negotiated_caps & (1 << VIRTIO_RING_F_EVENT_IDX)) {\n\t\tevent_idx = VQ_USED_EVENT_IDX(vq);\n\t\t/*\n\t\t * This calculation is per docs and the kernel\n\t\t * (see src/sys/dev/virtio/virtio_ring.h).\n\t\t */\n\t\tintr = (uint16_t)(new_idx - event_idx - 1) <\n\t\t\t(uint16_t)(new_idx - old_idx);\n\t} else {\n\t\tintr = new_idx != old_idx &&\n\t\t !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT);\n\t}\n\tif (intr)\n\t\tvq_interrupt(base, vq);\n}", "func_hash": 145906155484775800202965763344486526858, "file_name": "virtio.c", "file_hash": 96041167325874263830524674390847691199, "cwe": ["CWE-476"], "cve": "CVE-2021-36143", "cve_desc": "ACRN before 2.5 has a hw/pci/virtio/virtio.c vq_endchains NULL Pointer Dereference.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36143"} {"idx": 232979, "project": "acrn-hypervisor", "commit_id": "154fe59531c12b82e26d1b24b5531f5066d224f5", "project_url": "https://github.com/projectacrn/acrn-hypervisor", "commit_url": "https://github.com/projectacrn/acrn-hypervisor/commit/154fe59531c12b82e26d1b24b5531f5066d224f5", "commit_message": "dm: validate inputs in vq_endchains\n\n inputs shall be validated to avoid NULL pointer access.\n\nTracked-On: #6129\nSigned-off-by: Yonghua Huang ", "target": 0, "func": "vq_endchains(struct virtio_vq_info *vq, int used_all_avail)\n{\n\tstruct virtio_base *base;\n\tuint16_t event_idx, new_idx, old_idx;\n\tint intr;\n\n\tif (!vq || !vq->used)\n\t\treturn;\n\n\t/*\n\t * Interrupt generation: if we're using EVENT_IDX,\n\t * interrupt if we've crossed the event threshold.\n\t * Otherwise interrupt is generated if we added \"used\" entries,\n\t * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.\n\t *\n\t * In any case, though, if NOTIFY_ON_EMPTY is set and the\n\t * entire avail was processed, we need to interrupt always.\n\t */\n\n\tatomic_thread_fence();\n\n\tbase = vq->base;\n\told_idx = vq->save_used;\n\tvq->save_used = new_idx = vq->used->idx;\n\tif (used_all_avail &&\n\t (base->negotiated_caps & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)))\n\t\tintr = 1;\n\telse if (base->negotiated_caps & (1 << VIRTIO_RING_F_EVENT_IDX)) {\n\t\tevent_idx = VQ_USED_EVENT_IDX(vq);\n\t\t/*\n\t\t * This calculation is per docs and the kernel\n\t\t * (see src/sys/dev/virtio/virtio_ring.h).\n\t\t */\n\t\tintr = (uint16_t)(new_idx - event_idx - 1) <\n\t\t\t(uint16_t)(new_idx - old_idx);\n\t} else {\n\t\tintr = new_idx != old_idx &&\n\t\t !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT);\n\t}\n\tif (intr)\n\t\tvq_interrupt(base, vq);\n}", "func_hash": 89016246858790171127280744136865149595, "file_name": "virtio.c", "file_hash": 214244704212250010103437641366859496331, "cwe": ["CWE-476"], "cve": "CVE-2021-36143", "cve_desc": "ACRN before 2.5 has a hw/pci/virtio/virtio.c vq_endchains NULL Pointer Dereference.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36143"} {"idx": 195778, "project": "tensorflow", "commit_id": "25d622ffc432acc736b14ca3904177579e733cc6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/25d622ffc432acc736b14ca3904177579e733cc6", "commit_message": "A negative size in one of the split sizes allowed the computed size of another\nto exceed the total dimension, leading to a segfault and security vulnerability.\nAdding a check for negative sizes prevents this.\n\nPiperOrigin-RevId: 401035665\nChange-Id: I79bbe329787dac82aa4bf60397a9129b716aedab", "target": 1, "func": " void ComputeEasyCases(OpKernelContext* context, bool* done,\n std::vector* split_sizes_vec) {\n const int32_t num_split = context->num_outputs();\n const Tensor& input = context->input(0);\n const TensorShape& input_shape = input.shape();\n const Tensor& split_tensor = context->input(1);\n const Tensor& split_dim_tensor = context->input(2);\n\n OP_REQUIRES(context, split_dim_tensor.NumElements() == 1,\n errors::InvalidArgument(\"split_dim_tensor must have \"\n \"exactly one element.\"));\n\n const int32_t split_dim_orig = split_dim_tensor.flat()(0);\n const int32_t split_dim =\n split_dim_orig < 0 ? split_dim_orig + input.dims() : split_dim_orig;\n\n OP_REQUIRES(\n context,\n split_tensor.dims() == 1 && split_tensor.NumElements() == num_split,\n errors::InvalidArgument(\"size of the split_tensor must be 1-D and have \"\n \"the same elements as outputs got \",\n split_tensor.dims(), \" -D and \",\n split_tensor.NumElements(), \" elements\"));\n\n auto split_sizes_d = split_tensor.vec();\n\n split_sizes_vec->resize(split_sizes_d.size());\n\n std::copy(split_sizes_d.data(), split_sizes_d.data() + split_sizes_d.size(),\n split_sizes_vec->begin());\n\n OP_REQUIRES(\n context, num_split > 0,\n errors::InvalidArgument(\n \"Number of ways to split should be > 0, but got \", num_split));\n\n OP_REQUIRES(\n context, 0 <= split_dim && split_dim < input.dims(),\n errors::InvalidArgument(\"-input rank(-\", input.dims(),\n \") <= split_dim < input rank (\", input.dims(),\n \"), but got \", split_dim_orig));\n\n Tlen input_size_split_dim = input_shape.dim_size(split_dim);\n\n // Special case 1: num_split == 1. Nothing to do.\n if (num_split == 1) {\n context->set_output(0, context->input(0));\n OP_REQUIRES(\n context, (*split_sizes_vec)[0] == input_size_split_dim,\n errors::InvalidArgument(\"If there is only one output, it must have \"\n \"the same size as the input. Input size: \",\n input_size_split_dim,\n \" output size: \", (*split_sizes_vec)[0]));\n *done = true;\n return;\n }\n\n // Determine sizes of output, in case of a -1 input value\n int neg_one_dim = -1;\n Tlen determined_size = 0;\n for (int d = 0; d < split_sizes_vec->size(); ++d) {\n Tlen size = (*split_sizes_vec)[d];\n\n if (size == -1) {\n OP_REQUIRES(context, neg_one_dim == -1,\n errors::InvalidArgument(\"There can only be one -1 in the \"\n \"input.\"));\n neg_one_dim = d;\n } else {\n determined_size += size;\n }\n }\n\n OP_REQUIRES(\n context,\n (neg_one_dim == -1 && determined_size == input_size_split_dim) ||\n (neg_one_dim >= 0 && determined_size <= input_size_split_dim),\n errors::InvalidArgument(\"Determined shape must either match \"\n \"input shape along split_dim exactly if \"\n \"fully specified, or be less than the size of \"\n \"the input along split_dim if not fully \"\n \"specified. Got: \",\n determined_size));\n\n if (neg_one_dim >= 0) {\n (*split_sizes_vec)[neg_one_dim] = input_size_split_dim - determined_size;\n }\n\n // Special case 2: split along the 1st dimension. The requirements are that\n // either we are splitting the outer dimension of two or more such that\n // every outer subpart is aligned or that the split sizes mean that they are\n // always aligned. In these cases, we can share the underlying buffer.\n //\n // Apply this optimization conservatively: if input is aligned,\n // the resulting tensors must be aligned. It's conservative\n // because if the immediate consumer of the resulting tensors are\n // not using eigen for computation, its perfectly fine to avoid\n // the copying.\n if (SplitHasAlignedOutputsInFirstDimension(\n input_shape, split_dim, absl::MakeConstSpan(*split_sizes_vec))) {\n Tlen start = 0;\n for (int i = 0; i < num_split; ++i) {\n context->set_output(i,\n input.Slice(start, start + (*split_sizes_vec)[i]));\n start += (*split_sizes_vec)[i];\n }\n *done = true;\n return;\n }\n }", "func_hash": 65274731625410516112180803336857872025, "file_name": "split_v_op.cc", "file_hash": 94633507960884437276304869001559199296, "cwe": ["CWE-703"], "cve": "CVE-2021-41222", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the implementation of `SplitV` can trigger a segfault is an attacker supplies negative arguments. This occurs whenever `size_splits` contains more than one value and at least one value is negative. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41222"} {"idx": 233116, "project": "tensorflow", "commit_id": "25d622ffc432acc736b14ca3904177579e733cc6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/25d622ffc432acc736b14ca3904177579e733cc6", "commit_message": "A negative size in one of the split sizes allowed the computed size of another\nto exceed the total dimension, leading to a segfault and security vulnerability.\nAdding a check for negative sizes prevents this.\n\nPiperOrigin-RevId: 401035665\nChange-Id: I79bbe329787dac82aa4bf60397a9129b716aedab", "target": 0, "func": " void ComputeEasyCases(OpKernelContext* context, bool* done,\n std::vector* split_sizes_vec) {\n const int32_t num_split = context->num_outputs();\n const Tensor& input = context->input(0);\n const TensorShape& input_shape = input.shape();\n const Tensor& split_tensor = context->input(1);\n const Tensor& split_dim_tensor = context->input(2);\n\n OP_REQUIRES(context, split_dim_tensor.NumElements() == 1,\n errors::InvalidArgument(\"split_dim_tensor must have \"\n \"exactly one element.\"));\n\n const int32_t split_dim_orig = split_dim_tensor.flat()(0);\n const int32_t split_dim =\n split_dim_orig < 0 ? split_dim_orig + input.dims() : split_dim_orig;\n\n OP_REQUIRES(\n context,\n split_tensor.dims() == 1 && split_tensor.NumElements() == num_split,\n errors::InvalidArgument(\"size of the split_tensor must be 1-D and have \"\n \"the same elements as outputs got \",\n split_tensor.dims(), \" -D and \",\n split_tensor.NumElements(), \" elements\"));\n\n auto split_sizes_d = split_tensor.vec();\n\n split_sizes_vec->resize(split_sizes_d.size());\n\n std::copy(split_sizes_d.data(), split_sizes_d.data() + split_sizes_d.size(),\n split_sizes_vec->begin());\n\n OP_REQUIRES(\n context, num_split > 0,\n errors::InvalidArgument(\n \"Number of ways to split should be > 0, but got \", num_split));\n\n OP_REQUIRES(\n context, 0 <= split_dim && split_dim < input.dims(),\n errors::InvalidArgument(\"-input rank(-\", input.dims(),\n \") <= split_dim < input rank (\", input.dims(),\n \"), but got \", split_dim_orig));\n\n Tlen input_size_split_dim = input_shape.dim_size(split_dim);\n\n // Special case 1: num_split == 1. Nothing to do.\n if (num_split == 1) {\n context->set_output(0, context->input(0));\n OP_REQUIRES(\n context, (*split_sizes_vec)[0] == input_size_split_dim,\n errors::InvalidArgument(\"If there is only one output, it must have \"\n \"the same size as the input. Input size: \",\n input_size_split_dim,\n \" output size: \", (*split_sizes_vec)[0]));\n *done = true;\n return;\n }\n\n // Determine sizes of output, in case of a -1 input value\n int neg_one_dim = -1;\n Tlen determined_size = 0;\n for (int d = 0; d < split_sizes_vec->size(); ++d) {\n Tlen size = (*split_sizes_vec)[d];\n\n if (size == -1) {\n OP_REQUIRES(context, neg_one_dim == -1,\n errors::InvalidArgument(\"There can only be one -1 in the \"\n \"input.\"));\n neg_one_dim = d;\n } else {\n determined_size += size;\n }\n }\n\n OP_REQUIRES(\n context,\n (neg_one_dim == -1 && determined_size == input_size_split_dim) ||\n (neg_one_dim >= 0 && determined_size <= input_size_split_dim),\n errors::InvalidArgument(\"Determined shape must either match \"\n \"input shape along split_dim exactly if \"\n \"fully specified, or be less than the size of \"\n \"the input along split_dim if not fully \"\n \"specified. Got: \",\n determined_size));\n\n if (neg_one_dim >= 0) {\n (*split_sizes_vec)[neg_one_dim] = input_size_split_dim - determined_size;\n }\n\n for (int i = 0; i < split_sizes_vec->size(); ++i) {\n const Tlen& split_size = (*split_sizes_vec)[i];\n OP_REQUIRES(context, split_size >= Tlen(0),\n errors::InvalidArgument(\"Split size at index \", i,\n \" must be >= 0. Got: \", split_size));\n }\n\n // Special case 2: split along the 1st dimension. The requirements are that\n // either we are splitting the outer dimension of two or more such that\n // every outer subpart is aligned or that the split sizes mean that they are\n // always aligned. In these cases, we can share the underlying buffer.\n //\n // Apply this optimization conservatively: if input is aligned,\n // the resulting tensors must be aligned. It's conservative\n // because if the immediate consumer of the resulting tensors are\n // not using eigen for computation, its perfectly fine to avoid\n // the copying.\n if (SplitHasAlignedOutputsInFirstDimension(\n input_shape, split_dim, absl::MakeConstSpan(*split_sizes_vec))) {\n Tlen start = 0;\n for (int i = 0; i < num_split; ++i) {\n context->set_output(i,\n input.Slice(start, start + (*split_sizes_vec)[i]));\n start += (*split_sizes_vec)[i];\n }\n *done = true;\n return;\n }\n }", "func_hash": 226440837382964323795189024608704610307, "file_name": "split_v_op.cc", "file_hash": 282853662170008674931628126697158658327, "cwe": ["CWE-703"], "cve": "CVE-2021-41222", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the implementation of `SplitV` can trigger a segfault is an attacker supplies negative arguments. This occurs whenever `size_splits` contains more than one value and at least one value is negative. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41222"} {"idx": 195820, "project": "nDPI", "commit_id": "1ec621c85b9411cc611652fd57a892cfef478af3", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/1ec621c85b9411cc611652fd57a892cfef478af3", "commit_message": "Added further checks", "target": 1, "func": "int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct,\n\t\t\t struct ndpi_flow_struct *flow, uint32_t quic_version) {\n struct ndpi_packet_struct *packet = &flow->packet;\n union ja3_info ja3;\n u_int8_t invalid_ja3 = 0;\n u_int16_t tls_version, ja3_str_len;\n char ja3_str[JA3_STR_LEN];\n ndpi_MD5_CTX ctx;\n u_char md5_hash[16];\n int i;\n u_int16_t total_len;\n u_int8_t handshake_type;\n char buffer[64] = { '\\0' };\n int is_quic = (quic_version != 0);\n int is_dtls = packet->udp && (!is_quic);\n\n#ifdef DEBUG_TLS\n printf(\"TLS %s() called\\n\", __FUNCTION__);\n#endif\n\n memset(&ja3, 0, sizeof(ja3));\n\n handshake_type = packet->payload[0];\n total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3];\n\n if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0))\n return(0); /* Not found */\n\n total_len = packet->payload_packet_len;\n\n /* At least \"magic\" 3 bytes, null for string end, otherwise no need to waste cpu cycles */\n if(total_len > 4) {\n u_int16_t base_offset = (!is_dtls) ? 38 : 46;\n u_int16_t version_offset = (!is_dtls) ? 4 : 12;\n u_int16_t offset = (!is_dtls) ? 38 : 46, extension_len, j;\n u_int8_t session_id_len = 0;\n\n if((base_offset >= total_len) ||\n (version_offset + 1) >= total_len)\n return 0; /* Not found */\n\n session_id_len = packet->payload[base_offset];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [len: %u][handshake_type: %02X]\\n\", packet->payload_packet_len, handshake_type);\n#endif\n\n tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset]));\n\n if(handshake_type == 0x02 /* Server Hello */) {\n int i, rc;\n\n ja3.server.tls_handshake_version = tls_version;\n\n#ifdef DEBUG_TLS\n printf(\"TLS Server Hello [version: 0x%04X]\\n\", tls_version);\n#endif\n\n /*\n\tThe server hello decides about the TLS version of this flow\n\thttps://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3\n */\n if(packet->udp)\n\toffset += session_id_len + 1;\n else {\n\tif(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */)\n\t offset += session_id_len+1;\n }\n\n if((offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n ja3.server.num_cipher = 1, ja3.server.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset]));\n if((flow->protos.tls_quic_stun.tls_quic.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.server.cipher[0])) == 1)\n\tndpi_set_risk(flow, NDPI_TLS_WEAK_CIPHER);\n\n flow->protos.tls_quic_stun.tls_quic.server_cipher = ja3.server.cipher[0];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][session_id_len: %u][cipher: %04X]\\n\", session_id_len, ja3.server.cipher[0]);\n#endif\n\n offset += 2 + 1;\n\n if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n else\n\textension_len = 0;\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][extension_len: %u]\\n\", extension_len);\n#endif\n offset += 2;\n\n for(i=0; i packet->payload_packet_len) break;\n\n\textension_id = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2]));\n\n\tif(ja3.server.num_tls_extension < MAX_NUM_JA3)\n\t ja3.server.tls_extension[ja3.server.num_tls_extension++] = extension_id;\n\n#ifdef DEBUG_TLS\n\tprintf(\"TLS [server][extension_id: %u/0x%04X][len: %u]\\n\",\n\t extension_id, extension_id, extension_len);\n#endif\n\n\tif(extension_id == 43 /* supported versions */) {\n\t if(extension_len >= 2) {\n\t u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4]));\n\n#ifdef DEBUG_TLS\n\t printf(\"TLS [server] [TLS version: 0x%04X]\\n\", tls_version);\n#endif\n\n\t flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.server.tls_supported_version = tls_version;\n\t }\n\t} else if(extension_id == 16 /* application_layer_protocol_negotiation (ALPN) */) {\n\t u_int16_t s_offset = offset+4;\n\t u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t char alpn_str[256];\n\t u_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t s_offset += 2;\n\t tot_alpn_len += s_offset;\n\n\t while(s_offset < tot_alpn_len && s_offset < total_len) {\n\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t if((s_offset + alpn_len) <= tot_alpn_len) {\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t if(alpn_str_len > 0) {\n\t alpn_str[alpn_str_len] = ',';\n\t alpn_str_len++;\n\t }\n\n\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\t }\n\n\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } /* while */\n\n\t alpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn != NULL)\n\t tlsCheckUncommonALPN(flow);\n\n\t snprintf(ja3.server.alpn, sizeof(ja3.server.alpn), \"%s\", alpn_str);\n\n\t /* Replace , with - as in JA3 */\n\t for(i=0; ja3.server.alpn[i] != '\\0'; i++)\n\t if(ja3.server.alpn[i] == ',') ja3.server.alpn[i] = '-';\n\t} else if(extension_id == 11 /* ec_point_formats groups */) {\n\t u_int16_t s_offset = offset+4 + 1;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t if((s_offset+extension_len-1) <= total_len) {\n\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t if(ja3.server.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\tja3.server.elliptic_curve_point_format[ja3.server.num_elliptic_curve_point_format++] = s_group;\n\t else {\n\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Server TLS Invalid num elliptic %u\\n\", ja3.server.num_elliptic_curve_point_format);\n#endif\n\t }\n\t }\n\t } else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t }\n\t}\n\n\ti += 4 + extension_len, offset += 4 + extension_len;\n } /* for */\n\n ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), \"%u,\", ja3.server.tls_handshake_version);\n\n for(i=0; i 0) ? \"-\" : \"\", ja3.server.cipher[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc;\n\n /* ********** */\n\n for(i=0; i 0) ? \"-\" : \"\", ja3.server.tls_extension[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n if(ndpi_struct->enable_ja3_plus) {\n\tfor(i=0; i 0) ? \"-\" : \"\", ja3.server.elliptic_curve_point_format[i]);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t}\n\n\tif(ja3.server.alpn[0] != '\\0') {\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",%s\", ja3.server.alpn);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t}\n\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3+] Server: %s \\n\", ja3_str);\n#endif\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Server: %s \\n\", ja3_str);\n#endif\n }\n\n ndpi_MD5Init(&ctx);\n ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n ndpi_MD5Final(md5_hash, &ctx);\n\n for(i=0, j=0; i<16; i++) {\n\tint rc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_server[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_server)-j, \"%02x\", md5_hash[i]);\n\tif(rc <= 0) break; else j += rc;\n }\n\n#ifdef DEBUG_TLS\n printf(\"[JA3] Server: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_server);\n#endif\n } else if(handshake_type == 0x01 /* Client Hello */) {\n u_int16_t cipher_len, cipher_offset;\n u_int8_t cookie_len = 0;\n\n flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.client.tls_handshake_version = tls_version;\n if(flow->protos.tls_quic_stun.tls_quic.ssl_version < 0x0302) /* TLSv1.1 */\n\tndpi_set_risk(flow, NDPI_TLS_OBSOLETE_VERSION);\n\n if((session_id_len+base_offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n if(!is_dtls) {\n\tcipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8);\n\tcipher_offset = base_offset + session_id_len + 3;\n } else {\n\tcookie_len = packet->payload[base_offset+session_id_len+1];\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: DTLS cookie len %d\\n\", cookie_len);\n#endif\n\tif((session_id_len+base_offset+cookie_len+4) > packet->payload_packet_len)\n\t return(0); /* Not found */\n\tcipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+session_id_len+cookie_len+2]));\n\tcipher_offset = base_offset + session_id_len + cookie_len + 4;\n }\n\n#ifdef DEBUG_TLS\n printf(\"Client TLS [client cipher_len: %u][tls_version: 0x%04X]\\n\", cipher_len, tls_version);\n#endif\n\n if((cipher_offset+cipher_len) <= total_len) {\n\tu_int8_t safari_ciphers = 0, chrome_ciphers = 0;\n\n\tfor(i=0; ipayload[cipher_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [cipher suite: %u/0x%04X] [%d/%u]\\n\", ntohs(*id), ntohs(*id), i, cipher_len);\n#endif\n\t if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) {\n\t u_int16_t cipher_id = ntohs(*id);\n\t /*\n\t Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html]\n\t https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967\n\t */\n\n\t if(ja3.client.num_cipher < MAX_NUM_JA3)\n\t ja3.client.cipher[ja3.client.num_cipher++] = cipher_id;\n\t else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS Invalid cipher %u\\n\", ja3.client.num_cipher);\n#endif\n\t }\n\n\t switch(cipher_id) {\n\t case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++;\n\t break;\n\n\t case TLS_CIPHER_GREASE_RESERVED_0:\n\t case TLS_AES_128_GCM_SHA256:\n\t case TLS_AES_256_GCM_SHA384:\n\t case TLS_CHACHA20_POLY1305_SHA256:\n\t chrome_ciphers++;\n\t break;\n\n\t case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\n\t case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_RSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++, chrome_ciphers++;\n\t break;\n\t }\n\t }\n\n\t i += 2;\n\t} /* for */\n\n\tif(chrome_ciphers == 13)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 1;\n\telse if(safari_ciphers == 12)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 1;\n } else {\n\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS Invalid len %u vs %u\\n\", (cipher_offset+cipher_len), total_len);\n#endif\n }\n\n offset = base_offset + session_id_len + cookie_len + cipher_len + 2;\n offset += (!is_dtls) ? 1 : 2;\n\n if(offset < total_len) {\n\tu_int16_t compression_len;\n\tu_int16_t extensions_len;\n\n\tcompression_len = packet->payload[offset];\n\toffset++;\n\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS [compression_len: %u]\\n\", compression_len);\n#endif\n\n\t// offset += compression_len + 3;\n\toffset += compression_len;\n\n\tif(offset+1 < total_len) {\n\t extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\t offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extensions_len: %u]\\n\", extensions_len);\n#endif\n\n\t if((extensions_len+offset) <= total_len) {\n\t /* Move to the first extension\n\t Type is u_int to avoid possible overflow on extension_len addition */\n\t u_int extension_offset = 0;\n\t u_int32_t j;\n\n\t while(extension_offset < extensions_len &&\n\t\t offset+extension_offset+4 <= total_len) {\n\t u_int16_t extension_id, extension_len, extn_off = offset+extension_offset;\n\n\n\t extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n\t extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_id: %u][extension_len: %u]\\n\", extension_id, extension_len);\n#endif\n\n\t if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) {\n\t\t/* Skip GREASE */\n\n\t\tif(ja3.client.num_tls_extension < MAX_NUM_JA3)\n\t\t ja3.client.tls_extension[ja3.client.num_tls_extension++] = extension_id;\n\t\telse {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid extensions %u\\n\", ja3.client.num_tls_extension);\n#endif\n\t\t}\n\t }\n\n\t if(extension_id == 0 /* server name */) {\n\t\tu_int16_t len;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"[TLS] Extensions: found server name\\n\");\n#endif\n\t\tif((offset+extension_offset+4) < packet->payload_packet_len) {\n\n\t\t len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4];\n\t\t len = (u_int)ndpi_min(len, sizeof(buffer)-1);\n\n\t\t if((offset+extension_offset+5+len) <= packet->payload_packet_len) {\n\t\t strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len);\n\t\t buffer[len] = '\\0';\n\n\t\t cleanupServerName(buffer, sizeof(buffer));\n\n\t\t snprintf(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name,\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name),\n\t\t\t \"%s\", buffer);\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: [%s]\\n\", buffer);\n#endif\n\t\t if(!is_quic) {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t } else {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_QUIC, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t }\n\n\t\t if(ndpi_check_dga_name(ndpi_struct, flow,\n\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name, 1)) {\n\t\t char *sni = flow->protos.tls_quic_stun.tls_quic.client_requested_server_name;\n\t\t int len = strlen(sni);\n\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\n\t\t if((len >= 4)\n\t\t /* Check if it ends in .com or .net */\n\t\t && ((strcmp(&sni[len-4], \".com\") == 0) || (strcmp(&sni[len-4], \".net\") == 0))\n\t\t && (strncmp(sni, \"www.\", 4) == 0)) /* Not starting with www.... */\n\t\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TOR, NDPI_PROTOCOL_TLS);\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (NO DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\t\t }\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] Extensions server len too short: %u vs %u\\n\",\n\t\t\t offset+extension_offset+5+len,\n\t\t\t packet->payload_packet_len);\n#endif\n\t\t }\n\t\t}\n\t } else if(extension_id == 10 /* supported groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 2;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveGroups: len=%u]\\n\", extension_len);\n#endif\n\n\t\tif((s_offset+extension_len-2) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i]));\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurve: %u/0x%04X]\\n\", s_group, s_group);\n#endif\n\t\t if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) {\n\t\t /* Skip GREASE */\n\t\t if(ja3.client.num_elliptic_curve < MAX_NUM_JA3)\n\t\t\tja3.client.elliptic_curve[ja3.client.num_elliptic_curve++] = s_group;\n\t\t else {\n\t\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t\tprintf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve);\n#endif\n\t\t }\n\t\t }\n\n\t\t i += 2;\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", (s_offset+extension_len-1), total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 11 /* ec_point_formats groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 1;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t\tif((s_offset+extension_len-1) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t\t if(ja3.client.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\t ja3.client.elliptic_curve_point_format[ja3.client.num_elliptic_curve_point_format++] = s_group;\n\t\t else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve_point_format);\n#endif\n\t\t }\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 13 /* signature algorithms */) {\n\t\tu_int16_t s_offset = offset+extension_offset, safari_signature_algorithms = 0, chrome_signature_algorithms = 0;\n\t\tu_int16_t tot_signature_algorithms_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: block_len=%u/len=%u]\\n\", extension_len, tot_signature_algorithms_len);\n#endif\n\n\t\ts_offset += 2;\n\t\ttot_signature_algorithms_len = ndpi_min((sizeof(ja3.client.signature_algorithms) / 2) - 1, tot_signature_algorithms_len);\n\n#ifdef TLS_HANDLE_SIGNATURE_ALGORITMS\n\t\tflow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms = ndpi_min(tot_signature_algorithms_len / 2, MAX_NUM_TLS_SIGNATURE_ALGORITHMS);\n\n\t\tmemcpy(flow->protos.tls_quic_stun.tls_quic.client_signature_algorithms,\n\t\t &packet->payload[s_offset], 2 /* 16 bit */*flow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms);\n#endif\n\n\t\tfor(i=0; ipayload[s_offset+i]);\n\n\t\t if(rc < 0) break;\n\t\t}\n\n\t\tfor(i=0; ipayload[s_offset+i]));\n\n\t\t // printf(\"=>> %04X\\n\", cipher_id);\n\n\t\t switch(cipher_id) {\n\t\t case ECDSA_SECP521R1_SHA512:\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls = 1;\n\t\t break;\n\n\t\t case ECDSA_SECP256R1_SHA256:\n\t\t case ECDSA_SECP384R1_SHA384:\n\t\t case RSA_PKCS1_SHA256:\n\t\t case RSA_PKCS1_SHA384:\n\t\t case RSA_PKCS1_SHA512:\n\t\t case RSA_PSS_RSAE_SHA256:\n\t\t case RSA_PSS_RSAE_SHA384:\n\t\t case RSA_PSS_RSAE_SHA512:\n\t\t chrome_signature_algorithms++, safari_signature_algorithms++;\n\t\t break;\n\t\t }\n\t\t}\n\n\t\tif(flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0,\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tif(safari_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0;\n\n\t\tif(chrome_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tja3.client.signature_algorithms[i*2] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: %s]\\n\", ja3.client.signature_algorithms);\n#endif\n\t } else if(extension_id == 16 /* application_layer_protocol_negotiation */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\tchar alpn_str[256];\n\t\tu_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t\ts_offset += 2;\n\t\ttot_alpn_len += s_offset;\n\n\t\twhile(s_offset < tot_alpn_len && s_offset < total_len) {\n\t\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t\t if((s_offset + alpn_len) <= tot_alpn_len &&\n\t\t (s_offset + alpn_len) <= total_len) {\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t\t if(alpn_str_len > 0) {\n\t\t\talpn_str[alpn_str_len] = ',';\n\t\t\talpn_str_len++;\n\t\t }\n\n\t\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\n\t\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t\t } else\n\t\t break;\n\t\t } else\n\t\t break;\n\t\t} /* while */\n\n\t\talpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t\tif(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t\tsnprintf(ja3.client.alpn, sizeof(ja3.client.alpn), \"%s\", alpn_str);\n\n\t\t/* Replace , with - as in JA3 */\n\t\tfor(i=0; ja3.client.alpn[i] != '\\0'; i++)\n\t\t if(ja3.client.alpn[i] == ',') ja3.client.alpn[i] = '-';\n\n\t } else if(extension_id == 43 /* supported versions */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int8_t version_len = packet->payload[s_offset];\n\t\tchar version_str[256];\n\t\tu_int8_t version_str_len = 0;\n\t\tversion_str[0] = 0;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [TLS version len: %u]\\n\", version_len);\n#endif\n\n\t\tif(version_len == (extension_len-1)) {\n\t\t u_int8_t j;\n\t\t u_int16_t supported_versions_offset = 0;\n\n\t\t s_offset++;\n\n\t\t // careful not to overflow and loop forever with u_int8_t\n\t\t for(j=0; j+1payload[s_offset+j]));\n\t\t u_int8_t unknown_tls_version;\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [TLS version: %s/0x%04X]\\n\",\n\t\t\t ndpi_ssl_version2str(flow, tls_version, &unknown_tls_version), tls_version);\n#endif\n\n\t\t if((version_str_len+8) < sizeof(version_str)) {\n\t\t int rc = snprintf(&version_str[version_str_len],\n\t\t\t\t\tsizeof(version_str) - version_str_len, \"%s%s\",\n\t\t\t\t\t(version_str_len > 0) ? \",\" : \"\",\n\t\t\t\t\tndpi_ssl_version2str(flow, tls_version, &unknown_tls_version));\n\t\t if(rc <= 0)\n\t\t\tbreak;\n\t\t else\n\t\t\tversion_str_len += rc;\n\n\t\t rc = snprintf(&ja3.client.supported_versions[supported_versions_offset],\n\t\t\t\t sizeof(ja3.client.supported_versions)-supported_versions_offset,\n\t\t\t\t \"%s%04X\", (j > 0) ? \"-\" : \"\", tls_version);\n\n\t\t if(rc > 0)\n\t\t\tsupported_versions_offset += rc;\n\t\t }\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [SUPPORTED_VERSIONS: %s]\\n\", ja3.client.supported_versions);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.tls_supported_versions == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.tls_supported_versions = ndpi_strdup(version_str);\n\t\t}\n\t } else if(extension_id == 65486 /* encrypted server name */) {\n\t\t/*\n\t\t - https://tools.ietf.org/html/draft-ietf-tls-esni-06\n\t\t - https://blog.cloudflare.com/encrypted-sni/\n\t\t*/\n\t\tu_int16_t e_offset = offset+extension_offset;\n\t\tu_int16_t initial_offset = e_offset;\n\t\tu_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\n\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.cipher_suite = cipher_suite;\n\n\t\te_offset += 2; /* Cipher suite len */\n\n\t\t/* Key Share Entry */\n\t\te_offset += 2; /* Group */\n\t\te_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\tif((e_offset+4) < packet->payload_packet_len) {\n\t\t /* Record Digest */\n\t\t e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\t if((e_offset+4) < packet->payload_packet_len) {\n\t\t e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\t\t e_offset += 2;\n\n\t\t if((e_offset+e_sni_len-extension_len-initial_offset) >= 0 &&\n\t\t e_offset+e_sni_len < packet->payload_packet_len) {\n#ifdef DEBUG_ENCRYPTED_SNI\n\t\t printf(\"Client TLS [Encrypted Server Name len: %u]\\n\", e_sni_len);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) {\n\t\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1);\n\n\t\t\tif(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni) {\n\t\t\t u_int16_t i, off;\n\n\t\t\t for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) {\n\t\t\t int rc = sprintf(&flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off], \"%02X\", packet->payload[i] & 0XFF);\n\n\t\t\t if(rc <= 0) {\n\t\t\t flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off] = '\\0';\n\t\t\t break;\n\t\t\t } else\n\t\t\t off += rc;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t }\n\t\t }\n\t\t}\n\t } else if(extension_id == 65445 || /* QUIC transport parameters (drafts version) */\n\t\t extension_id == 57) { /* QUIC transport parameters (final version) */\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tuint16_t final_offset;\n\t\tint using_var_int = is_version_with_var_int_transport_params(quic_version);\n\n\t\tif(!using_var_int) {\n\t\t if(s_offset+1 >= total_len) {\n\t\t final_offset = 0; /* Force skipping extension */\n\t\t } else {\n\t\t u_int16_t seq_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t s_offset += 2;\n\t final_offset = MIN(total_len, s_offset + seq_len);\n\t\t }\n\t\t} else {\n\t final_offset = MIN(total_len, s_offset + extension_len);\n\t\t}\n\n\t\twhile(s_offset < final_offset) {\n\t\t u_int64_t param_type, param_len;\n\n if(!using_var_int) {\n\t\t if(s_offset+3 >= final_offset)\n\t\t break;\n\t\t param_type = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t param_len = ntohs(*((u_int16_t*)&packet->payload[s_offset + 2]));\n\t\t s_offset += 4;\n\t\t } else {\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_type);\n\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_len);\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [QUIC TP: Param 0x%x Len %d]\\n\", (int)param_type, (int)param_len);\n#endif\n\t\t if(s_offset+param_len > final_offset)\n\t\t break;\n\n\t\t if(param_type==0x3129) {\n#ifdef DEBUG_TLS\n\t\t printf(\"UA [%.*s]\\n\", (int)param_len, &packet->payload[s_offset]);\n#endif\n\t\t http_process_user_agent(ndpi_struct, flow,\n\t\t\t\t\t &packet->payload[s_offset], param_len);\n\t\t break;\n\t\t }\n\t\t s_offset += param_len;\n\t\t}\n\t }\n\n\t extension_offset += extension_len; /* Move to the next extension */\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_offset/len: %u/%u]\\n\", extension_offset, extension_len);\n#endif\n\t } /* while */\n\n\t if(!invalid_ja3) {\n\t int rc;\n\n\t compute_ja3c:\n\t ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), \"%u,\", ja3.client.tls_handshake_version);\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.cipher[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.tls_extension[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve_point_format[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t if(ndpi_struct->enable_ja3_plus) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len,\n\t\t\t \",%s,%s,%s\", ja3.client.signature_algorithms, ja3.client.supported_versions, ja3.client.alpn);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3+] Client: %s \\n\", ja3_str);\n#endif\n\n\t ndpi_MD5Init(&ctx);\n\t ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n\t ndpi_MD5Final(md5_hash, &ctx);\n\n\t for(i=0, j=0; i<16; i++) {\n\t\trc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_client[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_client)-j, \"%02x\",\n\t\t\t md5_hash[i]);\n\t\tif(rc > 0) j += rc; else break;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3] Client: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_client);\n#endif\n\n\t if(ndpi_struct->malicious_ja3_automa.ac_automa != NULL) {\n\t\tu_int16_t rc1 = ndpi_match_string(ndpi_struct->malicious_ja3_automa.ac_automa,\n\t\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.ja3_client);\n\n\t\tif(rc1 > 0)\n\t\t ndpi_set_risk(flow, NDPI_MALICIOUS_JA3);\n\t }\n\t }\n\n\t /* Before returning to the caller we need to make a final check */\n\t if((flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0303) /* >= TLSv1.2 */\n\t && (flow->protos.tls_quic_stun.tls_quic.alpn == NULL) /* No ALPN */) {\n\t ndpi_set_risk(flow, NDPI_TLS_NOT_CARRYING_HTTPS);\n\t }\n\n\t /* Suspicious Domain Fronting:\n\t https://github.com/SixGenInc/Noctilucent/blob/master/docs/ */\n\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni &&\n\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] != '\\0') {\n\t ndpi_set_risk(flow, NDPI_TLS_SUSPICIOUS_ESNI_USAGE);\n\t }\n\n\t /* Add check for missing SNI */\n\t if((flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] == 0)\n\t && (flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0302) /* TLSv1.1 */\n\t && (flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) /* No ESNI */\n\t ) {\n\t /* This is a bit suspicious */\n\t ndpi_set_risk(flow, NDPI_TLS_MISSING_SNI);\n\t }\n\n\t return(2 /* Client Certificate */);\n\t } else {\n#ifdef DEBUG_TLS\n\t printf(\"[TLS] Client: too short [%u vs %u]\\n\",\n\t\t (extensions_len+offset), total_len);\n#endif\n\t }\n\t} else if(offset == total_len) {\n\t /* TLS does not have extensions etc */\n\t goto compute_ja3c;\n\t}\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: invalid length detected\\n\");\n#endif\n }\n }\n }\n\n return(0); /* Not found */\n}", "func_hash": 51758344959309194709274963161140180419, "file_name": "tls.c", "file_hash": 315575182889663395258165823232661443239, "cwe": ["CWE-787"], "cve": "CVE-2021-36082", "cve_desc": "ntop nDPI 3.4 has a stack-based buffer overflow in processClientServerHello.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36082"} {"idx": 234082, "project": "nDPI", "commit_id": "1ec621c85b9411cc611652fd57a892cfef478af3", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/1ec621c85b9411cc611652fd57a892cfef478af3", "commit_message": "Added further checks", "target": 0, "func": "int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct,\n\t\t\t struct ndpi_flow_struct *flow, uint32_t quic_version) {\n struct ndpi_packet_struct *packet = &flow->packet;\n union ja3_info ja3;\n u_int8_t invalid_ja3 = 0;\n u_int16_t tls_version, ja3_str_len;\n char ja3_str[JA3_STR_LEN];\n ndpi_MD5_CTX ctx;\n u_char md5_hash[16];\n int i;\n u_int16_t total_len;\n u_int8_t handshake_type;\n char buffer[64] = { '\\0' };\n int is_quic = (quic_version != 0);\n int is_dtls = packet->udp && (!is_quic);\n\n#ifdef DEBUG_TLS\n printf(\"TLS %s() called\\n\", __FUNCTION__);\n#endif\n\n memset(&ja3, 0, sizeof(ja3));\n\n handshake_type = packet->payload[0];\n total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3];\n\n if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0))\n return(0); /* Not found */\n\n total_len = packet->payload_packet_len;\n\n /* At least \"magic\" 3 bytes, null for string end, otherwise no need to waste cpu cycles */\n if(total_len > 4) {\n u_int16_t base_offset = (!is_dtls) ? 38 : 46;\n u_int16_t version_offset = (!is_dtls) ? 4 : 12;\n u_int16_t offset = (!is_dtls) ? 38 : 46, extension_len, j;\n u_int8_t session_id_len = 0;\n\n if((base_offset >= total_len) ||\n (version_offset + 1) >= total_len)\n return 0; /* Not found */\n\n session_id_len = packet->payload[base_offset];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [len: %u][handshake_type: %02X]\\n\", packet->payload_packet_len, handshake_type);\n#endif\n\n tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset]));\n\n if(handshake_type == 0x02 /* Server Hello */) {\n int i, rc;\n\n ja3.server.tls_handshake_version = tls_version;\n\n#ifdef DEBUG_TLS\n printf(\"TLS Server Hello [version: 0x%04X]\\n\", tls_version);\n#endif\n\n /*\n\tThe server hello decides about the TLS version of this flow\n\thttps://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3\n */\n if(packet->udp)\n\toffset += session_id_len + 1;\n else {\n\tif(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */)\n\t offset += session_id_len+1;\n }\n\n if((offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n ja3.server.num_cipher = 1, ja3.server.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset]));\n if((flow->protos.tls_quic_stun.tls_quic.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.server.cipher[0])) == 1)\n\tndpi_set_risk(flow, NDPI_TLS_WEAK_CIPHER);\n\n flow->protos.tls_quic_stun.tls_quic.server_cipher = ja3.server.cipher[0];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][session_id_len: %u][cipher: %04X]\\n\", session_id_len, ja3.server.cipher[0]);\n#endif\n\n offset += 2 + 1;\n\n if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n else\n\textension_len = 0;\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][extension_len: %u]\\n\", extension_len);\n#endif\n offset += 2;\n\n for(i=0; i packet->payload_packet_len) break;\n\n\textension_id = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2]));\n\n\tif(ja3.server.num_tls_extension < MAX_NUM_JA3)\n\t ja3.server.tls_extension[ja3.server.num_tls_extension++] = extension_id;\n\n#ifdef DEBUG_TLS\n\tprintf(\"TLS [server][extension_id: %u/0x%04X][len: %u]\\n\",\n\t extension_id, extension_id, extension_len);\n#endif\n\n\tif(extension_id == 43 /* supported versions */) {\n\t if(extension_len >= 2) {\n\t u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4]));\n\n#ifdef DEBUG_TLS\n\t printf(\"TLS [server] [TLS version: 0x%04X]\\n\", tls_version);\n#endif\n\n\t flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.server.tls_supported_version = tls_version;\n\t }\n\t} else if(extension_id == 16 /* application_layer_protocol_negotiation (ALPN) */) {\n\t u_int16_t s_offset = offset+4;\n\t u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t char alpn_str[256];\n\t u_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t s_offset += 2;\n\t tot_alpn_len += s_offset;\n\n\t while(s_offset < tot_alpn_len && s_offset < total_len) {\n\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t if((s_offset + alpn_len) <= tot_alpn_len) {\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t if(alpn_str_len > 0) {\n\t alpn_str[alpn_str_len] = ',';\n\t alpn_str_len++;\n\t }\n\n\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\t }\n\n\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } /* while */\n\n\t alpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn != NULL)\n\t tlsCheckUncommonALPN(flow);\n\n\t snprintf(ja3.server.alpn, sizeof(ja3.server.alpn), \"%s\", alpn_str);\n\n\t /* Replace , with - as in JA3 */\n\t for(i=0; ja3.server.alpn[i] != '\\0'; i++)\n\t if(ja3.server.alpn[i] == ',') ja3.server.alpn[i] = '-';\n\t} else if(extension_id == 11 /* ec_point_formats groups */) {\n\t u_int16_t s_offset = offset+4 + 1;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t if((s_offset+extension_len-1) <= total_len) {\n\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t if(ja3.server.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\tja3.server.elliptic_curve_point_format[ja3.server.num_elliptic_curve_point_format++] = s_group;\n\t else {\n\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Server TLS Invalid num elliptic %u\\n\", ja3.server.num_elliptic_curve_point_format);\n#endif\n\t }\n\t }\n\t } else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t }\n\t}\n\n\ti += 4 + extension_len, offset += 4 + extension_len;\n } /* for */\n\n ja3_str_len = snprintf(ja3_str, JA3_STR_LEN, \"%u,\", ja3.server.tls_handshake_version);\n\n for(i=0; (i ja3_str_len); i++) {\n\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\", (i > 0) ? \"-\" : \"\", ja3.server.cipher[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n if(JA3_STR_LEN > ja3_str_len) {\n\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\tif(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc;\n }\n \n /* ********** */\n\n for(i=0; (i ja3_str_len); i++) {\n\tint rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\", (i > 0) ? \"-\" : \"\", ja3.server.tls_extension[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n if(ndpi_struct->enable_ja3_plus) {\n\tfor(i=0; (i ja3_str_len); i++) {\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\",\n\t\t\t(i > 0) ? \"-\" : \"\", ja3.server.elliptic_curve_point_format[i]);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t}\n\n\tif((ja3.server.alpn[0] != '\\0') && (JA3_STR_LEN > ja3_str_len)) {\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",%s\", ja3.server.alpn);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t}\n\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3+] Server: %s \\n\", ja3_str);\n#endif\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Server: %s \\n\", ja3_str);\n#endif\n }\n\n ndpi_MD5Init(&ctx);\n ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n ndpi_MD5Final(md5_hash, &ctx);\n\n for(i=0, j=0; i<16; i++) {\n\tint rc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_server[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_server)-j, \"%02x\", md5_hash[i]);\n\tif(rc <= 0) break; else j += rc;\n }\n\n#ifdef DEBUG_TLS\n printf(\"[JA3] Server: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_server);\n#endif\n } else if(handshake_type == 0x01 /* Client Hello */) {\n u_int16_t cipher_len, cipher_offset;\n u_int8_t cookie_len = 0;\n\n flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.client.tls_handshake_version = tls_version;\n if(flow->protos.tls_quic_stun.tls_quic.ssl_version < 0x0302) /* TLSv1.1 */\n\tndpi_set_risk(flow, NDPI_TLS_OBSOLETE_VERSION);\n\n if((session_id_len+base_offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n if(!is_dtls) {\n\tcipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8);\n\tcipher_offset = base_offset + session_id_len + 3;\n } else {\n\tcookie_len = packet->payload[base_offset+session_id_len+1];\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: DTLS cookie len %d\\n\", cookie_len);\n#endif\n\tif((session_id_len+base_offset+cookie_len+4) > packet->payload_packet_len)\n\t return(0); /* Not found */\n\tcipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+session_id_len+cookie_len+2]));\n\tcipher_offset = base_offset + session_id_len + cookie_len + 4;\n }\n\n#ifdef DEBUG_TLS\n printf(\"Client TLS [client cipher_len: %u][tls_version: 0x%04X]\\n\", cipher_len, tls_version);\n#endif\n\n if((cipher_offset+cipher_len) <= total_len) {\n\tu_int8_t safari_ciphers = 0, chrome_ciphers = 0;\n\n\tfor(i=0; ipayload[cipher_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [cipher suite: %u/0x%04X] [%d/%u]\\n\", ntohs(*id), ntohs(*id), i, cipher_len);\n#endif\n\t if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) {\n\t u_int16_t cipher_id = ntohs(*id);\n\t /*\n\t Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html]\n\t https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967\n\t */\n\n\t if(ja3.client.num_cipher < MAX_NUM_JA3)\n\t ja3.client.cipher[ja3.client.num_cipher++] = cipher_id;\n\t else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS Invalid cipher %u\\n\", ja3.client.num_cipher);\n#endif\n\t }\n\n\t switch(cipher_id) {\n\t case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++;\n\t break;\n\n\t case TLS_CIPHER_GREASE_RESERVED_0:\n\t case TLS_AES_128_GCM_SHA256:\n\t case TLS_AES_256_GCM_SHA384:\n\t case TLS_CHACHA20_POLY1305_SHA256:\n\t chrome_ciphers++;\n\t break;\n\n\t case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\n\t case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_RSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++, chrome_ciphers++;\n\t break;\n\t }\n\t }\n\n\t i += 2;\n\t} /* for */\n\n\tif(chrome_ciphers == 13)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 1;\n\telse if(safari_ciphers == 12)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 1;\n } else {\n\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS Invalid len %u vs %u\\n\", (cipher_offset+cipher_len), total_len);\n#endif\n }\n\n offset = base_offset + session_id_len + cookie_len + cipher_len + 2;\n offset += (!is_dtls) ? 1 : 2;\n\n if(offset < total_len) {\n\tu_int16_t compression_len;\n\tu_int16_t extensions_len;\n\n\tcompression_len = packet->payload[offset];\n\toffset++;\n\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS [compression_len: %u]\\n\", compression_len);\n#endif\n\n\t// offset += compression_len + 3;\n\toffset += compression_len;\n\n\tif(offset+1 < total_len) {\n\t extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\t offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extensions_len: %u]\\n\", extensions_len);\n#endif\n\n\t if((extensions_len+offset) <= total_len) {\n\t /* Move to the first extension\n\t Type is u_int to avoid possible overflow on extension_len addition */\n\t u_int extension_offset = 0;\n\t u_int32_t j;\n\n\t while(extension_offset < extensions_len &&\n\t\t offset+extension_offset+4 <= total_len) {\n\t u_int16_t extension_id, extension_len, extn_off = offset+extension_offset;\n\n\n\t extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n\t extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_id: %u][extension_len: %u]\\n\", extension_id, extension_len);\n#endif\n\n\t if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) {\n\t\t/* Skip GREASE */\n\n\t\tif(ja3.client.num_tls_extension < MAX_NUM_JA3)\n\t\t ja3.client.tls_extension[ja3.client.num_tls_extension++] = extension_id;\n\t\telse {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid extensions %u\\n\", ja3.client.num_tls_extension);\n#endif\n\t\t}\n\t }\n\n\t if(extension_id == 0 /* server name */) {\n\t\tu_int16_t len;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"[TLS] Extensions: found server name\\n\");\n#endif\n\t\tif((offset+extension_offset+4) < packet->payload_packet_len) {\n\n\t\t len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4];\n\t\t len = (u_int)ndpi_min(len, sizeof(buffer)-1);\n\n\t\t if((offset+extension_offset+5+len) <= packet->payload_packet_len) {\n\t\t strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len);\n\t\t buffer[len] = '\\0';\n\n\t\t cleanupServerName(buffer, sizeof(buffer));\n\n\t\t snprintf(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name,\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name),\n\t\t\t \"%s\", buffer);\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: [%s]\\n\", buffer);\n#endif\n\t\t if(!is_quic) {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t } else {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_QUIC, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t }\n\n\t\t if(ndpi_check_dga_name(ndpi_struct, flow,\n\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name, 1)) {\n\t\t char *sni = flow->protos.tls_quic_stun.tls_quic.client_requested_server_name;\n\t\t int len = strlen(sni);\n\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\n\t\t if((len >= 4)\n\t\t /* Check if it ends in .com or .net */\n\t\t && ((strcmp(&sni[len-4], \".com\") == 0) || (strcmp(&sni[len-4], \".net\") == 0))\n\t\t && (strncmp(sni, \"www.\", 4) == 0)) /* Not starting with www.... */\n\t\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TOR, NDPI_PROTOCOL_TLS);\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (NO DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\t\t }\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] Extensions server len too short: %u vs %u\\n\",\n\t\t\t offset+extension_offset+5+len,\n\t\t\t packet->payload_packet_len);\n#endif\n\t\t }\n\t\t}\n\t } else if(extension_id == 10 /* supported groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 2;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveGroups: len=%u]\\n\", extension_len);\n#endif\n\n\t\tif((s_offset+extension_len-2) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i]));\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurve: %u/0x%04X]\\n\", s_group, s_group);\n#endif\n\t\t if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) {\n\t\t /* Skip GREASE */\n\t\t if(ja3.client.num_elliptic_curve < MAX_NUM_JA3)\n\t\t\tja3.client.elliptic_curve[ja3.client.num_elliptic_curve++] = s_group;\n\t\t else {\n\t\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t\tprintf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve);\n#endif\n\t\t }\n\t\t }\n\n\t\t i += 2;\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", (s_offset+extension_len-1), total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 11 /* ec_point_formats groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 1;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t\tif((s_offset+extension_len-1) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t\t if(ja3.client.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\t ja3.client.elliptic_curve_point_format[ja3.client.num_elliptic_curve_point_format++] = s_group;\n\t\t else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve_point_format);\n#endif\n\t\t }\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 13 /* signature algorithms */) {\n\t\tu_int16_t s_offset = offset+extension_offset, safari_signature_algorithms = 0, chrome_signature_algorithms = 0;\n\t\tu_int16_t tot_signature_algorithms_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: block_len=%u/len=%u]\\n\", extension_len, tot_signature_algorithms_len);\n#endif\n\n\t\ts_offset += 2;\n\t\ttot_signature_algorithms_len = ndpi_min((sizeof(ja3.client.signature_algorithms) / 2) - 1, tot_signature_algorithms_len);\n\n#ifdef TLS_HANDLE_SIGNATURE_ALGORITMS\n\t\tflow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms = ndpi_min(tot_signature_algorithms_len / 2, MAX_NUM_TLS_SIGNATURE_ALGORITHMS);\n\n\t\tmemcpy(flow->protos.tls_quic_stun.tls_quic.client_signature_algorithms,\n\t\t &packet->payload[s_offset], 2 /* 16 bit */*flow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms);\n#endif\n\n\t\tfor(i=0; ipayload[s_offset+i]);\n\n\t\t if(rc < 0) break;\n\t\t}\n\n\t\tfor(i=0; ipayload[s_offset+i]));\n\n\t\t // printf(\"=>> %04X\\n\", cipher_id);\n\n\t\t switch(cipher_id) {\n\t\t case ECDSA_SECP521R1_SHA512:\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls = 1;\n\t\t break;\n\n\t\t case ECDSA_SECP256R1_SHA256:\n\t\t case ECDSA_SECP384R1_SHA384:\n\t\t case RSA_PKCS1_SHA256:\n\t\t case RSA_PKCS1_SHA384:\n\t\t case RSA_PKCS1_SHA512:\n\t\t case RSA_PSS_RSAE_SHA256:\n\t\t case RSA_PSS_RSAE_SHA384:\n\t\t case RSA_PSS_RSAE_SHA512:\n\t\t chrome_signature_algorithms++, safari_signature_algorithms++;\n\t\t break;\n\t\t }\n\t\t}\n\n\t\tif(flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0,\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tif(safari_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0;\n\n\t\tif(chrome_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tja3.client.signature_algorithms[i*2] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: %s]\\n\", ja3.client.signature_algorithms);\n#endif\n\t } else if(extension_id == 16 /* application_layer_protocol_negotiation */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\tchar alpn_str[256];\n\t\tu_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t\ts_offset += 2;\n\t\ttot_alpn_len += s_offset;\n\n\t\twhile(s_offset < tot_alpn_len && s_offset < total_len) {\n\t\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t\t if((s_offset + alpn_len) <= tot_alpn_len &&\n\t\t (s_offset + alpn_len) <= total_len) {\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t\t if(alpn_str_len > 0) {\n\t\t\talpn_str[alpn_str_len] = ',';\n\t\t\talpn_str_len++;\n\t\t }\n\n\t\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\n\t\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t\t } else\n\t\t break;\n\t\t } else\n\t\t break;\n\t\t} /* while */\n\n\t\talpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t\tif(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t\tsnprintf(ja3.client.alpn, sizeof(ja3.client.alpn), \"%s\", alpn_str);\n\n\t\t/* Replace , with - as in JA3 */\n\t\tfor(i=0; ja3.client.alpn[i] != '\\0'; i++)\n\t\t if(ja3.client.alpn[i] == ',') ja3.client.alpn[i] = '-';\n\n\t } else if(extension_id == 43 /* supported versions */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int8_t version_len = packet->payload[s_offset];\n\t\tchar version_str[256];\n\t\tu_int8_t version_str_len = 0;\n\t\tversion_str[0] = 0;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [TLS version len: %u]\\n\", version_len);\n#endif\n\n\t\tif(version_len == (extension_len-1)) {\n\t\t u_int8_t j;\n\t\t u_int16_t supported_versions_offset = 0;\n\n\t\t s_offset++;\n\n\t\t // careful not to overflow and loop forever with u_int8_t\n\t\t for(j=0; j+1payload[s_offset+j]));\n\t\t u_int8_t unknown_tls_version;\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [TLS version: %s/0x%04X]\\n\",\n\t\t\t ndpi_ssl_version2str(flow, tls_version, &unknown_tls_version), tls_version);\n#endif\n\n\t\t if((version_str_len+8) < sizeof(version_str)) {\n\t\t int rc = snprintf(&version_str[version_str_len],\n\t\t\t\t\tsizeof(version_str) - version_str_len, \"%s%s\",\n\t\t\t\t\t(version_str_len > 0) ? \",\" : \"\",\n\t\t\t\t\tndpi_ssl_version2str(flow, tls_version, &unknown_tls_version));\n\t\t if(rc <= 0)\n\t\t\tbreak;\n\t\t else\n\t\t\tversion_str_len += rc;\n\n\t\t rc = snprintf(&ja3.client.supported_versions[supported_versions_offset],\n\t\t\t\t sizeof(ja3.client.supported_versions)-supported_versions_offset,\n\t\t\t\t \"%s%04X\", (j > 0) ? \"-\" : \"\", tls_version);\n\n\t\t if(rc > 0)\n\t\t\tsupported_versions_offset += rc;\n\t\t }\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [SUPPORTED_VERSIONS: %s]\\n\", ja3.client.supported_versions);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.tls_supported_versions == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.tls_supported_versions = ndpi_strdup(version_str);\n\t\t}\n\t } else if(extension_id == 65486 /* encrypted server name */) {\n\t\t/*\n\t\t - https://tools.ietf.org/html/draft-ietf-tls-esni-06\n\t\t - https://blog.cloudflare.com/encrypted-sni/\n\t\t*/\n\t\tu_int16_t e_offset = offset+extension_offset;\n\t\tu_int16_t initial_offset = e_offset;\n\t\tu_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\n\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.cipher_suite = cipher_suite;\n\n\t\te_offset += 2; /* Cipher suite len */\n\n\t\t/* Key Share Entry */\n\t\te_offset += 2; /* Group */\n\t\te_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\tif((e_offset+4) < packet->payload_packet_len) {\n\t\t /* Record Digest */\n\t\t e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\t if((e_offset+4) < packet->payload_packet_len) {\n\t\t e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\t\t e_offset += 2;\n\n\t\t if((e_offset+e_sni_len-extension_len-initial_offset) >= 0 &&\n\t\t e_offset+e_sni_len < packet->payload_packet_len) {\n#ifdef DEBUG_ENCRYPTED_SNI\n\t\t printf(\"Client TLS [Encrypted Server Name len: %u]\\n\", e_sni_len);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) {\n\t\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1);\n\n\t\t\tif(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni) {\n\t\t\t u_int16_t i, off;\n\n\t\t\t for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) {\n\t\t\t int rc = sprintf(&flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off], \"%02X\", packet->payload[i] & 0XFF);\n\n\t\t\t if(rc <= 0) {\n\t\t\t flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off] = '\\0';\n\t\t\t break;\n\t\t\t } else\n\t\t\t off += rc;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t }\n\t\t }\n\t\t}\n\t } else if(extension_id == 65445 || /* QUIC transport parameters (drafts version) */\n\t\t extension_id == 57) { /* QUIC transport parameters (final version) */\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tuint16_t final_offset;\n\t\tint using_var_int = is_version_with_var_int_transport_params(quic_version);\n\n\t\tif(!using_var_int) {\n\t\t if(s_offset+1 >= total_len) {\n\t\t final_offset = 0; /* Force skipping extension */\n\t\t } else {\n\t\t u_int16_t seq_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t s_offset += 2;\n\t final_offset = MIN(total_len, s_offset + seq_len);\n\t\t }\n\t\t} else {\n\t final_offset = MIN(total_len, s_offset + extension_len);\n\t\t}\n\n\t\twhile(s_offset < final_offset) {\n\t\t u_int64_t param_type, param_len;\n\n if(!using_var_int) {\n\t\t if(s_offset+3 >= final_offset)\n\t\t break;\n\t\t param_type = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t param_len = ntohs(*((u_int16_t*)&packet->payload[s_offset + 2]));\n\t\t s_offset += 4;\n\t\t } else {\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_type);\n\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_len);\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [QUIC TP: Param 0x%x Len %d]\\n\", (int)param_type, (int)param_len);\n#endif\n\t\t if(s_offset+param_len > final_offset)\n\t\t break;\n\n\t\t if(param_type==0x3129) {\n#ifdef DEBUG_TLS\n\t\t printf(\"UA [%.*s]\\n\", (int)param_len, &packet->payload[s_offset]);\n#endif\n\t\t http_process_user_agent(ndpi_struct, flow,\n\t\t\t\t\t &packet->payload[s_offset], param_len);\n\t\t break;\n\t\t }\n\t\t s_offset += param_len;\n\t\t}\n\t }\n\n\t extension_offset += extension_len; /* Move to the next extension */\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_offset/len: %u/%u]\\n\", extension_offset, extension_len);\n#endif\n\t } /* while */\n\n\t if(!invalid_ja3) {\n\t int rc;\n\n\t compute_ja3c:\n\t ja3_str_len = snprintf(ja3_str, JA3_STR_LEN, \"%u,\", ja3.client.tls_handshake_version);\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.cipher[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.tls_extension[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve_point_format[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t if(ndpi_struct->enable_ja3_plus) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len,\n\t\t\t \",%s,%s,%s\", ja3.client.signature_algorithms, ja3.client.supported_versions, ja3.client.alpn);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3+] Client: %s \\n\", ja3_str);\n#endif\n\n\t ndpi_MD5Init(&ctx);\n\t ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n\t ndpi_MD5Final(md5_hash, &ctx);\n\n\t for(i=0, j=0; i<16; i++) {\n\t\trc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_client[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_client)-j, \"%02x\",\n\t\t\t md5_hash[i]);\n\t\tif(rc > 0) j += rc; else break;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3] Client: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_client);\n#endif\n\n\t if(ndpi_struct->malicious_ja3_automa.ac_automa != NULL) {\n\t\tu_int16_t rc1 = ndpi_match_string(ndpi_struct->malicious_ja3_automa.ac_automa,\n\t\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.ja3_client);\n\n\t\tif(rc1 > 0)\n\t\t ndpi_set_risk(flow, NDPI_MALICIOUS_JA3);\n\t }\n\t }\n\n\t /* Before returning to the caller we need to make a final check */\n\t if((flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0303) /* >= TLSv1.2 */\n\t && (flow->protos.tls_quic_stun.tls_quic.alpn == NULL) /* No ALPN */) {\n\t ndpi_set_risk(flow, NDPI_TLS_NOT_CARRYING_HTTPS);\n\t }\n\n\t /* Suspicious Domain Fronting:\n\t https://github.com/SixGenInc/Noctilucent/blob/master/docs/ */\n\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni &&\n\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] != '\\0') {\n\t ndpi_set_risk(flow, NDPI_TLS_SUSPICIOUS_ESNI_USAGE);\n\t }\n\n\t /* Add check for missing SNI */\n\t if((flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] == 0)\n\t && (flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0302) /* TLSv1.1 */\n\t && (flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) /* No ESNI */\n\t ) {\n\t /* This is a bit suspicious */\n\t ndpi_set_risk(flow, NDPI_TLS_MISSING_SNI);\n\t }\n\n\t return(2 /* Client Certificate */);\n\t } else {\n#ifdef DEBUG_TLS\n\t printf(\"[TLS] Client: too short [%u vs %u]\\n\",\n\t\t (extensions_len+offset), total_len);\n#endif\n\t }\n\t} else if(offset == total_len) {\n\t /* TLS does not have extensions etc */\n\t goto compute_ja3c;\n\t}\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: invalid length detected\\n\");\n#endif\n }\n }\n }\n\n return(0); /* Not found */\n}", "func_hash": 151731809095227477348152572326541206619, "file_name": "tls.c", "file_hash": 16631055130532905863562846439385168504, "cwe": ["CWE-787"], "cve": "CVE-2021-36082", "cve_desc": "ntop nDPI 3.4 has a stack-based buffer overflow in processClientServerHello.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36082"} {"idx": 195958, "project": "tensorflow", "commit_id": "31bd5026304677faa8a0b77602c6154171b9aec1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/31bd5026304677faa8a0b77602c6154171b9aec1", "commit_message": "Prevent check fail in FFT\n\nPiperOrigin-RevId: 372031044\nChange-Id: I50994e3e8a5d1342d01bde80256f6bf2730ca299", "target": 1, "func": " void DoRealForwardFFT(OpKernelContext* ctx, uint64* fft_shape,\n const Tensor& in, Tensor* out) {\n // Create the axes (which are always trailing).\n const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank);\n auto device = ctx->eigen_device();\n auto input = Tensor(in).flat_inner_dims();\n const auto input_dims = input.dimensions();\n\n // Slice input to fft_shape on its inner-most dimensions.\n Eigen::DSizes input_slice_sizes;\n input_slice_sizes[0] = input_dims[0];\n TensorShape temp_shape{input_dims[0]};\n for (int i = 1; i <= FFTRank; ++i) {\n input_slice_sizes[i] = fft_shape[i - 1];\n temp_shape.AddDim(fft_shape[i - 1]);\n }\n\n auto output = out->flat_inner_dims();\n const Eigen::DSizes zero_start_indices;\n\n // Compute the full FFT using a temporary tensor.\n Tensor temp;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::v(),\n temp_shape, &temp));\n auto full_fft = temp.flat_inner_dims();\n full_fft.device(device) =\n input.slice(zero_start_indices, input_slice_sizes)\n .template fft(axes);\n\n // Slice away the negative frequency components.\n output.device(device) =\n full_fft.slice(zero_start_indices, output.dimensions());\n }", "func_hash": 126036604253651491656743862215462541107, "file_name": "fft_ops.cc", "file_hash": 179883929073318615391606433334336113400, "cwe": ["CWE-703"], "cve": "CVE-2021-29563", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service by exploiting a `CHECK`-failure coming from the implementation of `tf.raw_ops.RFFT`. Eigen code operating on an empty matrix can trigger on an assertion and will cause program termination. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29563"} {"idx": 235720, "project": "tensorflow", "commit_id": "31bd5026304677faa8a0b77602c6154171b9aec1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/31bd5026304677faa8a0b77602c6154171b9aec1", "commit_message": "Prevent check fail in FFT\n\nPiperOrigin-RevId: 372031044\nChange-Id: I50994e3e8a5d1342d01bde80256f6bf2730ca299", "target": 0, "func": " void DoRealForwardFFT(OpKernelContext* ctx, uint64* fft_shape,\n const Tensor& in, Tensor* out) {\n // Create the axes (which are always trailing).\n const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank);\n auto device = ctx->eigen_device();\n auto input = Tensor(in).flat_inner_dims();\n const auto input_dims = input.dimensions();\n\n // Slice input to fft_shape on its inner-most dimensions.\n Eigen::DSizes input_slice_sizes;\n input_slice_sizes[0] = input_dims[0];\n TensorShape temp_shape{input_dims[0]};\n for (int i = 1; i <= FFTRank; ++i) {\n input_slice_sizes[i] = fft_shape[i - 1];\n temp_shape.AddDim(fft_shape[i - 1]);\n }\n OP_REQUIRES(ctx, temp_shape.num_elements() > 0,\n errors::InvalidArgument(\"Obtained a FFT shape of 0 elements: \",\n temp_shape.DebugString()));\n\n auto output = out->flat_inner_dims();\n const Eigen::DSizes zero_start_indices;\n\n // Compute the full FFT using a temporary tensor.\n Tensor temp;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::v(),\n temp_shape, &temp));\n auto full_fft = temp.flat_inner_dims();\n full_fft.device(device) =\n input.slice(zero_start_indices, input_slice_sizes)\n .template fft(axes);\n\n // Slice away the negative frequency components.\n output.device(device) =\n full_fft.slice(zero_start_indices, output.dimensions());\n }", "func_hash": 130508538201038059132096130275239239048, "file_name": "fft_ops.cc", "file_hash": 104645539874591012029357667020869704572, "cwe": ["CWE-703"], "cve": "CVE-2021-29563", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service by exploiting a `CHECK`-failure coming from the implementation of `tf.raw_ops.RFFT`. Eigen code operating on an empty matrix can trigger on an assertion and will cause program termination. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29563"} {"idx": 195966, "project": "bfgminer", "commit_id": "ff7f30129f15f7a2213f8ced0cd65c9a331493d9", "project_url": "https://github.com/luke-jr/bfgminer", "commit_url": "https://github.com/luke-jr/bfgminer/commit/ff7f30129f15f7a2213f8ced0cd65c9a331493d9", "commit_message": "Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated)\n\nThanks to Mick Ayzenberg for finding this!", "target": 1, "func": "bool initiate_stratum(struct pool *pool)\n{\n\tchar s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;\n\tjson_t *val = NULL, *res_val, *err_val;\n\tbool ret = false, recvd = false;\n\tjson_error_t err;\n\tint n2size;\n\n\tif (!setup_stratum_curl(pool))\n\t\tgoto out;\n\nresend:\n\tif (pool->sessionid)\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": [\\\"%s\\\"]}\", swork_id++, pool->sessionid);\n\telse\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": []}\", swork_id++);\n\n\tif (!__stratum_send(pool, s, strlen(s))) {\n\t\tapplog(LOG_DEBUG, \"Failed to send s in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tif (!socket_full(pool, true)) {\n\t\tapplog(LOG_DEBUG, \"Timed out waiting for response in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tsret = recv_line(pool);\n\tif (!sret)\n\t\tgoto out;\n\n\trecvd = true;\n\n\tval = JSON_LOADS(sret, &err);\n\tfree(sret);\n\tif (!val) {\n\t\tapplog(LOG_INFO, \"JSON decode failed(%d): %s\", err.line, err.text);\n\t\tgoto out;\n\t}\n\n\tres_val = json_object_get(val, \"result\");\n\terr_val = json_object_get(val, \"error\");\n\n\tif (!res_val || json_is_null(res_val) ||\n\t (err_val && !json_is_null(err_val))) {\n\t\tchar *ss;\n\n\t\tif (err_val)\n\t\t\tss = json_dumps(err_val, JSON_INDENT(3));\n\t\telse\n\t\t\tss = strdup(\"(unknown reason)\");\n\n\t\tapplog(LOG_INFO, \"JSON-RPC decode failed: %s\", ss);\n\n\t\tfree(ss);\n\n\t\tgoto out;\n\t}\n\n\tsessionid = json_array_string(json_array_get(res_val, 0), 1);\n\tif (!sessionid) {\n\t\tapplog(LOG_INFO, \"Failed to get sessionid in initiate_stratum\");\n\t\tgoto out;\n\t}\n\tnonce1 = json_array_string(res_val, 1);\n\tif (!nonce1) {\n\t\tapplog(LOG_INFO, \"Failed to get nonce1 in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tgoto out;\n\t}\n\tn2size = json_integer_value(json_array_get(res_val, 2));\n\tif (!n2size) {\n\t\tapplog(LOG_INFO, \"Failed to get n2size in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tfree(nonce1);\n\t\tgoto out;\n\t}\n\n\tmutex_lock(&pool->pool_lock);\n\tpool->sessionid = sessionid;\n\tfree(pool->nonce1);\n\tpool->nonce1 = nonce1;\n\tpool->n1_len = strlen(nonce1) / 2;\n\tpool->n2size = n2size;\n\tmutex_unlock(&pool->pool_lock);\n\n\tapplog(LOG_DEBUG, \"Pool %d stratum session id: %s\", pool->pool_no, pool->sessionid);\n\n\tret = true;\nout:\n\tif (val)\n\t\tjson_decref(val);\n\n\tif (ret) {\n\t\tif (!pool->stratum_url)\n\t\t\tpool->stratum_url = pool->sockaddr_url;\n\t\tpool->stratum_active = true;\n\t\tpool->swork.diff = 1;\n\t\tif (opt_protocol) {\n\t\t\tapplog(LOG_DEBUG, \"Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d\",\n\t\t\t pool->pool_no, pool->nonce1, pool->n2size);\n\t\t}\n\t} else {\n\t\tif (recvd && pool->sessionid) {\n\t\t\t/* Reset the sessionid used for stratum resuming in case the pool\n\t\t\t* does not support it, or does not know how to respond to the\n\t\t\t* presence of the sessionid parameter. */\n\t\t\tmutex_lock(&pool->pool_lock);\n\t\t\tfree(pool->sessionid);\n\t\t\tfree(pool->nonce1);\n\t\t\tpool->sessionid = pool->nonce1 = NULL;\n\t\t\tmutex_unlock(&pool->pool_lock);\n\t\t\tapplog(LOG_DEBUG, \"Failed to resume stratum, trying afresh\");\n\t\t\tgoto resend;\n\t\t}\n\t\tapplog(LOG_DEBUG, \"Initiate stratum failed\");\n\t\tif (pool->sock != INVSOCK) {\n\t\t\tshutdown(pool->sock, SHUT_RDWR);\n\t\t\tpool->sock = INVSOCK;\n\t\t}\n\t}\n\n\treturn ret;\n}", "func_hash": 128206970560263328528770470384770527025, "file_name": "util.c", "file_hash": 146159921639278376316040031637087798264, "cwe": ["CWE-787"], "cve": "CVE-2014-4502", "cve_desc": "Multiple heap-based buffer overflows in the parse_notify function in sgminer before 4.2.2, cgminer before 4.3.5, and BFGMiner before 4.1.0 allow remote pool servers to have unspecified impact via a (1) large or (2) negative value in the Extranonc2_size parameter in a mining.subscribe response and a crafted mining.notify request.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-4502"} {"idx": 235766, "project": "bfgminer", "commit_id": "ff7f30129f15f7a2213f8ced0cd65c9a331493d9", "project_url": "https://github.com/luke-jr/bfgminer", "commit_url": "https://github.com/luke-jr/bfgminer/commit/ff7f30129f15f7a2213f8ced0cd65c9a331493d9", "commit_message": "Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated)\n\nThanks to Mick Ayzenberg for finding this!", "target": 0, "func": "bool initiate_stratum(struct pool *pool)\n{\n\tchar s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;\n\tjson_t *val = NULL, *res_val, *err_val;\n\tbool ret = false, recvd = false;\n\tjson_error_t err;\n\tint n2size;\n\n\tif (!setup_stratum_curl(pool))\n\t\tgoto out;\n\nresend:\n\tif (pool->sessionid)\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": [\\\"%s\\\"]}\", swork_id++, pool->sessionid);\n\telse\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": []}\", swork_id++);\n\n\tif (!__stratum_send(pool, s, strlen(s))) {\n\t\tapplog(LOG_DEBUG, \"Failed to send s in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tif (!socket_full(pool, true)) {\n\t\tapplog(LOG_DEBUG, \"Timed out waiting for response in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tsret = recv_line(pool);\n\tif (!sret)\n\t\tgoto out;\n\n\trecvd = true;\n\n\tval = JSON_LOADS(sret, &err);\n\tfree(sret);\n\tif (!val) {\n\t\tapplog(LOG_INFO, \"JSON decode failed(%d): %s\", err.line, err.text);\n\t\tgoto out;\n\t}\n\n\tres_val = json_object_get(val, \"result\");\n\terr_val = json_object_get(val, \"error\");\n\n\tif (!res_val || json_is_null(res_val) ||\n\t (err_val && !json_is_null(err_val))) {\n\t\tchar *ss;\n\n\t\tif (err_val)\n\t\t\tss = json_dumps(err_val, JSON_INDENT(3));\n\t\telse\n\t\t\tss = strdup(\"(unknown reason)\");\n\n\t\tapplog(LOG_INFO, \"JSON-RPC decode failed: %s\", ss);\n\n\t\tfree(ss);\n\n\t\tgoto out;\n\t}\n\n\tsessionid = json_array_string(json_array_get(res_val, 0), 1);\n\tif (!sessionid) {\n\t\tapplog(LOG_INFO, \"Failed to get sessionid in initiate_stratum\");\n\t\tgoto out;\n\t}\n\tnonce1 = json_array_string(res_val, 1);\n\tif (!nonce1) {\n\t\tapplog(LOG_INFO, \"Failed to get nonce1 in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tgoto out;\n\t}\n\tn2size = json_integer_value(json_array_get(res_val, 2));\n\tif (n2size < 1)\n\t{\n\t\tapplog(LOG_INFO, \"Failed to get n2size in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tfree(nonce1);\n\t\tgoto out;\n\t}\n\n\tmutex_lock(&pool->pool_lock);\n\tpool->sessionid = sessionid;\n\tfree(pool->nonce1);\n\tpool->nonce1 = nonce1;\n\tpool->n1_len = strlen(nonce1) / 2;\n\tpool->n2size = n2size;\n\tmutex_unlock(&pool->pool_lock);\n\n\tapplog(LOG_DEBUG, \"Pool %d stratum session id: %s\", pool->pool_no, pool->sessionid);\n\n\tret = true;\nout:\n\tif (val)\n\t\tjson_decref(val);\n\n\tif (ret) {\n\t\tif (!pool->stratum_url)\n\t\t\tpool->stratum_url = pool->sockaddr_url;\n\t\tpool->stratum_active = true;\n\t\tpool->swork.diff = 1;\n\t\tif (opt_protocol) {\n\t\t\tapplog(LOG_DEBUG, \"Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d\",\n\t\t\t pool->pool_no, pool->nonce1, pool->n2size);\n\t\t}\n\t} else {\n\t\tif (recvd && pool->sessionid) {\n\t\t\t/* Reset the sessionid used for stratum resuming in case the pool\n\t\t\t* does not support it, or does not know how to respond to the\n\t\t\t* presence of the sessionid parameter. */\n\t\t\tmutex_lock(&pool->pool_lock);\n\t\t\tfree(pool->sessionid);\n\t\t\tfree(pool->nonce1);\n\t\t\tpool->sessionid = pool->nonce1 = NULL;\n\t\t\tmutex_unlock(&pool->pool_lock);\n\t\t\tapplog(LOG_DEBUG, \"Failed to resume stratum, trying afresh\");\n\t\t\tgoto resend;\n\t\t}\n\t\tapplog(LOG_DEBUG, \"Initiate stratum failed\");\n\t\tif (pool->sock != INVSOCK) {\n\t\t\tshutdown(pool->sock, SHUT_RDWR);\n\t\t\tpool->sock = INVSOCK;\n\t\t}\n\t}\n\n\treturn ret;\n}", "func_hash": 48086261582866314097149543017720124026, "file_name": "util.c", "file_hash": 122106294667611737847145152360032423441, "cwe": ["CWE-787"], "cve": "CVE-2014-4502", "cve_desc": "Multiple heap-based buffer overflows in the parse_notify function in sgminer before 4.2.2, cgminer before 4.3.5, and BFGMiner before 4.1.0 allow remote pool servers to have unspecified impact via a (1) large or (2) negative value in the Extranonc2_size parameter in a mining.subscribe response and a crafted mining.notify request.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-4502"} {"idx": 195972, "project": "tensorflow", "commit_id": "d9204be9f49520cdaaeb2541d1dc5187b23f31d9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/d9204be9f49520cdaaeb2541d1dc5187b23f31d9", "commit_message": "Disallow division by zero FPE in tf.raw_ops.SparseDenseCwiseDiv\n\nPiperOrigin-RevId: 383959809\nChange-Id: Ibe88458bdf66a686c93e354b8255dec94285c560", "target": 1, "func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *indices_t, *values_t, *shape_t, *dense_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_indices\", &indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_values\", &values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_shape\", &shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"dense\", &dense_t));\n\n // Validations.\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),\n errors::InvalidArgument(\n \"Input sp_indices should be a matrix but received shape: \",\n indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(values_t->shape()) &&\n TensorShapeUtils::IsVector(shape_t->shape()),\n errors::InvalidArgument(\n \"Inputs sp_values and sp_shape should be vectors \"\n \"but received shapes: \",\n values_t->shape().DebugString(), \" and \",\n shape_t->shape().DebugString()));\n OP_REQUIRES(\n ctx, values_t->dim_size(0) == indices_t->dim_size(0),\n errors::InvalidArgument(\n \"The first dimension of values and indices should match. (\",\n values_t->dim_size(0), \" vs. \", indices_t->dim_size(0), \")\"));\n\n const auto indices_mat = indices_t->matrix();\n const auto shape_vec = shape_t->vec();\n const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));\n const auto rhs_dims = BCast::FromShape(dense_t->shape());\n BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims.\n\n // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal\n // to dims in rhs (from right to left).\n auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {\n if (lhs.size() < rhs.size()) return false;\n for (size_t i = 0; i < rhs.size(); ++i) {\n if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;\n }\n return true;\n };\n OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),\n errors::InvalidArgument(\n \"SparseDenseBinaryOpShared broadcasts dense to sparse \"\n \"only; got incompatible shapes: [\",\n absl::StrJoin(lhs_dims, \",\"), \"] vs. [\",\n absl::StrJoin(rhs_dims, \",\"), \"]\"));\n\n Tensor *output_values = nullptr;\n Tensor dense_gathered;\n const int64 nnz = indices_t->dim_size(0);\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({nnz}), &output_values));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),\n &dense_gathered));\n\n // Pulls relevant entries from the dense side, with reshape and broadcasting\n // *of the dense side* taken into account. Use a TensorRef to avoid blowing\n // up memory.\n //\n // We can directly use the sparse indices to look up dense side, because\n // \"b.y_reshape()\" and \"b.y_bcast()\" are guaranteed to have rank \"ndims\".\n auto dense_gathered_flat = dense_gathered.flat();\n const int ndims = lhs_dims.size();\n switch (ndims) {\n#define CASE(NDIM) \\\n case NDIM: { \\\n TensorRef> rhs_ref = \\\n dense_t->shaped(b.y_reshape()) \\\n .broadcast(BCast::ToIndexArray(b.y_bcast())); \\\n Eigen::array idx; \\\n bool indices_valid = true; \\\n for (int i = 0; i < nnz; ++i) { \\\n for (int d = 0; d < NDIM; ++d) { \\\n idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \\\n if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \\\n indices_valid = false; \\\n } \\\n } \\\n OP_REQUIRES( \\\n ctx, indices_valid, \\\n errors::InvalidArgument(\"Provided indices are out-of-bounds w.r.t. \" \\\n \"dense side with broadcasted shape\")); \\\n dense_gathered_flat(i) = rhs_ref.coeff(idx); \\\n } \\\n break; \\\n }\n\n CASE(1);\n CASE(2);\n CASE(3);\n CASE(4);\n CASE(5);\n default:\n OP_REQUIRES(\n ctx, false,\n errors::InvalidArgument(\"Only tensors with ranks between 1 and 5 \"\n \"are currently supported. Tensor rank: \",\n ndims));\n#undef CASE\n }\n\n output_values->flat().device(ctx->eigen_device()) =\n values_t->flat().binaryExpr(dense_gathered_flat,\n typename Functor::func());\n }", "func_hash": 283059991789489796348795035846564251313, "file_name": "sparse_dense_binary_op_shared.cc", "file_hash": 141324138089319348166186599113963252226, "cwe": ["CWE-369"], "cve": "CVE-2021-37636", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.SparseDenseCwiseDiv` is vulnerable to a division by 0 error. The [implementation](https://github.com/tensorflow/tensorflow/blob/a1bc56203f21a5a4995311825ffaba7a670d7747/tensorflow/core/kernels/sparse_dense_binary_op_shared.cc#L56) uses a common class for all binary operations but fails to treat the division by 0 case separately. We have patched the issue in GitHub commit d9204be9f49520cdaaeb2541d1dc5187b23f31d9. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37636"} {"idx": 235840, "project": "tensorflow", "commit_id": "d9204be9f49520cdaaeb2541d1dc5187b23f31d9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/d9204be9f49520cdaaeb2541d1dc5187b23f31d9", "commit_message": "Disallow division by zero FPE in tf.raw_ops.SparseDenseCwiseDiv\n\nPiperOrigin-RevId: 383959809\nChange-Id: Ibe88458bdf66a686c93e354b8255dec94285c560", "target": 0, "func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *indices_t, *values_t, *shape_t, *dense_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_indices\", &indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_values\", &values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_shape\", &shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"dense\", &dense_t));\n\n // Validations.\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),\n errors::InvalidArgument(\n \"Input sp_indices should be a matrix but received shape: \",\n indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(values_t->shape()) &&\n TensorShapeUtils::IsVector(shape_t->shape()),\n errors::InvalidArgument(\n \"Inputs sp_values and sp_shape should be vectors \"\n \"but received shapes: \",\n values_t->shape().DebugString(), \" and \",\n shape_t->shape().DebugString()));\n OP_REQUIRES(\n ctx, values_t->dim_size(0) == indices_t->dim_size(0),\n errors::InvalidArgument(\n \"The first dimension of values and indices should match. (\",\n values_t->dim_size(0), \" vs. \", indices_t->dim_size(0), \")\"));\n\n const auto indices_mat = indices_t->matrix();\n const auto shape_vec = shape_t->vec();\n const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));\n const auto rhs_dims = BCast::FromShape(dense_t->shape());\n BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims.\n\n // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal\n // to dims in rhs (from right to left).\n auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {\n if (lhs.size() < rhs.size()) return false;\n for (size_t i = 0; i < rhs.size(); ++i) {\n if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;\n }\n return true;\n };\n OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),\n errors::InvalidArgument(\n \"SparseDenseBinaryOpShared broadcasts dense to sparse \"\n \"only; got incompatible shapes: [\",\n absl::StrJoin(lhs_dims, \",\"), \"] vs. [\",\n absl::StrJoin(rhs_dims, \",\"), \"]\"));\n\n Tensor *output_values = nullptr;\n Tensor dense_gathered;\n const int64 nnz = indices_t->dim_size(0);\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({nnz}), &output_values));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),\n &dense_gathered));\n bool op_is_div = false;\n if (absl::StrContains(ctx->op_kernel().type_string_view(), \"Div\")) {\n op_is_div = true;\n }\n // Pulls relevant entries from the dense side, with reshape and broadcasting\n // *of the dense side* taken into account. Use a TensorRef to avoid blowing\n // up memory.\n //\n // We can directly use the sparse indices to look up dense side, because\n // \"b.y_reshape()\" and \"b.y_bcast()\" are guaranteed to have rank \"ndims\".\n auto dense_gathered_flat = dense_gathered.flat();\n const int ndims = lhs_dims.size();\n switch (ndims) {\n#define CASE(NDIM) \\\n case NDIM: { \\\n TensorRef> rhs_ref = \\\n dense_t->shaped(b.y_reshape()) \\\n .broadcast(BCast::ToIndexArray(b.y_bcast())); \\\n Eigen::array idx; \\\n bool indices_valid = true; \\\n for (int i = 0; i < nnz; ++i) { \\\n for (int d = 0; d < NDIM; ++d) { \\\n idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \\\n if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \\\n indices_valid = false; \\\n } \\\n } \\\n OP_REQUIRES( \\\n ctx, indices_valid, \\\n errors::InvalidArgument(\"Provided indices are out-of-bounds w.r.t. \" \\\n \"dense side with broadcasted shape\")); \\\n dense_gathered_flat(i) = rhs_ref.coeff(idx); \\\n if (op_is_div) { \\\n OP_REQUIRES(ctx, dense_gathered_flat(i) != 0, \\\n errors::InvalidArgument( \\\n \"SparseDenseCwiseDiv cannot divide by zero,\" \\\n \"but input dense tensor contains zero \")); \\\n } \\\n } \\\n break; \\\n }\n\n CASE(1);\n CASE(2);\n CASE(3);\n CASE(4);\n CASE(5);\n default:\n OP_REQUIRES(\n ctx, false,\n errors::InvalidArgument(\"Only tensors with ranks between 1 and 5 \"\n \"are currently supported. Tensor rank: \",\n ndims));\n#undef CASE\n }\n\n output_values->flat().device(ctx->eigen_device()) =\n values_t->flat().binaryExpr(dense_gathered_flat,\n typename Functor::func());\n }", "func_hash": 40565907131529288539970375846015138778, "file_name": "sparse_dense_binary_op_shared.cc", "file_hash": 231553789851474814269116482536376605269, "cwe": ["CWE-369"], "cve": "CVE-2021-37636", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.SparseDenseCwiseDiv` is vulnerable to a division by 0 error. The [implementation](https://github.com/tensorflow/tensorflow/blob/a1bc56203f21a5a4995311825ffaba7a670d7747/tensorflow/core/kernels/sparse_dense_binary_op_shared.cc#L56) uses a common class for all binary operations but fails to treat the division by 0 case separately. We have patched the issue in GitHub commit d9204be9f49520cdaaeb2541d1dc5187b23f31d9. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37636"} {"idx": 195985, "project": "gpac", "commit_id": "13dad7d5ef74ca2e6fe4010f5b03eb12e9bbe0ec", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/13dad7d5ef74ca2e6fe4010f5b03eb12e9bbe0ec", "commit_message": "fixed #1719", "target": 1, "func": "static GF_Err av1dmx_parse_flush_sample(GF_Filter *filter, GF_AV1DmxCtx *ctx)\n{\n\tu32 pck_size;\n\tGF_FilterPacket *pck;\n\tu8 *output;\n\n\tgf_bs_get_content_no_truncate(ctx->state.bs, &ctx->state.frame_obus, &pck_size, &ctx->state.frame_obus_alloc);\n\n\tif (!pck_size) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1Dmx] no frame OBU, skipping OBU\\n\"));\n\t\treturn GF_OK;\n\t}\n\n\tpck = gf_filter_pck_new_alloc(ctx->opid, pck_size, &output);\n\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, pck);\n\n\tgf_filter_pck_set_cts(pck, ctx->cts);\n\tgf_filter_pck_set_sap(pck, ctx->state.frame_state.key_frame ? GF_FILTER_SAP_1 : 0);\n\n\tmemcpy(output, ctx->state.frame_obus, pck_size);\n\n\tif (ctx->deps) {\n\t\tu8 flags = 0;\n\t\t//dependsOn\n\t\tflags = ( ctx->state.frame_state.key_frame) ? 2 : 1;\n\t\tflags <<= 2;\n\t\t//dependedOn\n\t \tflags |= ctx->state.frame_state.refresh_frame_flags ? 1 : 2;\n\t\tflags <<= 2;\n\t\t//hasRedundant\n\t \t//flags |= ctx->has_redundant ? 1 : 2;\n\t \tgf_filter_pck_set_dependency_flags(pck, flags);\n\t}\n\n\tgf_filter_pck_send(pck);\n\n\tav1dmx_update_cts(ctx);\n\tgf_av1_reset_state(&ctx->state, GF_FALSE);\n\n\treturn GF_OK;\n\n}", "func_hash": 163821091707838311057288343440830623110, "file_name": "reframe_av1.c", "file_hash": 245337223498447224550795430483362619547, "cwe": ["CWE-787"], "cve": "CVE-2021-30015", "cve_desc": "There is a Null Pointer Dereference in function filter_core/filter_pck.c:gf_filter_pck_new_alloc_internal in GPAC 1.0.1. The pid comes from function av1dmx_parse_flush_sample, the ctx.opid maybe NULL. The result is a crash in gf_filter_pck_new_alloc_internal.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30015"} {"idx": 236225, "project": "gpac", "commit_id": "13dad7d5ef74ca2e6fe4010f5b03eb12e9bbe0ec", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/13dad7d5ef74ca2e6fe4010f5b03eb12e9bbe0ec", "commit_message": "fixed #1719", "target": 0, "func": "static GF_Err av1dmx_parse_flush_sample(GF_Filter *filter, GF_AV1DmxCtx *ctx)\n{\n\tu32 pck_size;\n\tGF_FilterPacket *pck;\n\tu8 *output;\n\n\tif (!ctx->opid)\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\n\tgf_bs_get_content_no_truncate(ctx->state.bs, &ctx->state.frame_obus, &pck_size, &ctx->state.frame_obus_alloc);\n\n\tif (!pck_size) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1Dmx] no frame OBU, skipping OBU\\n\"));\n\t\treturn GF_OK;\n\t}\n\n\tpck = gf_filter_pck_new_alloc(ctx->opid, pck_size, &output);\n\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, pck);\n\n\tgf_filter_pck_set_cts(pck, ctx->cts);\n\tgf_filter_pck_set_sap(pck, ctx->state.frame_state.key_frame ? GF_FILTER_SAP_1 : 0);\n\n\tmemcpy(output, ctx->state.frame_obus, pck_size);\n\n\tif (ctx->deps) {\n\t\tu8 flags = 0;\n\t\t//dependsOn\n\t\tflags = ( ctx->state.frame_state.key_frame) ? 2 : 1;\n\t\tflags <<= 2;\n\t\t//dependedOn\n\t \tflags |= ctx->state.frame_state.refresh_frame_flags ? 1 : 2;\n\t\tflags <<= 2;\n\t\t//hasRedundant\n\t \t//flags |= ctx->has_redundant ? 1 : 2;\n\t \tgf_filter_pck_set_dependency_flags(pck, flags);\n\t}\n\n\tgf_filter_pck_send(pck);\n\n\tav1dmx_update_cts(ctx);\n\tgf_av1_reset_state(&ctx->state, GF_FALSE);\n\n\treturn GF_OK;\n\n}", "func_hash": 93130523939018513534132964510186764351, "file_name": "reframe_av1.c", "file_hash": 227662026862057903468555505109325501530, "cwe": ["CWE-787"], "cve": "CVE-2021-30015", "cve_desc": "There is a Null Pointer Dereference in function filter_core/filter_pck.c:gf_filter_pck_new_alloc_internal in GPAC 1.0.1. The pid comes from function av1dmx_parse_flush_sample, the ctx.opid maybe NULL. The result is a crash in gf_filter_pck_new_alloc_internal.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30015"} {"idx": 195986, "project": "isolated-vm", "commit_id": "27151bfecc260e96714443613880e3b2e6596704", "project_url": "https://github.com/laverdet/isolated-vm", "commit_url": "https://github.com/laverdet/isolated-vm/commit/27151bfecc260e96714443613880e3b2e6596704", "commit_message": "Disallow NativeModule creation unless main isolate", "target": 1, "func": "NativeModule::NativeModule(const std::string& filename) : init(nullptr) {\n\tif (uv_dlopen(filename.c_str(), &lib) != 0) {\n\t\tthrow RuntimeGenericError(\"Failed to load module\");\n\t}\n\tif (uv_dlsym(&lib, \"InitForContext\", reinterpret_cast(&init)) != 0 || init == nullptr) {\n\t\tuv_dlclose(&lib);\n\t\tthrow RuntimeGenericError(\"Module is not isolated-vm compatible\");\n\t}\n}", "func_hash": 156490525757266279085158874002495217519, "file_name": "native_module_handle.cc", "file_hash": 14226612973290967838879483669708706603, "cwe": ["CWE-703"], "cve": "CVE-2021-21413", "cve_desc": "isolated-vm is a library for nodejs which gives you access to v8's Isolate interface. Versions of isolated-vm before v4.0.0 have API pitfalls which may make it easy for implementers to expose supposed secure isolates to the permissions of the main nodejs isolate. Reference objects allow access to the underlying reference's full prototype chain. In an environment where the implementer has exposed a Reference instance to an attacker they would be able to use it to acquire a Reference to the nodejs context's Function object. Similar application-specific attacks could be possible by modifying the local prototype of other API objects. Access to NativeModule objects could allow an attacker to load and run native code from anywhere on the filesystem. If combined with, for example, a file upload API this would allow for arbitrary code execution. This is addressed in v4.0.0 through a series of related changes.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21413"} {"idx": 236238, "project": "isolated-vm", "commit_id": "27151bfecc260e96714443613880e3b2e6596704", "project_url": "https://github.com/laverdet/isolated-vm", "commit_url": "https://github.com/laverdet/isolated-vm/commit/27151bfecc260e96714443613880e3b2e6596704", "commit_message": "Disallow NativeModule creation unless main isolate", "target": 0, "func": "NativeModule::NativeModule(const std::string& filename) : init(nullptr) {\n\tif (!IsolateEnvironment::GetCurrent()->IsDefault()) {\n\t\tthrow RuntimeGenericError(\"NativeModule may only be instantiated from default nodejs isolate\");\n\t}\n\tif (uv_dlopen(filename.c_str(), &lib) != 0) {\n\t\tthrow RuntimeGenericError(\"Failed to load module\");\n\t}\n\tif (uv_dlsym(&lib, \"InitForContext\", reinterpret_cast(&init)) != 0 || init == nullptr) {\n\t\tuv_dlclose(&lib);\n\t\tthrow RuntimeGenericError(\"Module is not isolated-vm compatible\");\n\t}\n}", "func_hash": 107134478997815178660104857388681045529, "file_name": "native_module_handle.cc", "file_hash": 164501683959715875224317133464425778581, "cwe": ["CWE-703"], "cve": "CVE-2021-21413", "cve_desc": "isolated-vm is a library for nodejs which gives you access to v8's Isolate interface. Versions of isolated-vm before v4.0.0 have API pitfalls which may make it easy for implementers to expose supposed secure isolates to the permissions of the main nodejs isolate. Reference objects allow access to the underlying reference's full prototype chain. In an environment where the implementer has exposed a Reference instance to an attacker they would be able to use it to acquire a Reference to the nodejs context's Function object. Similar application-specific attacks could be possible by modifying the local prototype of other API objects. Access to NativeModule objects could allow an attacker to load and run native code from anywhere on the filesystem. If combined with, for example, a file upload API this would allow for arbitrary code execution. This is addressed in v4.0.0 through a series of related changes.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21413"} {"idx": 196318, "project": "mruby", "commit_id": "44f591aa8f7091e6ca6cb418e428ae6d4ceaf77d", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/44f591aa8f7091e6ca6cb418e428ae6d4ceaf77d", "commit_message": "codegen.c: adjust stack position for `OP_SUPER` instruction.", "target": 1, "func": "codegen(codegen_scope *s, node *tree, int val)\n{\n int nt;\n int rlev = s->rlev;\n\n if (!tree) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n return;\n }\n\n s->rlev++;\n if (s->rlev > MRB_CODEGEN_LEVEL_MAX) {\n codegen_error(s, \"too complex expression\");\n }\n if (s->irep && s->filename_index != tree->filename_index) {\n mrb_sym fname = mrb_parser_get_filename(s->parser, s->filename_index);\n const char *filename = mrb_sym_name_len(s->mrb, fname, NULL);\n\n mrb_debug_info_append_file(s->mrb, s->irep->debug_info,\n filename, s->lines, s->debug_start_pos, s->pc);\n s->debug_start_pos = s->pc;\n s->filename_index = tree->filename_index;\n s->filename_sym = mrb_parser_get_filename(s->parser, tree->filename_index);\n }\n\n nt = nint(tree->car);\n s->lineno = tree->lineno;\n tree = tree->cdr;\n switch (nt) {\n case NODE_BEGIN:\n if (val && !tree) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n while (tree) {\n codegen(s, tree->car, tree->cdr ? NOVAL : val);\n tree = tree->cdr;\n }\n break;\n\n case NODE_RESCUE:\n {\n int noexc;\n uint32_t exend, pos1, pos2, tmp;\n struct loopinfo *lp;\n int catch_entry, begin, end;\n\n if (tree->car == NULL) goto exit;\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, VAL);\n pop();\n lp->type = LOOP_RESCUE;\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n tree = tree->cdr;\n exend = JMPLINK_START;\n pos1 = JMPLINK_START;\n if (tree->car) {\n node *n2 = tree->car;\n int exc = cursp();\n\n genop_1(s, OP_EXCEPT, exc);\n push();\n while (n2) {\n node *n3 = n2->car;\n node *n4 = n3->car;\n\n dispatch(s, pos1);\n pos2 = JMPLINK_START;\n do {\n if (n4 && n4->car && nint(n4->car->car) == NODE_SPLAT) {\n codegen(s, n4->car, VAL);\n gen_move(s, cursp(), exc, 0);\n push_n(2); pop_n(2); /* space for one arg and a block */\n pop();\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n if (n4) {\n codegen(s, n4->car, VAL);\n }\n else {\n genop_2(s, OP_GETCONST, cursp(), new_sym(s, MRB_SYM_2(s->mrb, StandardError)));\n push();\n }\n pop();\n genop_2(s, OP_RESCUE, exc, cursp());\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, val);\n pos2 = tmp;\n if (n4) {\n n4 = n4->cdr;\n }\n } while (n4);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n\n pop();\n if (n3->cdr->car) {\n gen_assignment(s, n3->cdr->car, NULL, exc, NOVAL);\n }\n if (n3->cdr->cdr->car) {\n codegen(s, n3->cdr->cdr->car, val);\n if (val) pop();\n }\n tmp = genjmp(s, OP_JMP, exend);\n exend = tmp;\n n2 = n2->cdr;\n push();\n }\n if (pos1 != JMPLINK_START) {\n dispatch(s, pos1);\n genop_1(s, OP_RAISEIF, exc);\n }\n }\n pop();\n tree = tree->cdr;\n dispatch(s, noexc);\n if (tree->car) {\n codegen(s, tree->car, val);\n }\n else if (val) {\n push();\n }\n dispatch_linked(s, exend);\n loop_pop(s, NOVAL);\n }\n break;\n\n case NODE_ENSURE:\n if (!tree->cdr || !tree->cdr->cdr ||\n (nint(tree->cdr->cdr->car) == NODE_BEGIN &&\n tree->cdr->cdr->cdr)) {\n int catch_entry, begin, end, target;\n int idx;\n\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, val);\n end = target = s->pc;\n push();\n idx = cursp();\n genop_1(s, OP_EXCEPT, idx);\n push();\n codegen(s, tree->cdr->cdr, NOVAL);\n pop();\n genop_1(s, OP_RAISEIF, idx);\n pop();\n catch_handler_set(s, catch_entry, MRB_CATCH_ENSURE, begin, end, target);\n }\n else { /* empty ensure ignored */\n codegen(s, tree->car, val);\n }\n break;\n\n case NODE_LAMBDA:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_LAMBDA, cursp(), idx);\n push();\n }\n break;\n\n case NODE_BLOCK:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_BLOCK, cursp(), idx);\n push();\n }\n break;\n\n case NODE_IF:\n {\n uint32_t pos1, pos2;\n mrb_bool nil_p = FALSE;\n node *elsepart = tree->cdr->cdr->car;\n\n if (!tree->car) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (true_always(tree->car)) {\n codegen(s, tree->cdr->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n mrb_sym mid = nsym(n->cdr->car);\n mrb_sym sym_nil_p = MRB_SYM_Q_2(s->mrb, nil);\n if (mid == sym_nil_p && n->cdr->cdr->car == NULL) {\n nil_p = TRUE;\n codegen(s, n->car, VAL);\n }\n }\n if (!nil_p) {\n codegen(s, tree->car, VAL);\n }\n pop();\n if (val || tree->cdr->car) {\n if (nil_p) {\n pos2 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch(s, pos2);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->car, val);\n if (val) pop();\n if (elsepart || val) {\n pos2 = genjmp_0(s, OP_JMP);\n dispatch(s, pos1);\n codegen(s, elsepart, val);\n dispatch(s, pos2);\n }\n else {\n dispatch(s, pos1);\n }\n }\n else { /* empty then-part */\n if (elsepart) {\n if (nil_p) {\n pos1 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPIF, cursp(), val);\n }\n codegen(s, elsepart, val);\n dispatch(s, pos1);\n }\n else if (val && !nil_p) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n }\n break;\n\n case NODE_AND:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_OR:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPIF, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_WHILE:\n case NODE_UNTIL:\n {\n if (true_always(tree->car)) {\n if (nt == NODE_UNTIL) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n else if (false_always(tree->car)) {\n if (nt == NODE_WHILE) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n\n uint32_t pos = JMPLINK_START;\n struct loopinfo *lp = loop_push(s, LOOP_NORMAL);\n\n if (!val) lp->reg = -1;\n lp->pc0 = new_label(s);\n codegen(s, tree->car, VAL);\n pop();\n if (nt == NODE_WHILE) {\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), NOVAL);\n }\n else {\n pos = genjmp2_0(s, OP_JMPIF, cursp(), NOVAL);\n }\n lp->pc1 = new_label(s);\n codegen(s, tree->cdr, NOVAL);\n genjmp(s, OP_JMP, lp->pc0);\n dispatch(s, pos);\n loop_pop(s, val);\n }\n break;\n\n case NODE_FOR:\n for_body(s, tree);\n if (val) push();\n break;\n\n case NODE_CASE:\n {\n int head = 0;\n uint32_t pos1, pos2, pos3, tmp;\n node *n;\n\n pos3 = JMPLINK_START;\n if (tree->car) {\n head = cursp();\n codegen(s, tree->car, VAL);\n }\n tree = tree->cdr;\n while (tree) {\n n = tree->car->car;\n pos1 = pos2 = JMPLINK_START;\n while (n) {\n codegen(s, n->car, VAL);\n if (head) {\n gen_move(s, cursp(), head, 0);\n push(); push(); pop(); pop(); pop();\n if (nint(n->car->car) == NODE_SPLAT) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_OPSYM_2(s->mrb, eqq)), 1);\n }\n }\n else {\n pop();\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, NOVAL);\n pos2 = tmp;\n n = n->cdr;\n }\n if (tree->car->car) {\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n }\n codegen(s, tree->car->cdr, val);\n if (val) pop();\n tmp = genjmp(s, OP_JMP, pos3);\n pos3 = tmp;\n dispatch(s, pos1);\n tree = tree->cdr;\n }\n if (val) {\n uint32_t pos = cursp();\n genop_1(s, OP_LOADNIL, cursp());\n if (pos3 != JMPLINK_START) dispatch_linked(s, pos3);\n if (head) pop();\n if (cursp() != pos) {\n gen_move(s, cursp(), pos, 0);\n }\n push();\n }\n else {\n if (pos3 != JMPLINK_START) {\n dispatch_linked(s, pos3);\n }\n if (head) {\n pop();\n }\n }\n }\n break;\n\n case NODE_SCOPE:\n scope_body(s, tree, NOVAL);\n break;\n\n case NODE_FCALL:\n case NODE_CALL:\n gen_call(s, tree, val, 0);\n break;\n case NODE_SCALL:\n gen_call(s, tree, val, 1);\n break;\n\n case NODE_DOT2:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_INC, cursp());\n push();\n }\n break;\n\n case NODE_DOT3:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_EXC, cursp());\n push();\n }\n break;\n\n case NODE_COLON2:\n {\n int sym = new_sym(s, nsym(tree->cdr));\n\n codegen(s, tree->car, VAL);\n pop();\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_COLON3:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_ARRAY:\n {\n int n;\n\n n = gen_values(s, tree, val, 0);\n if (val) {\n if (n >= 0) {\n pop_n(n);\n genop_2(s, OP_ARRAY, cursp(), n);\n }\n push();\n }\n }\n break;\n\n case NODE_HASH:\n case NODE_KW_HASH:\n {\n int nk = gen_hash(s, tree, val, GEN_LIT_ARY_MAX);\n if (val && nk >= 0) {\n pop_n(nk*2);\n genop_2(s, OP_HASH, cursp(), nk);\n push();\n }\n }\n break;\n\n case NODE_SPLAT:\n codegen(s, tree, val);\n break;\n\n case NODE_ASGN:\n gen_assignment(s, tree->car, tree->cdr, 0, val);\n break;\n\n case NODE_MASGN:\n {\n int len = 0, n = 0, post = 0;\n node *t = tree->cdr, *p;\n int rhs = cursp();\n\n if (nint(t->car) == NODE_ARRAY && t->cdr && nosplat(t->cdr)) {\n /* fixed rhs */\n t = t->cdr;\n while (t) {\n codegen(s, t->car, VAL);\n len++;\n t = t->cdr;\n }\n tree = tree->car;\n if (tree->car) { /* pre */\n t = tree->car;\n n = 0;\n while (t) {\n if (n < len) {\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n n++;\n }\n else {\n genop_1(s, OP_LOADNIL, rhs+n);\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n }\n t = t->cdr;\n }\n }\n t = tree->cdr;\n if (t) {\n if (t->cdr) { /* post count */\n p = t->cdr->car;\n while (p) {\n post++;\n p = p->cdr;\n }\n }\n if (t->car) { /* rest (len - pre - post) */\n int rn;\n\n if (len < post + n) {\n rn = 0;\n }\n else {\n rn = len - post - n;\n }\n genop_3(s, OP_ARRAY2, cursp(), rhs+n, rn);\n gen_assignment(s, t->car, NULL, cursp(), NOVAL);\n n += rn;\n }\n if (t->cdr && t->cdr->car) {\n t = t->cdr->car;\n while (ncar, NULL, rhs+n, NOVAL);\n t = t->cdr;\n n++;\n }\n }\n }\n pop_n(len);\n if (val) {\n genop_2(s, OP_ARRAY, rhs, len);\n push();\n }\n }\n else {\n /* variable rhs */\n codegen(s, t, VAL);\n gen_vmassignment(s, tree->car, rhs, val);\n if (!val) {\n pop();\n }\n }\n }\n break;\n\n case NODE_OP_ASGN:\n {\n mrb_sym sym = nsym(tree->cdr->car);\n mrb_int len;\n const char *name = mrb_sym_name_len(s->mrb, sym, &len);\n int idx, callargs = -1, vsp = -1;\n\n if ((len == 2 && name[0] == '|' && name[1] == '|') &&\n (nint(tree->car->car) == NODE_CONST ||\n nint(tree->car->car) == NODE_CVAR)) {\n int catch_entry, begin, end;\n int noexc, exc;\n struct loopinfo *lp;\n\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n exc = cursp();\n codegen(s, tree->car, VAL);\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n lp->type = LOOP_RESCUE;\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n genop_1(s, OP_EXCEPT, exc);\n genop_1(s, OP_LOADF, exc);\n dispatch(s, noexc);\n loop_pop(s, NOVAL);\n }\n else if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n int base, i, nargs = 0;\n callargs = 0;\n\n if (val) {\n vsp = cursp();\n push();\n }\n codegen(s, n->car, VAL); /* receiver */\n idx = new_sym(s, nsym(n->cdr->car));\n base = cursp()-1;\n if (n->cdr->cdr->car) {\n nargs = gen_values(s, n->cdr->cdr->car->car, VAL, 13);\n if (nargs >= 0) {\n callargs = nargs;\n }\n else { /* varargs */\n push();\n nargs = 1;\n callargs = CALL_MAXARGS;\n }\n }\n /* copy receiver and arguments */\n gen_move(s, cursp(), base, 1);\n for (i=0; icar, VAL);\n }\n if (len == 2 &&\n ((name[0] == '|' && name[1] == '|') ||\n (name[0] == '&' && name[1] == '&'))) {\n uint32_t pos;\n\n pop();\n if (val) {\n if (vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n else {\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n pop();\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n if (nint(tree->car->car) == NODE_CALL) {\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s, nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n else {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n dispatch(s, pos);\n goto exit;\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n push(); pop();\n pop(); pop();\n\n if (len == 1 && name[0] == '+') {\n gen_addsub(s, OP_ADD, cursp());\n }\n else if (len == 1 && name[0] == '-') {\n gen_addsub(s, OP_SUB, cursp());\n }\n else if (len == 1 && name[0] == '*') {\n genop_1(s, OP_MUL, cursp());\n }\n else if (len == 1 && name[0] == '/') {\n genop_1(s, OP_DIV, cursp());\n }\n else if (len == 1 && name[0] == '<') {\n genop_1(s, OP_LT, cursp());\n }\n else if (len == 2 && name[0] == '<' && name[1] == '=') {\n genop_1(s, OP_LE, cursp());\n }\n else if (len == 1 && name[0] == '>') {\n genop_1(s, OP_GT, cursp());\n }\n else if (len == 2 && name[0] == '>' && name[1] == '=') {\n genop_1(s, OP_GE, cursp());\n }\n else {\n idx = new_sym(s, sym);\n genop_3(s, OP_SEND, cursp(), idx, 1);\n }\n if (callargs < 0) {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n else {\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 0);\n }\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s,nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n }\n break;\n\n case NODE_SUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n int n = 0, nk = 0, st = 0;\n\n push();\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (tree) {\n node *args = tree->car;\n if (args) {\n st = n = gen_values(s, args, VAL, 14);\n if (n < 0) {\n st = 1; n = 15;\n push();\n }\n }\n /* keyword arguments */\n if (s2 && (s2->ainfo & 0x1) && tree->cdr->car) {\n nk = gen_hash(s, tree->cdr->car->cdr, VAL, 14);\n if (nk < 0) {st++; nk = 15;}\n else st += nk*2;\n n |= nk<<4;\n }\n /* block arguments */\n if (tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else if (!s2) {/* super at top-level */\n push(); /* no need to push block */\n }\n else {\n gen_blkmove(s, s2->ainfo, lv);\n }\n st++;\n }\n else {\n if (!s2) push();\n else gen_blkmove(s, s2->ainfo, lv);\n st++;\n }\n pop_n(st+1);\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_ZSUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n uint16_t ainfo = 0;\n int n = CALL_MAXARGS;\n int sp = cursp();\n\n push(); /* room for receiver */\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2 && s2->ainfo > 0) {\n ainfo = s2->ainfo;\n }\n if (ainfo > 0) {\n genop_2S(s, OP_ARGARY, cursp(), (ainfo<<4)|(lv & 0xf));\n push(); push(); push(); /* ARGARY pushes 3 values at most */\n pop(); pop(); pop();\n /* keyword arguments */\n if (ainfo & 0x1) {\n n |= CALL_MAXARGS<<4;\n push();\n }\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n push();\n codegen(s, tree->cdr->cdr, VAL);\n }\n }\n else {\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else {\n gen_blkmove(s, 0, lv);\n }\n n = 0;\n }\n s->sp = sp;\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_RETURN:\n if (tree) {\n gen_retval(s, tree);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n if (s->loop) {\n gen_return(s, OP_RETURN_BLK, cursp());\n }\n else {\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_YIELD:\n {\n codegen_scope *s2 = s;\n int lv = 0, ainfo = -1;\n int n = 0, sendv = 0;\n\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2) {\n ainfo = (int)s2->ainfo;\n }\n if (ainfo < 0) codegen_error(s, \"invalid yield (SyntaxError)\");\n push();\n if (tree) {\n n = gen_values(s, tree, VAL, 14);\n if (n < 0) {\n n = sendv = 1;\n push();\n }\n }\n push();pop(); /* space for a block */\n pop_n(n+1);\n genop_2S(s, OP_BLKPUSH, cursp(), (ainfo<<4)|(lv & 0xf));\n if (sendv) n = CALL_MAXARGS;\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, call)), n);\n if (val) push();\n }\n break;\n\n case NODE_BREAK:\n loop_break(s, tree);\n if (val) push();\n break;\n\n case NODE_NEXT:\n if (!s->loop) {\n raise_error(s, \"unexpected next\");\n }\n else if (s->loop->type == LOOP_NORMAL) {\n codegen(s, tree, NOVAL);\n genjmp(s, OP_JMPUW, s->loop->pc0);\n }\n else {\n if (tree) {\n codegen(s, tree, VAL);\n pop();\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_REDO:\n if (!s->loop || s->loop->type == LOOP_BEGIN || s->loop->type == LOOP_RESCUE) {\n raise_error(s, \"unexpected redo\");\n }\n else {\n genjmp(s, OP_JMPUW, s->loop->pc1);\n }\n if (val) push();\n break;\n\n case NODE_RETRY:\n {\n const char *msg = \"unexpected retry\";\n const struct loopinfo *lp = s->loop;\n\n while (lp && lp->type != LOOP_RESCUE) {\n lp = lp->prev;\n }\n if (!lp) {\n raise_error(s, msg);\n }\n else {\n genjmp(s, OP_JMPUW, lp->pc0);\n }\n if (val) push();\n }\n break;\n\n case NODE_LVAR:\n if (val) {\n int idx = lv_idx(s, nsym(tree));\n\n if (idx > 0) {\n gen_move(s, cursp(), idx, val);\n }\n else {\n gen_getupvar(s, cursp(), nsym(tree));\n }\n push();\n }\n break;\n\n case NODE_NVAR:\n if (val) {\n int idx = nint(tree);\n\n gen_move(s, cursp(), idx, val);\n\n push();\n }\n break;\n\n case NODE_GVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_IVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETIV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CONST:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCONST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_BACK_REF:\n if (val) {\n char buf[] = {'$', nchar(tree)};\n int sym = new_sym(s, mrb_intern(s->mrb, buf, sizeof(buf)));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_NTH_REF:\n if (val) {\n mrb_state *mrb = s->mrb;\n mrb_value str;\n int sym;\n\n str = mrb_format(mrb, \"$%d\", nint(tree));\n sym = new_sym(s, mrb_intern_str(mrb, str));\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_ARG:\n /* should not happen */\n break;\n\n case NODE_BLOCK_ARG:\n if (!tree) {\n int idx = lv_idx(s, MRB_OPSYM_2(s->mrb, and));\n\n if (idx == 0) {\n codegen_error(s, \"no anonymous block argument\");\n }\n gen_move(s, cursp(), idx, val);\n }\n else {\n codegen(s, tree, val);\n }\n break;\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->car;\n int base = nint(tree->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, FALSE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, FALSE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_NEGATE:\n {\n nt = nint(tree->car);\n switch (nt) {\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree->cdr;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, -f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->cdr->car;\n int base = nint(tree->cdr->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, TRUE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, TRUE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n default:\n if (val) {\n codegen(s, tree, VAL);\n pop();\n push_n(2);pop_n(2); /* space for receiver&block */\n mrb_sym minus = MRB_OPSYM_2(s->mrb, minus);\n if (!gen_uniop(s, minus, cursp())) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, minus), 0);\n }\n push();\n }\n else {\n codegen(s, tree, NOVAL);\n }\n break;\n }\n }\n break;\n\n case NODE_STR:\n if (val) {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n\n mrb_gc_arena_restore(s->mrb, ai);\n genop_2(s, OP_STRING, cursp(), off);\n push();\n }\n break;\n\n case NODE_HEREDOC:\n tree = ((struct mrb_parser_heredoc_info *)tree)->doc;\n /* fall through */\n case NODE_DSTR:\n if (val) {\n node *n = tree;\n\n if (!n) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n break;\n }\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n }\n else {\n node *n = tree;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_WORDS:\n gen_literal_array(s, tree, FALSE, val);\n break;\n\n case NODE_SYMBOLS:\n gen_literal_array(s, tree, TRUE, val);\n break;\n\n case NODE_DXSTR:\n {\n node *n;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, MRB_SYM_2(s->mrb, Kernel));\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n codegen(s, tree->car, VAL);\n n = tree->cdr;\n while (n) {\n if (nint(n->car->car) == NODE_XSTR) {\n n->car->car = (struct mrb_ast_node*)(intptr_t)NODE_STR;\n mrb_assert(!n->cdr); /* must be the end */\n }\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n push(); /* for block */\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_XSTR:\n {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n int sym;\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push(); push();\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_REGX:\n if (val) {\n char *p1 = (char*)tree->car;\n char *p2 = (char*)tree->cdr->car;\n char *p3 = (char*)tree->cdr->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int off = new_lit(s, mrb_str_new_cstr(s->mrb, p1));\n int argc = 1;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push();\n if (p2 || p3) {\n if (p2) { /* opt */\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n push();\n argc++;\n if (p3) { /* enc */\n off = new_lit(s, mrb_str_new(s->mrb, p3, 1));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n break;\n\n case NODE_DREGX:\n if (val) {\n node *n = tree->car;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int argc = 1;\n int off;\n char *p;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n n = tree->cdr->cdr;\n if (n->car) { /* tail */\n p = (char*)n->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p));\n codegen(s, tree->car, VAL);\n genop_2(s, OP_STRING, cursp(), off);\n pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n }\n if (n->cdr->car) { /* opt */\n char *p2 = (char*)n->cdr->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n if (n->cdr->cdr) { /* enc */\n char *p2 = (char*)n->cdr->cdr;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n else {\n node *n = tree->car;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_SYM:\n if (val) {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_LOADSYM, cursp(), sym);\n push();\n }\n break;\n\n case NODE_DSYM:\n codegen(s, tree, val);\n if (val) {\n gen_intern(s);\n }\n break;\n\n case NODE_SELF:\n if (val) {\n genop_1(s, OP_LOADSELF, cursp());\n push();\n }\n break;\n\n case NODE_NIL:\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n break;\n\n case NODE_TRUE:\n if (val) {\n genop_1(s, OP_LOADT, cursp());\n push();\n }\n break;\n\n case NODE_FALSE:\n if (val) {\n genop_1(s, OP_LOADF, cursp());\n push();\n }\n break;\n\n case NODE_ALIAS:\n {\n int a = new_sym(s, nsym(tree->car));\n int b = new_sym(s, nsym(tree->cdr));\n\n genop_2(s, OP_ALIAS, a, b);\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_UNDEF:\n {\n node *t = tree;\n\n while (t) {\n int symbol = new_sym(s, nsym(t->car));\n genop_1(s, OP_UNDEF, symbol);\n t = t->cdr;\n }\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_CLASS:\n {\n int idx;\n node *body;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n if (tree->cdr->car) {\n codegen(s, tree->cdr->car, VAL);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n pop(); pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_CLASS, cursp(), idx);\n body = tree->cdr->cdr->car;\n if (nint(body->cdr->car) == NODE_BEGIN && body->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, body, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_MODULE:\n {\n int idx;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_MODULE, cursp(), idx);\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_SCLASS:\n {\n int idx;\n\n codegen(s, tree->car, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_DEF:\n {\n int sym = new_sym(s, nsym(tree->car));\n int idx = lambda_body(s, tree->cdr, 0);\n\n genop_1(s, OP_TCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n push(); pop();\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_SDEF:\n {\n node *recv = tree->car;\n int sym = new_sym(s, nsym(tree->cdr->car));\n int idx = lambda_body(s, tree->cdr->cdr, 0);\n\n codegen(s, recv, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_POSTEXE:\n codegen(s, tree, NOVAL);\n break;\n\n default:\n break;\n }\n exit:\n s->rlev = rlev;\n}", "func_hash": 58515144323548179990155902514562288963, "file_name": "codegen.c", "file_hash": 69656694646846748382204460208931803734, "cwe": ["CWE-476"], "cve": "CVE-2022-0632", "cve_desc": "NULL Pointer Dereference in Homebrew mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0632"} {"idx": 238366, "project": "mruby", "commit_id": "44f591aa8f7091e6ca6cb418e428ae6d4ceaf77d", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/44f591aa8f7091e6ca6cb418e428ae6d4ceaf77d", "commit_message": "codegen.c: adjust stack position for `OP_SUPER` instruction.", "target": 0, "func": "codegen(codegen_scope *s, node *tree, int val)\n{\n int nt;\n int rlev = s->rlev;\n\n if (!tree) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n return;\n }\n\n s->rlev++;\n if (s->rlev > MRB_CODEGEN_LEVEL_MAX) {\n codegen_error(s, \"too complex expression\");\n }\n if (s->irep && s->filename_index != tree->filename_index) {\n mrb_sym fname = mrb_parser_get_filename(s->parser, s->filename_index);\n const char *filename = mrb_sym_name_len(s->mrb, fname, NULL);\n\n mrb_debug_info_append_file(s->mrb, s->irep->debug_info,\n filename, s->lines, s->debug_start_pos, s->pc);\n s->debug_start_pos = s->pc;\n s->filename_index = tree->filename_index;\n s->filename_sym = mrb_parser_get_filename(s->parser, tree->filename_index);\n }\n\n nt = nint(tree->car);\n s->lineno = tree->lineno;\n tree = tree->cdr;\n switch (nt) {\n case NODE_BEGIN:\n if (val && !tree) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n while (tree) {\n codegen(s, tree->car, tree->cdr ? NOVAL : val);\n tree = tree->cdr;\n }\n break;\n\n case NODE_RESCUE:\n {\n int noexc;\n uint32_t exend, pos1, pos2, tmp;\n struct loopinfo *lp;\n int catch_entry, begin, end;\n\n if (tree->car == NULL) goto exit;\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, VAL);\n pop();\n lp->type = LOOP_RESCUE;\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n tree = tree->cdr;\n exend = JMPLINK_START;\n pos1 = JMPLINK_START;\n if (tree->car) {\n node *n2 = tree->car;\n int exc = cursp();\n\n genop_1(s, OP_EXCEPT, exc);\n push();\n while (n2) {\n node *n3 = n2->car;\n node *n4 = n3->car;\n\n dispatch(s, pos1);\n pos2 = JMPLINK_START;\n do {\n if (n4 && n4->car && nint(n4->car->car) == NODE_SPLAT) {\n codegen(s, n4->car, VAL);\n gen_move(s, cursp(), exc, 0);\n push_n(2); pop_n(2); /* space for one arg and a block */\n pop();\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n if (n4) {\n codegen(s, n4->car, VAL);\n }\n else {\n genop_2(s, OP_GETCONST, cursp(), new_sym(s, MRB_SYM_2(s->mrb, StandardError)));\n push();\n }\n pop();\n genop_2(s, OP_RESCUE, exc, cursp());\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, val);\n pos2 = tmp;\n if (n4) {\n n4 = n4->cdr;\n }\n } while (n4);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n\n pop();\n if (n3->cdr->car) {\n gen_assignment(s, n3->cdr->car, NULL, exc, NOVAL);\n }\n if (n3->cdr->cdr->car) {\n codegen(s, n3->cdr->cdr->car, val);\n if (val) pop();\n }\n tmp = genjmp(s, OP_JMP, exend);\n exend = tmp;\n n2 = n2->cdr;\n push();\n }\n if (pos1 != JMPLINK_START) {\n dispatch(s, pos1);\n genop_1(s, OP_RAISEIF, exc);\n }\n }\n pop();\n tree = tree->cdr;\n dispatch(s, noexc);\n if (tree->car) {\n codegen(s, tree->car, val);\n }\n else if (val) {\n push();\n }\n dispatch_linked(s, exend);\n loop_pop(s, NOVAL);\n }\n break;\n\n case NODE_ENSURE:\n if (!tree->cdr || !tree->cdr->cdr ||\n (nint(tree->cdr->cdr->car) == NODE_BEGIN &&\n tree->cdr->cdr->cdr)) {\n int catch_entry, begin, end, target;\n int idx;\n\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, val);\n end = target = s->pc;\n push();\n idx = cursp();\n genop_1(s, OP_EXCEPT, idx);\n push();\n codegen(s, tree->cdr->cdr, NOVAL);\n pop();\n genop_1(s, OP_RAISEIF, idx);\n pop();\n catch_handler_set(s, catch_entry, MRB_CATCH_ENSURE, begin, end, target);\n }\n else { /* empty ensure ignored */\n codegen(s, tree->car, val);\n }\n break;\n\n case NODE_LAMBDA:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_LAMBDA, cursp(), idx);\n push();\n }\n break;\n\n case NODE_BLOCK:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_BLOCK, cursp(), idx);\n push();\n }\n break;\n\n case NODE_IF:\n {\n uint32_t pos1, pos2;\n mrb_bool nil_p = FALSE;\n node *elsepart = tree->cdr->cdr->car;\n\n if (!tree->car) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (true_always(tree->car)) {\n codegen(s, tree->cdr->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n mrb_sym mid = nsym(n->cdr->car);\n mrb_sym sym_nil_p = MRB_SYM_Q_2(s->mrb, nil);\n if (mid == sym_nil_p && n->cdr->cdr->car == NULL) {\n nil_p = TRUE;\n codegen(s, n->car, VAL);\n }\n }\n if (!nil_p) {\n codegen(s, tree->car, VAL);\n }\n pop();\n if (val || tree->cdr->car) {\n if (nil_p) {\n pos2 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch(s, pos2);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->car, val);\n if (val) pop();\n if (elsepart || val) {\n pos2 = genjmp_0(s, OP_JMP);\n dispatch(s, pos1);\n codegen(s, elsepart, val);\n dispatch(s, pos2);\n }\n else {\n dispatch(s, pos1);\n }\n }\n else { /* empty then-part */\n if (elsepart) {\n if (nil_p) {\n pos1 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPIF, cursp(), val);\n }\n codegen(s, elsepart, val);\n dispatch(s, pos1);\n }\n else if (val && !nil_p) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n }\n break;\n\n case NODE_AND:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_OR:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPIF, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_WHILE:\n case NODE_UNTIL:\n {\n if (true_always(tree->car)) {\n if (nt == NODE_UNTIL) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n else if (false_always(tree->car)) {\n if (nt == NODE_WHILE) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n\n uint32_t pos = JMPLINK_START;\n struct loopinfo *lp = loop_push(s, LOOP_NORMAL);\n\n if (!val) lp->reg = -1;\n lp->pc0 = new_label(s);\n codegen(s, tree->car, VAL);\n pop();\n if (nt == NODE_WHILE) {\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), NOVAL);\n }\n else {\n pos = genjmp2_0(s, OP_JMPIF, cursp(), NOVAL);\n }\n lp->pc1 = new_label(s);\n codegen(s, tree->cdr, NOVAL);\n genjmp(s, OP_JMP, lp->pc0);\n dispatch(s, pos);\n loop_pop(s, val);\n }\n break;\n\n case NODE_FOR:\n for_body(s, tree);\n if (val) push();\n break;\n\n case NODE_CASE:\n {\n int head = 0;\n uint32_t pos1, pos2, pos3, tmp;\n node *n;\n\n pos3 = JMPLINK_START;\n if (tree->car) {\n head = cursp();\n codegen(s, tree->car, VAL);\n }\n tree = tree->cdr;\n while (tree) {\n n = tree->car->car;\n pos1 = pos2 = JMPLINK_START;\n while (n) {\n codegen(s, n->car, VAL);\n if (head) {\n gen_move(s, cursp(), head, 0);\n push(); push(); pop(); pop(); pop();\n if (nint(n->car->car) == NODE_SPLAT) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_OPSYM_2(s->mrb, eqq)), 1);\n }\n }\n else {\n pop();\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, NOVAL);\n pos2 = tmp;\n n = n->cdr;\n }\n if (tree->car->car) {\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n }\n codegen(s, tree->car->cdr, val);\n if (val) pop();\n tmp = genjmp(s, OP_JMP, pos3);\n pos3 = tmp;\n dispatch(s, pos1);\n tree = tree->cdr;\n }\n if (val) {\n uint32_t pos = cursp();\n genop_1(s, OP_LOADNIL, cursp());\n if (pos3 != JMPLINK_START) dispatch_linked(s, pos3);\n if (head) pop();\n if (cursp() != pos) {\n gen_move(s, cursp(), pos, 0);\n }\n push();\n }\n else {\n if (pos3 != JMPLINK_START) {\n dispatch_linked(s, pos3);\n }\n if (head) {\n pop();\n }\n }\n }\n break;\n\n case NODE_SCOPE:\n scope_body(s, tree, NOVAL);\n break;\n\n case NODE_FCALL:\n case NODE_CALL:\n gen_call(s, tree, val, 0);\n break;\n case NODE_SCALL:\n gen_call(s, tree, val, 1);\n break;\n\n case NODE_DOT2:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_INC, cursp());\n push();\n }\n break;\n\n case NODE_DOT3:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_EXC, cursp());\n push();\n }\n break;\n\n case NODE_COLON2:\n {\n int sym = new_sym(s, nsym(tree->cdr));\n\n codegen(s, tree->car, VAL);\n pop();\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_COLON3:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_ARRAY:\n {\n int n;\n\n n = gen_values(s, tree, val, 0);\n if (val) {\n if (n >= 0) {\n pop_n(n);\n genop_2(s, OP_ARRAY, cursp(), n);\n }\n push();\n }\n }\n break;\n\n case NODE_HASH:\n case NODE_KW_HASH:\n {\n int nk = gen_hash(s, tree, val, GEN_LIT_ARY_MAX);\n if (val && nk >= 0) {\n pop_n(nk*2);\n genop_2(s, OP_HASH, cursp(), nk);\n push();\n }\n }\n break;\n\n case NODE_SPLAT:\n codegen(s, tree, val);\n break;\n\n case NODE_ASGN:\n gen_assignment(s, tree->car, tree->cdr, 0, val);\n break;\n\n case NODE_MASGN:\n {\n int len = 0, n = 0, post = 0;\n node *t = tree->cdr, *p;\n int rhs = cursp();\n\n if (nint(t->car) == NODE_ARRAY && t->cdr && nosplat(t->cdr)) {\n /* fixed rhs */\n t = t->cdr;\n while (t) {\n codegen(s, t->car, VAL);\n len++;\n t = t->cdr;\n }\n tree = tree->car;\n if (tree->car) { /* pre */\n t = tree->car;\n n = 0;\n while (t) {\n if (n < len) {\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n n++;\n }\n else {\n genop_1(s, OP_LOADNIL, rhs+n);\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n }\n t = t->cdr;\n }\n }\n t = tree->cdr;\n if (t) {\n if (t->cdr) { /* post count */\n p = t->cdr->car;\n while (p) {\n post++;\n p = p->cdr;\n }\n }\n if (t->car) { /* rest (len - pre - post) */\n int rn;\n\n if (len < post + n) {\n rn = 0;\n }\n else {\n rn = len - post - n;\n }\n genop_3(s, OP_ARRAY2, cursp(), rhs+n, rn);\n gen_assignment(s, t->car, NULL, cursp(), NOVAL);\n n += rn;\n }\n if (t->cdr && t->cdr->car) {\n t = t->cdr->car;\n while (ncar, NULL, rhs+n, NOVAL);\n t = t->cdr;\n n++;\n }\n }\n }\n pop_n(len);\n if (val) {\n genop_2(s, OP_ARRAY, rhs, len);\n push();\n }\n }\n else {\n /* variable rhs */\n codegen(s, t, VAL);\n gen_vmassignment(s, tree->car, rhs, val);\n if (!val) {\n pop();\n }\n }\n }\n break;\n\n case NODE_OP_ASGN:\n {\n mrb_sym sym = nsym(tree->cdr->car);\n mrb_int len;\n const char *name = mrb_sym_name_len(s->mrb, sym, &len);\n int idx, callargs = -1, vsp = -1;\n\n if ((len == 2 && name[0] == '|' && name[1] == '|') &&\n (nint(tree->car->car) == NODE_CONST ||\n nint(tree->car->car) == NODE_CVAR)) {\n int catch_entry, begin, end;\n int noexc, exc;\n struct loopinfo *lp;\n\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n exc = cursp();\n codegen(s, tree->car, VAL);\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n lp->type = LOOP_RESCUE;\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n genop_1(s, OP_EXCEPT, exc);\n genop_1(s, OP_LOADF, exc);\n dispatch(s, noexc);\n loop_pop(s, NOVAL);\n }\n else if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n int base, i, nargs = 0;\n callargs = 0;\n\n if (val) {\n vsp = cursp();\n push();\n }\n codegen(s, n->car, VAL); /* receiver */\n idx = new_sym(s, nsym(n->cdr->car));\n base = cursp()-1;\n if (n->cdr->cdr->car) {\n nargs = gen_values(s, n->cdr->cdr->car->car, VAL, 13);\n if (nargs >= 0) {\n callargs = nargs;\n }\n else { /* varargs */\n push();\n nargs = 1;\n callargs = CALL_MAXARGS;\n }\n }\n /* copy receiver and arguments */\n gen_move(s, cursp(), base, 1);\n for (i=0; icar, VAL);\n }\n if (len == 2 &&\n ((name[0] == '|' && name[1] == '|') ||\n (name[0] == '&' && name[1] == '&'))) {\n uint32_t pos;\n\n pop();\n if (val) {\n if (vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n else {\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n pop();\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n if (nint(tree->car->car) == NODE_CALL) {\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s, nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n else {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n dispatch(s, pos);\n goto exit;\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n push(); pop();\n pop(); pop();\n\n if (len == 1 && name[0] == '+') {\n gen_addsub(s, OP_ADD, cursp());\n }\n else if (len == 1 && name[0] == '-') {\n gen_addsub(s, OP_SUB, cursp());\n }\n else if (len == 1 && name[0] == '*') {\n genop_1(s, OP_MUL, cursp());\n }\n else if (len == 1 && name[0] == '/') {\n genop_1(s, OP_DIV, cursp());\n }\n else if (len == 1 && name[0] == '<') {\n genop_1(s, OP_LT, cursp());\n }\n else if (len == 2 && name[0] == '<' && name[1] == '=') {\n genop_1(s, OP_LE, cursp());\n }\n else if (len == 1 && name[0] == '>') {\n genop_1(s, OP_GT, cursp());\n }\n else if (len == 2 && name[0] == '>' && name[1] == '=') {\n genop_1(s, OP_GE, cursp());\n }\n else {\n idx = new_sym(s, sym);\n genop_3(s, OP_SEND, cursp(), idx, 1);\n }\n if (callargs < 0) {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n else {\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 0);\n }\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s,nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n }\n break;\n\n case NODE_SUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n int n = 0, nk = 0, st = 0;\n\n push();\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (tree) {\n node *args = tree->car;\n if (args) {\n st = n = gen_values(s, args, VAL, 14);\n if (n < 0) {\n st = 1; n = 15;\n push();\n }\n }\n /* keyword arguments */\n if (s2 && (s2->ainfo & 0x1) && tree->cdr->car) {\n nk = gen_hash(s, tree->cdr->car->cdr, VAL, 14);\n if (nk < 0) {st++; nk = 15;}\n else st += nk*2;\n n |= nk<<4;\n }\n /* block arguments */\n if (tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else if (s2) gen_blkmove(s, s2->ainfo, lv);\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n else {\n if (s2) gen_blkmove(s, s2->ainfo, lv);\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n st++;\n pop_n(st+1);\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_ZSUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n uint16_t ainfo = 0;\n int n = CALL_MAXARGS;\n int sp = cursp();\n\n push(); /* room for receiver */\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2 && s2->ainfo > 0) {\n ainfo = s2->ainfo;\n }\n if (ainfo > 0) {\n genop_2S(s, OP_ARGARY, cursp(), (ainfo<<4)|(lv & 0xf));\n push(); push(); push(); /* ARGARY pushes 3 values at most */\n pop(); pop(); pop();\n /* keyword arguments */\n if (ainfo & 0x1) {\n n |= CALL_MAXARGS<<4;\n push();\n }\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n push();\n codegen(s, tree->cdr->cdr, VAL);\n }\n }\n else {\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else {\n gen_blkmove(s, 0, lv);\n }\n n = 0;\n }\n s->sp = sp;\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_RETURN:\n if (tree) {\n gen_retval(s, tree);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n if (s->loop) {\n gen_return(s, OP_RETURN_BLK, cursp());\n }\n else {\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_YIELD:\n {\n codegen_scope *s2 = s;\n int lv = 0, ainfo = -1;\n int n = 0, sendv = 0;\n\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2) {\n ainfo = (int)s2->ainfo;\n }\n if (ainfo < 0) codegen_error(s, \"invalid yield (SyntaxError)\");\n push();\n if (tree) {\n n = gen_values(s, tree, VAL, 14);\n if (n < 0) {\n n = sendv = 1;\n push();\n }\n }\n push();pop(); /* space for a block */\n pop_n(n+1);\n genop_2S(s, OP_BLKPUSH, cursp(), (ainfo<<4)|(lv & 0xf));\n if (sendv) n = CALL_MAXARGS;\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, call)), n);\n if (val) push();\n }\n break;\n\n case NODE_BREAK:\n loop_break(s, tree);\n if (val) push();\n break;\n\n case NODE_NEXT:\n if (!s->loop) {\n raise_error(s, \"unexpected next\");\n }\n else if (s->loop->type == LOOP_NORMAL) {\n codegen(s, tree, NOVAL);\n genjmp(s, OP_JMPUW, s->loop->pc0);\n }\n else {\n if (tree) {\n codegen(s, tree, VAL);\n pop();\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_REDO:\n if (!s->loop || s->loop->type == LOOP_BEGIN || s->loop->type == LOOP_RESCUE) {\n raise_error(s, \"unexpected redo\");\n }\n else {\n genjmp(s, OP_JMPUW, s->loop->pc1);\n }\n if (val) push();\n break;\n\n case NODE_RETRY:\n {\n const char *msg = \"unexpected retry\";\n const struct loopinfo *lp = s->loop;\n\n while (lp && lp->type != LOOP_RESCUE) {\n lp = lp->prev;\n }\n if (!lp) {\n raise_error(s, msg);\n }\n else {\n genjmp(s, OP_JMPUW, lp->pc0);\n }\n if (val) push();\n }\n break;\n\n case NODE_LVAR:\n if (val) {\n int idx = lv_idx(s, nsym(tree));\n\n if (idx > 0) {\n gen_move(s, cursp(), idx, val);\n }\n else {\n gen_getupvar(s, cursp(), nsym(tree));\n }\n push();\n }\n break;\n\n case NODE_NVAR:\n if (val) {\n int idx = nint(tree);\n\n gen_move(s, cursp(), idx, val);\n\n push();\n }\n break;\n\n case NODE_GVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_IVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETIV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CONST:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCONST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_BACK_REF:\n if (val) {\n char buf[] = {'$', nchar(tree)};\n int sym = new_sym(s, mrb_intern(s->mrb, buf, sizeof(buf)));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_NTH_REF:\n if (val) {\n mrb_state *mrb = s->mrb;\n mrb_value str;\n int sym;\n\n str = mrb_format(mrb, \"$%d\", nint(tree));\n sym = new_sym(s, mrb_intern_str(mrb, str));\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_ARG:\n /* should not happen */\n break;\n\n case NODE_BLOCK_ARG:\n if (!tree) {\n int idx = lv_idx(s, MRB_OPSYM_2(s->mrb, and));\n\n if (idx == 0) {\n codegen_error(s, \"no anonymous block argument\");\n }\n gen_move(s, cursp(), idx, val);\n if (val) push();\n }\n else {\n codegen(s, tree, val);\n }\n break;\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->car;\n int base = nint(tree->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, FALSE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, FALSE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_NEGATE:\n {\n nt = nint(tree->car);\n switch (nt) {\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree->cdr;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, -f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->cdr->car;\n int base = nint(tree->cdr->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, TRUE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, TRUE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n default:\n if (val) {\n codegen(s, tree, VAL);\n pop();\n push_n(2);pop_n(2); /* space for receiver&block */\n mrb_sym minus = MRB_OPSYM_2(s->mrb, minus);\n if (!gen_uniop(s, minus, cursp())) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, minus), 0);\n }\n push();\n }\n else {\n codegen(s, tree, NOVAL);\n }\n break;\n }\n }\n break;\n\n case NODE_STR:\n if (val) {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n\n mrb_gc_arena_restore(s->mrb, ai);\n genop_2(s, OP_STRING, cursp(), off);\n push();\n }\n break;\n\n case NODE_HEREDOC:\n tree = ((struct mrb_parser_heredoc_info *)tree)->doc;\n /* fall through */\n case NODE_DSTR:\n if (val) {\n node *n = tree;\n\n if (!n) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n break;\n }\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n }\n else {\n node *n = tree;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_WORDS:\n gen_literal_array(s, tree, FALSE, val);\n break;\n\n case NODE_SYMBOLS:\n gen_literal_array(s, tree, TRUE, val);\n break;\n\n case NODE_DXSTR:\n {\n node *n;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, MRB_SYM_2(s->mrb, Kernel));\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n codegen(s, tree->car, VAL);\n n = tree->cdr;\n while (n) {\n if (nint(n->car->car) == NODE_XSTR) {\n n->car->car = (struct mrb_ast_node*)(intptr_t)NODE_STR;\n mrb_assert(!n->cdr); /* must be the end */\n }\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n push(); /* for block */\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_XSTR:\n {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n int sym;\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push(); push();\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_REGX:\n if (val) {\n char *p1 = (char*)tree->car;\n char *p2 = (char*)tree->cdr->car;\n char *p3 = (char*)tree->cdr->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int off = new_lit(s, mrb_str_new_cstr(s->mrb, p1));\n int argc = 1;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push();\n if (p2 || p3) {\n if (p2) { /* opt */\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n push();\n argc++;\n if (p3) { /* enc */\n off = new_lit(s, mrb_str_new(s->mrb, p3, 1));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n break;\n\n case NODE_DREGX:\n if (val) {\n node *n = tree->car;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int argc = 1;\n int off;\n char *p;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n n = tree->cdr->cdr;\n if (n->car) { /* tail */\n p = (char*)n->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p));\n codegen(s, tree->car, VAL);\n genop_2(s, OP_STRING, cursp(), off);\n pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n }\n if (n->cdr->car) { /* opt */\n char *p2 = (char*)n->cdr->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n if (n->cdr->cdr) { /* enc */\n char *p2 = (char*)n->cdr->cdr;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n else {\n node *n = tree->car;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_SYM:\n if (val) {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_LOADSYM, cursp(), sym);\n push();\n }\n break;\n\n case NODE_DSYM:\n codegen(s, tree, val);\n if (val) {\n gen_intern(s);\n }\n break;\n\n case NODE_SELF:\n if (val) {\n genop_1(s, OP_LOADSELF, cursp());\n push();\n }\n break;\n\n case NODE_NIL:\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n break;\n\n case NODE_TRUE:\n if (val) {\n genop_1(s, OP_LOADT, cursp());\n push();\n }\n break;\n\n case NODE_FALSE:\n if (val) {\n genop_1(s, OP_LOADF, cursp());\n push();\n }\n break;\n\n case NODE_ALIAS:\n {\n int a = new_sym(s, nsym(tree->car));\n int b = new_sym(s, nsym(tree->cdr));\n\n genop_2(s, OP_ALIAS, a, b);\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_UNDEF:\n {\n node *t = tree;\n\n while (t) {\n int symbol = new_sym(s, nsym(t->car));\n genop_1(s, OP_UNDEF, symbol);\n t = t->cdr;\n }\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_CLASS:\n {\n int idx;\n node *body;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n if (tree->cdr->car) {\n codegen(s, tree->cdr->car, VAL);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n pop(); pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_CLASS, cursp(), idx);\n body = tree->cdr->cdr->car;\n if (nint(body->cdr->car) == NODE_BEGIN && body->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, body, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_MODULE:\n {\n int idx;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_MODULE, cursp(), idx);\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_SCLASS:\n {\n int idx;\n\n codegen(s, tree->car, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_DEF:\n {\n int sym = new_sym(s, nsym(tree->car));\n int idx = lambda_body(s, tree->cdr, 0);\n\n genop_1(s, OP_TCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n push(); pop();\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_SDEF:\n {\n node *recv = tree->car;\n int sym = new_sym(s, nsym(tree->cdr->car));\n int idx = lambda_body(s, tree->cdr->cdr, 0);\n\n codegen(s, recv, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_POSTEXE:\n codegen(s, tree, NOVAL);\n break;\n\n default:\n break;\n }\n exit:\n s->rlev = rlev;\n}", "func_hash": 161613158530480219097800617147460946525, "file_name": "codegen.c", "file_hash": 98037279219613199656864426696127946253, "cwe": ["CWE-476"], "cve": "CVE-2022-0632", "cve_desc": "NULL Pointer Dereference in Homebrew mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0632"} {"idx": 196327, "project": "jerryscript", "commit_id": "c2b662170245a16f46ce02eae68815c325d99821", "project_url": "https://github.com/zherczeg/jerryscript", "commit_url": "https://github.com/jerryscript-project/jerryscript/commit/c2b662170245a16f46ce02eae68815c325d99821", "commit_message": "Fix adding entries to the internal buffer of a Map object (#3805)\n\nWhen appending the key/value pair separately, garbage collection could be\ntriggered before the value is added, which could cause problems during\nmarking. This patch changes insertion to add both values at the same\ntime, which prevents partial entries from being present in the internal\nbuffer.\n\nFixes #3804.\n\nJerryScript-DCO-1.0-Signed-off-by: D\u00e1niel B\u00e1tyai dbatyai@inf.u-szeged.hu", "target": 1, "func": "ecma_op_internal_buffer_append (ecma_collection_t *container_p, /**< internal container pointer */\n ecma_value_t key_arg, /**< key argument */\n ecma_value_t value_arg, /**< value argument */\n lit_magic_string_id_t lit_id) /**< class id */\n{\n JERRY_ASSERT (container_p != NULL);\n\n ecma_collection_push_back (container_p, ecma_copy_value_if_not_object (key_arg));\n\n if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL)\n {\n ecma_collection_push_back (container_p, ecma_copy_value_if_not_object (value_arg));\n }\n\n ECMA_CONTAINER_SET_SIZE (container_p, ECMA_CONTAINER_GET_SIZE (container_p) + 1);\n} /* ecma_op_internal_buffer_append */", "func_hash": 258768242921743946612678935179867504606, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2020-14163", "cve_desc": "An issue was discovered in ecma/operations/ecma-container-object.c in JerryScript 2.2.0. Operations with key/value pairs did not consider the case where garbage collection is triggered after the key operation but before the value operation, as demonstrated by improper read access to memory in ecma_gc_set_object_visited in ecma/base/ecma-gc.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14163"} {"idx": 238757, "project": "jerryscript", "commit_id": "c2b662170245a16f46ce02eae68815c325d99821", "project_url": "https://github.com/zherczeg/jerryscript", "commit_url": "https://github.com/jerryscript-project/jerryscript/commit/c2b662170245a16f46ce02eae68815c325d99821", "commit_message": "Fix adding entries to the internal buffer of a Map object (#3805)\n\nWhen appending the key/value pair separately, garbage collection could be\ntriggered before the value is added, which could cause problems during\nmarking. This patch changes insertion to add both values at the same\ntime, which prevents partial entries from being present in the internal\nbuffer.\n\nFixes #3804.\n\nJerryScript-DCO-1.0-Signed-off-by: D\u00e1niel B\u00e1tyai dbatyai@inf.u-szeged.hu", "target": 0, "func": "ecma_op_internal_buffer_append (ecma_collection_t *container_p, /**< internal container pointer */\n ecma_value_t key_arg, /**< key argument */\n ecma_value_t value_arg, /**< value argument */\n lit_magic_string_id_t lit_id) /**< class id */\n{\n JERRY_ASSERT (container_p != NULL);\n\n if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL)\n {\n ecma_value_t values[] = { ecma_copy_value_if_not_object (key_arg), ecma_copy_value_if_not_object (value_arg) };\n ecma_collection_append (container_p, values, 2);\n }\n else\n {\n ecma_collection_push_back (container_p, ecma_copy_value_if_not_object (key_arg));\n }\n\n ECMA_CONTAINER_SET_SIZE (container_p, ECMA_CONTAINER_GET_SIZE (container_p) + 1);\n} /* ecma_op_internal_buffer_append */", "func_hash": 258997274496404637065803978438012811833, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2020-14163", "cve_desc": "An issue was discovered in ecma/operations/ecma-container-object.c in JerryScript 2.2.0. Operations with key/value pairs did not consider the case where garbage collection is triggered after the key operation but before the value operation, as demonstrated by improper read access to memory in ecma_gc_set_object_visited in ecma/base/ecma-gc.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14163"} {"idx": 196329, "project": "tensorflow", "commit_id": "2e0ee46f1a47675152d3d865797a18358881d7a6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/2e0ee46f1a47675152d3d865797a18358881d7a6", "commit_message": "Ensure non-empty input_splits in tf.raw_ops.UnicodeEncode\n\nPiperOrigin-RevId: 387170080\nChange-Id: I3b489acc51c5cb4124c535b9df7cc6e62ef21766", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n // Operation will treat first argument in input_splits as if it were zero\n // regardless of its actual value since splits should begin with zero and\n // end with the length of the input values vector.\n OP_REQUIRES(\n context, input_splits_flat(0) == 0,\n errors::InvalidArgument(\"First value in input_splits must be zero.\"));\n OP_REQUIRES(context,\n input_splits_flat(input_splits_flat.size() - 1) ==\n input_tensor_flat.size(),\n errors::InvalidArgument(\"Last value in input_splits must be \"\n \"equal to length of input_tensor.\"));\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n OP_REQUIRES(\n context, input_splits_flat(i - 1) <= input_splits_flat(i),\n errors::InvalidArgument(\n \"Values in input_splits must be equal or in ascending order.\"));\n OP_REQUIRES(\n context, input_splits_flat(i) <= input_tensor_flat.size(),\n errors::InvalidArgument(\"Values in input_splits must be less than or \"\n \"equal to input_tensor length.\"));\n for (; idx < input_splits_flat(i); ++idx) {\n int32_t code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "func_hash": 276078631062997071451849125891936041878, "file_name": "unicode_ops.cc", "file_hash": 207141108577863458468228430898848881308, "cwe": ["CWE-787"], "cve": "CVE-2021-37667", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.UnicodeEncode`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/unicode_ops.cc#L533-L539) reads the first dimension of the `input_splits` tensor before validating that this tensor is not empty. We have patched the issue in GitHub commit 2e0ee46f1a47675152d3d865797a18358881d7a6. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37667"} {"idx": 238838, "project": "tensorflow", "commit_id": "2e0ee46f1a47675152d3d865797a18358881d7a6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/2e0ee46f1a47675152d3d865797a18358881d7a6", "commit_message": "Ensure non-empty input_splits in tf.raw_ops.UnicodeEncode\n\nPiperOrigin-RevId: 387170080\nChange-Id: I3b489acc51c5cb4124c535b9df7cc6e62ef21766", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n OP_REQUIRES(\n context, input_splits.NumElements() > 0,\n errors::InvalidArgument(\"Input_splits should contain elements, but \"\n \"given input_values has 0 elements\"));\n // Operation will treat first argument in input_splits as if it were zero\n // regardless of its actual value since splits should begin with zero and\n // end with the length of the input values vector.\n OP_REQUIRES(\n context, input_splits_flat(0) == 0,\n errors::InvalidArgument(\"First value in input_splits must be zero.\"));\n OP_REQUIRES(context,\n input_splits_flat(input_splits_flat.size() - 1) ==\n input_tensor_flat.size(),\n errors::InvalidArgument(\"Last value in input_splits must be \"\n \"equal to length of input_tensor.\"));\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n OP_REQUIRES(\n context, input_splits_flat(i - 1) <= input_splits_flat(i),\n errors::InvalidArgument(\n \"Values in input_splits must be equal or in ascending order.\"));\n OP_REQUIRES(\n context, input_splits_flat(i) <= input_tensor_flat.size(),\n errors::InvalidArgument(\"Values in input_splits must be less than or \"\n \"equal to input_tensor length.\"));\n for (; idx < input_splits_flat(i); ++idx) {\n int32_t code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "func_hash": 223886596515488614384307289586924525522, "file_name": "unicode_ops.cc", "file_hash": 143679864469205740849479952287086508876, "cwe": ["CWE-787"], "cve": "CVE-2021-37667", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.UnicodeEncode`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/unicode_ops.cc#L533-L539) reads the first dimension of the `input_splits` tensor before validating that this tensor is not empty. We have patched the issue in GitHub commit 2e0ee46f1a47675152d3d865797a18358881d7a6. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37667"} {"idx": 196330, "project": "tensorflow", "commit_id": "3ade2efec2e90c6237de32a19680caaa3ebc2845", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/3ade2efec2e90c6237de32a19680caaa3ebc2845", "commit_message": "Fix segmentation fault in tf.image.crop_and_resize when boxes is inf or nan\n\nThis fix tries to address the issue raised in 42129 where segmentation fault\nhappened in tf.image.crop_and_resize when boxes is inf or nan.\n\nThis fix adds the check to make sure boxes is not inf or nan (isfinite)\n\nThis fix fixes 42129.\n\nSigned-off-by: Yong Tang ", "target": 1, "func": "static inline Status ParseAndCheckBoxSizes(const Tensor& boxes,\n const Tensor& box_index,\n int* num_boxes) {\n if (boxes.NumElements() == 0 && box_index.NumElements() == 0) {\n *num_boxes = 0;\n return Status::OK();\n }\n // The shape of 'boxes' is [num_boxes, 4].\n if (boxes.dims() != 2) {\n return errors::InvalidArgument(\"boxes must be 2-D\",\n boxes.shape().DebugString());\n }\n *num_boxes = boxes.dim_size(0);\n if (boxes.dim_size(1) != 4) {\n return errors::InvalidArgument(\"boxes must have 4 columns\");\n }\n // The shape of 'box_index' is [num_boxes].\n if (box_index.dims() != 1) {\n return errors::InvalidArgument(\"box_index must be 1-D\",\n box_index.shape().DebugString());\n }\n if (box_index.dim_size(0) != *num_boxes) {\n return errors::InvalidArgument(\"box_index has incompatible shape\");\n }\n return Status::OK();\n}", "func_hash": 100014527184127166664260006578703403844, "file_name": "crop_and_resize_op.cc", "file_hash": 69576598700769385071105764317719479311, "cwe": ["CWE-787"], "cve": "CVE-2020-15266", "cve_desc": "In Tensorflow before version 2.4.0, when the `boxes` argument of `tf.image.crop_and_resize` has a very large value, the CPU kernel implementation receives it as a C++ `nan` floating point value. Attempting to operate on this is undefined behavior which later produces a segmentation fault. The issue is patched in eccb7ec454e6617738554a255d77f08e60ee0808 and TensorFlow 2.4.0 will be released containing the patch. TensorFlow nightly packages after this commit will also have the issue resolved.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15266"} {"idx": 238855, "project": "tensorflow", "commit_id": "3ade2efec2e90c6237de32a19680caaa3ebc2845", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/3ade2efec2e90c6237de32a19680caaa3ebc2845", "commit_message": "Fix segmentation fault in tf.image.crop_and_resize when boxes is inf or nan\n\nThis fix tries to address the issue raised in 42129 where segmentation fault\nhappened in tf.image.crop_and_resize when boxes is inf or nan.\n\nThis fix adds the check to make sure boxes is not inf or nan (isfinite)\n\nThis fix fixes 42129.\n\nSigned-off-by: Yong Tang ", "target": 0, "func": "static inline Status ParseAndCheckBoxSizes(const Tensor& boxes,\n const Tensor& box_index,\n int* num_boxes) {\n if (boxes.NumElements() == 0 && box_index.NumElements() == 0) {\n *num_boxes = 0;\n return Status::OK();\n }\n // The shape of 'boxes' is [num_boxes, 4].\n if (boxes.dims() != 2) {\n return errors::InvalidArgument(\"boxes must be 2-D\",\n boxes.shape().DebugString());\n }\n *num_boxes = boxes.dim_size(0);\n if (boxes.dim_size(1) != 4) {\n return errors::InvalidArgument(\"boxes must have 4 columns\");\n }\n for (int64 i = 0; i < *num_boxes; i++) {\n for (int64 j = 0; j < 4; j++) {\n if (!isfinite(boxes.tensor()(i, j))) {\n return errors::InvalidArgument(\n \"boxes values must be finite, received boxes[\", i, \"]: \",\n boxes.tensor()(i, 0), \", \",\n boxes.tensor()(i, 1), \", \",\n boxes.tensor()(i, 2), \", \",\n boxes.tensor()(i, 3));\n }\n }\n }\n // The shape of 'box_index' is [num_boxes].\n if (box_index.dims() != 1) {\n return errors::InvalidArgument(\"box_index must be 1-D\",\n box_index.shape().DebugString());\n }\n if (box_index.dim_size(0) != *num_boxes) {\n return errors::InvalidArgument(\"box_index has incompatible shape\");\n }\n return Status::OK();\n}", "func_hash": 76836827274956714288877696329579947080, "file_name": "crop_and_resize_op.cc", "file_hash": 16772032748049123826338750354707972387, "cwe": ["CWE-787"], "cve": "CVE-2020-15266", "cve_desc": "In Tensorflow before version 2.4.0, when the `boxes` argument of `tf.image.crop_and_resize` has a very large value, the CPU kernel implementation receives it as a C++ `nan` floating point value. Attempting to operate on this is undefined behavior which later produces a segmentation fault. The issue is patched in eccb7ec454e6617738554a255d77f08e60ee0808 and TensorFlow 2.4.0 will be released containing the patch. TensorFlow nightly packages after this commit will also have the issue resolved.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15266"} {"idx": 196589, "project": "fluent-bit", "commit_id": "22346a74c07ceb90296be872be2d53eb92252a54", "project_url": "https://github.com/fluent/fluent-bit", "commit_url": "https://github.com/fluent/fluent-bit/commit/22346a74c07ceb90296be872be2d53eb92252a54", "commit_message": "parser: json: fix double-free (#3453)\n\nSigned-off-by: davkor ", "target": 1, "func": "int flb_parser_json_do(struct flb_parser *parser,\n const char *in_buf, size_t in_size,\n void **out_buf, size_t *out_size,\n struct flb_time *out_time)\n{\n int i;\n int skip;\n int ret;\n int slen;\n int root_type;\n int records;\n double tmfrac = 0;\n char *mp_buf = NULL;\n char *time_key;\n char *tmp_out_buf = NULL;\n char tmp[255];\n size_t tmp_out_size = 0;\n size_t off = 0;\n size_t map_size;\n size_t mp_size;\n size_t len;\n msgpack_sbuffer mp_sbuf;\n msgpack_packer mp_pck;\n msgpack_unpacked result;\n msgpack_object map;\n msgpack_object *k = NULL;\n msgpack_object *v = NULL;\n time_t time_lookup;\n struct tm tm = {0};\n struct flb_time *t;\n\n /* Convert incoming in_buf JSON message to message pack format */\n ret = flb_pack_json_recs(in_buf, in_size, &mp_buf, &mp_size, &root_type,\n &records);\n if (ret != 0) {\n return -1;\n }\n\n if (records != 1) {\n flb_free(mp_buf);\n return -1;\n }\n\n /* Make sure object is a map */\n msgpack_unpacked_init(&result);\n if (msgpack_unpack_next(&result, mp_buf, mp_size, &off) == MSGPACK_UNPACK_SUCCESS) {\n map = result.data;\n if (map.type != MSGPACK_OBJECT_MAP) {\n flb_free(mp_buf);\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n }\n else {\n if (mp_size > 0) {\n flb_free(mp_buf);\n }\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n /* Export results (might change later) */\n tmp_out_buf = mp_buf;\n tmp_out_size = mp_size;\n\n /* Do we have some decoders set ? */\n if (parser->decoders) {\n ret = flb_parser_decoder_do(parser->decoders,\n mp_buf, mp_size,\n &tmp_out_buf, &tmp_out_size);\n if (ret == 0) {\n /* re-process the unpack context */\n off = 0;\n msgpack_unpacked_destroy(&result);\n msgpack_unpacked_init(&result);\n msgpack_unpack_next(&result, tmp_out_buf, tmp_out_size, &off);\n map = result.data;\n }\n }\n\n /* Set the possible outgoing buffer */\n *out_buf = tmp_out_buf;\n *out_size = tmp_out_size;\n if (mp_buf != tmp_out_buf) {\n flb_free(mp_buf);\n }\n\n /* Do time resolution ? */\n if (!parser->time_fmt) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n if (parser->time_key) {\n time_key = parser->time_key;\n }\n else {\n time_key = \"time\";\n }\n slen = strlen(time_key);\n\n /* Lookup time field */\n map_size = map.via.map.size;\n skip = map_size;\n for (i = 0; i < map_size; i++) {\n k = &map.via.map.ptr[i].key;\n v = &map.via.map.ptr[i].val;\n\n if (k->via.str.size != slen) {\n continue;\n }\n\n /* Ensure the pointer we are about to read is not NULL */\n if (k->via.str.ptr == NULL) {\n flb_free(mp_buf);\n *out_buf = NULL;\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n if (strncmp(k->via.str.ptr, time_key, k->via.str.size) == 0) {\n /* We found the key, break the loop and keep the index */\n if (parser->time_keep == FLB_FALSE) {\n skip = i;\n break;\n }\n else {\n skip = -1;\n }\n break;\n }\n\n k = NULL;\n v = NULL;\n }\n\n /* No time_key field found */\n if (i >= map_size || !k || !v) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Ensure we have an accurate type */\n if (v->type != MSGPACK_OBJECT_STR) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Lookup time */\n ret = flb_parser_time_lookup(v->via.str.ptr, v->via.str.size,\n 0, parser, &tm, &tmfrac);\n if (ret == -1) {\n len = v->via.str.size;\n if (len > sizeof(tmp) - 1) {\n len = sizeof(tmp) - 1;\n }\n memcpy(tmp, v->via.str.ptr, len);\n tmp[len] = '\\0';\n flb_warn(\"[parser:%s] invalid time format %s for '%s'\",\n parser->name, parser->time_fmt_full, tmp);\n time_lookup = 0;\n }\n else {\n time_lookup = flb_parser_tm2time(&tm);\n }\n\n /* Compose a new map without the time_key field */\n msgpack_sbuffer_init(&mp_sbuf);\n msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write);\n\n if (parser->time_keep == FLB_FALSE) {\n msgpack_pack_map(&mp_pck, map_size - 1);\n }\n else {\n msgpack_pack_map(&mp_pck, map_size);\n }\n\n for (i = 0; i < map_size; i++) {\n if (i == skip) {\n continue;\n }\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].key);\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].val);\n }\n\n /* Export the proper buffer */\n flb_free(tmp_out_buf);\n *out_buf = mp_sbuf.data;\n *out_size = mp_sbuf.size;\n\n t = out_time;\n t->tm.tv_sec = time_lookup;\n t->tm.tv_nsec = (tmfrac * 1000000000);\n\n msgpack_unpacked_destroy(&result);\n return *out_size;\n}", "func_hash": 162449149585052394007966262271333690474, "file_name": "flb_parser_json.c", "file_hash": 339397882825981434727539636685538926928, "cwe": ["CWE-415"], "cve": "CVE-2021-36088", "cve_desc": "Fluent Bit (aka fluent-bit) 1.7.0 through 1.7,4 has a double free in flb_free (called from flb_parser_json_do and flb_parser_do).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36088"} {"idx": 240791, "project": "fluent-bit", "commit_id": "22346a74c07ceb90296be872be2d53eb92252a54", "project_url": "https://github.com/fluent/fluent-bit", "commit_url": "https://github.com/fluent/fluent-bit/commit/22346a74c07ceb90296be872be2d53eb92252a54", "commit_message": "parser: json: fix double-free (#3453)\n\nSigned-off-by: davkor ", "target": 0, "func": "int flb_parser_json_do(struct flb_parser *parser,\n const char *in_buf, size_t in_size,\n void **out_buf, size_t *out_size,\n struct flb_time *out_time)\n{\n int i;\n int skip;\n int ret;\n int slen;\n int root_type;\n int records;\n double tmfrac = 0;\n char *mp_buf = NULL;\n char *time_key;\n char *tmp_out_buf = NULL;\n char tmp[255];\n size_t tmp_out_size = 0;\n size_t off = 0;\n size_t map_size;\n size_t mp_size;\n size_t len;\n msgpack_sbuffer mp_sbuf;\n msgpack_packer mp_pck;\n msgpack_unpacked result;\n msgpack_object map;\n msgpack_object *k = NULL;\n msgpack_object *v = NULL;\n time_t time_lookup;\n struct tm tm = {0};\n struct flb_time *t;\n\n /* Convert incoming in_buf JSON message to message pack format */\n ret = flb_pack_json_recs(in_buf, in_size, &mp_buf, &mp_size, &root_type,\n &records);\n if (ret != 0) {\n return -1;\n }\n\n if (records != 1) {\n flb_free(mp_buf);\n return -1;\n }\n\n /* Make sure object is a map */\n msgpack_unpacked_init(&result);\n if (msgpack_unpack_next(&result, mp_buf, mp_size, &off) == MSGPACK_UNPACK_SUCCESS) {\n map = result.data;\n if (map.type != MSGPACK_OBJECT_MAP) {\n flb_free(mp_buf);\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n }\n else {\n if (mp_size > 0) {\n flb_free(mp_buf);\n }\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n /* Export results (might change later) */\n tmp_out_buf = mp_buf;\n tmp_out_size = mp_size;\n\n /* Do we have some decoders set ? */\n if (parser->decoders) {\n ret = flb_parser_decoder_do(parser->decoders,\n mp_buf, mp_size,\n &tmp_out_buf, &tmp_out_size);\n if (ret == 0) {\n /* re-process the unpack context */\n off = 0;\n msgpack_unpacked_destroy(&result);\n msgpack_unpacked_init(&result);\n msgpack_unpack_next(&result, tmp_out_buf, tmp_out_size, &off);\n map = result.data;\n }\n }\n\n /* Set the possible outgoing buffer */\n *out_buf = tmp_out_buf;\n *out_size = tmp_out_size;\n if (mp_buf != tmp_out_buf) {\n flb_free(mp_buf);\n mp_buf = NULL;\n }\n\n /* Do time resolution ? */\n if (!parser->time_fmt) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n if (parser->time_key) {\n time_key = parser->time_key;\n }\n else {\n time_key = \"time\";\n }\n slen = strlen(time_key);\n\n /* Lookup time field */\n map_size = map.via.map.size;\n skip = map_size;\n for (i = 0; i < map_size; i++) {\n k = &map.via.map.ptr[i].key;\n v = &map.via.map.ptr[i].val;\n\n if (k->via.str.size != slen) {\n continue;\n }\n\n /* Ensure the pointer we are about to read is not NULL */\n if (k->via.str.ptr == NULL) {\n flb_free(mp_buf);\n flb_free(tmp_out_buf);\n *out_buf = NULL;\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n if (strncmp(k->via.str.ptr, time_key, k->via.str.size) == 0) {\n /* We found the key, break the loop and keep the index */\n if (parser->time_keep == FLB_FALSE) {\n skip = i;\n break;\n }\n else {\n skip = -1;\n }\n break;\n }\n\n k = NULL;\n v = NULL;\n }\n\n /* No time_key field found */\n if (i >= map_size || !k || !v) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Ensure we have an accurate type */\n if (v->type != MSGPACK_OBJECT_STR) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Lookup time */\n ret = flb_parser_time_lookup(v->via.str.ptr, v->via.str.size,\n 0, parser, &tm, &tmfrac);\n if (ret == -1) {\n len = v->via.str.size;\n if (len > sizeof(tmp) - 1) {\n len = sizeof(tmp) - 1;\n }\n memcpy(tmp, v->via.str.ptr, len);\n tmp[len] = '\\0';\n flb_warn(\"[parser:%s] invalid time format %s for '%s'\",\n parser->name, parser->time_fmt_full, tmp);\n time_lookup = 0;\n }\n else {\n time_lookup = flb_parser_tm2time(&tm);\n }\n\n /* Compose a new map without the time_key field */\n msgpack_sbuffer_init(&mp_sbuf);\n msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write);\n\n if (parser->time_keep == FLB_FALSE) {\n msgpack_pack_map(&mp_pck, map_size - 1);\n }\n else {\n msgpack_pack_map(&mp_pck, map_size);\n }\n\n for (i = 0; i < map_size; i++) {\n if (i == skip) {\n continue;\n }\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].key);\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].val);\n }\n\n /* Export the proper buffer */\n flb_free(tmp_out_buf);\n *out_buf = mp_sbuf.data;\n *out_size = mp_sbuf.size;\n\n t = out_time;\n t->tm.tv_sec = time_lookup;\n t->tm.tv_nsec = (tmfrac * 1000000000);\n\n msgpack_unpacked_destroy(&result);\n return *out_size;\n}", "func_hash": 263828158100306060781500021260289861580, "file_name": "flb_parser_json.c", "file_hash": 171623833063445907544445323931023485538, "cwe": ["CWE-415"], "cve": "CVE-2021-36088", "cve_desc": "Fluent Bit (aka fluent-bit) 1.7.0 through 1.7,4 has a double free in flb_free (called from flb_parser_json_do and flb_parser_do).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36088"} {"idx": 196601, "project": "OpenDoas", "commit_id": "d5acd52e2a15c36a8e06f9103d35622933aa422d", "project_url": "https://github.com/Duncaen/OpenDoas", "commit_url": "https://github.com/Duncaen/OpenDoas/commit/d5acd52e2a15c36a8e06f9103d35622933aa422d", "commit_message": "correctly reset path for rules without specific command\n\nThis is a fixup for commit 01c658f8c45cb92a343be5f32aa6da70b2032168\nwhere the behaviour was changed to not inherit the PATH variable\nby default.", "target": 1, "func": "main(int argc, char **argv)\n{\n\tconst char *safepath = \"/bin:/sbin:/usr/bin:/usr/sbin:\"\n\t \"/usr/local/bin:/usr/local/sbin\";\n\tconst char *confpath = NULL;\n\tchar *shargv[] = { NULL, NULL };\n\tchar *sh;\n\tconst char *p;\n\tconst char *cmd;\n\tchar cmdline[LINE_MAX];\n\tstruct passwd mypwstore, targpwstore;\n\tstruct passwd *mypw, *targpw;\n\tconst struct rule *rule;\n\tuid_t uid;\n\tuid_t target = 0;\n\tgid_t groups[NGROUPS_MAX + 1];\n\tint ngroups;\n\tint i, ch, rv;\n\tint sflag = 0;\n\tint nflag = 0;\n\tchar cwdpath[PATH_MAX];\n\tconst char *cwd;\n\tchar **envp;\n\n\tsetprogname(\"doas\");\n\n\tclosefrom(STDERR_FILENO + 1);\n\n\tuid = getuid();\n\n\twhile ((ch = getopt(argc, argv, \"+C:Lnsu:\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'C':\n\t\t\tconfpath = optarg;\n\t\t\tbreak;\n\t\tcase 'L':\n#if defined(USE_TIMESTAMP)\n\t\t\texit(timestamp_clear() == -1);\n#else\n\t\t\texit(0);\n#endif\n\t\tcase 'u':\n\t\t\tif (parseuid(optarg, &target) != 0)\n\t\t\t\terrx(1, \"unknown user\");\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tnflag = 1;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tsflag = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\targv += optind;\n\targc -= optind;\n\n\tif (confpath) {\n\t\tif (sflag)\n\t\t\tusage();\n\t} else if ((!sflag && !argc) || (sflag && argc))\n\t\tusage();\n\n\trv = mygetpwuid_r(uid, &mypwstore, &mypw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (mypw == NULL)\n\t\terrx(1, \"no passwd entry for self\");\n\tngroups = getgroups(NGROUPS_MAX, groups);\n\tif (ngroups == -1)\n\t\terr(1, \"can't get groups\");\n\tgroups[ngroups++] = getgid();\n\n\tif (sflag) {\n\t\tsh = getenv(\"SHELL\");\n\t\tif (sh == NULL || *sh == '\\0') {\n\t\t\tshargv[0] = mypw->pw_shell;\n\t\t} else\n\t\t\tshargv[0] = sh;\n\t\targv = shargv;\n\t\targc = 1;\n\t}\n\n\tif (confpath) {\n\t\tcheckconfig(confpath, argc, argv, uid, groups, ngroups,\n\t\t target);\n\t\texit(1);\t/* fail safe */\n\t}\n\n\tif (geteuid())\n\t\terrx(1, \"not installed setuid\");\n\n\tparseconfig(DOAS_CONF, 1);\n\n\t/* cmdline is used only for logging, no need to abort on truncate */\n\t(void)strlcpy(cmdline, argv[0], sizeof(cmdline));\n\tfor (i = 1; i < argc; i++) {\n\t\tif (strlcat(cmdline, \" \", sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t\tif (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t}\n\n\tcmd = argv[0];\n\tif (!permit(uid, groups, ngroups, &rule, target, cmd,\n\t (const char **)argv + 1)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_NOTICE,\n\t\t \"command not permitted for %s: %s\", mypw->pw_name, cmdline);\n\t\terrc(1, EPERM, NULL);\n\t}\n\n#if defined(USE_SHADOW)\n\tif (!(rule->options & NOPASS)) {\n\t\tif (nflag)\n\t\t\terrx(1, \"Authorization required\");\n\n\t\tshadowauth(mypw->pw_name, rule->options & PERSIST);\n\t}\n#elif !defined(USE_PAM)\n\t/* no authentication provider, only allow NOPASS rules */\n\t(void) nflag;\n\tif (!(rule->options & NOPASS))\n\t\terrx(1, \"Authorization required\");\n#endif\n\n\tif ((p = getenv(\"PATH\")) != NULL)\n\t\tformerpath = strdup(p);\n\tif (formerpath == NULL)\n\t\tformerpath = \"\";\n\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t}\n\n\trv = mygetpwuid_r(target, &targpwstore, &targpw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (targpw == NULL)\n\t\terrx(1, \"no passwd entry for target\");\n\n#if defined(USE_PAM)\n\tpamauth(targpw->pw_name, mypw->pw_name, !nflag, rule->options & NOPASS,\n\t rule->options & PERSIST);\n#endif\n\n#ifdef HAVE_LOGIN_CAP_H\n\tif (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |\n\t LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |\n\t LOGIN_SETUSER) != 0)\n\t\terrx(1, \"failed to set user context for target\");\n#else\n\tif (setresgid(targpw->pw_gid, targpw->pw_gid, targpw->pw_gid) != 0)\n\t\terr(1, \"setresgid\");\n\tif (initgroups(targpw->pw_name, targpw->pw_gid) != 0)\n\t\terr(1, \"initgroups\");\n\tif (setresuid(target, target, target) != 0)\n\t\terr(1, \"setresuid\");\n#endif\n\n\tif (getcwd(cwdpath, sizeof(cwdpath)) == NULL)\n\t\tcwd = \"(failed)\";\n\telse\n\t\tcwd = cwdpath;\n\n\tif (!(rule->options & NOLOG)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_INFO,\n\t\t \"%s ran command %s as %s from %s\",\n\t\t mypw->pw_name, cmdline, targpw->pw_name, cwd);\n\t}\n\n\tenvp = prepenv(rule, mypw, targpw);\n\n\t/* setusercontext set path for the next process, so reset it for us */\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t} else {\n\t\tif (setenv(\"PATH\", formerpath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", formerpath);\n\t}\n\texecvpe(cmd, argv, envp);\n\tif (errno == ENOENT)\n\t\terrx(1, \"%s: command not found\", cmd);\n\terr(1, \"%s\", cmd);\n}", "func_hash": 247826199860235000336677240403191174369, "file_name": "doas.c", "file_hash": 113814017926535317972521321753082604384, "cwe": ["CWE-200"], "cve": "CVE-2019-25016", "cve_desc": "In OpenDoas from 6.6 to 6.8 the users PATH variable was incorrectly inherited by authenticated executions if the authenticating rule allowed the user to execute any command. Rules that only allowed to authenticated user to execute specific commands were not affected by this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-25016"} {"idx": 240829, "project": "OpenDoas", "commit_id": "d5acd52e2a15c36a8e06f9103d35622933aa422d", "project_url": "https://github.com/Duncaen/OpenDoas", "commit_url": "https://github.com/Duncaen/OpenDoas/commit/d5acd52e2a15c36a8e06f9103d35622933aa422d", "commit_message": "correctly reset path for rules without specific command\n\nThis is a fixup for commit 01c658f8c45cb92a343be5f32aa6da70b2032168\nwhere the behaviour was changed to not inherit the PATH variable\nby default.", "target": 0, "func": "main(int argc, char **argv)\n{\n\tconst char *safepath = \"/bin:/sbin:/usr/bin:/usr/sbin:\"\n\t \"/usr/local/bin:/usr/local/sbin\";\n\tconst char *confpath = NULL;\n\tchar *shargv[] = { NULL, NULL };\n\tchar *sh;\n\tconst char *p;\n\tconst char *cmd;\n\tchar cmdline[LINE_MAX];\n\tstruct passwd mypwstore, targpwstore;\n\tstruct passwd *mypw, *targpw;\n\tconst struct rule *rule;\n\tuid_t uid;\n\tuid_t target = 0;\n\tgid_t groups[NGROUPS_MAX + 1];\n\tint ngroups;\n\tint i, ch, rv;\n\tint sflag = 0;\n\tint nflag = 0;\n\tchar cwdpath[PATH_MAX];\n\tconst char *cwd;\n\tchar **envp;\n\n\tsetprogname(\"doas\");\n\n\tclosefrom(STDERR_FILENO + 1);\n\n\tuid = getuid();\n\n\twhile ((ch = getopt(argc, argv, \"+C:Lnsu:\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'C':\n\t\t\tconfpath = optarg;\n\t\t\tbreak;\n\t\tcase 'L':\n#if defined(USE_TIMESTAMP)\n\t\t\texit(timestamp_clear() == -1);\n#else\n\t\t\texit(0);\n#endif\n\t\tcase 'u':\n\t\t\tif (parseuid(optarg, &target) != 0)\n\t\t\t\terrx(1, \"unknown user\");\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tnflag = 1;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tsflag = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\targv += optind;\n\targc -= optind;\n\n\tif (confpath) {\n\t\tif (sflag)\n\t\t\tusage();\n\t} else if ((!sflag && !argc) || (sflag && argc))\n\t\tusage();\n\n\trv = mygetpwuid_r(uid, &mypwstore, &mypw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (mypw == NULL)\n\t\terrx(1, \"no passwd entry for self\");\n\tngroups = getgroups(NGROUPS_MAX, groups);\n\tif (ngroups == -1)\n\t\terr(1, \"can't get groups\");\n\tgroups[ngroups++] = getgid();\n\n\tif (sflag) {\n\t\tsh = getenv(\"SHELL\");\n\t\tif (sh == NULL || *sh == '\\0') {\n\t\t\tshargv[0] = mypw->pw_shell;\n\t\t} else\n\t\t\tshargv[0] = sh;\n\t\targv = shargv;\n\t\targc = 1;\n\t}\n\n\tif (confpath) {\n\t\tcheckconfig(confpath, argc, argv, uid, groups, ngroups,\n\t\t target);\n\t\texit(1);\t/* fail safe */\n\t}\n\n\tif (geteuid())\n\t\terrx(1, \"not installed setuid\");\n\n\tparseconfig(DOAS_CONF, 1);\n\n\t/* cmdline is used only for logging, no need to abort on truncate */\n\t(void)strlcpy(cmdline, argv[0], sizeof(cmdline));\n\tfor (i = 1; i < argc; i++) {\n\t\tif (strlcat(cmdline, \" \", sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t\tif (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t}\n\n\tcmd = argv[0];\n\tif (!permit(uid, groups, ngroups, &rule, target, cmd,\n\t (const char **)argv + 1)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_NOTICE,\n\t\t \"command not permitted for %s: %s\", mypw->pw_name, cmdline);\n\t\terrc(1, EPERM, NULL);\n\t}\n\n#if defined(USE_SHADOW)\n\tif (!(rule->options & NOPASS)) {\n\t\tif (nflag)\n\t\t\terrx(1, \"Authorization required\");\n\n\t\tshadowauth(mypw->pw_name, rule->options & PERSIST);\n\t}\n#elif !defined(USE_PAM)\n\t/* no authentication provider, only allow NOPASS rules */\n\t(void) nflag;\n\tif (!(rule->options & NOPASS))\n\t\terrx(1, \"Authorization required\");\n#endif\n\n\tif ((p = getenv(\"PATH\")) != NULL)\n\t\tformerpath = strdup(p);\n\tif (formerpath == NULL)\n\t\tformerpath = \"\";\n\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t}\n\n\trv = mygetpwuid_r(target, &targpwstore, &targpw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (targpw == NULL)\n\t\terrx(1, \"no passwd entry for target\");\n\n#if defined(USE_PAM)\n\tpamauth(targpw->pw_name, mypw->pw_name, !nflag, rule->options & NOPASS,\n\t rule->options & PERSIST);\n#endif\n\n#ifdef HAVE_LOGIN_CAP_H\n\tif (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |\n\t LOGIN_SETPATH |\n\t LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |\n\t LOGIN_SETUSER) != 0)\n\t\terrx(1, \"failed to set user context for target\");\n#else\n\tif (setresgid(targpw->pw_gid, targpw->pw_gid, targpw->pw_gid) != 0)\n\t\terr(1, \"setresgid\");\n\tif (initgroups(targpw->pw_name, targpw->pw_gid) != 0)\n\t\terr(1, \"initgroups\");\n\tif (setresuid(target, target, target) != 0)\n\t\terr(1, \"setresuid\");\n\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\terr(1, \"failed to set PATH '%s'\", safepath);\n#endif\n\n\tif (getcwd(cwdpath, sizeof(cwdpath)) == NULL)\n\t\tcwd = \"(failed)\";\n\telse\n\t\tcwd = cwdpath;\n\n\tif (!(rule->options & NOLOG)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_INFO,\n\t\t \"%s ran command %s as %s from %s\",\n\t\t mypw->pw_name, cmdline, targpw->pw_name, cwd);\n\t}\n\n\tenvp = prepenv(rule, mypw, targpw);\n\n\t/* setusercontext set path for the next process, so reset it for us */\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t} else {\n\t\tif (setenv(\"PATH\", formerpath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", formerpath);\n\t}\n\texecvpe(cmd, argv, envp);\n\tif (errno == ENOENT)\n\t\terrx(1, \"%s: command not found\", cmd);\n\terr(1, \"%s\", cmd);\n}", "func_hash": 185471747531387376844624223726546301304, "file_name": "doas.c", "file_hash": 4223392589306026612602636000546085539, "cwe": ["CWE-200"], "cve": "CVE-2019-25016", "cve_desc": "In OpenDoas from 6.6 to 6.8 the users PATH variable was incorrectly inherited by authenticated executions if the authenticating rule allowed the user to execute any command. Rules that only allowed to authenticated user to execute specific commands were not affected by this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-25016"} {"idx": 196610, "project": "veyon", "commit_id": "f231ec511b9a09f43f49b2c7bb7c60b8046276b1", "project_url": "https://github.com/veyon/veyon", "commit_url": "https://github.com/veyon/veyon/commit/f231ec511b9a09f43f49b2c7bb7c60b8046276b1", "commit_message": "WindowsServiceControl: quote service binary path\n\nFix unquoted service path vulnerability.\n\nCloses #657.", "target": 1, "func": "bool WindowsServiceControl::install( const QString& filePath, const QString& displayName )\n{\n\tm_serviceHandle = CreateService(\n\t\t\t\tm_serviceManager,\t\t// SCManager database\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( displayName ),// name to display\n\t\t\t\tSERVICE_ALL_ACCESS,\t// desired access\n\t\t\t\tSERVICE_WIN32_OWN_PROCESS,\n\t\t\t\t// service type\n\t\t\t\tSERVICE_AUTO_START,\t// start type\n\t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( filePath ),\t\t// service's binary\n\t\t\t\tnullptr,\t\t\t// no load ordering group\n\t\t\t\tnullptr,\t\t\t// no tag identifier\n\t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies\n\t\t\t\tnullptr,\t\t\t// LocalSystem account\n\t\t\t\tnullptr );\t\t\t// no password\n\n\tif( m_serviceHandle == nullptr )\n\t{\n\t\tconst auto error = GetLastError();\n\t\tif( error == ERROR_SERVICE_EXISTS )\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" is already installed.\" ).arg( m_name ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" could not be installed.\" ).arg( m_name ) );\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tSC_ACTION serviceActions;\n\tserviceActions.Delay = 10000;\n\tserviceActions.Type = SC_ACTION_RESTART;\n\n\tSERVICE_FAILURE_ACTIONS serviceFailureActions;\n\tserviceFailureActions.dwResetPeriod = 0;\n\tserviceFailureActions.lpRebootMsg = nullptr;\n\tserviceFailureActions.lpCommand = nullptr;\n\tserviceFailureActions.lpsaActions = &serviceActions;\n\tserviceFailureActions.cActions = 1;\n\tChangeServiceConfig2( m_serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailureActions );\n\n\t// Everything went fine\n\tvInfo() << qUtf8Printable( tr( \"The service \\\"%1\\\" has been installed successfully.\" ).arg( m_name ) );\n\n\treturn true;\n}", "func_hash": 204117627609408299633955467486685280461, "file_name": "WindowsServiceControl.cpp", "file_hash": 3322002666768295149724423250702459603, "cwe": ["CWE-295"], "cve": "CVE-2020-15261", "cve_desc": "On Windows the Veyon Service before version 4.4.2 contains an unquoted service path vulnerability, allowing locally authenticated users with administrative privileges to run malicious executables with LocalSystem privileges. Since Veyon users (both students and teachers) usually don't have administrative privileges, this vulnerability is only dangerous in anyway unsafe setups. The problem has been fixed in version 4.4.2. As a workaround, the exploitation of the vulnerability can be prevented by revoking administrative privileges from all potentially untrustworthy users.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15261"} {"idx": 241036, "project": "veyon", "commit_id": "f231ec511b9a09f43f49b2c7bb7c60b8046276b1", "project_url": "https://github.com/veyon/veyon", "commit_url": "https://github.com/veyon/veyon/commit/f231ec511b9a09f43f49b2c7bb7c60b8046276b1", "commit_message": "WindowsServiceControl: quote service binary path\n\nFix unquoted service path vulnerability.\n\nCloses #657.", "target": 0, "func": "bool WindowsServiceControl::install( const QString& filePath, const QString& displayName )\n{\n\tconst auto binaryPath = QStringLiteral(\"\\\"%1\\\"\").arg( QString( filePath ).replace( QLatin1Char('\"'), QString() ) );\n\n\tm_serviceHandle = CreateService(\n\t\t\t\tm_serviceManager,\t\t// SCManager database\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( displayName ),// name to display\n\t\t\t\tSERVICE_ALL_ACCESS,\t// desired access\n\t\t\t\tSERVICE_WIN32_OWN_PROCESS,\n\t\t\t\t// service type\n\t\t\t\tSERVICE_AUTO_START,\t// start type\n\t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( binaryPath ),\t\t// service's binary\n\t\t\t\tnullptr,\t\t\t// no load ordering group\n\t\t\t\tnullptr,\t\t\t// no tag identifier\n\t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies\n\t\t\t\tnullptr,\t\t\t// LocalSystem account\n\t\t\t\tnullptr );\t\t\t// no password\n\n\tif( m_serviceHandle == nullptr )\n\t{\n\t\tconst auto error = GetLastError();\n\t\tif( error == ERROR_SERVICE_EXISTS )\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" is already installed.\" ).arg( m_name ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" could not be installed.\" ).arg( m_name ) );\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tSC_ACTION serviceActions;\n\tserviceActions.Delay = 10000;\n\tserviceActions.Type = SC_ACTION_RESTART;\n\n\tSERVICE_FAILURE_ACTIONS serviceFailureActions;\n\tserviceFailureActions.dwResetPeriod = 0;\n\tserviceFailureActions.lpRebootMsg = nullptr;\n\tserviceFailureActions.lpCommand = nullptr;\n\tserviceFailureActions.lpsaActions = &serviceActions;\n\tserviceFailureActions.cActions = 1;\n\tChangeServiceConfig2( m_serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailureActions );\n\n\t// Everything went fine\n\tvInfo() << qUtf8Printable( tr( \"The service \\\"%1\\\" has been installed successfully.\" ).arg( m_name ) );\n\n\treturn true;\n}", "func_hash": 279890801832788590329200988345711746886, "file_name": "WindowsServiceControl.cpp", "file_hash": 88919436772981177393878259857665949362, "cwe": ["CWE-295"], "cve": "CVE-2020-15261", "cve_desc": "On Windows the Veyon Service before version 4.4.2 contains an unquoted service path vulnerability, allowing locally authenticated users with administrative privileges to run malicious executables with LocalSystem privileges. Since Veyon users (both students and teachers) usually don't have administrative privileges, this vulnerability is only dangerous in anyway unsafe setups. The problem has been fixed in version 4.4.2. As a workaround, the exploitation of the vulnerability can be prevented by revoking administrative privileges from all potentially untrustworthy users.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15261"} {"idx": 196624, "project": "nDPI", "commit_id": "8e7b1ea7a136cc4e4aa9880072ec2d69900a825e", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/8e7b1ea7a136cc4e4aa9880072ec2d69900a825e", "commit_message": "Fix for potential heap-buffer-overflow in ndpi_search_openvpn", "target": 1, "func": "void ndpi_search_openvpn(struct ndpi_detection_module_struct* ndpi_struct,\n struct ndpi_flow_struct* flow) {\n struct ndpi_packet_struct* packet = &flow->packet;\n const u_int8_t * ovpn_payload = packet->payload;\n const u_int8_t * session_remote;\n u_int8_t opcode;\n u_int8_t alen;\n int8_t hmac_size;\n int8_t failed = 0;\n\n if(packet->payload_packet_len >= 40) {\n // skip openvpn TCP transport packet size\n if(packet->tcp != NULL)\n ovpn_payload += 2;\n\n opcode = ovpn_payload[0] & P_OPCODE_MASK;\n\n if(packet->udp) {\n#ifdef DEBUG\n printf(\"[packet_id: %u][opcode: %u][Packet ID: %d][%u <-> %u][len: %u]\\n\",\n\t flow->num_processed_pkts,\n\t opcode, check_pkid_and_detect_hmac_size(ovpn_payload),\n\t htons(packet->udp->source), htons(packet->udp->dest), packet->payload_packet_len);\t \n#endif\n \n if(\n\t (flow->num_processed_pkts == 1)\n\t && (\n\t ((packet->payload_packet_len == 112)\n\t && ((opcode == 168) || (opcode == 192))\n\t )\n\t || ((packet->payload_packet_len == 80)\n\t\t && ((opcode == 184) || (opcode == 88) || (opcode == 160) || (opcode == 168) || (opcode == 200)))\n\t )) {\n\tNDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n }\n \n if(flow->ovpn_counter < P_HARD_RESET_CLIENT_MAX_COUNT && (opcode == P_CONTROL_HARD_RESET_CLIENT_V1 ||\n\t\t\t\t opcode == P_CONTROL_HARD_RESET_CLIENT_V2)) {\n if(check_pkid_and_detect_hmac_size(ovpn_payload) > 0) {\n memcpy(flow->ovpn_session_id, ovpn_payload+1, 8);\n\n NDPI_LOG_DBG2(ndpi_struct,\n\t\t \"session key: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t flow->ovpn_session_id[0], flow->ovpn_session_id[1], flow->ovpn_session_id[2], flow->ovpn_session_id[3],\n\t\t flow->ovpn_session_id[4], flow->ovpn_session_id[5], flow->ovpn_session_id[6], flow->ovpn_session_id[7]);\n }\n } else if(flow->ovpn_counter >= 1 && flow->ovpn_counter <= P_HARD_RESET_CLIENT_MAX_COUNT &&\n (opcode == P_CONTROL_HARD_RESET_SERVER_V1 || opcode == P_CONTROL_HARD_RESET_SERVER_V2)) {\n\n hmac_size = check_pkid_and_detect_hmac_size(ovpn_payload);\n\n if(hmac_size > 0) {\n alen = ovpn_payload[P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size)];\n if (alen > 0) {\n\t session_remote = ovpn_payload + P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size) + 1 + alen * 4;\n\n if(memcmp(flow->ovpn_session_id, session_remote, 8) == 0) {\n\t NDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t } else {\n NDPI_LOG_DBG2(ndpi_struct,\n\t\t \"key mismatch: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t session_remote[0], session_remote[1], session_remote[2], session_remote[3],\n\t\t session_remote[4], session_remote[5], session_remote[6], session_remote[7]);\n failed = 1;\n }\n } else\n failed = 1;\n } else\n failed = 1;\n } else\n failed = 1;\n\n flow->ovpn_counter++;\n \n if(failed) {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n }\n}", "func_hash": 48076903410110522487931388973656145578, "file_name": "openvpn.c", "file_hash": 35324936257117100981320631335169560464, "cwe": ["CWE-125"], "cve": "CVE-2020-15473", "cve_desc": "In nDPI through 3.2, the OpenVPN dissector is vulnerable to a heap-based buffer over-read in ndpi_search_openvpn in lib/protocols/openvpn.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15473"} {"idx": 241321, "project": "nDPI", "commit_id": "8e7b1ea7a136cc4e4aa9880072ec2d69900a825e", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/8e7b1ea7a136cc4e4aa9880072ec2d69900a825e", "commit_message": "Fix for potential heap-buffer-overflow in ndpi_search_openvpn", "target": 0, "func": "void ndpi_search_openvpn(struct ndpi_detection_module_struct* ndpi_struct,\n struct ndpi_flow_struct* flow) {\n struct ndpi_packet_struct* packet = &flow->packet;\n const u_int8_t * ovpn_payload = packet->payload;\n const u_int8_t * session_remote;\n u_int8_t opcode;\n u_int8_t alen;\n int8_t hmac_size;\n int8_t failed = 0;\n /* No u_ */int16_t ovpn_payload_len = packet->payload_packet_len;\n \n if(ovpn_payload_len >= 40) {\n // skip openvpn TCP transport packet size\n if(packet->tcp != NULL)\n ovpn_payload += 2, ovpn_payload_len -= 2;;\n\n opcode = ovpn_payload[0] & P_OPCODE_MASK;\n\n if(packet->udp) {\n#ifdef DEBUG\n printf(\"[packet_id: %u][opcode: %u][Packet ID: %d][%u <-> %u][len: %u]\\n\",\n\t flow->num_processed_pkts,\n\t opcode, check_pkid_and_detect_hmac_size(ovpn_payload),\n\t htons(packet->udp->source), htons(packet->udp->dest), ovpn_payload_len);\t \n#endif\n \n if(\n\t (flow->num_processed_pkts == 1)\n\t && (\n\t ((ovpn_payload_len == 112)\n\t && ((opcode == 168) || (opcode == 192))\n\t )\n\t || ((ovpn_payload_len == 80)\n\t\t && ((opcode == 184) || (opcode == 88) || (opcode == 160) || (opcode == 168) || (opcode == 200)))\n\t )) {\n\tNDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n }\n \n if(flow->ovpn_counter < P_HARD_RESET_CLIENT_MAX_COUNT && (opcode == P_CONTROL_HARD_RESET_CLIENT_V1 ||\n\t\t\t\t opcode == P_CONTROL_HARD_RESET_CLIENT_V2)) {\n if(check_pkid_and_detect_hmac_size(ovpn_payload) > 0) {\n memcpy(flow->ovpn_session_id, ovpn_payload+1, 8);\n\n NDPI_LOG_DBG2(ndpi_struct,\n\t\t \"session key: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t flow->ovpn_session_id[0], flow->ovpn_session_id[1], flow->ovpn_session_id[2], flow->ovpn_session_id[3],\n\t\t flow->ovpn_session_id[4], flow->ovpn_session_id[5], flow->ovpn_session_id[6], flow->ovpn_session_id[7]);\n }\n } else if(flow->ovpn_counter >= 1 && flow->ovpn_counter <= P_HARD_RESET_CLIENT_MAX_COUNT &&\n (opcode == P_CONTROL_HARD_RESET_SERVER_V1 || opcode == P_CONTROL_HARD_RESET_SERVER_V2)) {\n\n hmac_size = check_pkid_and_detect_hmac_size(ovpn_payload);\n\n if(hmac_size > 0) {\n\tu_int16_t offset = P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size);\n\t \n alen = ovpn_payload[offset];\n\t\n if (alen > 0) {\n\t offset += 1 + alen * 4;\n\n\t if((offset+8) <= ovpn_payload_len) {\n\t session_remote = &ovpn_payload[offset];\n\t \n\t if(memcmp(flow->ovpn_session_id, session_remote, 8) == 0) {\n\t NDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t } else {\n\t NDPI_LOG_DBG2(ndpi_struct,\n\t\t\t \"key mismatch: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t\t session_remote[0], session_remote[1], session_remote[2], session_remote[3],\n\t\t\t session_remote[4], session_remote[5], session_remote[6], session_remote[7]);\n\t failed = 1;\n\t }\n\t } else\n\t failed = 1;\n\t} else\n failed = 1;\n } else\n failed = 1;\n } else\n failed = 1;\n\n flow->ovpn_counter++;\n \n if(failed) {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n }\n}", "func_hash": 313273893764747740102532370191345010369, "file_name": "openvpn.c", "file_hash": 84017168379963342605241263539279209330, "cwe": ["CWE-125"], "cve": "CVE-2020-15473", "cve_desc": "In nDPI through 3.2, the OpenVPN dissector is vulnerable to a heap-based buffer over-read in ndpi_search_openvpn in lib/protocols/openvpn.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15473"} {"idx": 196632, "project": "tensorflow", "commit_id": "2be2cdf3a123e231b16f766aa0e27d56b4606535", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/2be2cdf3a123e231b16f766aa0e27d56b4606535", "commit_message": "Prevent yet another division by zero\n\nPiperOrigin-RevId: 369343977\nChange-Id: I1a60da4cf512e60fd91e069c16e026544632fe7f", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& input_sizes = context->input(0);\n const Tensor& filter = context->input(1);\n const Tensor& out_backprop = context->input(2);\n\n TensorShape input_shape;\n OP_REQUIRES_OK(context,\n Conv2DBackpropComputeInputShape(input_sizes, filter.shape(),\n out_backprop.shape(),\n data_format_, &input_shape));\n\n ConvBackpropDimensions dims;\n OP_REQUIRES_OK(context,\n ConvBackpropComputeDimensionsV2(\n \"Conv2DCustomBackpropInput\", /*num_spatial_dims=*/2,\n input_shape, filter.shape(), out_backprop.shape(),\n /*dilations=*/{1, 1, 1, 1}, strides_, padding_,\n explicit_paddings_, data_format_, &dims));\n\n OP_REQUIRES(context, dims.in_depth == filter.shape().dim_size(2),\n errors::InvalidArgument(\"Computed input depth \", dims.in_depth,\n \" doesn't match filter input depth \",\n filter.shape().dim_size(2)));\n OP_REQUIRES(\n context, dims.out_depth == filter.shape().dim_size(3),\n errors::InvalidArgument(\"Computed output depth \", dims.out_depth,\n \" doesn't match filter output depth \",\n filter.shape().dim_size(3)));\n\n Tensor* in_backprop = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input_shape, &in_backprop));\n\n // If there is nothing to compute, return.\n if (input_shape.num_elements() == 0) {\n return;\n }\n\n// TODO(ezhulenev): Remove custom kernel and move XSMM support to\n// LaunchConv2DBackpropInputOp functor.\n#if defined TENSORFLOW_USE_LIBXSMM_CONVOLUTIONS && \\\n defined TENSORFLOW_USE_LIBXSMM_BACKWARD_CONVOLUTIONS\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n if (pad_left == pad_right && pad_top == pad_bottom) {\n if (LaunchXsmmBackwardInputConvolution()(\n context, context->eigen_device(),\n in_backprop->tensor(), filter.tensor(),\n out_backprop.tensor(), dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n static_cast(dims.spatial_dims[0].stride),\n static_cast(dims.spatial_dims[1].stride),\n static_cast(pad_top), static_cast(pad_left),\n data_format_)) {\n return;\n }\n }\n#else\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n#endif\n if (padding_ == Padding::EXPLICIT) {\n pad_top = explicit_paddings_[2];\n pad_bottom = explicit_paddings_[3];\n pad_left = explicit_paddings_[4];\n pad_right = explicit_paddings_[5];\n }\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n // The total dimension size of each kernel.\n const int filter_total_size = dims.spatial_dims[0].filter_size *\n dims.spatial_dims[1].filter_size *\n dims.in_depth;\n // The output image size is the spatial size of the output.\n const int output_image_size =\n dims.spatial_dims[0].output_size * dims.spatial_dims[1].output_size;\n\n // TODO(andydavis) Get L2/L3 cache sizes from device.\n const size_t l2_cache_size = 256LL << 10;\n const size_t l3_cache_size = 30LL << 20;\n\n // Use L3 cache size as target working set size.\n const size_t target_working_set_size = l3_cache_size / sizeof(T);\n\n // Calculate size of matrices involved in MatMul: C = A x B.\n const size_t size_A = output_image_size * dims.out_depth;\n\n const size_t size_B = filter_total_size * dims.out_depth;\n\n const size_t size_C = output_image_size * filter_total_size;\n\n const size_t work_unit_size = size_A + size_B + size_C;\n\n auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads());\n\n // Calculate per-thread work unit size.\n const size_t thread_work_unit_size =\n work_unit_size / worker_threads.num_threads;\n\n // Set minimum per-thread work unit size to size of L2 cache.\n const size_t min_thread_work_unit_size = l2_cache_size / sizeof(T);\n\n // Use parallel tensor contractions if there is no batching, or if the\n // minimum per-thread work unit size threshold has been exceeded.\n // Otherwise, revert to multiple single-threaded matmul ops running in\n // parallel to keep all threads busy.\n // TODO(andydavis) Explore alternatives to branching the code in this way\n // (i.e. run multiple, parallel tensor contractions in another thread pool).\n const bool use_parallel_contraction =\n dims.batch_size == 1 ||\n thread_work_unit_size >= min_thread_work_unit_size;\n\n const size_t shard_size =\n use_parallel_contraction\n ? 1\n : (target_working_set_size + work_unit_size - 1) / work_unit_size;\n\n Tensor col_buffer;\n OP_REQUIRES_OK(context,\n context->allocate_temp(\n DataTypeToEnum::value,\n TensorShape({static_cast(shard_size),\n static_cast(output_image_size),\n static_cast(filter_total_size)}),\n &col_buffer));\n\n // The input offset corresponding to a single input image.\n const int input_offset = dims.spatial_dims[0].input_size *\n dims.spatial_dims[1].input_size * dims.in_depth;\n // The output offset corresponding to a single output image.\n const int output_offset = dims.spatial_dims[0].output_size *\n dims.spatial_dims[1].output_size * dims.out_depth;\n\n const T* filter_data = filter.template flat().data();\n T* col_buffer_data = col_buffer.template flat().data();\n const T* out_backprop_data = out_backprop.template flat().data();\n\n auto in_backprop_flat = in_backprop->template flat();\n T* input_backprop_data = in_backprop_flat.data();\n in_backprop_flat.device(context->eigen_device()) =\n in_backprop_flat.constant(T(0));\n\n if (use_parallel_contraction) {\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n TensorMap;\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n ConstTensorMap;\n\n // Initialize contraction dims (we need to transpose 'B' below).\n Eigen::array, 1> contract_dims;\n contract_dims[0].first = 1;\n contract_dims[0].second = 1;\n\n for (int image_id = 0; image_id < dims.batch_size; ++image_id) {\n // Compute gradient into col_buffer.\n TensorMap C(col_buffer_data, output_image_size, filter_total_size);\n\n ConstTensorMap A(out_backprop_data + output_offset * image_id,\n output_image_size, dims.out_depth);\n ConstTensorMap B(filter_data, filter_total_size, dims.out_depth);\n\n C.device(context->eigen_cpu_device()) = A.contract(B, contract_dims);\n\n Col2im(\n col_buffer_data, dims.in_depth, dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left, pad_bottom,\n pad_right, dims.spatial_dims[0].stride, dims.spatial_dims[1].stride,\n input_backprop_data);\n\n input_backprop_data += input_offset;\n }\n } else {\n for (int image_id = 0; image_id < dims.batch_size;\n image_id += shard_size) {\n const int shard_limit =\n std::min(static_cast(shard_size),\n static_cast(dims.batch_size) - image_id);\n\n auto shard = [&context, &dims, &pad_top, &pad_left, &pad_bottom,\n &pad_right, &output_image_size, &filter_total_size,\n &input_backprop_data, &col_buffer_data,\n &out_backprop_data, &filter_data, &input_offset,\n &output_offset, &size_C](int64 start, int64 limit) {\n for (int shard_id = start; shard_id < limit; ++shard_id) {\n T* im2col_buf = col_buffer_data + shard_id * size_C;\n T* input_data = input_backprop_data + shard_id * input_offset;\n const T* out_data = out_backprop_data + shard_id * output_offset;\n\n Conv2DCustomBackpropInputMatMulFunctor()(\n context, out_data, filter_data, filter_total_size,\n output_image_size, dims.out_depth, im2col_buf);\n\n Col2im(im2col_buf, dims.in_depth,\n dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left,\n pad_bottom, pad_right, dims.spatial_dims[0].stride,\n dims.spatial_dims[1].stride, input_data);\n }\n };\n Shard(worker_threads.num_threads, worker_threads.workers, shard_limit,\n work_unit_size, shard);\n\n input_backprop_data += input_offset * shard_limit;\n out_backprop_data += output_offset * shard_limit;\n }\n }\n }", "func_hash": 99399822915689754888750647298325650461, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29525", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a division by 0 in `tf.raw_ops.Conv2DBackpropInput`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/b40060c9f697b044e3107917c797ba052f4506ab/tensorflow/core/kernels/conv_grad_input_ops.h#L625-L655) does a division by a quantity that is controlled by the caller. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29525"} {"idx": 241532, "project": "tensorflow", "commit_id": "2be2cdf3a123e231b16f766aa0e27d56b4606535", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/2be2cdf3a123e231b16f766aa0e27d56b4606535", "commit_message": "Prevent yet another division by zero\n\nPiperOrigin-RevId: 369343977\nChange-Id: I1a60da4cf512e60fd91e069c16e026544632fe7f", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& input_sizes = context->input(0);\n const Tensor& filter = context->input(1);\n const Tensor& out_backprop = context->input(2);\n\n TensorShape input_shape;\n OP_REQUIRES_OK(context,\n Conv2DBackpropComputeInputShape(input_sizes, filter.shape(),\n out_backprop.shape(),\n data_format_, &input_shape));\n\n ConvBackpropDimensions dims;\n OP_REQUIRES_OK(context,\n ConvBackpropComputeDimensionsV2(\n \"Conv2DCustomBackpropInput\", /*num_spatial_dims=*/2,\n input_shape, filter.shape(), out_backprop.shape(),\n /*dilations=*/{1, 1, 1, 1}, strides_, padding_,\n explicit_paddings_, data_format_, &dims));\n\n OP_REQUIRES(context, dims.in_depth == filter.shape().dim_size(2),\n errors::InvalidArgument(\"Computed input depth \", dims.in_depth,\n \" doesn't match filter input depth \",\n filter.shape().dim_size(2)));\n OP_REQUIRES(\n context, dims.out_depth == filter.shape().dim_size(3),\n errors::InvalidArgument(\"Computed output depth \", dims.out_depth,\n \" doesn't match filter output depth \",\n filter.shape().dim_size(3)));\n\n Tensor* in_backprop = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input_shape, &in_backprop));\n\n // If there is nothing to compute, return.\n if (input_shape.num_elements() == 0) {\n return;\n }\n\n// TODO(ezhulenev): Remove custom kernel and move XSMM support to\n// LaunchConv2DBackpropInputOp functor.\n#if defined TENSORFLOW_USE_LIBXSMM_CONVOLUTIONS && \\\n defined TENSORFLOW_USE_LIBXSMM_BACKWARD_CONVOLUTIONS\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n if (pad_left == pad_right && pad_top == pad_bottom) {\n if (LaunchXsmmBackwardInputConvolution()(\n context, context->eigen_device(),\n in_backprop->tensor(), filter.tensor(),\n out_backprop.tensor(), dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n static_cast(dims.spatial_dims[0].stride),\n static_cast(dims.spatial_dims[1].stride),\n static_cast(pad_top), static_cast(pad_left),\n data_format_)) {\n return;\n }\n }\n#else\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n#endif\n if (padding_ == Padding::EXPLICIT) {\n pad_top = explicit_paddings_[2];\n pad_bottom = explicit_paddings_[3];\n pad_left = explicit_paddings_[4];\n pad_right = explicit_paddings_[5];\n }\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n // The total dimension size of each kernel.\n const int filter_total_size = dims.spatial_dims[0].filter_size *\n dims.spatial_dims[1].filter_size *\n dims.in_depth;\n // The output image size is the spatial size of the output.\n const int output_image_size =\n dims.spatial_dims[0].output_size * dims.spatial_dims[1].output_size;\n\n // TODO(andydavis) Get L2/L3 cache sizes from device.\n const size_t l2_cache_size = 256LL << 10;\n const size_t l3_cache_size = 30LL << 20;\n\n // Use L3 cache size as target working set size.\n const size_t target_working_set_size = l3_cache_size / sizeof(T);\n\n // Calculate size of matrices involved in MatMul: C = A x B.\n const size_t size_A = output_image_size * dims.out_depth;\n\n const size_t size_B = filter_total_size * dims.out_depth;\n\n const size_t size_C = output_image_size * filter_total_size;\n\n const size_t work_unit_size = size_A + size_B + size_C;\n\n auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads());\n\n // Calculate per-thread work unit size.\n const size_t thread_work_unit_size =\n work_unit_size / worker_threads.num_threads;\n\n // Set minimum per-thread work unit size to size of L2 cache.\n const size_t min_thread_work_unit_size = l2_cache_size / sizeof(T);\n\n // Use parallel tensor contractions if there is no batching, or if the\n // minimum per-thread work unit size threshold has been exceeded.\n // Otherwise, revert to multiple single-threaded matmul ops running in\n // parallel to keep all threads busy.\n // TODO(andydavis) Explore alternatives to branching the code in this way\n // (i.e. run multiple, parallel tensor contractions in another thread pool).\n const bool use_parallel_contraction =\n dims.batch_size == 1 ||\n thread_work_unit_size >= min_thread_work_unit_size;\n\n OP_REQUIRES(\n context, work_unit_size > 0,\n errors::InvalidArgument(\"input, filter_sizes and out_backprop tensors \"\n \"must all have at least 1 element\"));\n\n const size_t shard_size =\n use_parallel_contraction\n ? 1\n : (target_working_set_size + work_unit_size - 1) / work_unit_size;\n\n Tensor col_buffer;\n OP_REQUIRES_OK(context,\n context->allocate_temp(\n DataTypeToEnum::value,\n TensorShape({static_cast(shard_size),\n static_cast(output_image_size),\n static_cast(filter_total_size)}),\n &col_buffer));\n\n // The input offset corresponding to a single input image.\n const int input_offset = dims.spatial_dims[0].input_size *\n dims.spatial_dims[1].input_size * dims.in_depth;\n // The output offset corresponding to a single output image.\n const int output_offset = dims.spatial_dims[0].output_size *\n dims.spatial_dims[1].output_size * dims.out_depth;\n\n const T* filter_data = filter.template flat().data();\n T* col_buffer_data = col_buffer.template flat().data();\n const T* out_backprop_data = out_backprop.template flat().data();\n\n auto in_backprop_flat = in_backprop->template flat();\n T* input_backprop_data = in_backprop_flat.data();\n in_backprop_flat.device(context->eigen_device()) =\n in_backprop_flat.constant(T(0));\n\n if (use_parallel_contraction) {\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n TensorMap;\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n ConstTensorMap;\n\n // Initialize contraction dims (we need to transpose 'B' below).\n Eigen::array, 1> contract_dims;\n contract_dims[0].first = 1;\n contract_dims[0].second = 1;\n\n for (int image_id = 0; image_id < dims.batch_size; ++image_id) {\n // Compute gradient into col_buffer.\n TensorMap C(col_buffer_data, output_image_size, filter_total_size);\n\n ConstTensorMap A(out_backprop_data + output_offset * image_id,\n output_image_size, dims.out_depth);\n ConstTensorMap B(filter_data, filter_total_size, dims.out_depth);\n\n C.device(context->eigen_cpu_device()) = A.contract(B, contract_dims);\n\n Col2im(\n col_buffer_data, dims.in_depth, dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left, pad_bottom,\n pad_right, dims.spatial_dims[0].stride, dims.spatial_dims[1].stride,\n input_backprop_data);\n\n input_backprop_data += input_offset;\n }\n } else {\n for (int image_id = 0; image_id < dims.batch_size;\n image_id += shard_size) {\n const int shard_limit =\n std::min(static_cast(shard_size),\n static_cast(dims.batch_size) - image_id);\n\n auto shard = [&context, &dims, &pad_top, &pad_left, &pad_bottom,\n &pad_right, &output_image_size, &filter_total_size,\n &input_backprop_data, &col_buffer_data,\n &out_backprop_data, &filter_data, &input_offset,\n &output_offset, &size_C](int64 start, int64 limit) {\n for (int shard_id = start; shard_id < limit; ++shard_id) {\n T* im2col_buf = col_buffer_data + shard_id * size_C;\n T* input_data = input_backprop_data + shard_id * input_offset;\n const T* out_data = out_backprop_data + shard_id * output_offset;\n\n Conv2DCustomBackpropInputMatMulFunctor()(\n context, out_data, filter_data, filter_total_size,\n output_image_size, dims.out_depth, im2col_buf);\n\n Col2im(im2col_buf, dims.in_depth,\n dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left,\n pad_bottom, pad_right, dims.spatial_dims[0].stride,\n dims.spatial_dims[1].stride, input_data);\n }\n };\n Shard(worker_threads.num_threads, worker_threads.workers, shard_limit,\n work_unit_size, shard);\n\n input_backprop_data += input_offset * shard_limit;\n out_backprop_data += output_offset * shard_limit;\n }\n }\n }", "func_hash": 228130944130613960700859876177349934827, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29525", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a division by 0 in `tf.raw_ops.Conv2DBackpropInput`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/b40060c9f697b044e3107917c797ba052f4506ab/tensorflow/core/kernels/conv_grad_input_ops.h#L625-L655) does a division by a quantity that is controlled by the caller. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29525"} {"idx": 196672, "project": "exif", "commit_id": "eb84b0e3c5f2a86013b6fcfb800d187896a648fa", "project_url": "https://github.com/libexif/exif", "commit_url": "https://github.com/libexif/exif/commit/eb84b0e3c5f2a86013b6fcfb800d187896a648fa", "commit_message": "actually return empty stringand not 'em,pty string' as expected", "target": 1, "func": "escape_xml(const char *text)\n{\n\tstatic char *escaped;\n\tstatic size_t escaped_size;\n\tchar *out;\n\tsize_t len;\n\n\tif (!strlen(text)) return \"empty string\";\n\n\tfor (out=escaped, len=0; *text; ++len, ++out, ++text) {\n\t\t/* Make sure there's plenty of room for a quoted character */\n\t\tif ((len + 8) > escaped_size) {\n\t\t\tchar *bigger_escaped;\n\t\t\tescaped_size += 128;\n\t\t\tbigger_escaped = realloc(escaped, escaped_size);\n\t\t\tif (!bigger_escaped) {\n\t\t\t\tfree(escaped);\t/* avoid leaking memory */\n\t\t\t\tescaped = NULL;\n\t\t\t\tescaped_size = 0;\n\t\t\t\t/* Error string is cleverly chosen to fail XML validation */\n\t\t\t\treturn \">>> out of memory <<<\";\n\t\t\t}\n\t\t\tout = bigger_escaped + len;\n\t\t\tescaped = bigger_escaped;\n\t\t}\n\t\tswitch (*text) {\n\t\t\tcase '&':\n\t\t\t\tstrcpy(out, \"&\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '<':\n\t\t\t\tstrcpy(out, \"<\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\tstrcpy(out, \">\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*out = *text;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t*out = '\\x0'; /* NUL terminate the string */\n\treturn escaped;\n}", "func_hash": 156953271027124614414196627170461856533, "file_name": "actions.c", "file_hash": 25441250072000837477079225522161171175, "cwe": ["CWE-476"], "cve": "CVE-2021-27815", "cve_desc": "NULL Pointer Deference in the exif command line tool, when printing out XML formatted EXIF data, in exif v0.6.22 and earlier allows attackers to cause a Denial of Service (DoS) by uploading a malicious JPEG file, causing the application to crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27815"} {"idx": 242168, "project": "exif", "commit_id": "eb84b0e3c5f2a86013b6fcfb800d187896a648fa", "project_url": "https://github.com/libexif/exif", "commit_url": "https://github.com/libexif/exif/commit/eb84b0e3c5f2a86013b6fcfb800d187896a648fa", "commit_message": "actually return empty stringand not 'em,pty string' as expected", "target": 0, "func": "escape_xml(const char *text)\n{\n\tstatic char *escaped;\n\tstatic size_t escaped_size;\n\tchar *out;\n\tsize_t len;\n\n\tif (!strlen(text)) return \"\";\n\n\tfor (out=escaped, len=0; *text; ++len, ++out, ++text) {\n\t\t/* Make sure there's plenty of room for a quoted character */\n\t\tif ((len + 8) > escaped_size) {\n\t\t\tchar *bigger_escaped;\n\t\t\tescaped_size += 128;\n\t\t\tbigger_escaped = realloc(escaped, escaped_size);\n\t\t\tif (!bigger_escaped) {\n\t\t\t\tfree(escaped);\t/* avoid leaking memory */\n\t\t\t\tescaped = NULL;\n\t\t\t\tescaped_size = 0;\n\t\t\t\t/* Error string is cleverly chosen to fail XML validation */\n\t\t\t\treturn \">>> out of memory <<<\";\n\t\t\t}\n\t\t\tout = bigger_escaped + len;\n\t\t\tescaped = bigger_escaped;\n\t\t}\n\t\tswitch (*text) {\n\t\t\tcase '&':\n\t\t\t\tstrcpy(out, \"&\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '<':\n\t\t\t\tstrcpy(out, \"<\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\tstrcpy(out, \">\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*out = *text;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t*out = '\\x0'; /* NUL terminate the string */\n\treturn escaped;\n}", "func_hash": 83043654988282180947871382180325886616, "file_name": "actions.c", "file_hash": 32573353393816462428180862563110986088, "cwe": ["CWE-476"], "cve": "CVE-2021-27815", "cve_desc": "NULL Pointer Deference in the exif command line tool, when printing out XML formatted EXIF data, in exif v0.6.22 and earlier allows attackers to cause a Denial of Service (DoS) by uploading a malicious JPEG file, causing the application to crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27815"} {"idx": 196673, "project": "tensorflow", "commit_id": "f6c40f0c6cbf00d46c7717a26419f2062f2f8694", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f6c40f0c6cbf00d46c7717a26419f2062f2f8694", "commit_message": "Validate min and max arguments to `QuantizedResizeBilinear`.\n\nPiperOrigin-RevId: 369765091\nChange-Id: I33be8b78273ab7d08b97541692fe05cb7f94963a", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const float in_min = context->input(2).flat()(0);\n const float in_max = context->input(3).flat()(0);\n\n ImageResizerState st(align_corners_, false);\n st.ValidateAndCreateOutput(context);\n\n if (!context->status().ok()) return;\n\n // Return if the output is empty.\n if (st.output->NumElements() == 0) return;\n\n typename TTypes::ConstTensor image_data(\n context->input(0).tensor());\n typename TTypes::Tensor output_data(st.output->tensor());\n\n ResizeBilinear(image_data, st.height_scale, st.width_scale, in_min,\n in_max, half_pixel_centers_, &output_data);\n Tensor* out_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &out_min));\n out_min->flat()(0) = in_min;\n\n Tensor* out_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max));\n out_max->flat()(0) = in_max;\n }", "func_hash": 25016603720643279084374282743345163716, "file_name": "quantized_resize_bilinear_op.cc", "file_hash": 68713638681821120759434578709181360950, "cwe": ["CWE-787"], "cve": "CVE-2021-29537", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `QuantizedResizeBilinear` by passing in invalid thresholds for the quantization. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/50711818d2e61ccce012591eeb4fdf93a8496726/tensorflow/core/kernels/quantized_resize_bilinear_op.cc#L705-L706) assumes that the 2 arguments are always valid scalars and tries to access the numeric value directly. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29537"} {"idx": 242186, "project": "tensorflow", "commit_id": "f6c40f0c6cbf00d46c7717a26419f2062f2f8694", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f6c40f0c6cbf00d46c7717a26419f2062f2f8694", "commit_message": "Validate min and max arguments to `QuantizedResizeBilinear`.\n\nPiperOrigin-RevId: 369765091\nChange-Id: I33be8b78273ab7d08b97541692fe05cb7f94963a", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const auto& in_min_tensor = context->input(2);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(in_min_tensor.shape()),\n errors::InvalidArgument(\"min must be a scalar\"));\n const float in_min = in_min_tensor.flat()(0);\n const auto& in_max_tensor = context->input(3);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(in_max_tensor.shape()),\n errors::InvalidArgument(\"max must be a scalar\"));\n const float in_max = in_max_tensor.flat()(0);\n\n ImageResizerState st(align_corners_, false);\n st.ValidateAndCreateOutput(context);\n\n if (!context->status().ok()) return;\n\n // Return if the output is empty.\n if (st.output->NumElements() == 0) return;\n\n typename TTypes::ConstTensor image_data(\n context->input(0).tensor());\n typename TTypes::Tensor output_data(st.output->tensor());\n\n ResizeBilinear(image_data, st.height_scale, st.width_scale, in_min,\n in_max, half_pixel_centers_, &output_data);\n Tensor* out_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &out_min));\n out_min->flat()(0) = in_min;\n\n Tensor* out_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max));\n out_max->flat()(0) = in_max;\n }", "func_hash": 57975313827815836865817216671695647101, "file_name": "quantized_resize_bilinear_op.cc", "file_hash": 207987506164343488757189036768001101755, "cwe": ["CWE-787"], "cve": "CVE-2021-29537", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `QuantizedResizeBilinear` by passing in invalid thresholds for the quantization. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/50711818d2e61ccce012591eeb4fdf93a8496726/tensorflow/core/kernels/quantized_resize_bilinear_op.cc#L705-L706) assumes that the 2 arguments are always valid scalars and tries to access the numeric value directly. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29537"} {"idx": 196719, "project": "gpac", "commit_id": "289ffce3e0d224d314f5f92a744d5fe35999f20b", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/289ffce3e0d224d314f5f92a744d5fe35999f20b", "commit_message": "fixed #1767 (fuzz)", "target": 1, "func": "void gf_inspect_format_timecode(const u8 *data, u32 size, u32 tmcd_flags, u32 tc_num, u32 tc_den, u32 tmcd_fpt, char szFmt[100]);\n\nvoid DumpTrackInfo(GF_ISOFile *file, GF_ISOTrackID trackID, Bool full_dump, Bool is_track_num, Bool dump_m4sys)\n{\n\tchar szCodec[RFC6381_CODEC_NAME_SIZE_MAX];\n\tDouble scale, max_rate, rate;\n\tBool is_od_track = 0;\n\tu32 trackNum, i, j, ts, mtype, msub_type, timescale, sr, nb_ch, count, alt_group, nb_groups, nb_edits, cdur, csize, bps, pfmt, codecid;\n\tu64 time_slice, dur, size;\n\ts32 cts_shift;\n\tGF_ESD *esd;\n\tchar szDur[50];\n\tchar *lang;\n\n\tif (!is_track_num) {\n\t\ttrackNum = gf_isom_get_track_by_id(file, trackID);\n\t} else {\n\t\ttrackNum = trackID;\n\t\ttrackID = gf_isom_get_track_id(file, trackNum);\n\t}\n\tif (!trackNum) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"No track with ID %d found\\n\", trackID));\n\t\treturn;\n\t}\n\n\ttimescale = gf_isom_get_media_timescale(file, trackNum);\n\tfprintf(stderr, \"# Track %d Info - ID %d - TimeScale %d\\n\", trackNum, trackID, timescale);\n\n\tdur = gf_isom_get_media_original_duration(file, trackNum);\n\tsize = gf_isom_get_media_duration(file, trackNum);\n\tfprintf(stderr, \"Media Duration %s \", format_duration(dur, timescale, szDur));\n\tif (dur != size)\n\t\tfprintf(stderr, \" (recomputed %s)\", format_duration(size, timescale, szDur));\n\tfprintf(stderr, \"\\n\");\n\n\tif (gf_isom_check_data_reference(file, trackNum, 1) != GF_OK) {\n\t\tM4_LOG(GF_LOG_WARNING, (\"Track uses external data reference not supported by GPAC!\\n\"));\n\t}\n\n\tnb_edits = gf_isom_get_edits_count(file, trackNum);\n\tif (nb_edits)\n\t\tfprintf(stderr, \"Track has %d edits: track duration is %s\\n\", nb_edits, format_duration(gf_isom_get_track_duration(file, trackNum), gf_isom_get_timescale(file), szDur));\n\n\tcts_shift = gf_isom_get_composition_offset_shift(file, trackNum);\n\tif (cts_shift)\n\t\tfprintf(stderr, \"Track composition offset shift (negative CTS offset): %d\\n\", cts_shift);\n\n\tif (gf_isom_is_track_in_root_od(file, trackNum) ) fprintf(stderr, \"Track is present in Root OD\\n\");\n\tif (!gf_isom_is_track_enabled(file, trackNum)) fprintf(stderr, \"Track is disabled\\n\");\n\tgf_isom_get_media_language(file, trackNum, &lang);\n\tfprintf(stderr, \"Media Info: Language \\\"%s (%s)\\\" - \", GetLanguage(lang), lang );\n\tgf_free(lang);\n\tmtype = gf_isom_get_media_type(file, trackNum);\n\tfprintf(stderr, \"Type \\\"%s:\", gf_4cc_to_str(mtype));\n\tmsub_type = gf_isom_get_mpeg4_subtype(file, trackNum, 1);\n\tif (!msub_type) msub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tfprintf(stderr, \"%s\\\" - %d samples\\n\", gf_4cc_to_str(msub_type), gf_isom_get_sample_count(file, trackNum));\n\n\tpfmt = gf_pixel_fmt_from_qt_type(msub_type);\n\tcodecid = gf_codec_id_from_isobmf(msub_type);\n\n\tcount = gf_isom_get_track_kind_count(file, trackNum);\n\tfor (i = 0; i < count; i++) {\n\t\tchar *kind_scheme, *kind_value;\n\t\tgf_isom_get_track_kind(file, trackNum, i, &kind_scheme, &kind_value);\n\t\tfprintf(stderr, \"Kind: %s - %s\\n\", kind_scheme ? kind_scheme : \"null\", kind_value ? kind_value : \"null\");\n\t\tif (kind_scheme) gf_free(kind_scheme);\n\t\tif (kind_value) gf_free(kind_value);\n\t}\n\n\tif (gf_isom_is_track_fragmented(file, trackID) ) {\n\t\tu32 defaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess;\n\t\tu8 defaultPadding;\n\t\tu16 defaultDegradationPriority;\n\t\tu32 frag_samples;\n\t\tu64 frag_duration;\n\t\tgf_isom_get_fragmented_samples_info(file, trackID, &frag_samples, &frag_duration);\n\t\tfprintf(stderr, \"Fragmented track: %d samples - Media Duration %s\\n\", frag_samples, format_duration(frag_duration, timescale, szDur));\n\n\t\tgf_isom_get_fragment_defaults(file, trackNum, &defaultDuration, &defaultSize, &defaultDescriptionIndex, &defaultRandomAccess, &defaultPadding, &defaultDegradationPriority);\n\n\t\tfprintf(stderr, \"Fragment sample defaults: duration %d size %d stsd %d sync %d padding %d degradation_priority %d\\n\",\n\t\t\t\tdefaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess,\n\t\t\t\t(u32) defaultPadding, (u32) defaultDegradationPriority\n\t\t);\n\t}\n\n\tif (!gf_isom_is_self_contained(file, trackNum, 1)) {\n\t\tconst char *url, *urn;\n\t\tgf_isom_get_data_reference(file, trackNum, 1, &url, &urn);\n\t\tfprintf(stderr, \"Media Data Location: %s\\n\", url ? url : urn);\n\t}\n\n\tif (full_dump) {\n\t\tconst char *handler_name;\n\t\tgf_isom_get_handler_name(file, trackNum, &handler_name);\n\t\tfprintf(stderr, \"Handler name: %s\\n\", handler_name);\n\t}\n\n\tprint_udta(file, trackNum, GF_FALSE);\n\n\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\ts32 tx, ty;\n\t\tu32 w, h;\n\t\tu16 bit_depth;\n\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tgf_isom_get_visual_bit_depth(file, trackNum, 1, &bit_depth);\n\t\tfprintf(stderr, \"Visual Sample Entry Info: width=%d height=%d (depth=%d bits)\\n\", w, h, (int)bit_depth);\n\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, NULL);\n\t\tfprintf(stderr, \"Visual Track layout: x=%d y=%d width=%d height=%d\\n\", tx, ty, w, h);\n\t}\n\n\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, &bps);\n\tgf_isom_set_nalu_extract_mode(file, trackNum, GF_ISOM_NALU_EXTRACT_INSPECT);\n\n\tmsub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tif (msub_type==GF_ISOM_SUBTYPE_MPEG4_CRYP)\n\t\tgf_isom_get_original_format_type(file, trackNum, 1, &msub_type);\n\n\tif ((msub_type==GF_ISOM_SUBTYPE_MPEG4)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC2_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC3_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC4_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_SVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_MVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_LSR1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC2)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV2)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHE1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVT1)\n\t ) {\n\t\tesd = gf_isom_get_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"WARNING: Broken MPEG-4 Track\\n\"));\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\t} else {\n\t\t\tconst char *st = gf_stream_type_name(esd->decoderConfig->streamType);\n\t\t\tif (dump_m4sys) {\n\t\t\t\tif (st) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%s%s Stream - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", st, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%sStream Type 0x%02x - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", esd->decoderConfig->streamType, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_OD)\n\t\t\t\tis_od_track=1;\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\tu32 w, h;\n\t\t\t\tu16 rvc_predef;\n\t\t\t\tw = h = 0;\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo) {\n#else\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d\\n\", w, h);\n#endif\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Non-compliant MPEG-4 Visual track: video_object_layer infos not found in sample description\\n\"));\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGF_M4VDecSpecInfo dsi;\n\t\t\t\t\t\tgf_m4v_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &dsi);\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tw = dsi.width;\n\t\t\t\t\t\th = dsi.height;\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d - %s\\n\", w, h, gf_m4v_get_profile_name(dsi.VideoPL));\n\t\t\t\t\t\tif (dsi.par_den && dsi.par_num) {\n\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\tfprintf(stderr, \"Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", dsi.par_num, dsi.par_den, tw, th);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t} else if (gf_isom_get_avc_svc_type(file, trackNum, 1) != GF_ISOM_AVCTYPE_NONE) {\n\t\t\t\t\tGF_AVCConfig *avccfg, *svccfg, *mvccfg;\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"AVC/H264 Video - Visual Size %d x %d\\n\", w, h);\n\n\t\t\t\t\tavccfg = gf_isom_avc_config_get(file, trackNum, 1);\n\t\t\t\t\tsvccfg = gf_isom_svc_config_get(file, trackNum, 1);\n\t\t\t\t\tmvccfg = gf_isom_mvc_config_get(file, trackNum, 1);\n\t\t\t\t\tif (!avccfg && !svccfg && !mvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant AVC track: SPS/PPS not found in sample description\\n\"));\n\t\t\t\t\t} else if (avccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tAVC Info: %d SPS - %d PPS\", gf_list_count(avccfg->sequenceParameterSets) , gf_list_count(avccfg->pictureParameterSets) );\n\t\t\t\t\t\tfprintf(stderr, \" - Profile %s @ Level %g\\n\", gf_avc_get_profile_name(avccfg->AVCProfileIndication), ((Double)avccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tNAL Unit length bits: %d\\n\", 8*avccfg->nal_unit_size);\n\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(avccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, NULL, NULL, NULL, &par_n, &par_d);\n\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!full_dump) break;\n\t\t\t\t\t\t}\n#endif\n\n\t\t\t\t\t\tif (avccfg->chroma_bit_depth) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tChroma format %s - Luma bit depth %d - chroma bit depth %d\\n\", gf_avc_hevc_get_chroma_format_name(avccfg->chroma_format), avccfg->luma_bit_depth, avccfg->chroma_bit_depth);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprint_config_hash(avccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(avccfg->pictureParameterSets, \"PPS\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(avccfg);\n\t\t\t\t\t}\n\t\t\t\t\tif (svccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tSVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(svccfg->sequenceParameterSets) , gf_list_count(svccfg->pictureParameterSets), gf_avc_get_profile_name(svccfg->AVCProfileIndication), ((Double)svccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tSVC NAL Unit length bits: %d\\n\", 8*svccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(svccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSetExtensions, \"SPSEx\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (mvccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tMVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(mvccfg->sequenceParameterSets) , gf_list_count(mvccfg->pictureParameterSets), gf_avc_get_profile_name(mvccfg->AVCProfileIndication), ((Double)mvccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tMVC NAL Unit length bits: %d\\n\", 8*mvccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(mvccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(mvccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(mvccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tgf_odf_avc_cfg_del(mvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t} else if ((esd->decoderConfig->objectTypeIndication==GF_CODECID_HEVC)\n\t\t\t\t || (esd->decoderConfig->objectTypeIndication==GF_CODECID_LHVC)\n\t\t\t\t ) {\n\t\t\t\t\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\t\t\t\t\tGF_OperatingPointsInformation *oinf;\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\tHEVCState hevc_state;\n\t\t\t\t\tmemset(&hevc_state, 0, sizeof(HEVCState));\n\t\t\t\t\thevc_state.sps_active_idx = -1;\n#endif\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"HEVC Video - Visual Size %d x %d\\n\", w, h);\n\t\t\t\t\thevccfg = gf_isom_hevc_config_get(file, trackNum, 1);\n\t\t\t\t\tlhvccfg = gf_isom_lhvc_config_get(file, trackNum, 1);\n\n\t\t\t\t\tif (msub_type==GF_ISOM_SUBTYPE_HVT1) {\n\t\t\t\t\t\tconst u8 *data;\n\t\t\t\t\t\tu32 tsize;\n\t\t\t\t\t\tu32 is_default, tx,ty,tw,th, id, independent;\n\t\t\t\t\t\tBool full_frame;\n\t\t\t\t\t\tif (gf_isom_get_tile_info(file, trackNum, 1, &is_default, &id, &independent, &full_frame, &tx, &ty, &tw, &th)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile - ID %d independent %d (x,y,w,h)=%d,%d,%d,%d \\n\", id, independent, tx, ty, tw, th);\n\t\t\t\t\t\t} else if (gf_isom_get_sample_group_info(file, trackNum, 1, GF_ISOM_SAMPLE_GROUP_TRIF, &is_default, &data, &tsize)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track containing a tile set\\n\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track without tiling info\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!hevccfg && !lhvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant HEVC track: No hvcC or shcC found in sample description\\n\"));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_SABT)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile base track\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (hevccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(hevccfg);\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (lhvccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, lhvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(lhvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_oinf_info(file, trackNum, &oinf)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tOperating Points Information -\");\n\t\t\t\t\t\tfprintf(stderr, \" scalability_mask %d (\", oinf->scalability_mask);\n\t\t\t\t\t\tswitch (oinf->scalability_mask) {\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tfprintf(stderr, \"Multiview\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tfprintf(stderr, \"Spatial scalability\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\tfprintf(stderr, \"Auxilary\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfprintf(stderr, \"unknown\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//TODO: need to dump more info ?\n\t\t\t\t\t\tfprintf(stderr, \") num_profile_tier_level %d \", gf_list_count(oinf->profile_tier_levels) );\n\t\t\t\t\t\tfprintf(stderr, \" num_operating_points %d dependency layers %d \\n\", gf_list_count(oinf->operating_points), gf_list_count(oinf->dependency_layers) );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*OGG media*/\n\t\t\t\telse if (esd->decoderConfig->objectTypeIndication==GF_CODECID_THEORA) {\n\t\t\t\t\tchar *szName;\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (!strnicmp((char *) &esd->decoderConfig->decoderSpecificInfo->data[3], \"theora\", 6)) szName = \"Theora\";\n\t\t\t\t\telse szName = \"Unknown\";\n\t\t\t\t\tfprintf(stderr, \"Ogg/%s video / GPAC Mux - Visual Size %d x %d\\n\", szName, w, h);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//check if we know this codec from its OTI\n\t\t\t\t\tu32 codec_id = gf_codecid_from_oti(GF_STREAM_VISUAL, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\t\tfprintf(stderr, \"%s - Visual Size %d x %d\\n\", gf_codecid_name(codec_id), w, h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!w || !h) {\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"Visual Size %d x %d\\n\", w, h);\n\t\t\t\t}\n\t\t\t\tif (gf_isom_get_rvc_config(file, trackNum, 1, &rvc_predef, NULL, NULL, NULL)==GF_OK) {\n\t\t\t\t\tfprintf(stderr, \"Has RVC signaled - Predefined configuration %d\\n\", rvc_predef);\n\t\t\t\t}\n\n\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\tGF_Err e;\n\t\t\t\tu32 oti;\n#endif\n\t\t\t\tu32 codec_id;\n\t\t\t\tBool is_mp2 = GF_FALSE;\n\t\t\t\tswitch (esd->decoderConfig->objectTypeIndication) {\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_MP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_LCP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_SSRP:\n\t\t\t\t\tis_mp2 = GF_TRUE;\n\t\t\t\tcase GF_CODECID_AAC_MPEG4:\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo)\n\t\t\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\t\telse\n\t\t\t\t\t\te = gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Corrupted AAC Config\\n\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchar *signaling = \"implicit\";\n\t\t\t\t\t\tchar *heaac = \"\";\n\t\t\t\t\t\tif (!is_mp2 && a_cfg.has_sbr) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps) heaac = \"(HE-AAC v2) \";\n\t\t\t\t\t\t\telse heaac = \"(HE-AAC v1) \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (a_cfg.base_object_type==2) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps || a_cfg.has_sbr)\n\t\t\t\t\t\t\t\tsignaling = \"backward compatible\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsignaling = \"hierarchical\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfprintf(stderr, \"%s (AOT=%d %s) %s- %d Channel(s) - SampleRate %d\", gf_m4a_object_type_name(a_cfg.base_object_type), a_cfg.base_object_type, signaling, heaac, a_cfg.nb_chan, a_cfg.base_sr);\n\t\t\t\t\t\tif (is_mp2) fprintf(stderr, \" (MPEG-2 Signaling)\");\n\t\t\t\t\t\tif (a_cfg.has_sbr) fprintf(stderr, \" - SBR: SampleRate %d Type %s\", a_cfg.sbr_sr, gf_m4a_object_type_name(a_cfg.sbr_object_type));\n\t\t\t\t\t\tif (a_cfg.has_ps) fprintf(stderr, \" - PS\");\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n#else\n\t\t\t\t\tfprintf(stderr, \"MPEG-2/4 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_MPEG2_PART3:\n\t\t\t\tcase GF_CODECID_MPEG_AUDIO:\n\t\t\t\t\tif (msub_type == GF_ISOM_SUBTYPE_MPEG4_CRYP) {\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n\t\t\t\t\t} else {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, &oti);\n\t\t\t\t\t\tif (samp) {\n\t\t\t\t\t\t\tu32 mhdr = GF_4CC((u8)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%s Audio - %d Channel(s) - SampleRate %d - Layer %d\\n\",\n\t\t\t\t\t\t\t gf_mp3_version_name(mhdr),\n\t\t\t\t\t\t\t gf_mp3_num_channels(mhdr),\n\t\t\t\t\t\t\t gf_mp3_sampling_rate(mhdr),\n\t\t\t\t\t\t\t gf_mp3_layer(mhdr)\n\t\t\t\t\t\t\t );\n\t\t\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error fetching sample: %s\\n\", gf_error_to_string(gf_isom_last_error(file)) ));\n\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_EVRC:\n\t\t\t\t\tfprintf(stderr, \"EVRC Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_SMV:\n\t\t\t\t\tfprintf(stderr, \"SMV Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_QCELP:\n\t\t\t\t\tfprintf(stderr, \"QCELP Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t/*packetVideo hack for EVRC...*/\n\t\t\t\tcase GF_CODECID_EVRC_PV:\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo && (esd->decoderConfig->decoderSpecificInfo->dataLength==8)\n\t\t\t\t\t && !strnicmp((char *)esd->decoderConfig->decoderSpecificInfo->data, \"pvmm\", 4)) {\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tfprintf(stderr, \"EVRC Audio (PacketVideo Mux) - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcodec_id = gf_codecid_from_oti(GF_STREAM_AUDIO, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codec_id), sr, nb_ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (esd->decoderConfig->streamType==GF_STREAM_SCENE) {\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication<=4) {\n\t\t\t\t\tGF_BIFSConfig *b_cfg = gf_odf_get_bifs_config(esd->decoderConfig->decoderSpecificInfo, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tfprintf(stderr, \"BIFS Scene description - %s stream\\n\", b_cfg->elementaryMasks ? \"Animation\" : \"Command\");\n\t\t\t\t\tif (full_dump && !b_cfg->elementaryMasks) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tWidth %d Height %d Pixel Metrics %s\\n\", b_cfg->pixelWidth, b_cfg->pixelHeight, b_cfg->pixelMetrics ? \"yes\" : \"no\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)b_cfg);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AFX) {\n\t\t\t\t\tu8 tag = esd->decoderConfig->decoderSpecificInfo ? esd->decoderConfig->decoderSpecificInfo->data[0] : 0xFF;\n\t\t\t\t\tconst char *afxtype = gf_stream_type_afx_name(tag);\n\t\t\t\t\tfprintf(stderr, \"AFX Stream - type %s (%d)\\n\", afxtype, tag);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_FONT) {\n\t\t\t\t\tfprintf(stderr, \"Font Data stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_LASER) {\n\t\t\t\t\tGF_LASERConfig l_cfg;\n\t\t\t\t\tgf_odf_get_laser_config(esd->decoderConfig->decoderSpecificInfo, &l_cfg);\n\t\t\t\t\tfprintf(stderr, \"LASER Stream - %s\\n\", l_cfg.newSceneIndicator ? \"Full Scene\" : \"Scene Segment\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_TEXT_MPEG4) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Streaming Text stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_SYNTHESIZED_TEXTURE) {\n\t\t\t\t\tfprintf(stderr, \"Synthetized Texture stream stream\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Unknown Systems stream OTI %d\\n\", esd->decoderConfig->objectTypeIndication));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*sync is only valid if we open all tracks to take care of default MP4 sync..*/\n\t\t\tif (!full_dump) {\n\t\t\t\tif (dump_m4sys) {\n\t\t\t\t\tif (!esd->OCRESID || (esd->OCRESID == esd->ESID))\n\t\t\t\t\t\tfprintf(stderr, \"Self-synchronized\\n\");\n\t\t\t\t\telse\n\t\t\t\t\t\tfprintf(stderr, \"Synchronized on stream %d\\n\", esd->OCRESID);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"\\tDecoding Buffer size %d - Bitrate: avg %d - max %d kbps\\n\", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate/1000, esd->decoderConfig->maxBitrate/1000);\n\t\t\t\tif (esd->dependsOnESID)\n\t\t\t\t\tfprintf(stderr, \"\\tDepends on stream %d for decoding\\n\", esd->dependsOnESID);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, \"\\tNo stream dependencies for decoding\\n\");\n\n\t\t\t\tfprintf(stderr, \"\\tStreamPriority %d\\n\", esd->streamPriority);\n\t\t\t\tif (esd->URLString) fprintf(stderr, \"\\tRemote Data Source %s\\n\", esd->URLString);\n\t\t\t}\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_AV01) {\n\t\tGF_AV1Config *av1c;\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);\n\n\t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);\n\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n\n\t\tif (av1c->initial_presentation_delay_present)\n\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n\n\t\tcount = gf_list_count(av1c->obu_array);\n\t\tfor (i=0; iobu_array, i);\n\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n\t\tgf_odf_av1_cfg_del(av1c);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\t3GPP H263 stream - Resolution %d x %d\\n\", w, h);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MJP2) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tMotionJPEG2000 stream - Resolution %d x %d\\n\", w, h);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_3GP_AMR) || (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB)) {\n\t\tfprintf(stderr, \"\\t3GPP AMR%s stream - Sample Rate %d - %d channel(s) %d bps\\n\", (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB) ? \" Wide Band\" : \"\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_EVRC) {\n\t\tfprintf(stderr, \"\\t3GPP EVRC stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_QCELP) {\n\t\tfprintf(stderr, \"\\t3GPP QCELP stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MP3) {\n\t\tfprintf(stderr, \"\\tMPEG 1/2 Audio stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_AC3) || (msub_type == GF_ISOM_SUBTYPE_EC3)) {\n\t\tu32 br = 0;\n\t\tconst char *lfe = \"\";\n\t\tBool is_ec3 = (msub_type == GF_ISOM_SUBTYPE_EC3) ? GF_TRUE : GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\tGF_AC3Config *ac3 = gf_isom_ac3_config_get(file, trackNum, 1);\n\t\tif (ac3) {\n\t\t\tnb_ch = gf_ac3_get_channels(ac3->streams[0].acmod);\n\t\t\tfor (i=0; istreams[0].nb_dep_sub; ++i) {\n\t\t\t\tassert(ac3->streams[0].nb_dep_sub == 1);\n\t\t\t\tnb_ch += gf_ac3_get_channels(ac3->streams[0].chan_loc);\n\t\t\t}\n\t\t\tif (ac3->streams[0].lfon) lfe = \".1\";\n\t\t\tbr = ac3->is_ec3 ? ac3->brcode : gf_ac3_get_bitrate(ac3->brcode);\n\t\t\tis_ec3 = ac3->is_ec3;\n\t\t\tgf_free(ac3);\n\t\t}\n#endif\n\t\tfprintf(stderr, \"\\t%s stream - Sample Rate %d - %d%s channel(s) - bitrate %d\\n\", is_ec3 ? \"EC-3\" : \"AC-3\", sr, nb_ch, lfe, br);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_SMV) {\n\t\tfprintf(stderr, \"\\t3GPP SMV stream - Sample Rate %d - %d channel(s) %d bits per samples\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_DIMS) {\n\t\tu32 w, h;\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\n\t\tgf_isom_get_dims_description(file, trackNum, 1, &dims);\n\t\tfprintf(stderr, \"\\t3GPP DIMS stream - size %d x %d - Profile %d - Level %d\\n\", w, h, dims.profile, dims.level);\n\t\tfprintf(stderr, \"\\tpathComponents: %d - useFullRequestHost: %s\\n\", dims.pathComponents, dims.fullRequestHost ? \"yes\" : \"no\");\n\t\tfprintf(stderr, \"\\tstream type: %s - redundant: %s\\n\", dims.streamType ? \"primary\" : \"secondary\", (dims.containsRedundant==1) ? \"main\" : ((dims.containsRedundant==2) ? \"redundant\" : \"main+redundant\") );\n\t\tif (dims.textEncoding[0]) fprintf(stderr, \"\\ttext encoding %s\\n\", dims.textEncoding);\n\t\tif (dims.contentEncoding[0]) fprintf(stderr, \"\\tcontent encoding %s\\n\", dims.contentEncoding);\n\t\tif (dims.content_script_types) fprintf(stderr, \"\\tscript languages %s\\n\", dims.content_script_types);\n\t} else if (mtype==GF_ISOM_MEDIA_HINT) {\n\t\tu32 refTrack;\n\t\ts32 refCount = gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_HINT);\n\t\tif (refCount>0) {\n\t\t\tfprintf(stderr, \"Streaming Hint Track for track%s \", (refCount>1) ? \"s\" :\"\");\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tgf_isom_get_reference(file, trackNum, GF_ISOM_REF_HINT, i+1, &refTrack);\n\t\t\t\tif (i) fprintf(stderr, \" - \");\n\t\t\t\tfprintf(stderr, \"ID %d\", gf_isom_get_track_id(file, refTrack));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Streaming Hint Track (no refs)\\n\");\n\t\t}\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\trefCount = gf_isom_get_payt_count(file, trackNum);\n\t\tif (refCount>0) {\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tconst char *name = gf_isom_get_payt_info(file, trackNum, i+1, &refTrack);\n\t\t\t\tfprintf(stderr, \"\\tPayload ID %d: type %s\\n\", refTrack, name);\n\t\t\t}\n\t\t}\n#endif\n\t} else if (mtype==GF_ISOM_MEDIA_FLASH) {\n\t\tfprintf(stderr, \"Macromedia Flash Movie\\n\");\n\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) || (mtype==GF_ISOM_MEDIA_MPEG_SUBT)) {\n\t\tu32 w, h;\n\t\ts16 l;\n\t\ts32 tx, ty;\n\t\tconst char *content_encoding = NULL;\n\t\tconst char *mime = NULL;\n\t\tconst char *config = NULL;\n\t\tconst char *_namespace = NULL;\n\t\tconst char *schema_loc = NULL;\n\t\tconst char *auxiliary_mimes = NULL;\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, &l);\n\t\tif (msub_type == GF_ISOM_SUBTYPE_SBTT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STXT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Simple Timed Text Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STPP) {\n\t\t\tgf_isom_xml_subtitle_get_description(file, trackNum, 1, &_namespace, &schema_loc, &auxiliary_mimes);\n\t\t\tfprintf(stderr, \"XML Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- namespace %s\", _namespace);\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tif (auxiliary_mimes != NULL) {\n\t\t\t\tfprintf(stderr, \" - auxiliary-mime-types %s\", auxiliary_mimes);\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Text Stream\");\n\t\t}\n\t\tfprintf(stderr, \"\\n Size %d x %d - Translation X=%d Y=%d - Layer %d\\n\", w, h, tx, ty, l);\n\t} else if (mtype == GF_ISOM_MEDIA_META) {\n\t\tconst char *content_encoding = NULL;\n\t\tif (msub_type == GF_ISOM_SUBTYPE_METT) {\n\t\t\tconst char *mime = NULL;\n\t\t\tconst char *config = NULL;\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Metadata Stream - mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_METX) {\n\t\t\tconst char *_namespace = NULL;\n\t\t\tconst char *schema_loc = NULL;\n\t\t\tgf_isom_get_xml_metadata_description(file, trackNum, 1, &_namespace, &schema_loc, &content_encoding);\n\t\t\tfprintf(stderr, \"XML Metadata Stream - namespace %s\", _namespace);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Metadata Stream\\n\");\n\t\t}\n\t} else if ((msub_type==GF_ISOM_SUBTYPE_VVC1) || (msub_type==GF_ISOM_SUBTYPE_VVI1)) {\n\t\tGF_VVCConfig *vvccfg;\n\t\tu32 w, h;\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tVVCState *vvc_state;\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (vvc_state) vvc_state->sps_active_idx = -1;\n#endif\n\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\tfprintf(stderr, \"VVC Video - Visual Size %d x %d\\n\", w, h);\n\t\tvvccfg = gf_isom_vvc_config_get(file, trackNum, 1);\n\n\t\tif (!vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Non-compliant VVC track: No vvcC found in sample description\\n\"));\n\t\t} else {\n\t\t\tdump_vvc_track_info(file, trackNum, vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\t\t\t, vvc_state\n#endif\n\t\t\t);\n\t\t\tgf_odf_vvc_cfg_del(vvccfg);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tif (vvc_state) gf_free(vvc_state);\n#endif\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_MH3D_MHA1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHA2)\n\t\t\t|| (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2)\n\t) {\n\t\tconst u8 *compat_profiles;\n\t\tu32 nb_compat_profiles;\n\t\tBool valid = GF_FALSE;\n\t\tBool allow_inband = GF_FALSE;\n\t\tif ( (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2))\n\t\t\tallow_inband = GF_TRUE;\n\n\t\tfprintf(stderr, \"\\tMPEG-H Audio stream - Sample Rate %d\\n\", sr);\n\n\t\tesd = gf_media_map_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig || !esd->decoderConfig->decoderSpecificInfo\n\t\t\t|| !esd->decoderConfig->decoderSpecificInfo->data\n\t\t) {\n\t\t\tif (allow_inband) {\n\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, NULL);\n\t\t\t\tif (samp) {\n\t\t\t\t\tu64 ch_layout=0;\n\t\t\t\t\ts32 PL = gf_mpegh_get_mhas_pl(samp->data, samp->dataLength, &ch_layout);\n\t\t\t\t\tif (PL>=0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X\", PL);\n\t\t\t\t\t\tif (ch_layout)\n\t\t\t\t\t\t\tfprintf(stderr, \" - Reference Channel Layout %s\", gf_audio_fmt_get_layout_name(ch_layout) );\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t}\n\t\t\t\tvalid = GF_TRUE;\n\t\t\t}\n\t\t} else if (esd->decoderConfig->decoderSpecificInfo->dataLength>=5) {\n\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X - Reference Channel Layout %s\\n\", esd->decoderConfig->decoderSpecificInfo->data[1]\n\t\t\t\t, gf_audio_fmt_get_layout_name_from_cicp(esd->decoderConfig->decoderSpecificInfo->data[2])\n\t\t\t);\n\t\t\tvalid = GF_TRUE;\n\t\t}\n\t\tif (!valid) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Invalid MPEG-H audio config\\n\"));\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\tcompat_profiles = gf_isom_get_mpegh_compatible_profiles(file, trackNum, 1, &nb_compat_profiles);\n\t\tfor (i=0; idata, sample->dataLength, tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt, szTimecode);\n\n\t\t\tgf_isom_sample_del(&sample);\n\t\t\tfprintf(stderr, \"\\tFirst timecode: %s\\n\", szTimecode);\n\t\t}\n\t} else {\n\t\tGF_GenericSampleDescription *udesc;\n\n\t\tudesc = gf_isom_get_generic_sample_description(file, trackNum, 1);\n\t\tif (udesc) {\n\t\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n fprintf(stderr, \"%s - Compressor \\\"%s\\\" - Resolution %d x %d\\n\",\n\t\t\t\t\t\t( (mtype == GF_ISOM_MEDIA_VISUAL ? \"Visual\" : \"Auxiliary Video\") ),\n udesc->compressor_name, udesc->width, udesc->height);\n\t\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\t\tfprintf(stderr, \"Audio - Sample Rate %d - %d channel(s)\\n\", udesc->samplerate, udesc->nb_channels);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown media type\\n\");\n\t\t\t}\n\t\t\tif (udesc->vendor_code)\n\t\t\t\tfprintf(stderr, \"\\tVendor code \\\"%s\\\" - Version %d - revision %d\\n\", gf_4cc_to_str(udesc->vendor_code), udesc->version, udesc->revision);\n\n\t\t\tif (udesc->extension_buf) {\n\t\t\t\tfprintf(stderr, \"\\tCodec configuration data size: %d bytes\\n\", udesc->extension_buf_size);\n\t\t\t\tgf_free(udesc->extension_buf);\n\t\t\t}\n\t\t\tgf_free(udesc);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown track type\\n\");\n\t\t}\n\t}\n\n\n\t/*Crypto info*/\n\tif (gf_isom_is_track_encrypted(file, trackNum)) {\n\t\tconst char *scheme_URI, *KMS_URI;\n\t\tu32 scheme_type, version;\n\t\tu32 IV_size;\n\t\tBool use_sel_enc;\n\n\t\tif (gf_isom_is_ismacryp_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_ismacryp_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by ISMA E&A scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tif (scheme_URI) fprintf(stderr, \"scheme location: %s\\n\", scheme_URI);\n\t\t\tif (KMS_URI) {\n\t\t\t\tif (!strnicmp(KMS_URI, \"(key)\", 5)) fprintf(stderr, \"\\tKMS location: key in file\\n\");\n\t\t\t\telse fprintf(stderr, \"\\tKMS location: %s\\n\", KMS_URI);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if (gf_isom_is_omadrm_media(file, trackNum, 1)) {\n\t\t\tconst char *textHdrs;\n\t\t\tu32 enc_type, hdr_len;\n\t\t\tu64 orig_len;\n\t\t\tgf_isom_get_omadrm_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &textHdrs, &hdr_len, &orig_len, &enc_type, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by OMA DRM scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tfprintf(stderr, \"\\tRights Issuer: %s\\n\", KMS_URI);\n\t\t\tfprintf(stderr, \"\\tContent ID: %s\\n\", scheme_URI);\n\t\t\tif (textHdrs) {\n\t\t\t\tu32 offset;\n\t\t\t\tconst char *start = textHdrs;\n\t\t\t\tfprintf(stderr, \"\\tOMA Textual Headers:\\n\");\n\t\t\t\ti=0;\n\t\t\t\toffset=0;\n\t\t\t\twhile (iDTS+samp->CTS_Offset;\n\t\t\tsize += samp->dataLength;\n\t\t\trate += samp->dataLength;\n\t\t\tif (samp->DTS - time_slice > ts) {\n\t\t\t\tDouble max_tmp = rate * ts / (samp->DTS - time_slice);\n\t\t\t\tif (max_rate < max_tmp )\n\t\t\t\t\tmax_rate = max_tmp;\n\n\t\t\t\trate = 0;\n\t\t\t\ttime_slice = samp->DTS;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\nComputed info from media:\\n\");\n\tif (csize && cdur) {\n\t\tfprintf(stderr, \"\\tConstant sample size %d bytes and dur %d / %d\\n\", csize, cdur, ts);\n\t}\n\tscale = 1000.0 / ts;\n\tdur = (u64) (scale * dur);\n\tfprintf(stderr, \"\\tTotal size \"LLU\" bytes - Total samples duration \"LLU\" ms\\n\", size, dur);\n\tif (!dur) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\t/*rate in byte, dur is in ms*/\n\trate = 8000.0 * size / dur;\n\n\tif (!max_rate)\n\t\tmax_rate = rate;\n\telse\n\t\tmax_rate *= 8.0;\n\n\tif (rate >= 1500) {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f kbps - Max Rate %.2f kbps\\n\", rate/1000, max_rate/1000);\n\t} else {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f bps - Max Rate %.2f bps\\n\", rate, max_rate);\n\t}\n\n\t{\n\t\tu32 dmin, dmax, davg, smin, smax, savg;\n\t\tgf_isom_get_chunks_infos(file, trackNum, &dmin, &davg, &dmax, &smin, &savg, &smax);\n\t\tfprintf(stderr, \"\\tChunk durations: min %d ms - max %d ms - average %d ms\\n\", (1000*dmin)/ts, (1000*dmax)/ts, (1000*davg)/ts);\n\t\tfprintf(stderr, \"\\tChunk sizes (bytes): min %d - max %d - average %d\\n\", smin, smax, savg);\n\t}\n\tfprintf(stderr, \"\\n\");\n\n\tcount = gf_isom_get_chapter_count(file, trackNum);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (j=0; jdecoderConfig) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"WARNING: Broken MPEG-4 Track\\n\"));\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\t} else {\n\t\t\tconst char *st = gf_stream_type_name(esd->decoderConfig->streamType);\n\t\t\tif (dump_m4sys) {\n\t\t\t\tif (st) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%s%s Stream - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", st, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%sStream Type 0x%02x - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", esd->decoderConfig->streamType, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_OD)\n\t\t\t\tis_od_track=1;\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\tu32 w, h;\n\t\t\t\tu16 rvc_predef;\n\t\t\t\tw = h = 0;\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo) {\n#else\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d\\n\", w, h);\n#endif\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Non-compliant MPEG-4 Visual track: video_object_layer infos not found in sample description\\n\"));\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGF_M4VDecSpecInfo dsi;\n\t\t\t\t\t\tgf_m4v_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &dsi);\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tw = dsi.width;\n\t\t\t\t\t\th = dsi.height;\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d - %s\\n\", w, h, gf_m4v_get_profile_name(dsi.VideoPL));\n\t\t\t\t\t\tif (dsi.par_den && dsi.par_num) {\n\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\tfprintf(stderr, \"Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", dsi.par_num, dsi.par_den, tw, th);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t} else if (gf_isom_get_avc_svc_type(file, trackNum, 1) != GF_ISOM_AVCTYPE_NONE) {\n\t\t\t\t\tGF_AVCConfig *avccfg, *svccfg, *mvccfg;\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"AVC/H264 Video - Visual Size %d x %d\\n\", w, h);\n\n\t\t\t\t\tavccfg = gf_isom_avc_config_get(file, trackNum, 1);\n\t\t\t\t\tsvccfg = gf_isom_svc_config_get(file, trackNum, 1);\n\t\t\t\t\tmvccfg = gf_isom_mvc_config_get(file, trackNum, 1);\n\t\t\t\t\tif (!avccfg && !svccfg && !mvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant AVC track: SPS/PPS not found in sample description\\n\"));\n\t\t\t\t\t} else if (avccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tAVC Info: %d SPS - %d PPS\", gf_list_count(avccfg->sequenceParameterSets) , gf_list_count(avccfg->pictureParameterSets) );\n\t\t\t\t\t\tfprintf(stderr, \" - Profile %s @ Level %g\\n\", gf_avc_get_profile_name(avccfg->AVCProfileIndication), ((Double)avccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tNAL Unit length bits: %d\\n\", 8*avccfg->nal_unit_size);\n\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(avccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, NULL, NULL, NULL, &par_n, &par_d);\n\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!full_dump) break;\n\t\t\t\t\t\t}\n#endif\n\n\t\t\t\t\t\tif (avccfg->chroma_bit_depth) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tChroma format %s - Luma bit depth %d - chroma bit depth %d\\n\", gf_avc_hevc_get_chroma_format_name(avccfg->chroma_format), avccfg->luma_bit_depth, avccfg->chroma_bit_depth);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprint_config_hash(avccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(avccfg->pictureParameterSets, \"PPS\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(avccfg);\n\t\t\t\t\t}\n\t\t\t\t\tif (svccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tSVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(svccfg->sequenceParameterSets) , gf_list_count(svccfg->pictureParameterSets), gf_avc_get_profile_name(svccfg->AVCProfileIndication), ((Double)svccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tSVC NAL Unit length bits: %d\\n\", 8*svccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(svccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSetExtensions, \"SPSEx\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (mvccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tMVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(mvccfg->sequenceParameterSets) , gf_list_count(mvccfg->pictureParameterSets), gf_avc_get_profile_name(mvccfg->AVCProfileIndication), ((Double)mvccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tMVC NAL Unit length bits: %d\\n\", 8*mvccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(mvccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(mvccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(mvccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tgf_odf_avc_cfg_del(mvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t} else if ((esd->decoderConfig->objectTypeIndication==GF_CODECID_HEVC)\n\t\t\t\t || (esd->decoderConfig->objectTypeIndication==GF_CODECID_LHVC)\n\t\t\t\t ) {\n\t\t\t\t\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\t\t\t\t\tGF_OperatingPointsInformation *oinf;\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\tHEVCState hevc_state;\n\t\t\t\t\tmemset(&hevc_state, 0, sizeof(HEVCState));\n\t\t\t\t\thevc_state.sps_active_idx = -1;\n#endif\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"HEVC Video - Visual Size %d x %d\\n\", w, h);\n\t\t\t\t\thevccfg = gf_isom_hevc_config_get(file, trackNum, 1);\n\t\t\t\t\tlhvccfg = gf_isom_lhvc_config_get(file, trackNum, 1);\n\n\t\t\t\t\tif (msub_type==GF_ISOM_SUBTYPE_HVT1) {\n\t\t\t\t\t\tconst u8 *data;\n\t\t\t\t\t\tu32 tsize;\n\t\t\t\t\t\tu32 is_default, tx,ty,tw,th, id, independent;\n\t\t\t\t\t\tBool full_frame;\n\t\t\t\t\t\tif (gf_isom_get_tile_info(file, trackNum, 1, &is_default, &id, &independent, &full_frame, &tx, &ty, &tw, &th)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile - ID %d independent %d (x,y,w,h)=%d,%d,%d,%d \\n\", id, independent, tx, ty, tw, th);\n\t\t\t\t\t\t} else if (gf_isom_get_sample_group_info(file, trackNum, 1, GF_ISOM_SAMPLE_GROUP_TRIF, &is_default, &data, &tsize)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track containing a tile set\\n\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track without tiling info\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!hevccfg && !lhvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant HEVC track: No hvcC or shcC found in sample description\\n\"));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_SABT)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile base track\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (hevccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(hevccfg);\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (lhvccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, lhvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(lhvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_oinf_info(file, trackNum, &oinf)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tOperating Points Information -\");\n\t\t\t\t\t\tfprintf(stderr, \" scalability_mask %d (\", oinf->scalability_mask);\n\t\t\t\t\t\tswitch (oinf->scalability_mask) {\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tfprintf(stderr, \"Multiview\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tfprintf(stderr, \"Spatial scalability\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\tfprintf(stderr, \"Auxilary\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfprintf(stderr, \"unknown\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//TODO: need to dump more info ?\n\t\t\t\t\t\tfprintf(stderr, \") num_profile_tier_level %d \", gf_list_count(oinf->profile_tier_levels) );\n\t\t\t\t\t\tfprintf(stderr, \" num_operating_points %d dependency layers %d \\n\", gf_list_count(oinf->operating_points), gf_list_count(oinf->dependency_layers) );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*OGG media*/\n\t\t\t\telse if (esd->decoderConfig->objectTypeIndication==GF_CODECID_THEORA) {\n\t\t\t\t\tchar *szName;\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (!strnicmp((char *) &esd->decoderConfig->decoderSpecificInfo->data[3], \"theora\", 6)) szName = \"Theora\";\n\t\t\t\t\telse szName = \"Unknown\";\n\t\t\t\t\tfprintf(stderr, \"Ogg/%s video / GPAC Mux - Visual Size %d x %d\\n\", szName, w, h);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//check if we know this codec from its OTI\n\t\t\t\t\tu32 codec_id = gf_codecid_from_oti(GF_STREAM_VISUAL, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\t\tfprintf(stderr, \"%s - Visual Size %d x %d\\n\", gf_codecid_name(codec_id), w, h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!w || !h) {\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"Visual Size %d x %d\\n\", w, h);\n\t\t\t\t}\n\t\t\t\tif (gf_isom_get_rvc_config(file, trackNum, 1, &rvc_predef, NULL, NULL, NULL)==GF_OK) {\n\t\t\t\t\tfprintf(stderr, \"Has RVC signaled - Predefined configuration %d\\n\", rvc_predef);\n\t\t\t\t}\n\n\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\tGF_Err e;\n\t\t\t\tu32 oti;\n#endif\n\t\t\t\tu32 codec_id;\n\t\t\t\tBool is_mp2 = GF_FALSE;\n\t\t\t\tswitch (esd->decoderConfig->objectTypeIndication) {\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_MP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_LCP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_SSRP:\n\t\t\t\t\tis_mp2 = GF_TRUE;\n\t\t\t\tcase GF_CODECID_AAC_MPEG4:\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo)\n\t\t\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\t\telse\n\t\t\t\t\t\te = gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Corrupted AAC Config\\n\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchar *signaling = \"implicit\";\n\t\t\t\t\t\tchar *heaac = \"\";\n\t\t\t\t\t\tif (!is_mp2 && a_cfg.has_sbr) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps) heaac = \"(HE-AAC v2) \";\n\t\t\t\t\t\t\telse heaac = \"(HE-AAC v1) \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (a_cfg.base_object_type==2) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps || a_cfg.has_sbr)\n\t\t\t\t\t\t\t\tsignaling = \"backward compatible\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsignaling = \"hierarchical\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfprintf(stderr, \"%s (AOT=%d %s) %s- %d Channel(s) - SampleRate %d\", gf_m4a_object_type_name(a_cfg.base_object_type), a_cfg.base_object_type, signaling, heaac, a_cfg.nb_chan, a_cfg.base_sr);\n\t\t\t\t\t\tif (is_mp2) fprintf(stderr, \" (MPEG-2 Signaling)\");\n\t\t\t\t\t\tif (a_cfg.has_sbr) fprintf(stderr, \" - SBR: SampleRate %d Type %s\", a_cfg.sbr_sr, gf_m4a_object_type_name(a_cfg.sbr_object_type));\n\t\t\t\t\t\tif (a_cfg.has_ps) fprintf(stderr, \" - PS\");\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n#else\n\t\t\t\t\tfprintf(stderr, \"MPEG-2/4 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_MPEG2_PART3:\n\t\t\t\tcase GF_CODECID_MPEG_AUDIO:\n\t\t\t\t\tif (msub_type == GF_ISOM_SUBTYPE_MPEG4_CRYP) {\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n\t\t\t\t\t} else {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, &oti);\n\t\t\t\t\t\tif (samp) {\n\t\t\t\t\t\t\tu32 mhdr = GF_4CC((u8)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%s Audio - %d Channel(s) - SampleRate %d - Layer %d\\n\",\n\t\t\t\t\t\t\t gf_mp3_version_name(mhdr),\n\t\t\t\t\t\t\t gf_mp3_num_channels(mhdr),\n\t\t\t\t\t\t\t gf_mp3_sampling_rate(mhdr),\n\t\t\t\t\t\t\t gf_mp3_layer(mhdr)\n\t\t\t\t\t\t\t );\n\t\t\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error fetching sample: %s\\n\", gf_error_to_string(gf_isom_last_error(file)) ));\n\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_EVRC:\n\t\t\t\t\tfprintf(stderr, \"EVRC Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_SMV:\n\t\t\t\t\tfprintf(stderr, \"SMV Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_QCELP:\n\t\t\t\t\tfprintf(stderr, \"QCELP Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t/*packetVideo hack for EVRC...*/\n\t\t\t\tcase GF_CODECID_EVRC_PV:\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo && (esd->decoderConfig->decoderSpecificInfo->dataLength==8)\n\t\t\t\t\t && !strnicmp((char *)esd->decoderConfig->decoderSpecificInfo->data, \"pvmm\", 4)) {\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tfprintf(stderr, \"EVRC Audio (PacketVideo Mux) - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcodec_id = gf_codecid_from_oti(GF_STREAM_AUDIO, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codec_id), sr, nb_ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (esd->decoderConfig->streamType==GF_STREAM_SCENE) {\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication<=4) {\n\t\t\t\t\tGF_BIFSConfig *b_cfg = gf_odf_get_bifs_config(esd->decoderConfig->decoderSpecificInfo, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tfprintf(stderr, \"BIFS Scene description - %s stream\\n\", b_cfg->elementaryMasks ? \"Animation\" : \"Command\");\n\t\t\t\t\tif (full_dump && !b_cfg->elementaryMasks) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tWidth %d Height %d Pixel Metrics %s\\n\", b_cfg->pixelWidth, b_cfg->pixelHeight, b_cfg->pixelMetrics ? \"yes\" : \"no\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)b_cfg);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AFX) {\n\t\t\t\t\tu8 tag = esd->decoderConfig->decoderSpecificInfo ? esd->decoderConfig->decoderSpecificInfo->data[0] : 0xFF;\n\t\t\t\t\tconst char *afxtype = gf_stream_type_afx_name(tag);\n\t\t\t\t\tfprintf(stderr, \"AFX Stream - type %s (%d)\\n\", afxtype, tag);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_FONT) {\n\t\t\t\t\tfprintf(stderr, \"Font Data stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_LASER) {\n\t\t\t\t\tGF_LASERConfig l_cfg;\n\t\t\t\t\tgf_odf_get_laser_config(esd->decoderConfig->decoderSpecificInfo, &l_cfg);\n\t\t\t\t\tfprintf(stderr, \"LASER Stream - %s\\n\", l_cfg.newSceneIndicator ? \"Full Scene\" : \"Scene Segment\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_TEXT_MPEG4) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Streaming Text stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_SYNTHESIZED_TEXTURE) {\n\t\t\t\t\tfprintf(stderr, \"Synthetized Texture stream stream\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Unknown Systems stream OTI %d\\n\", esd->decoderConfig->objectTypeIndication));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*sync is only valid if we open all tracks to take care of default MP4 sync..*/\n\t\t\tif (!full_dump) {\n\t\t\t\tif (dump_m4sys) {\n\t\t\t\t\tif (!esd->OCRESID || (esd->OCRESID == esd->ESID))\n\t\t\t\t\t\tfprintf(stderr, \"Self-synchronized\\n\");\n\t\t\t\t\telse\n\t\t\t\t\t\tfprintf(stderr, \"Synchronized on stream %d\\n\", esd->OCRESID);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"\\tDecoding Buffer size %d - Bitrate: avg %d - max %d kbps\\n\", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate/1000, esd->decoderConfig->maxBitrate/1000);\n\t\t\t\tif (esd->dependsOnESID)\n\t\t\t\t\tfprintf(stderr, \"\\tDepends on stream %d for decoding\\n\", esd->dependsOnESID);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, \"\\tNo stream dependencies for decoding\\n\");\n\n\t\t\t\tfprintf(stderr, \"\\tStreamPriority %d\\n\", esd->streamPriority);\n\t\t\t\tif (esd->URLString) fprintf(stderr, \"\\tRemote Data Source %s\\n\", esd->URLString);\n\t\t\t}\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_AV01) {\n\t\tGF_AV1Config *av1c;\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);\n\n\t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);\n\t\tif (!av1c) {\n\t\t\tfprintf(stderr, \"\\tCorrupted av1 config\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n\t\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n\t\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n\n\t\t\tif (av1c->initial_presentation_delay_present)\n\t\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n\n\t\t\tcount = gf_list_count(av1c->obu_array);\n\t\t\tfor (i=0; iobu_array, i);\n\t\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n\t\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n\t\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t\tgf_odf_av1_cfg_del(av1c);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\t3GPP H263 stream - Resolution %d x %d\\n\", w, h);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MJP2) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tMotionJPEG2000 stream - Resolution %d x %d\\n\", w, h);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_3GP_AMR) || (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB)) {\n\t\tfprintf(stderr, \"\\t3GPP AMR%s stream - Sample Rate %d - %d channel(s) %d bps\\n\", (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB) ? \" Wide Band\" : \"\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_EVRC) {\n\t\tfprintf(stderr, \"\\t3GPP EVRC stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_QCELP) {\n\t\tfprintf(stderr, \"\\t3GPP QCELP stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MP3) {\n\t\tfprintf(stderr, \"\\tMPEG 1/2 Audio stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_AC3) || (msub_type == GF_ISOM_SUBTYPE_EC3)) {\n\t\tu32 br = 0;\n\t\tconst char *lfe = \"\";\n\t\tBool is_ec3 = (msub_type == GF_ISOM_SUBTYPE_EC3) ? GF_TRUE : GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\tGF_AC3Config *ac3 = gf_isom_ac3_config_get(file, trackNum, 1);\n\t\tif (ac3) {\n\t\t\tnb_ch = gf_ac3_get_channels(ac3->streams[0].acmod);\n\t\t\tfor (i=0; istreams[0].nb_dep_sub; ++i) {\n\t\t\t\tassert(ac3->streams[0].nb_dep_sub == 1);\n\t\t\t\tnb_ch += gf_ac3_get_channels(ac3->streams[0].chan_loc);\n\t\t\t}\n\t\t\tif (ac3->streams[0].lfon) lfe = \".1\";\n\t\t\tbr = ac3->is_ec3 ? ac3->brcode : gf_ac3_get_bitrate(ac3->brcode);\n\t\t\tis_ec3 = ac3->is_ec3;\n\t\t\tgf_free(ac3);\n\t\t}\n#endif\n\t\tfprintf(stderr, \"\\t%s stream - Sample Rate %d - %d%s channel(s) - bitrate %d\\n\", is_ec3 ? \"EC-3\" : \"AC-3\", sr, nb_ch, lfe, br);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_SMV) {\n\t\tfprintf(stderr, \"\\t3GPP SMV stream - Sample Rate %d - %d channel(s) %d bits per samples\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_DIMS) {\n\t\tu32 w, h;\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\n\t\tgf_isom_get_dims_description(file, trackNum, 1, &dims);\n\t\tfprintf(stderr, \"\\t3GPP DIMS stream - size %d x %d - Profile %d - Level %d\\n\", w, h, dims.profile, dims.level);\n\t\tfprintf(stderr, \"\\tpathComponents: %d - useFullRequestHost: %s\\n\", dims.pathComponents, dims.fullRequestHost ? \"yes\" : \"no\");\n\t\tfprintf(stderr, \"\\tstream type: %s - redundant: %s\\n\", dims.streamType ? \"primary\" : \"secondary\", (dims.containsRedundant==1) ? \"main\" : ((dims.containsRedundant==2) ? \"redundant\" : \"main+redundant\") );\n\t\tif (dims.textEncoding[0]) fprintf(stderr, \"\\ttext encoding %s\\n\", dims.textEncoding);\n\t\tif (dims.contentEncoding[0]) fprintf(stderr, \"\\tcontent encoding %s\\n\", dims.contentEncoding);\n\t\tif (dims.content_script_types) fprintf(stderr, \"\\tscript languages %s\\n\", dims.content_script_types);\n\t} else if (mtype==GF_ISOM_MEDIA_HINT) {\n\t\tu32 refTrack;\n\t\ts32 refCount = gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_HINT);\n\t\tif (refCount>0) {\n\t\t\tfprintf(stderr, \"Streaming Hint Track for track%s \", (refCount>1) ? \"s\" :\"\");\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tgf_isom_get_reference(file, trackNum, GF_ISOM_REF_HINT, i+1, &refTrack);\n\t\t\t\tif (i) fprintf(stderr, \" - \");\n\t\t\t\tfprintf(stderr, \"ID %d\", gf_isom_get_track_id(file, refTrack));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Streaming Hint Track (no refs)\\n\");\n\t\t}\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\trefCount = gf_isom_get_payt_count(file, trackNum);\n\t\tif (refCount>0) {\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tconst char *name = gf_isom_get_payt_info(file, trackNum, i+1, &refTrack);\n\t\t\t\tfprintf(stderr, \"\\tPayload ID %d: type %s\\n\", refTrack, name);\n\t\t\t}\n\t\t}\n#endif\n\t} else if (mtype==GF_ISOM_MEDIA_FLASH) {\n\t\tfprintf(stderr, \"Macromedia Flash Movie\\n\");\n\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) || (mtype==GF_ISOM_MEDIA_MPEG_SUBT)) {\n\t\tu32 w, h;\n\t\ts16 l;\n\t\ts32 tx, ty;\n\t\tconst char *content_encoding = NULL;\n\t\tconst char *mime = NULL;\n\t\tconst char *config = NULL;\n\t\tconst char *_namespace = NULL;\n\t\tconst char *schema_loc = NULL;\n\t\tconst char *auxiliary_mimes = NULL;\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, &l);\n\t\tif (msub_type == GF_ISOM_SUBTYPE_SBTT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STXT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Simple Timed Text Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STPP) {\n\t\t\tgf_isom_xml_subtitle_get_description(file, trackNum, 1, &_namespace, &schema_loc, &auxiliary_mimes);\n\t\t\tfprintf(stderr, \"XML Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- namespace %s\", _namespace);\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tif (auxiliary_mimes != NULL) {\n\t\t\t\tfprintf(stderr, \" - auxiliary-mime-types %s\", auxiliary_mimes);\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Text Stream\");\n\t\t}\n\t\tfprintf(stderr, \"\\n Size %d x %d - Translation X=%d Y=%d - Layer %d\\n\", w, h, tx, ty, l);\n\t} else if (mtype == GF_ISOM_MEDIA_META) {\n\t\tconst char *content_encoding = NULL;\n\t\tif (msub_type == GF_ISOM_SUBTYPE_METT) {\n\t\t\tconst char *mime = NULL;\n\t\t\tconst char *config = NULL;\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Metadata Stream - mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_METX) {\n\t\t\tconst char *_namespace = NULL;\n\t\t\tconst char *schema_loc = NULL;\n\t\t\tgf_isom_get_xml_metadata_description(file, trackNum, 1, &_namespace, &schema_loc, &content_encoding);\n\t\t\tfprintf(stderr, \"XML Metadata Stream - namespace %s\", _namespace);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Metadata Stream\\n\");\n\t\t}\n\t} else if ((msub_type==GF_ISOM_SUBTYPE_VVC1) || (msub_type==GF_ISOM_SUBTYPE_VVI1)) {\n\t\tGF_VVCConfig *vvccfg;\n\t\tu32 w, h;\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tVVCState *vvc_state;\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (vvc_state) vvc_state->sps_active_idx = -1;\n#endif\n\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\tfprintf(stderr, \"VVC Video - Visual Size %d x %d\\n\", w, h);\n\t\tvvccfg = gf_isom_vvc_config_get(file, trackNum, 1);\n\n\t\tif (!vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Non-compliant VVC track: No vvcC found in sample description\\n\"));\n\t\t} else {\n\t\t\tdump_vvc_track_info(file, trackNum, vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\t\t\t, vvc_state\n#endif\n\t\t\t);\n\t\t\tgf_odf_vvc_cfg_del(vvccfg);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tif (vvc_state) gf_free(vvc_state);\n#endif\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_MH3D_MHA1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHA2)\n\t\t\t|| (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2)\n\t) {\n\t\tconst u8 *compat_profiles;\n\t\tu32 nb_compat_profiles;\n\t\tBool valid = GF_FALSE;\n\t\tBool allow_inband = GF_FALSE;\n\t\tif ( (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2))\n\t\t\tallow_inband = GF_TRUE;\n\n\t\tfprintf(stderr, \"\\tMPEG-H Audio stream - Sample Rate %d\\n\", sr);\n\n\t\tesd = gf_media_map_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig || !esd->decoderConfig->decoderSpecificInfo\n\t\t\t|| !esd->decoderConfig->decoderSpecificInfo->data\n\t\t) {\n\t\t\tif (allow_inband) {\n\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, NULL);\n\t\t\t\tif (samp) {\n\t\t\t\t\tu64 ch_layout=0;\n\t\t\t\t\ts32 PL = gf_mpegh_get_mhas_pl(samp->data, samp->dataLength, &ch_layout);\n\t\t\t\t\tif (PL>=0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X\", PL);\n\t\t\t\t\t\tif (ch_layout)\n\t\t\t\t\t\t\tfprintf(stderr, \" - Reference Channel Layout %s\", gf_audio_fmt_get_layout_name(ch_layout) );\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t}\n\t\t\t\tvalid = GF_TRUE;\n\t\t\t}\n\t\t} else if (esd->decoderConfig->decoderSpecificInfo->dataLength>=5) {\n\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X - Reference Channel Layout %s\\n\", esd->decoderConfig->decoderSpecificInfo->data[1]\n\t\t\t\t, gf_audio_fmt_get_layout_name_from_cicp(esd->decoderConfig->decoderSpecificInfo->data[2])\n\t\t\t);\n\t\t\tvalid = GF_TRUE;\n\t\t}\n\t\tif (!valid) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Invalid MPEG-H audio config\\n\"));\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\tcompat_profiles = gf_isom_get_mpegh_compatible_profiles(file, trackNum, 1, &nb_compat_profiles);\n\t\tfor (i=0; idata, sample->dataLength, tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt, szTimecode);\n\n\t\t\tgf_isom_sample_del(&sample);\n\t\t\tfprintf(stderr, \"\\tFirst timecode: %s\\n\", szTimecode);\n\t\t}\n\t} else {\n\t\tGF_GenericSampleDescription *udesc;\n\n\t\tudesc = gf_isom_get_generic_sample_description(file, trackNum, 1);\n\t\tif (udesc) {\n\t\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n fprintf(stderr, \"%s - Compressor \\\"%s\\\" - Resolution %d x %d\\n\",\n\t\t\t\t\t\t( (mtype == GF_ISOM_MEDIA_VISUAL ? \"Visual\" : \"Auxiliary Video\") ),\n udesc->compressor_name, udesc->width, udesc->height);\n\t\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\t\tfprintf(stderr, \"Audio - Sample Rate %d - %d channel(s)\\n\", udesc->samplerate, udesc->nb_channels);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown media type\\n\");\n\t\t\t}\n\t\t\tif (udesc->vendor_code)\n\t\t\t\tfprintf(stderr, \"\\tVendor code \\\"%s\\\" - Version %d - revision %d\\n\", gf_4cc_to_str(udesc->vendor_code), udesc->version, udesc->revision);\n\n\t\t\tif (udesc->extension_buf) {\n\t\t\t\tfprintf(stderr, \"\\tCodec configuration data size: %d bytes\\n\", udesc->extension_buf_size);\n\t\t\t\tgf_free(udesc->extension_buf);\n\t\t\t}\n\t\t\tgf_free(udesc);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown track type\\n\");\n\t\t}\n\t}\n\n\n\t/*Crypto info*/\n\tif (gf_isom_is_track_encrypted(file, trackNum)) {\n\t\tconst char *scheme_URI, *KMS_URI;\n\t\tu32 scheme_type, version;\n\t\tu32 IV_size;\n\t\tBool use_sel_enc;\n\n\t\tif (gf_isom_is_ismacryp_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_ismacryp_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by ISMA E&A scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tif (scheme_URI) fprintf(stderr, \"scheme location: %s\\n\", scheme_URI);\n\t\t\tif (KMS_URI) {\n\t\t\t\tif (!strnicmp(KMS_URI, \"(key)\", 5)) fprintf(stderr, \"\\tKMS location: key in file\\n\");\n\t\t\t\telse fprintf(stderr, \"\\tKMS location: %s\\n\", KMS_URI);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if (gf_isom_is_omadrm_media(file, trackNum, 1)) {\n\t\t\tconst char *textHdrs;\n\t\t\tu32 enc_type, hdr_len;\n\t\t\tu64 orig_len;\n\t\t\tgf_isom_get_omadrm_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &textHdrs, &hdr_len, &orig_len, &enc_type, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by OMA DRM scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tfprintf(stderr, \"\\tRights Issuer: %s\\n\", KMS_URI);\n\t\t\tfprintf(stderr, \"\\tContent ID: %s\\n\", scheme_URI);\n\t\t\tif (textHdrs) {\n\t\t\t\tu32 offset;\n\t\t\t\tconst char *start = textHdrs;\n\t\t\t\tfprintf(stderr, \"\\tOMA Textual Headers:\\n\");\n\t\t\t\ti=0;\n\t\t\t\toffset=0;\n\t\t\t\twhile (iDTS+samp->CTS_Offset;\n\t\t\tsize += samp->dataLength;\n\t\t\trate += samp->dataLength;\n\t\t\tif (samp->DTS - time_slice > ts) {\n\t\t\t\tDouble max_tmp = rate * ts / (samp->DTS - time_slice);\n\t\t\t\tif (max_rate < max_tmp )\n\t\t\t\t\tmax_rate = max_tmp;\n\n\t\t\t\trate = 0;\n\t\t\t\ttime_slice = samp->DTS;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\nComputed info from media:\\n\");\n\tif (csize && cdur) {\n\t\tfprintf(stderr, \"\\tConstant sample size %d bytes and dur %d / %d\\n\", csize, cdur, ts);\n\t}\n\tscale = 1000.0 / ts;\n\tdur = (u64) (scale * dur);\n\tfprintf(stderr, \"\\tTotal size \"LLU\" bytes - Total samples duration \"LLU\" ms\\n\", size, dur);\n\tif (!dur) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\t/*rate in byte, dur is in ms*/\n\trate = 8000.0 * size / dur;\n\n\tif (!max_rate)\n\t\tmax_rate = rate;\n\telse\n\t\tmax_rate *= 8.0;\n\n\tif (rate >= 1500) {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f kbps - Max Rate %.2f kbps\\n\", rate/1000, max_rate/1000);\n\t} else {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f bps - Max Rate %.2f bps\\n\", rate, max_rate);\n\t}\n\n\t{\n\t\tu32 dmin, dmax, davg, smin, smax, savg;\n\t\tgf_isom_get_chunks_infos(file, trackNum, &dmin, &davg, &dmax, &smin, &savg, &smax);\n\t\tfprintf(stderr, \"\\tChunk durations: min %d ms - max %d ms - average %d ms\\n\", (1000*dmin)/ts, (1000*dmax)/ts, (1000*davg)/ts);\n\t\tfprintf(stderr, \"\\tChunk sizes (bytes): min %d - max %d - average %d\\n\", smin, smax, savg);\n\t}\n\tfprintf(stderr, \"\\n\");\n\n\tcount = gf_isom_get_chapter_count(file, trackNum);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (j=0; jinput(0);\n auto flat_in = input.flat();\n\n int fixed_length;\n const auto& length_input = context->input(1);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(length_input.shape()),\n errors::InvalidArgument(\"k must be scalar, got shape \",\n length_input.shape().DebugString()));\n fixed_length = length_input.scalar()();\n\n OP_REQUIRES(\n context, fixed_length % sizeof(T) == 0,\n errors::InvalidArgument(\n \"fixed_length (\", fixed_length,\n \") must be a multiple of the size of out_type (\", sizeof(T), \")\"));\n\n OP_REQUIRES(context, fixed_length > 0,\n errors::InvalidArgument(\"fixed_length (\", fixed_length,\n \") must be greater than zero.\"));\n\n int width = fixed_length / sizeof(T);\n\n TensorShape out_shape = input.shape();\n out_shape.AddDim(width);\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(\n context, context->allocate_output(\"output\", out_shape, &output_tensor));\n\n if (flat_in.size() == 0) { // Empty input\n return;\n }\n\n auto out = output_tensor->flat_inner_dims();\n T* out_data = out.data();\n\n // Forcibly clear memory - we're going to copy variable length strings in,\n // and need to ensure that if we don't write to byte N when we copy, that\n // we're not getting random data.\n memset(out_data, 0, fixed_length * flat_in.size());\n\n // If the data is already in the host's byte order, or if the width of the\n // output type is a single byte (meaning the ordering doesn't matter), we\n // can copy the memory directly.\n if (!convert_data_endianness_ || sizeof(T) == 1) {\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const T* in_data = reinterpret_cast(flat_in(i).data());\n\n if (flat_in(i).size() > fixed_length) {\n memcpy(out_data, in_data, fixed_length);\n } else {\n memcpy(out_data, in_data, flat_in(i).size());\n }\n out_data += fixed_length;\n }\n } else {\n // Otherwise, the data is not in the host's byte order, and rather than a\n // direct copy, we need to reverse the byte ordering of each element.\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const char* in_data_bytes =\n reinterpret_cast(flat_in(i).data());\n char* out_data_bytes = reinterpret_cast(out_data);\n const char* p_in = in_data_bytes;\n char* p_out = out_data_bytes;\n for (; p_in < in_data_bytes + fixed_length;\n p_in += sizeof(T), p_out += sizeof(T)) {\n std::reverse_copy(p_in, p_in + sizeof(T), p_out);\n }\n out_data += fixed_length;\n }\n }\n }", "func_hash": 106141405546135875852058102116979444186, "file_name": "decode_padded_raw_op.cc", "file_hash": 28575621848378495770499070822414192442, "cwe": ["CWE-787"], "cve": "CVE-2021-29614", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.io.decode_raw` produces incorrect results and crashes the Python interpreter when combining `fixed_length` and wider datatypes. The implementation of the padded version(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc) is buggy due to a confusion about pointer arithmetic rules. First, the code computes(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc#L61) the width of each output element by dividing the `fixed_length` value to the size of the type argument. The `fixed_length` argument is also used to determine the size needed for the output tensor(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc#L63-L79). This is followed by reencoding code(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc#L85-L94). The erroneous code is the last line above: it is moving the `out_data` pointer by `fixed_length * sizeof(T)` bytes whereas it only copied at most `fixed_length` bytes from the input. This results in parts of the input not being decoded into the output. Furthermore, because the pointer advance is far wider than desired, this quickly leads to writing to outside the bounds of the backing data. This OOB write leads to interpreter crash in the reproducer mentioned here, but more severe attacks can be mounted too, given that this gadget allows writing to periodically placed locations in memory. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29614"} {"idx": 243619, "project": "tensorflow", "commit_id": "698e01511f62a3c185754db78ebce0eee1f0184d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/698e01511f62a3c185754db78ebce0eee1f0184d", "commit_message": "Fix `tf.io.decode_raw` bugs and update documentation.\n\nFixes cases where specifying `fixed_length` resulted in data loss and even segfault and corruption of the Python interpreter. The fix is subtle but needed due to pointer arithmetic rules.\n\nMakes sure that `fixed_length` does not change the output when present but not needed.\n\nEliminates needless copy and cast in the main codepath.\n\nPiperOrigin-RevId: 371322725\nChange-Id: I514ef67a2961c86422f69d05122d31615e87896c", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const auto& input = context->input(0);\n auto flat_in = input.flat();\n\n int fixed_length;\n const auto& length_input = context->input(1);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(length_input.shape()),\n errors::InvalidArgument(\"k must be scalar, got shape \",\n length_input.shape().DebugString()));\n fixed_length = length_input.scalar()();\n\n OP_REQUIRES(\n context, fixed_length % sizeof(T) == 0,\n errors::InvalidArgument(\n \"fixed_length (\", fixed_length,\n \") must be a multiple of the size of out_type (\", sizeof(T), \")\"));\n\n OP_REQUIRES(context, fixed_length > 0,\n errors::InvalidArgument(\"fixed_length (\", fixed_length,\n \") must be greater than zero.\"));\n\n int width = fixed_length / sizeof(T);\n\n TensorShape out_shape = input.shape();\n out_shape.AddDim(width);\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(\n context, context->allocate_output(\"output\", out_shape, &output_tensor));\n\n if (flat_in.size() == 0) { // Empty input\n return;\n }\n\n auto out = output_tensor->flat_inner_dims();\n T* out_data = out.data();\n\n // Forcibly clear memory - we're going to copy variable length strings in,\n // and need to ensure that if we don't write to byte N when we copy, that\n // we're not getting random data.\n memset(out_data, 0, fixed_length * flat_in.size());\n\n // If the data is already in the host's byte order, or if the width of the\n // output type is a single byte (meaning the ordering doesn't matter), we\n // can copy the memory directly.\n if (!convert_data_endianness_ || sizeof(T) == 1) {\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const auto to_copy =\n std::min(flat_in(i).size(), static_cast(fixed_length));\n memcpy(out_data, flat_in(i).data(), to_copy);\n // Note: increase out_data by width since it's already of type T* so\n // each shift amount is implicitly multiplied by sizeof(T) according to\n // pointer arithmetic rules.\n out_data += width;\n }\n } else {\n // Otherwise, the data is not in the host's byte order, and rather than a\n // direct copy, we need to reverse the byte ordering of each element.\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const char* in_data_bytes =\n reinterpret_cast(flat_in(i).data());\n char* out_data_bytes = reinterpret_cast(out_data);\n const char* p_in = in_data_bytes;\n char* p_out = out_data_bytes;\n for (; p_in < in_data_bytes + fixed_length;\n p_in += sizeof(T), p_out += sizeof(T)) {\n std::reverse_copy(p_in, p_in + sizeof(T), p_out);\n }\n // Note: increase out_data by width since it's already of type T* so\n // each shift amount is implicitly multiplied by sizeof(T) according to\n // pointer arithmetic rules.\n out_data += width;\n }\n }\n }", "func_hash": 163563866590548182870030561633538238624, "file_name": "decode_padded_raw_op.cc", "file_hash": 45272002305828262568390340151055331988, "cwe": ["CWE-787"], "cve": "CVE-2021-29614", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.io.decode_raw` produces incorrect results and crashes the Python interpreter when combining `fixed_length` and wider datatypes. The implementation of the padded version(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc) is buggy due to a confusion about pointer arithmetic rules. First, the code computes(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc#L61) the width of each output element by dividing the `fixed_length` value to the size of the type argument. The `fixed_length` argument is also used to determine the size needed for the output tensor(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc#L63-L79). This is followed by reencoding code(https://github.com/tensorflow/tensorflow/blob/1d8903e5b167ed0432077a3db6e462daf781d1fe/tensorflow/core/kernels/decode_padded_raw_op.cc#L85-L94). The erroneous code is the last line above: it is moving the `out_data` pointer by `fixed_length * sizeof(T)` bytes whereas it only copied at most `fixed_length` bytes from the input. This results in parts of the input not being decoded into the output. Furthermore, because the pointer advance is far wider than desired, this quickly leads to writing to outside the bounds of the backing data. This OOB write leads to interpreter crash in the reproducer mentioned here, but more severe attacks can be mounted too, given that this gadget allows writing to periodically placed locations in memory. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29614"} {"idx": 196763, "project": "tensorflow", "commit_id": "a776040a5e7ebf76eeb7eb923bf1ae417dd4d233", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a776040a5e7ebf76eeb7eb923bf1ae417dd4d233", "commit_message": "Disallow dims input of 0 in tf.raw_ops.UnravelIndex\n\nPiperOrigin-RevId: 384284198\nChange-Id: Ia1804ef1aec57b4d857ea507e6891bcccde18e9b", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& indices_tensor = ctx->input(0);\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(indices_tensor.shape()) ||\n TensorShapeUtils::IsScalar(indices_tensor.shape()),\n errors::InvalidArgument(\n \"The indices can only be scalar or vector, got \\\"\",\n indices_tensor.shape().DebugString(), \"\\\"\"));\n\n const Tensor& dims_tensor = ctx->input(1);\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(dims_tensor.shape()),\n errors::InvalidArgument(\"The indices can only be 1-D, got \\\"\",\n dims_tensor.shape().DebugString(), \"\\\"\"));\n\n auto dims = dims_tensor.vec();\n\n // Chek to make sure indices is not out of boundary\n Eigen::Tensor dims_prod_eigen = dims.prod();\n Tidx dims_prod = dims_prod_eigen();\n const Tidx* indices = indices_tensor.flat().data();\n int64 size = indices_tensor.NumElements();\n bool check = std::all_of(indices, indices + size,\n [&](Tidx index) { return index < dims_prod; });\n OP_REQUIRES(ctx, check,\n errors::InvalidArgument(\"index is out of bound as with dims\"));\n\n Eigen::array reverse({true});\n\n Tensor strides_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_tensor));\n\n auto strides = strides_tensor.vec();\n strides = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), false)\n .reverse(reverse);\n\n Tensor strides_shifted_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_shifted_tensor));\n\n auto strides_shifted = strides_shifted_tensor.vec();\n strides_shifted = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), true)\n .reverse(reverse);\n\n Tensor* output_tensor = nullptr;\n if (TensorShapeUtils::IsScalar(indices_tensor.shape())) {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({dims_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->vec();\n\n output = output.constant(indices_tensor.scalar()());\n output = output.binaryExpr(strides, mod_op()) / strides_shifted;\n } else {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0,\n TensorShape({dims_tensor.NumElements(),\n indices_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->matrix();\n\n Eigen::array reshape{\n {static_cast(dims_tensor.NumElements()), 1}};\n Eigen::array bcast(\n {1, static_cast(indices_tensor.NumElements())});\n Eigen::array indices_reshape{\n {1, static_cast(indices_tensor.NumElements())}};\n Eigen::array indices_bcast(\n {static_cast(dims_tensor.NumElements()), 1});\n\n output = indices_tensor.vec()\n .reshape(indices_reshape)\n .broadcast(indices_bcast);\n output = output.binaryExpr(strides.reshape(reshape).broadcast(bcast),\n mod_op()) /\n strides_shifted.reshape(reshape).broadcast(bcast);\n }\n }", "func_hash": 286810916287011317427894603208843726687, "file_name": "unravel_index_op.cc", "file_hash": 26403207102970414005546290244973528194, "cwe": ["CWE-369"], "cve": "CVE-2021-37668", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause denial of service in applications serving models using `tf.raw_ops.UnravelIndex` by triggering a division by 0. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/unravel_index_op.cc#L36) does not check that the tensor subsumed by `dims` is not empty. Hence, if one element of `dims` is 0, the implementation does a division by 0. We have patched the issue in GitHub commit a776040a5e7ebf76eeb7eb923bf1ae417dd4d233. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37668"} {"idx": 243980, "project": "tensorflow", "commit_id": "a776040a5e7ebf76eeb7eb923bf1ae417dd4d233", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a776040a5e7ebf76eeb7eb923bf1ae417dd4d233", "commit_message": "Disallow dims input of 0 in tf.raw_ops.UnravelIndex\n\nPiperOrigin-RevId: 384284198\nChange-Id: Ia1804ef1aec57b4d857ea507e6891bcccde18e9b", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& indices_tensor = ctx->input(0);\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(indices_tensor.shape()) ||\n TensorShapeUtils::IsScalar(indices_tensor.shape()),\n errors::InvalidArgument(\n \"The indices can only be scalar or vector, got \\\"\",\n indices_tensor.shape().DebugString(), \"\\\"\"));\n\n const Tensor& dims_tensor = ctx->input(1);\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(dims_tensor.shape()),\n errors::InvalidArgument(\"The indices can only be 1-D, got \\\"\",\n dims_tensor.shape().DebugString(), \"\\\"\"));\n\n auto dims = dims_tensor.vec();\n // Make sure dims does not contain a zero\n for (int i = 0; i < dims.size(); i++) {\n OP_REQUIRES(\n ctx, dims(i) != 0,\n errors::InvalidArgument(\"Input dims cannot contain a dim of zero, \"\n \"but dims contains zero at index \",\n i));\n }\n\n // Chek to make sure indices is not out of boundary\n Eigen::Tensor dims_prod_eigen = dims.prod();\n Tidx dims_prod = dims_prod_eigen();\n const Tidx* indices = indices_tensor.flat().data();\n int64 size = indices_tensor.NumElements();\n bool check = std::all_of(indices, indices + size,\n [&](Tidx index) { return index < dims_prod; });\n OP_REQUIRES(ctx, check,\n errors::InvalidArgument(\"index is out of bound as with dims\"));\n\n Eigen::array reverse({true});\n\n Tensor strides_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_tensor));\n\n auto strides = strides_tensor.vec();\n strides = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), false)\n .reverse(reverse);\n\n Tensor strides_shifted_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_shifted_tensor));\n\n auto strides_shifted = strides_shifted_tensor.vec();\n strides_shifted = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), true)\n .reverse(reverse);\n\n Tensor* output_tensor = nullptr;\n if (TensorShapeUtils::IsScalar(indices_tensor.shape())) {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({dims_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->vec();\n\n output = output.constant(indices_tensor.scalar()());\n output = output.binaryExpr(strides, mod_op()) / strides_shifted;\n } else {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0,\n TensorShape({dims_tensor.NumElements(),\n indices_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->matrix();\n\n Eigen::array reshape{\n {static_cast(dims_tensor.NumElements()), 1}};\n Eigen::array bcast(\n {1, static_cast(indices_tensor.NumElements())});\n Eigen::array indices_reshape{\n {1, static_cast(indices_tensor.NumElements())}};\n Eigen::array indices_bcast(\n {static_cast(dims_tensor.NumElements()), 1});\n\n output = indices_tensor.vec()\n .reshape(indices_reshape)\n .broadcast(indices_bcast);\n output = output.binaryExpr(strides.reshape(reshape).broadcast(bcast),\n mod_op()) /\n strides_shifted.reshape(reshape).broadcast(bcast);\n }\n }", "func_hash": 307861682960923262742021468299095358440, "file_name": "unravel_index_op.cc", "file_hash": 192453314224064324133517301961666343729, "cwe": ["CWE-369"], "cve": "CVE-2021-37668", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause denial of service in applications serving models using `tf.raw_ops.UnravelIndex` by triggering a division by 0. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/unravel_index_op.cc#L36) does not check that the tensor subsumed by `dims` is not empty. Hence, if one element of `dims` is 0, the implementation does a division by 0. We have patched the issue in GitHub commit a776040a5e7ebf76eeb7eb923bf1ae417dd4d233. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37668"} {"idx": 196766, "project": "gpac", "commit_id": "9eeac00b38348c664dfeae2525bba0cf1bc32349", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/9eeac00b38348c664dfeae2525bba0cf1bc32349", "commit_message": "fixed #1565", "target": 1, "func": "static void nhmldump_send_header(GF_NHMLDumpCtx *ctx)\n{\n\tGF_FilterPacket *dst_pck;\n\tchar nhml[1024];\n\tu32 size;\n\tu8 *output;\n\tconst GF_PropertyValue *p;\n\n\tctx->szRootName = \"NHNTStream\";\n\tif (ctx->dims) {\n\t\tctx->szRootName = \"DIMSStream\";\n\t}\n\n\tif (!ctx->filep) {\n\t\tsprintf(nhml, \"\\n\");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\t/*write header*/\n\tsprintf(nhml, \"<%s version=\\\"1.0\\\" \", ctx->szRootName);\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\n\tNHML_PRINT_UINT(GF_PROP_PID_ID, NULL, \"trackID\")\n\tNHML_PRINT_UINT(GF_PROP_PID_TIMESCALE, NULL, \"timeScale\")\n\n\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_IN_IOD);\n\tif (p && p->value.boolean) {\n\t\tsprintf(nhml, \"inRootOD=\\\"yes\\\" \");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tif (ctx->oti && (ctx->otistreamtype, ctx->oti);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32)strlen(nhml));\n\t} else {\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_SUBTYPE);\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"%s=\\\"%s\\\" \", \"mediaType\", gf_4cc_to_str(p->value.uint));\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_ISOM_SUBTYPE, \"mediaSubType\", \"mediaSubType\")\n\t\t} else {\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_CODECID, NULL, \"codecID\")\n\t\t}\n\t}\n\n\tif (ctx->w && ctx->h) {\n\t\t//compatibility with old arch, we might want to remove this\n\t\tswitch (ctx->streamtype) {\n\t\tcase GF_STREAM_VISUAL:\n\t\tcase GF_STREAM_SCENE:\n\t\t\tsprintf(nhml, \"width=\\\"%d\\\" height=\\\"%d\\\" \", ctx->w, ctx->h);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (ctx->sr && ctx->chan) {\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_AUDIO_FORMAT);\n\t\tsprintf(nhml, \"bitsPerSample=\\\"%d\\\" \", gf_audio_fmt_bit_depth(p->value.uint));\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tNHML_PRINT_4CC(0, \"codec_vendor\", \"codecVendor\")\n\tNHML_PRINT_UINT(0, \"codec_version\", \"codecVersion\")\n\tNHML_PRINT_UINT(0, \"codec_revision\", \"codecRevision\")\n\tNHML_PRINT_STRING(0, \"compressor_name\", \"compressorName\")\n\tNHML_PRINT_UINT(0, \"temporal_quality\", \"temporalQuality\")\n\tNHML_PRINT_UINT(0, \"spatial_quality\", \"spatialQuality\")\n\tNHML_PRINT_UINT(0, \"hres\", \"horizontalResolution\")\n\tNHML_PRINT_UINT(0, \"vres\", \"verticalResolution\")\n\tNHML_PRINT_UINT(GF_PROP_PID_BIT_DEPTH_Y, NULL, \"bitDepth\")\n\n\tNHML_PRINT_STRING(0, \"meta:xmlns\", \"xml_namespace\")\n\tNHML_PRINT_STRING(0, \"meta:schemaloc\", \"xml_schema_location\")\n\tNHML_PRINT_STRING(0, \"meta:mime\", \"mime_type\")\n\n\tNHML_PRINT_STRING(0, \"meta:config\", \"config\")\n\tNHML_PRINT_STRING(0, \"meta:aux_mimes\", \"aux_mime_type\")\n\n\tif (ctx->codecid == GF_CODECID_DIMS) {\n\t\tif (gf_filter_pid_get_property_str(ctx->ipid, \"meta:xmlns\")==NULL) {\n\t\t\tsprintf(nhml, \"xmlns=\\\"http://www.3gpp.org/richmedia\\\" \");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\n\t\tNHML_PRINT_UINT(0, \"dims:profile\", \"profile\")\n\t\tNHML_PRINT_UINT(0, \"dims:level\", \"level\")\n\t\tNHML_PRINT_UINT(0, \"dims:pathComponents\", \"pathComponents\")\n\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:fullRequestHost\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"useFullRequestHost=\\\"%s\\\" \", p->value.boolean ? \"yes\" : \"no\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:streamType\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"stream_type=\\\"%s\\\" \", p->value.boolean ? \"primary\" : \"secondary\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:redundant\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"contains_redundant=\\\"%s\\\" \", (p->value.uint==1) ? \"main\" : ((p->value.uint==1) ? \"redundant\" : \"main+redundant\") );\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tNHML_PRINT_UINT(0, \"dims:scriptTypes\", \"scriptTypes\")\n\t}\n\n\t//send DCD\n\tif (ctx->opid_info) {\n\t\tsprintf(nhml, \"specificInfoFile=\\\"%s\\\" \", gf_file_basename(ctx->info_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\tdst_pck = gf_filter_pck_new_shared(ctx->opid_info, ctx->dcfg, ctx->dcfg_size, NULL);\n\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\t\tgf_filter_pck_set_readonly(dst_pck);\n\t\tgf_filter_pck_send(dst_pck);\n\t}\n\n\tNHML_PRINT_STRING(0, \"meta:encoding\", \"encoding\")\n\tNHML_PRINT_STRING(0, \"meta:contentEncoding\", \"content_encoding\")\n\tctx->uncompress = GF_FALSE;\n\tif (p) {\n\t\tif (!strcmp(p->value.string, \"deflate\")) ctx->uncompress = GF_TRUE;\n\t\telse {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[NHMLMx] content_encoding %s not supported\\n\", p->value.string ));\n\t\t}\n\t}\n\n\tif (ctx->opid_mdia) {\n\t\tsprintf(nhml, \"baseMediaFile=\\\"%s\\\" \", gf_file_basename(ctx->media_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\tsprintf(nhml, \">\\n\");\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\tgf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);\n\n\tif (ctx->filep) {\n\t\tgf_fwrite(ctx->nhml_buffer, size, ctx->filep);\n\t\treturn;\n\t}\n\n\tdst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);\n\tmemcpy(output, ctx->nhml_buffer, size);\n\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);\n\tgf_filter_pck_send(dst_pck);\n}", "func_hash": 130167393127480235225719678478908159882, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2020-23930", "cve_desc": "An issue was discovered in gpac through 20200801. A NULL pointer dereference exists in the function nhmldump_send_header located in write_nhml.c. It allows an attacker to cause Denial of Service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-23930"} {"idx": 244385, "project": "gpac", "commit_id": "9eeac00b38348c664dfeae2525bba0cf1bc32349", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/9eeac00b38348c664dfeae2525bba0cf1bc32349", "commit_message": "fixed #1565", "target": 0, "func": "static void nhmldump_send_header(GF_NHMLDumpCtx *ctx)\n{\n\tGF_FilterPacket *dst_pck;\n\tchar nhml[1024];\n\tu32 size;\n\tu8 *output;\n\tconst GF_PropertyValue *p;\n\n\tctx->szRootName = \"NHNTStream\";\n\tif (ctx->dims) {\n\t\tctx->szRootName = \"DIMSStream\";\n\t}\n\n\tif (!ctx->filep) {\n\t\tsprintf(nhml, \"\\n\");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\t/*write header*/\n\tsprintf(nhml, \"<%s version=\\\"1.0\\\" \", ctx->szRootName);\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\n\tNHML_PRINT_UINT(GF_PROP_PID_ID, NULL, \"trackID\")\n\tNHML_PRINT_UINT(GF_PROP_PID_TIMESCALE, NULL, \"timeScale\")\n\n\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_IN_IOD);\n\tif (p && p->value.boolean) {\n\t\tsprintf(nhml, \"inRootOD=\\\"yes\\\" \");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tif (ctx->oti && (ctx->otistreamtype, ctx->oti);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32)strlen(nhml));\n\t} else {\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_SUBTYPE);\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"%s=\\\"%s\\\" \", \"mediaType\", gf_4cc_to_str(p->value.uint));\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_ISOM_SUBTYPE, \"mediaSubType\", \"mediaSubType\")\n\t\t} else {\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_CODECID, NULL, \"codecID\")\n\t\t}\n\t}\n\n\tif (ctx->w && ctx->h) {\n\t\t//compatibility with old arch, we might want to remove this\n\t\tswitch (ctx->streamtype) {\n\t\tcase GF_STREAM_VISUAL:\n\t\tcase GF_STREAM_SCENE:\n\t\t\tsprintf(nhml, \"width=\\\"%d\\\" height=\\\"%d\\\" \", ctx->w, ctx->h);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (ctx->sr && ctx->chan) {\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_AUDIO_FORMAT);\n\t\tif (p)\n\t\t\tsprintf(nhml, \"bitsPerSample=\\\"%d\\\" \", gf_audio_fmt_bit_depth(p->value.uint));\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tNHML_PRINT_4CC(0, \"codec_vendor\", \"codecVendor\")\n\tNHML_PRINT_UINT(0, \"codec_version\", \"codecVersion\")\n\tNHML_PRINT_UINT(0, \"codec_revision\", \"codecRevision\")\n\tNHML_PRINT_STRING(0, \"compressor_name\", \"compressorName\")\n\tNHML_PRINT_UINT(0, \"temporal_quality\", \"temporalQuality\")\n\tNHML_PRINT_UINT(0, \"spatial_quality\", \"spatialQuality\")\n\tNHML_PRINT_UINT(0, \"hres\", \"horizontalResolution\")\n\tNHML_PRINT_UINT(0, \"vres\", \"verticalResolution\")\n\tNHML_PRINT_UINT(GF_PROP_PID_BIT_DEPTH_Y, NULL, \"bitDepth\")\n\n\tNHML_PRINT_STRING(0, \"meta:xmlns\", \"xml_namespace\")\n\tNHML_PRINT_STRING(0, \"meta:schemaloc\", \"xml_schema_location\")\n\tNHML_PRINT_STRING(0, \"meta:mime\", \"mime_type\")\n\n\tNHML_PRINT_STRING(0, \"meta:config\", \"config\")\n\tNHML_PRINT_STRING(0, \"meta:aux_mimes\", \"aux_mime_type\")\n\n\tif (ctx->codecid == GF_CODECID_DIMS) {\n\t\tif (gf_filter_pid_get_property_str(ctx->ipid, \"meta:xmlns\")==NULL) {\n\t\t\tsprintf(nhml, \"xmlns=\\\"http://www.3gpp.org/richmedia\\\" \");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\n\t\tNHML_PRINT_UINT(0, \"dims:profile\", \"profile\")\n\t\tNHML_PRINT_UINT(0, \"dims:level\", \"level\")\n\t\tNHML_PRINT_UINT(0, \"dims:pathComponents\", \"pathComponents\")\n\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:fullRequestHost\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"useFullRequestHost=\\\"%s\\\" \", p->value.boolean ? \"yes\" : \"no\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:streamType\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"stream_type=\\\"%s\\\" \", p->value.boolean ? \"primary\" : \"secondary\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:redundant\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"contains_redundant=\\\"%s\\\" \", (p->value.uint==1) ? \"main\" : ((p->value.uint==1) ? \"redundant\" : \"main+redundant\") );\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tNHML_PRINT_UINT(0, \"dims:scriptTypes\", \"scriptTypes\")\n\t}\n\n\t//send DCD\n\tif (ctx->opid_info) {\n\t\tsprintf(nhml, \"specificInfoFile=\\\"%s\\\" \", gf_file_basename(ctx->info_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\tdst_pck = gf_filter_pck_new_shared(ctx->opid_info, ctx->dcfg, ctx->dcfg_size, NULL);\n\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\t\tgf_filter_pck_set_readonly(dst_pck);\n\t\tgf_filter_pck_send(dst_pck);\n\t}\n\n\tNHML_PRINT_STRING(0, \"meta:encoding\", \"encoding\")\n\tNHML_PRINT_STRING(0, \"meta:contentEncoding\", \"content_encoding\")\n\tctx->uncompress = GF_FALSE;\n\tif (p) {\n\t\tif (!strcmp(p->value.string, \"deflate\")) ctx->uncompress = GF_TRUE;\n\t\telse {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[NHMLMx] content_encoding %s not supported\\n\", p->value.string ));\n\t\t}\n\t}\n\n\tif (ctx->opid_mdia) {\n\t\tsprintf(nhml, \"baseMediaFile=\\\"%s\\\" \", gf_file_basename(ctx->media_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\tsprintf(nhml, \">\\n\");\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\tgf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);\n\n\tif (ctx->filep) {\n\t\tgf_fwrite(ctx->nhml_buffer, size, ctx->filep);\n\t\treturn;\n\t}\n\n\tdst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);\n\tmemcpy(output, ctx->nhml_buffer, size);\n\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);\n\tgf_filter_pck_send(dst_pck);\n}", "func_hash": 1121305354660317879727415090650741456, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2020-23930", "cve_desc": "An issue was discovered in gpac through 20200801. A NULL pointer dereference exists in the function nhmldump_send_header located in write_nhml.c. It allows an attacker to cause Denial of Service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-23930"} {"idx": 196768, "project": "FFmpeg", "commit_id": "27a99e2c7d450fef15594671eef4465c8a166bd7", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/27a99e2c7d450fef15594671eef4465c8a166bd7", "commit_message": "avformat/vividas: improve extradata packing checks in track_header()\n\nFixes: out of array accesses\nFixes: 26622/clusterfuzz-testcase-minimized-ffmpeg_dem_VIVIDAS_fuzzer-6581200338288640\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer ", "target": 1, "func": "static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)\n{\n int i, j, ret;\n int64_t off;\n int val_1;\n int num_video;\n AVIOContext pb0, *pb = &pb0;\n\n ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);\n\n ffio_read_varlen(pb); // track_header_len\n avio_r8(pb); // '1'\n\n val_1 = ffio_read_varlen(pb);\n\n for (i=0;iid = i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;\n st->codecpar->codec_id = AV_CODEC_ID_VP6;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb);\n avio_r8(pb); // '3'\n avio_r8(pb); // val_7\n num = avio_rl32(pb); // frame_time\n den = avio_rl32(pb); // time_base\n avpriv_set_pts_info(st, 64, num, den);\n st->nb_frames = avio_rl32(pb); // n frames\n st->codecpar->width = avio_rl16(pb); // width\n st->codecpar->height = avio_rl16(pb); // height\n avio_r8(pb); // val_8\n avio_rl32(pb); // val_9\n\n avio_seek(pb, off, SEEK_SET);\n }\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_10\n avio_r8(pb); // '4'\n viv->num_audio = avio_r8(pb);\n avio_seek(pb, off, SEEK_SET);\n\n if (viv->num_audio != 1)\n av_log(s, AV_LOG_WARNING, \"number of audio tracks %d is not 1\\n\", viv->num_audio);\n\n for(i=0;inum_audio;i++) {\n int q;\n AVStream *st = avformat_new_stream(s, NULL);\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = num_video + i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codecpar->codec_id = AV_CODEC_ID_VORBIS;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // length\n avio_r8(pb); // '5'\n avio_r8(pb); //codec_id\n avio_rl16(pb); //codec_subid\n st->codecpar->channels = avio_rl16(pb); // channels\n st->codecpar->sample_rate = avio_rl32(pb); // sample_rate\n avio_seek(pb, 10, SEEK_CUR); // data_1\n q = avio_r8(pb);\n avio_seek(pb, q, SEEK_CUR); // data_2\n avio_r8(pb); // zeropad\n\n if (avio_tell(pb) < off) {\n int num_data;\n int xd_size = 0;\n int data_len[256];\n int offset = 1;\n uint8_t *p;\n ffio_read_varlen(pb); // val_13\n avio_r8(pb); // '19'\n ffio_read_varlen(pb); // len_3\n num_data = avio_r8(pb);\n for (j = 0; j < num_data; j++) {\n uint64_t len = ffio_read_varlen(pb);\n if (len > INT_MAX/2 - xd_size) {\n return AVERROR_INVALIDDATA;\n }\n data_len[j] = len;\n xd_size += len;\n }\n\n ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255);\n if (ret < 0)\n return ret;\n\n p = st->codecpar->extradata;\n p[0] = 2;\n\n for (j = 0; j < num_data - 1; j++) {\n unsigned delta = av_xiphlacing(&p[offset], data_len[j]);\n if (delta > data_len[j]) {\n return AVERROR_INVALIDDATA;\n }\n offset += delta;\n }\n\n for (j = 0; j < num_data; j++) {\n int ret = avio_read(pb, &p[offset], data_len[j]);\n if (ret < data_len[j]) {\n st->codecpar->extradata_size = 0;\n av_freep(&st->codecpar->extradata);\n break;\n }\n offset += data_len[j];\n }\n\n if (offset < st->codecpar->extradata_size)\n st->codecpar->extradata_size = offset;\n }\n }\n\n return 0;\n}", "func_hash": 13089550855747948958069008742414388411, "file_name": "vividas.c", "file_hash": 271219049985990970138755852619852430360, "cwe": ["CWE-787"], "cve": "CVE-2020-35964", "cve_desc": "track_header in libavformat/vividas.c in FFmpeg 4.3.1 has an out-of-bounds write because of incorrect extradata packing.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35964"} {"idx": 244426, "project": "FFmpeg", "commit_id": "27a99e2c7d450fef15594671eef4465c8a166bd7", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/27a99e2c7d450fef15594671eef4465c8a166bd7", "commit_message": "avformat/vividas: improve extradata packing checks in track_header()\n\nFixes: out of array accesses\nFixes: 26622/clusterfuzz-testcase-minimized-ffmpeg_dem_VIVIDAS_fuzzer-6581200338288640\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer ", "target": 0, "func": "static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)\n{\n int i, j, ret;\n int64_t off;\n int val_1;\n int num_video;\n AVIOContext pb0, *pb = &pb0;\n\n ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);\n\n ffio_read_varlen(pb); // track_header_len\n avio_r8(pb); // '1'\n\n val_1 = ffio_read_varlen(pb);\n\n for (i=0;iid = i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;\n st->codecpar->codec_id = AV_CODEC_ID_VP6;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb);\n avio_r8(pb); // '3'\n avio_r8(pb); // val_7\n num = avio_rl32(pb); // frame_time\n den = avio_rl32(pb); // time_base\n avpriv_set_pts_info(st, 64, num, den);\n st->nb_frames = avio_rl32(pb); // n frames\n st->codecpar->width = avio_rl16(pb); // width\n st->codecpar->height = avio_rl16(pb); // height\n avio_r8(pb); // val_8\n avio_rl32(pb); // val_9\n\n avio_seek(pb, off, SEEK_SET);\n }\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_10\n avio_r8(pb); // '4'\n viv->num_audio = avio_r8(pb);\n avio_seek(pb, off, SEEK_SET);\n\n if (viv->num_audio != 1)\n av_log(s, AV_LOG_WARNING, \"number of audio tracks %d is not 1\\n\", viv->num_audio);\n\n for(i=0;inum_audio;i++) {\n int q;\n AVStream *st = avformat_new_stream(s, NULL);\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = num_video + i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codecpar->codec_id = AV_CODEC_ID_VORBIS;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // length\n avio_r8(pb); // '5'\n avio_r8(pb); //codec_id\n avio_rl16(pb); //codec_subid\n st->codecpar->channels = avio_rl16(pb); // channels\n st->codecpar->sample_rate = avio_rl32(pb); // sample_rate\n avio_seek(pb, 10, SEEK_CUR); // data_1\n q = avio_r8(pb);\n avio_seek(pb, q, SEEK_CUR); // data_2\n avio_r8(pb); // zeropad\n\n if (avio_tell(pb) < off) {\n int num_data;\n int xd_size = 1;\n int data_len[256];\n int offset = 1;\n uint8_t *p;\n ffio_read_varlen(pb); // val_13\n avio_r8(pb); // '19'\n ffio_read_varlen(pb); // len_3\n num_data = avio_r8(pb);\n for (j = 0; j < num_data; j++) {\n uint64_t len = ffio_read_varlen(pb);\n if (len > INT_MAX/2 - xd_size) {\n return AVERROR_INVALIDDATA;\n }\n data_len[j] = len;\n xd_size += len + 1 + len/255;\n }\n\n ret = ff_alloc_extradata(st->codecpar, xd_size);\n if (ret < 0)\n return ret;\n\n p = st->codecpar->extradata;\n p[0] = 2;\n\n for (j = 0; j < num_data - 1; j++) {\n unsigned delta = av_xiphlacing(&p[offset], data_len[j]);\n av_assert0(delta <= xd_size - offset);\n offset += delta;\n }\n\n for (j = 0; j < num_data; j++) {\n int ret = avio_read(pb, &p[offset], data_len[j]);\n if (ret < data_len[j]) {\n st->codecpar->extradata_size = 0;\n av_freep(&st->codecpar->extradata);\n break;\n }\n av_assert0(data_len[j] <= xd_size - offset);\n offset += data_len[j];\n }\n\n if (offset < st->codecpar->extradata_size)\n st->codecpar->extradata_size = offset;\n }\n }\n\n return 0;\n}", "func_hash": 258461746950756836518921556510166851106, "file_name": "vividas.c", "file_hash": 2304210843304193605837003346913531628, "cwe": ["CWE-787"], "cve": "CVE-2020-35964", "cve_desc": "track_header in libavformat/vividas.c in FFmpeg 4.3.1 has an out-of-bounds write because of incorrect extradata packing.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35964"} {"idx": 196781, "project": "libarchive", "commit_id": "94821008d6eea81e315c5881cdf739202961040a", "project_url": "https://github.com/libarchive/libarchive", "commit_url": "https://github.com/libarchive/libarchive/commit/94821008d6eea81e315c5881cdf739202961040a", "commit_message": "RAR5 reader: reject files that declare invalid header flags\n\nOne of the fields in RAR5's base block structure is the size of the\nheader. Some invalid files declare a 0 header size setting, which can\nconfuse the unpacker. Minimum header size for RAR5 base blocks is 7\nbytes (4 bytes for CRC, and 3 bytes for the rest), so block size of 0\nbytes should be rejected at header parsing stage.\n\nThe fix adds an error condition if header size of 0 bytes is detected.\nIn this case, the unpacker will not attempt to unpack the file, as the\nheader is corrupted.\n\nThe commit also adds OSSFuzz #20459 sample to test further regressions\nin this area.", "target": 1, "func": "static int process_base_block(struct archive_read* a,\n struct archive_entry* entry)\n{\n\tstruct rar5* rar = get_context(a);\n\tuint32_t hdr_crc, computed_crc;\n\tsize_t raw_hdr_size = 0, hdr_size_len, hdr_size;\n\tsize_t header_id = 0;\n\tsize_t header_flags = 0;\n\tconst uint8_t* p;\n\tint ret;\n\n\tenum HEADER_TYPE {\n\t\tHEAD_MARK = 0x00, HEAD_MAIN = 0x01, HEAD_FILE = 0x02,\n\t\tHEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05,\n\t\tHEAD_UNKNOWN = 0xff,\n\t};\n\n\t/* Skip any unprocessed data for this file. */\n\tret = skip_unprocessed_bytes(a);\n\tif(ret != ARCHIVE_OK)\n\t\treturn ret;\n\n\t/* Read the expected CRC32 checksum. */\n\tif(!read_u32(a, &hdr_crc)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Read header size. */\n\tif(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Sanity check, maximum header size for RAR5 is 2MB. */\n\tif(raw_hdr_size > (2 * 1024 * 1024)) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Base block header is too large\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\thdr_size = raw_hdr_size + hdr_size_len;\n\n\t/* Read the whole header data into memory, maximum memory use here is\n\t * 2MB. */\n\tif(!read_ahead(a, hdr_size, &p)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Verify the CRC32 of the header data. */\n\tcomputed_crc = (uint32_t) crc32(0, p, (int) hdr_size);\n\tif(computed_crc != hdr_crc) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Header CRC error\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* If the checksum is OK, we proceed with parsing. */\n\tif(ARCHIVE_OK != consume(a, hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\tif(!read_var_sized(a, &header_id, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\tif(!read_var_sized(a, &header_flags, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\trar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0;\n\trar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0;\n\trar->generic.size = (int)hdr_size;\n\trar->generic.last_header_id = (int)header_id;\n\trar->main.endarc = 0;\n\n\t/* Those are possible header ids in RARv5. */\n\tswitch(header_id) {\n\t\tcase HEAD_MAIN:\n\t\t\tret = process_head_main(a, rar, entry, header_flags);\n\n\t\t\t/* Main header doesn't have any files in it, so it's\n\t\t\t * pointless to return to the caller. Retry to next\n\t\t\t * header, which should be HEAD_FILE/HEAD_SERVICE. */\n\t\t\tif(ret == ARCHIVE_OK)\n\t\t\t\treturn ARCHIVE_RETRY;\n\n\t\t\treturn ret;\n\t\tcase HEAD_SERVICE:\n\t\t\tret = process_head_service(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_FILE:\n\t\t\tret = process_head_file(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_CRYPT:\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Encryption is not supported\");\n\t\t\treturn ARCHIVE_FATAL;\n\t\tcase HEAD_ENDARC:\n\t\t\trar->main.endarc = 1;\n\n\t\t\t/* After encountering an end of file marker, we need\n\t\t\t * to take into consideration if this archive is\n\t\t\t * continued in another file (i.e. is it part01.rar:\n\t\t\t * is there a part02.rar?) */\n\t\t\tif(rar->main.volume) {\n\t\t\t\t/* In case there is part02.rar, position the\n\t\t\t\t * read pointer in a proper place, so we can\n\t\t\t\t * resume parsing. */\n\t\t\t\tret = scan_for_signature(a);\n\t\t\t\tif(ret == ARCHIVE_FATAL) {\n\t\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t\t} else {\n\t\t\t\t\tif(rar->vol.expected_vol_no ==\n\t\t\t\t\t UINT_MAX) {\n\t\t\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t\t\t \"Header error\");\n\t\t\t\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t\t\t}\n\n\t\t\t\t\trar->vol.expected_vol_no =\n\t\t\t\t\t rar->main.vol_no + 1;\n\t\t\t\t\treturn ARCHIVE_OK;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t}\n\t\tcase HEAD_MARK:\n\t\t\treturn ARCHIVE_EOF;\n\t\tdefault:\n\t\t\tif((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) {\n\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t \"Header type error\");\n\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t} else {\n\t\t\t\t/* If the block is marked as 'skip if unknown',\n\t\t\t\t * do as the flag says: skip the block\n\t\t\t\t * instead on failing on it. */\n\t\t\t\treturn ARCHIVE_RETRY;\n\t\t\t}\n\t}\n\n#if !defined WIN32\n\t// Not reached.\n\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,\n\t \"Internal unpacker error\");\n\treturn ARCHIVE_FATAL;\n#endif\n}", "func_hash": 170965058768559263696808482962086889195, "file_name": "archive_read_support_format_rar5.c", "file_hash": 125096314190646392463565840071483677777, "cwe": ["CWE-125"], "cve": "CVE-2020-9308", "cve_desc": "archive_read_support_format_rar5.c in libarchive before 3.4.2 attempts to unpack a RAR5 file with an invalid or corrupted header (such as a header size of zero), leading to a SIGSEGV or possibly unspecified other impact.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-9308"} {"idx": 244730, "project": "libarchive", "commit_id": "94821008d6eea81e315c5881cdf739202961040a", "project_url": "https://github.com/libarchive/libarchive", "commit_url": "https://github.com/libarchive/libarchive/commit/94821008d6eea81e315c5881cdf739202961040a", "commit_message": "RAR5 reader: reject files that declare invalid header flags\n\nOne of the fields in RAR5's base block structure is the size of the\nheader. Some invalid files declare a 0 header size setting, which can\nconfuse the unpacker. Minimum header size for RAR5 base blocks is 7\nbytes (4 bytes for CRC, and 3 bytes for the rest), so block size of 0\nbytes should be rejected at header parsing stage.\n\nThe fix adds an error condition if header size of 0 bytes is detected.\nIn this case, the unpacker will not attempt to unpack the file, as the\nheader is corrupted.\n\nThe commit also adds OSSFuzz #20459 sample to test further regressions\nin this area.", "target": 0, "func": "static int process_base_block(struct archive_read* a,\n struct archive_entry* entry)\n{\n\tconst size_t SMALLEST_RAR5_BLOCK_SIZE = 3;\n\n\tstruct rar5* rar = get_context(a);\n\tuint32_t hdr_crc, computed_crc;\n\tsize_t raw_hdr_size = 0, hdr_size_len, hdr_size;\n\tsize_t header_id = 0;\n\tsize_t header_flags = 0;\n\tconst uint8_t* p;\n\tint ret;\n\n\tenum HEADER_TYPE {\n\t\tHEAD_MARK = 0x00, HEAD_MAIN = 0x01, HEAD_FILE = 0x02,\n\t\tHEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05,\n\t\tHEAD_UNKNOWN = 0xff,\n\t};\n\n\t/* Skip any unprocessed data for this file. */\n\tret = skip_unprocessed_bytes(a);\n\tif(ret != ARCHIVE_OK)\n\t\treturn ret;\n\n\t/* Read the expected CRC32 checksum. */\n\tif(!read_u32(a, &hdr_crc)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Read header size. */\n\tif(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\thdr_size = raw_hdr_size + hdr_size_len;\n\n\t/* Sanity check, maximum header size for RAR5 is 2MB. */\n\tif(hdr_size > (2 * 1024 * 1024)) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Base block header is too large\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* Additional sanity checks to weed out invalid files. */\n\tif(raw_hdr_size == 0 || hdr_size_len == 0 ||\n\t\thdr_size < SMALLEST_RAR5_BLOCK_SIZE)\n\t{\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Too small block encountered (%ld bytes)\",\n\t\t raw_hdr_size);\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* Read the whole header data into memory, maximum memory use here is\n\t * 2MB. */\n\tif(!read_ahead(a, hdr_size, &p)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Verify the CRC32 of the header data. */\n\tcomputed_crc = (uint32_t) crc32(0, p, (int) hdr_size);\n\tif(computed_crc != hdr_crc) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Header CRC error\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* If the checksum is OK, we proceed with parsing. */\n\tif(ARCHIVE_OK != consume(a, hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\tif(!read_var_sized(a, &header_id, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\tif(!read_var_sized(a, &header_flags, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\trar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0;\n\trar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0;\n\trar->generic.size = (int)hdr_size;\n\trar->generic.last_header_id = (int)header_id;\n\trar->main.endarc = 0;\n\n\t/* Those are possible header ids in RARv5. */\n\tswitch(header_id) {\n\t\tcase HEAD_MAIN:\n\t\t\tret = process_head_main(a, rar, entry, header_flags);\n\n\t\t\t/* Main header doesn't have any files in it, so it's\n\t\t\t * pointless to return to the caller. Retry to next\n\t\t\t * header, which should be HEAD_FILE/HEAD_SERVICE. */\n\t\t\tif(ret == ARCHIVE_OK)\n\t\t\t\treturn ARCHIVE_RETRY;\n\n\t\t\treturn ret;\n\t\tcase HEAD_SERVICE:\n\t\t\tret = process_head_service(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_FILE:\n\t\t\tret = process_head_file(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_CRYPT:\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Encryption is not supported\");\n\t\t\treturn ARCHIVE_FATAL;\n\t\tcase HEAD_ENDARC:\n\t\t\trar->main.endarc = 1;\n\n\t\t\t/* After encountering an end of file marker, we need\n\t\t\t * to take into consideration if this archive is\n\t\t\t * continued in another file (i.e. is it part01.rar:\n\t\t\t * is there a part02.rar?) */\n\t\t\tif(rar->main.volume) {\n\t\t\t\t/* In case there is part02.rar, position the\n\t\t\t\t * read pointer in a proper place, so we can\n\t\t\t\t * resume parsing. */\n\t\t\t\tret = scan_for_signature(a);\n\t\t\t\tif(ret == ARCHIVE_FATAL) {\n\t\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t\t} else {\n\t\t\t\t\tif(rar->vol.expected_vol_no ==\n\t\t\t\t\t UINT_MAX) {\n\t\t\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t\t\t \"Header error\");\n\t\t\t\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t\t\t}\n\n\t\t\t\t\trar->vol.expected_vol_no =\n\t\t\t\t\t rar->main.vol_no + 1;\n\t\t\t\t\treturn ARCHIVE_OK;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t}\n\t\tcase HEAD_MARK:\n\t\t\treturn ARCHIVE_EOF;\n\t\tdefault:\n\t\t\tif((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) {\n\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t \"Header type error\");\n\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t} else {\n\t\t\t\t/* If the block is marked as 'skip if unknown',\n\t\t\t\t * do as the flag says: skip the block\n\t\t\t\t * instead on failing on it. */\n\t\t\t\treturn ARCHIVE_RETRY;\n\t\t\t}\n\t}\n\n#if !defined WIN32\n\t// Not reached.\n\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,\n\t \"Internal unpacker error\");\n\treturn ARCHIVE_FATAL;\n#endif\n}", "func_hash": 270620491810022152943726456949127253043, "file_name": "archive_read_support_format_rar5.c", "file_hash": 277736351383611009741469139170719534686, "cwe": ["CWE-125"], "cve": "CVE-2020-9308", "cve_desc": "archive_read_support_format_rar5.c in libarchive before 3.4.2 attempts to unpack a RAR5 file with an invalid or corrupted header (such as a header size of zero), leading to a SIGSEGV or possibly unspecified other impact.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-9308"} {"idx": 196791, "project": "tensorflow", "commit_id": "51300ba1cc2f487aefec6e6631fef03b0e08b298", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/51300ba1cc2f487aefec6e6631fef03b0e08b298", "commit_message": "Fix heap buffer overflow in tf.raw_ops.UnicodeEncode.\n\nPiperOrigin-RevId: 371717714\nChange-Id: If33443b28f158e58078f1268f6b92f2728d219e0", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n for (; idx < input_splits_flat(i); ++idx) {\n int32 code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "func_hash": 70733896575970437223303124140006322233, "file_name": "unicode_ops.cc", "file_hash": 119507898118607127058444848746811856552, "cwe": ["CWE-787"], "cve": "CVE-2021-29559", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can access data outside of bounds of heap allocated array in `tf.raw_ops.UnicodeEncode`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/472c1f12ad9063405737679d4f6bd43094e1d36d/tensorflow/core/kernels/unicode_ops.cc) assumes that the `input_value`/`input_splits` pair specify a valid sparse tensor. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29559"} {"idx": 245150, "project": "tensorflow", "commit_id": "51300ba1cc2f487aefec6e6631fef03b0e08b298", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/51300ba1cc2f487aefec6e6631fef03b0e08b298", "commit_message": "Fix heap buffer overflow in tf.raw_ops.UnicodeEncode.\n\nPiperOrigin-RevId: 371717714\nChange-Id: If33443b28f158e58078f1268f6b92f2728d219e0", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n // Operation will treat first argument in input_splits as if it were zero\n // regardless of its actual value since splits should begin with zero and\n // end with the length of the input values vector.\n OP_REQUIRES(\n context, input_splits_flat(0) == 0,\n errors::InvalidArgument(\"First value in input_splits must be zero.\"));\n OP_REQUIRES(context,\n input_splits_flat(input_splits_flat.size() - 1) ==\n input_tensor_flat.size(),\n errors::InvalidArgument(\"Last value in input_splits must be \"\n \"equal to length of input_tensor.\"));\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n OP_REQUIRES(\n context, input_splits_flat(i - 1) <= input_splits_flat(i),\n errors::InvalidArgument(\n \"Values in input_splits must be equal or in ascending order.\"));\n OP_REQUIRES(\n context, input_splits_flat(i) <= input_tensor_flat.size(),\n errors::InvalidArgument(\"Values in input_splits must be less than or \"\n \"equal to input_tensor length.\"));\n for (; idx < input_splits_flat(i); ++idx) {\n int32 code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "func_hash": 287502470916754845370174358931939555514, "file_name": "unicode_ops.cc", "file_hash": 60241217623082627679817861175132907210, "cwe": ["CWE-787"], "cve": "CVE-2021-29559", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can access data outside of bounds of heap allocated array in `tf.raw_ops.UnicodeEncode`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/472c1f12ad9063405737679d4f6bd43094e1d36d/tensorflow/core/kernels/unicode_ops.cc) assumes that the `input_value`/`input_splits` pair specify a valid sparse tensor. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29559"} {"idx": 196800, "project": "tensorflow", "commit_id": "eccb7ec454e6617738554a255d77f08e60ee0808", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/eccb7ec454e6617738554a255d77f08e60ee0808", "commit_message": "Prevent segfault in `quantize_and_dequantize`\n\nFixes #42105.\n\nIf `tf.quantization.quantize_and_dequantize` is called with `axis` argument pointing to outside of the input tensor, we obtain a `CHECK` fail which then aborts the application/interpreter. This change adds a condition check and returns a `Status` instead of crashing.\n\nPiperOrigin-RevId: 337972243\nChange-Id: I71ec32c00a87266e364fb017f0ad5dfd3e23542f", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor input_min_tensor;\n Tensor input_max_tensor;\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar()();\n auto max_val = input_max_tensor.scalar()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_max_tensor));\n }\n\n if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor f;\n f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_,\n range_given_, &input_min_tensor, &input_max_tensor, round_mode_,\n narrow_range_, output->flat());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor f;\n f(ctx->eigen_device(),\n input.template flat_inner_outer_dims(axis_ - 1), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n round_mode_, narrow_range_,\n output->template flat_inner_outer_dims(axis_ - 1));\n }\n }", "func_hash": 226689436565985202010086695734816430296, "file_name": "quantize_and_dequantize_op.cc", "file_hash": 93708131576607265641213388793921465091, "cwe": ["CWE-787"], "cve": "CVE-2020-15265", "cve_desc": "In Tensorflow before version 2.4.0, an attacker can pass an invalid `axis` value to `tf.quantization.quantize_and_dequantize`. This results in accessing a dimension outside the rank of the input tensor in the C++ kernel implementation. However, dim_size only does a DCHECK to validate the argument and then uses it to access the corresponding element of an array. Since in normal builds, `DCHECK`-like macros are no-ops, this results in segfault and access out of bounds of the array. The issue is patched in eccb7ec454e6617738554a255d77f08e60ee0808 and TensorFlow 2.4.0 will be released containing the patch. TensorFlow nightly packages after this commit will also have the issue resolved.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15265"} {"idx": 245427, "project": "tensorflow", "commit_id": "eccb7ec454e6617738554a255d77f08e60ee0808", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/eccb7ec454e6617738554a255d77f08e60ee0808", "commit_message": "Prevent segfault in `quantize_and_dequantize`\n\nFixes #42105.\n\nIf `tf.quantization.quantize_and_dequantize` is called with `axis` argument pointing to outside of the input tensor, we obtain a `CHECK` fail which then aborts the application/interpreter. This change adds a condition check and returns a `Status` instead of crashing.\n\nPiperOrigin-RevId: 337972243\nChange-Id: I71ec32c00a87266e364fb017f0ad5dfd3e23542f", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n\n // One global scale.\n Tensor input_min_tensor(DataTypeToEnum::value, TensorShape());\n Tensor input_max_tensor(DataTypeToEnum::value, TensorShape());\n // Initialize the tensors with the values in the Attrs.\n input_min_tensor.template scalar()() = static_cast(input_min_);\n input_max_tensor.template scalar()() = static_cast(input_max_);\n\n functor::QuantizeAndDequantizeOneScaleFunctor functor;\n functor(ctx->eigen_device(), input.flat(), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, /*narrow_range=*/false, output->flat());\n }", "func_hash": 287515842787274296316492689513504718353, "file_name": "quantize_and_dequantize_op.cc", "file_hash": 149077864405379849027595796830913818555, "cwe": ["CWE-787"], "cve": "CVE-2020-15265", "cve_desc": "In Tensorflow before version 2.4.0, an attacker can pass an invalid `axis` value to `tf.quantization.quantize_and_dequantize`. This results in accessing a dimension outside the rank of the input tensor in the C++ kernel implementation. However, dim_size only does a DCHECK to validate the argument and then uses it to access the corresponding element of an array. Since in normal builds, `DCHECK`-like macros are no-ops, this results in segfault and access out of bounds of the array. The issue is patched in eccb7ec454e6617738554a255d77f08e60ee0808 and TensorFlow 2.4.0 will be released containing the patch. TensorFlow nightly packages after this commit will also have the issue resolved.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15265"} {"idx": 196802, "project": "tensorflow", "commit_id": "dcd7867de0fea4b72a2b34bd41eb74548dc23886", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/dcd7867de0fea4b72a2b34bd41eb74548dc23886", "commit_message": "Fix heap buffer overflow\n\nPiperOrigin-RevId: 372132844\nChange-Id: Idef9895efaf145f2b1c23d31983601ec980cd5e4", "target": 1, "func": " static void launch(OpKernelContext* context, const PoolParameters& params,\n const Tensor& grad_in, const Tensor& argmax,\n Tensor* grad_out, const bool include_batch_in_index) {\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n auto shard = [&grad_in, &argmax, &grad_out, include_batch_in_index](\n int64 start, int64 limit) {\n const int64 batch_size =\n GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 output_size_per_batch = grad_out->NumElements() / batch_size;\n const int64 input_size_per_batch = grad_in.NumElements() / batch_size;\n\n {\n auto grad_out_flat = grad_out->flat();\n auto argmax_flat = argmax.flat();\n auto grad_in_flat = grad_in.flat();\n\n const int64 output_start = start * output_size_per_batch;\n const int64 output_end = limit * output_size_per_batch;\n EigenMatrixMap inputShard(grad_out_flat.data() + output_start, 1,\n output_end - output_start);\n inputShard.setConstant(T(0));\n\n const int input_start = start * input_size_per_batch;\n const int input_end = limit * input_size_per_batch;\n for (int64 index = input_start; index < input_end; index++) {\n int64 grad_out_index = argmax_flat(index);\n if (!include_batch_in_index) {\n const int64 cur_batch = index / input_size_per_batch;\n grad_out_index += cur_batch * output_size_per_batch;\n }\n CHECK(grad_out_index >= output_start && grad_out_index < output_end)\n << \"Invalid output gradient index: \" << grad_out_index << \", \"\n << output_start << \", \" << output_end;\n grad_out_flat(grad_out_index) += grad_in_flat(index);\n }\n }\n };\n\n const int64 batch_size = GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 shard_cost = grad_out->NumElements() / batch_size;\n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n shard_cost, shard);\n }", "func_hash": 207971431401479628289292154496151586515, "file_name": "maxpooling_op.cc", "file_hash": 118822301031976306218889895119996613635, "cwe": ["CWE-125"], "cve": "CVE-2021-29570", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.MaxPoolGradWithArgmax` can cause reads outside of bounds of heap allocated data if attacker supplies specially crafted inputs. The implementation(https://github.com/tensorflow/tensorflow/blob/ef0c008ee84bad91ec6725ddc42091e19a30cf0e/tensorflow/core/kernels/maxpooling_op.cc#L1016-L1017) uses the same value to index in two different arrays but there is no guarantee that the sizes are identical. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29570"} {"idx": 245438, "project": "tensorflow", "commit_id": "dcd7867de0fea4b72a2b34bd41eb74548dc23886", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/dcd7867de0fea4b72a2b34bd41eb74548dc23886", "commit_message": "Fix heap buffer overflow\n\nPiperOrigin-RevId: 372132844\nChange-Id: Idef9895efaf145f2b1c23d31983601ec980cd5e4", "target": 0, "func": " static void launch(OpKernelContext* context, const PoolParameters& params,\n const Tensor& grad_in, const Tensor& argmax,\n Tensor* grad_out, const bool include_batch_in_index) {\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n auto shard = [&grad_in, &argmax, &grad_out, include_batch_in_index](\n int64 start, int64 limit) {\n const int64 batch_size =\n GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 output_size_per_batch = grad_out->NumElements() / batch_size;\n const int64 input_size_per_batch = grad_in.NumElements() / batch_size;\n\n {\n auto grad_out_flat = grad_out->flat();\n auto argmax_flat = argmax.flat();\n auto grad_in_flat = grad_in.flat();\n\n const int64 output_start = start * output_size_per_batch;\n const int64 output_end = limit * output_size_per_batch;\n EigenMatrixMap inputShard(grad_out_flat.data() + output_start, 1,\n output_end - output_start);\n inputShard.setConstant(T(0));\n\n const int input_start = start * input_size_per_batch;\n const int input_end = limit * input_size_per_batch;\n for (int64 index = input_start; index < input_end; index++) {\n if (index >= argmax.NumElements()) {\n break;\n }\n int64 grad_out_index = argmax_flat(index);\n if (!include_batch_in_index) {\n const int64 cur_batch = index / input_size_per_batch;\n grad_out_index += cur_batch * output_size_per_batch;\n }\n CHECK(grad_out_index >= output_start && grad_out_index < output_end)\n << \"Invalid output gradient index: \" << grad_out_index << \", \"\n << output_start << \", \" << output_end;\n grad_out_flat(grad_out_index) += grad_in_flat(index);\n }\n }\n };\n\n const int64 batch_size = GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 shard_cost = grad_out->NumElements() / batch_size;\n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n shard_cost, shard);\n }", "func_hash": 21221216383140371775310119279743448324, "file_name": "maxpooling_op.cc", "file_hash": 68790224195291456093262869219197591059, "cwe": ["CWE-125"], "cve": "CVE-2021-29570", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.MaxPoolGradWithArgmax` can cause reads outside of bounds of heap allocated data if attacker supplies specially crafted inputs. The implementation(https://github.com/tensorflow/tensorflow/blob/ef0c008ee84bad91ec6725ddc42091e19a30cf0e/tensorflow/core/kernels/maxpooling_op.cc#L1016-L1017) uses the same value to index in two different arrays but there is no guarantee that the sizes are identical. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29570"} {"idx": 196811, "project": "tensorflow", "commit_id": "7bdf50bb4f5c54a4997c379092888546c97c3ebd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/7bdf50bb4f5c54a4997c379092888546c97c3ebd", "commit_message": "Ensure non-empty compressed input in tf.raw_ops.UncompressElement\n\nPiperOrigin-RevId: 383955815\nChange-Id: I072a84fd02738dd2f51b3f42836ed80067dba4a8", "target": 1, "func": "void UncompressElementOp::Compute(OpKernelContext* ctx) {\n Tensor tensor = ctx->input(0);\n const Variant& variant = tensor.scalar()();\n const CompressedElement* compressed = variant.get();\n\n std::vector components;\n OP_REQUIRES_OK(ctx, UncompressElement(*compressed, &components));\n OP_REQUIRES(ctx, components.size() == output_types_.size(),\n errors::FailedPrecondition(\"Expected \", output_types_.size(),\n \" outputs from uncompress, but got \",\n components.size()));\n for (int i = 0; i < components.size(); ++i) {\n OP_REQUIRES(\n ctx, components[i].dtype() == output_types_[i],\n errors::FailedPrecondition(\"Expected a tensor of type \",\n DataTypeString(output_types_[i]),\n \" but got a tensor of type \",\n DataTypeString(components[i].dtype())));\n ctx->set_output(i, components[i]);\n }\n}", "func_hash": 36144672404758850948918783634752279625, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-37649", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The code for `tf.raw_ops.UncompressElement` can be made to trigger a null pointer dereference. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/data/experimental/compression_ops.cc#L50-L53) obtains a pointer to a `CompressedElement` from a `Variant` tensor and then proceeds to dereference it for decompressing. There is no check that the `Variant` tensor contained a `CompressedElement`, so the pointer is actually `nullptr`. We have patched the issue in GitHub commit 7bdf50bb4f5c54a4997c379092888546c97c3ebd. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37649"} {"idx": 245642, "project": "tensorflow", "commit_id": "7bdf50bb4f5c54a4997c379092888546c97c3ebd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/7bdf50bb4f5c54a4997c379092888546c97c3ebd", "commit_message": "Ensure non-empty compressed input in tf.raw_ops.UncompressElement\n\nPiperOrigin-RevId: 383955815\nChange-Id: I072a84fd02738dd2f51b3f42836ed80067dba4a8", "target": 0, "func": "void UncompressElementOp::Compute(OpKernelContext* ctx) {\n Tensor tensor = ctx->input(0);\n const Variant& variant = tensor.scalar()();\n const CompressedElement* compressed = variant.get();\n OP_REQUIRES(\n ctx, compressed != nullptr,\n errors::InvalidArgument(\n \"Input does not contain a compressed element. Instead got tensor \",\n tensor.DebugString()));\n\n std::vector components;\n OP_REQUIRES_OK(ctx, UncompressElement(*compressed, &components));\n OP_REQUIRES(ctx, components.size() == output_types_.size(),\n errors::FailedPrecondition(\"Expected \", output_types_.size(),\n \" outputs from uncompress, but got \",\n components.size()));\n for (int i = 0; i < components.size(); ++i) {\n OP_REQUIRES(\n ctx, components[i].dtype() == output_types_[i],\n errors::FailedPrecondition(\"Expected a tensor of type \",\n DataTypeString(output_types_[i]),\n \" but got a tensor of type \",\n DataTypeString(components[i].dtype())));\n ctx->set_output(i, components[i]);\n }\n}", "func_hash": 153775402171206536218479342097532927826, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-37649", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The code for `tf.raw_ops.UncompressElement` can be made to trigger a null pointer dereference. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/data/experimental/compression_ops.cc#L50-L53) obtains a pointer to a `CompressedElement` from a `Variant` tensor and then proceeds to dereference it for decompressing. There is no check that the `Variant` tensor contained a `CompressedElement`, so the pointer is actually `nullptr`. We have patched the issue in GitHub commit 7bdf50bb4f5c54a4997c379092888546c97c3ebd. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37649"} {"idx": 196831, "project": "asylo", "commit_id": "83036fd841d33baa7e039f842d131aa7881fdcc2", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/83036fd841d33baa7e039f842d131aa7881fdcc2", "commit_message": "Verify UntrustedCall output is outside enclave\n\nPiperOrigin-RevId: 333781703\nChange-Id: I9df55c04dc8b04f4bf0bda8e68cc32bca81b933a", "target": 1, "func": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "func_hash": 216577886866138465008511878597186100264, "file_name": "trusted_sgx.cc", "file_hash": 43034046919615221000331636956844476960, "cwe": ["CWE-125"], "cve": "CVE-2020-8936", "cve_desc": "An arbitrary memory overwrite vulnerability in Asylo versions up to 0.6.0 allows an attacker to make a host call to UntrustedCall. UntrustedCall failed to validate the buffer range within sgx_params and allowed the host to return a pointer that was an address within the enclave memory. This allowed an attacker to read memory values from within the enclave.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8936"} {"idx": 246050, "project": "asylo", "commit_id": "83036fd841d33baa7e039f842d131aa7881fdcc2", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/83036fd841d33baa7e039f842d131aa7881fdcc2", "commit_message": "Verify UntrustedCall output is outside enclave\n\nPiperOrigin-RevId: 333781703\nChange-Id: I9df55c04dc8b04f4bf0bda8e68cc32bca81b933a", "target": 0, "func": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n sgx_params->output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "func_hash": 98641191944334442241289496061501381391, "file_name": "trusted_sgx.cc", "file_hash": 234646855773751418886779792645520395040, "cwe": ["CWE-125"], "cve": "CVE-2020-8936", "cve_desc": "An arbitrary memory overwrite vulnerability in Asylo versions up to 0.6.0 allows an attacker to make a host call to UntrustedCall. UntrustedCall failed to validate the buffer range within sgx_params and allowed the host to return a pointer that was an address within the enclave memory. This allowed an attacker to read memory values from within the enclave.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8936"} {"idx": 196843, "project": "FreeRTOS-Kernel", "commit_id": "d05b9c123f2bf9090bce386a244fc934ae44db5b", "project_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel", "commit_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel/commit/d05b9c123f2bf9090bce386a244fc934ae44db5b", "commit_message": "Add addition overflow check for stream buffer (#226)", "target": 1, "func": " StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,\r\n size_t xTriggerLevelBytes,\r\n BaseType_t xIsMessageBuffer )\r\n {\r\n uint8_t * pucAllocatedMemory;\r\n uint8_t ucFlags;\r\n\r\n /* In case the stream buffer is going to be used as a message buffer\r\n * (that is, it will hold discrete messages with a little meta data that\r\n * says how big the next message is) check the buffer will be large enough\r\n * to hold at least one message. */\r\n if( xIsMessageBuffer == pdTRUE )\r\n {\r\n /* Is a message buffer but not statically allocated. */\r\n ucFlags = sbFLAGS_IS_MESSAGE_BUFFER;\r\n configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );\r\n }\r\n else\r\n {\r\n /* Not a message buffer and not statically allocated. */\r\n ucFlags = 0;\r\n configASSERT( xBufferSizeBytes > 0 );\r\n }\r\n\r\n configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );\r\n\r\n /* A trigger level of 0 would cause a waiting task to unblock even when\r\n * the buffer was empty. */\r\n if( xTriggerLevelBytes == ( size_t ) 0 )\r\n {\r\n xTriggerLevelBytes = ( size_t ) 1;\r\n }\r\n\r\n /* A stream buffer requires a StreamBuffer_t structure and a buffer.\r\n * Both are allocated in a single call to pvPortMalloc(). The\r\n * StreamBuffer_t structure is placed at the start of the allocated memory\r\n * and the buffer follows immediately after. The requested size is\r\n * incremented so the free space is returned as the user would expect -\r\n * this is a quirk of the implementation that means otherwise the free\r\n * space would be reported as one byte smaller than would be logically\r\n * expected. */\r\n xBufferSizeBytes++;\r\n pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */\r\n\r\n if( pucAllocatedMemory != NULL )\r\n {\r\n prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */\r\n pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */\r\n xBufferSizeBytes,\r\n xTriggerLevelBytes,\r\n ucFlags );\r\n\r\n traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer );\r\n }\r\n else\r\n {\r\n traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer );\r\n }\r\n\r\n return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */\r\n }\r", "func_hash": 157943297719963429489721944670885280629, "file_name": "stream_buffer.c", "file_hash": 333385912408463578286123447116318985658, "cwe": ["CWE-190"], "cve": "CVE-2021-31572", "cve_desc": "The kernel in Amazon Web Services FreeRTOS before 10.4.3 has an integer overflow in stream_buffer.c for a stream buffer.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31572"} {"idx": 246422, "project": "FreeRTOS-Kernel", "commit_id": "d05b9c123f2bf9090bce386a244fc934ae44db5b", "project_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel", "commit_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel/commit/d05b9c123f2bf9090bce386a244fc934ae44db5b", "commit_message": "Add addition overflow check for stream buffer (#226)", "target": 0, "func": " StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,\r\n size_t xTriggerLevelBytes,\r\n BaseType_t xIsMessageBuffer )\r\n {\r\n uint8_t * pucAllocatedMemory;\r\n uint8_t ucFlags;\r\n\r\n /* In case the stream buffer is going to be used as a message buffer\r\n * (that is, it will hold discrete messages with a little meta data that\r\n * says how big the next message is) check the buffer will be large enough\r\n * to hold at least one message. */\r\n if( xIsMessageBuffer == pdTRUE )\r\n {\r\n /* Is a message buffer but not statically allocated. */\r\n ucFlags = sbFLAGS_IS_MESSAGE_BUFFER;\r\n configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );\r\n }\r\n else\r\n {\r\n /* Not a message buffer and not statically allocated. */\r\n ucFlags = 0;\r\n configASSERT( xBufferSizeBytes > 0 );\r\n }\r\n\r\n configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );\r\n\r\n /* A trigger level of 0 would cause a waiting task to unblock even when\r\n * the buffer was empty. */\r\n if( xTriggerLevelBytes == ( size_t ) 0 )\r\n {\r\n xTriggerLevelBytes = ( size_t ) 1;\r\n }\r\n\r\n /* A stream buffer requires a StreamBuffer_t structure and a buffer.\r\n * Both are allocated in a single call to pvPortMalloc(). The\r\n * StreamBuffer_t structure is placed at the start of the allocated memory\r\n * and the buffer follows immediately after. The requested size is\r\n * incremented so the free space is returned as the user would expect -\r\n * this is a quirk of the implementation that means otherwise the free\r\n * space would be reported as one byte smaller than would be logically\r\n * expected. */\r\n if( xBufferSizeBytes < ( xBufferSizeBytes + 1 + sizeof( StreamBuffer_t ) ) )\r\n {\r\n xBufferSizeBytes++;\r\n pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */\r\n }\r\n else\r\n {\r\n pucAllocatedMemory = NULL;\r\n }\r\n \r\n\r\n if( pucAllocatedMemory != NULL )\r\n {\r\n prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */\r\n pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */\r\n xBufferSizeBytes,\r\n xTriggerLevelBytes,\r\n ucFlags );\r\n\r\n traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer );\r\n }\r\n else\r\n {\r\n traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer );\r\n }\r\n\r\n return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */\r\n }\r", "func_hash": 228448000830444602002812046582419483276, "file_name": "stream_buffer.c", "file_hash": 110678113897106824669893942540507544724, "cwe": ["CWE-190"], "cve": "CVE-2021-31572", "cve_desc": "The kernel in Amazon Web Services FreeRTOS before 10.4.3 has an integer overflow in stream_buffer.c for a stream buffer.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31572"} {"idx": 196856, "project": "tensorflow", "commit_id": "5dc7f6981fdaf74c8c5be41f393df705841fb7c5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5dc7f6981fdaf74c8c5be41f393df705841fb7c5", "commit_message": "Fix accessing possible nullptr in tensorflow::data::CompressElement and UncompressElement which are used in tf.data.service.\n\nPiperOrigin-RevId: 373920841\nChange-Id: Ia88d78aee09fa19bb53a0f163fd19620d0c68743", "target": 1, "func": "Status CompressElement(const std::vector& element,\n CompressedElement* out) {\n // Step 1: Determine the total uncompressed size. This requires serializing\n // non-memcopyable tensors, which we save to use again later.\n std::vector non_memcpy_components;\n int64 total_size = 0;\n for (auto& component : element) {\n if (DataTypeCanUseMemcpy(component.dtype())) {\n // Some datatypes can be memcopied, allowing us to save two copies\n // (AsProtoTensorContent and SerializeToArray).\n total_size += DMAHelper::buffer(&component)->size();\n } else {\n non_memcpy_components.emplace_back();\n component.AsProtoTensorContent(&non_memcpy_components.back());\n total_size += non_memcpy_components.back().ByteSizeLong();\n }\n }\n\n // Step 2: Write the tensor data to a buffer, and compress that buffer.\n // We use tstring for access to resize_uninitialized.\n tstring uncompressed;\n uncompressed.resize_uninitialized(total_size);\n // Position in `uncompressed` to write the next component.\n char* position = uncompressed.mdata();\n int non_memcpy_component_index = 0;\n for (auto& component : element) {\n CompressedComponentMetadata* metadata =\n out->mutable_component_metadata()->Add();\n metadata->set_dtype(component.dtype());\n component.shape().AsProto(metadata->mutable_tensor_shape());\n if (DataTypeCanUseMemcpy(component.dtype())) {\n const TensorBuffer* buffer = DMAHelper::buffer(&component);\n memcpy(position, buffer->data(), buffer->size());\n metadata->set_tensor_size_bytes(buffer->size());\n } else {\n TensorProto& proto = non_memcpy_components[non_memcpy_component_index++];\n proto.SerializeToArray(position, proto.ByteSizeLong());\n metadata->set_tensor_size_bytes(proto.ByteSizeLong());\n }\n position += metadata->tensor_size_bytes();\n }\n DCHECK_EQ(position, uncompressed.mdata() + total_size);\n\n if (!port::Snappy_Compress(uncompressed.mdata(), total_size,\n out->mutable_data())) {\n return errors::Internal(\"Failed to compress using snappy.\");\n }\n VLOG(3) << \"Compressed element from \" << total_size << \" bytes to \"\n << out->data().size() << \" bytes\";\n return Status::OK();\n}", "func_hash": 186422718707666126332665509788952218278, "file_name": "compression_utils.cc", "file_hash": 167746652663003824748260703046556259107, "cwe": ["CWE-125"], "cve": "CVE-2021-37637", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. It is possible to trigger a null pointer dereference in TensorFlow by passing an invalid input to `tf.raw_ops.CompressElement`. The [implementation](https://github.com/tensorflow/tensorflow/blob/47a06f40411a69c99f381495f490536972152ac0/tensorflow/core/data/compression_utils.cc#L34) was accessing the size of a buffer obtained from the return of a separate function call before validating that said buffer is valid. We have patched the issue in GitHub commit 5dc7f6981fdaf74c8c5be41f393df705841fb7c5. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37637"} {"idx": 246589, "project": "tensorflow", "commit_id": "5dc7f6981fdaf74c8c5be41f393df705841fb7c5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5dc7f6981fdaf74c8c5be41f393df705841fb7c5", "commit_message": "Fix accessing possible nullptr in tensorflow::data::CompressElement and UncompressElement which are used in tf.data.service.\n\nPiperOrigin-RevId: 373920841\nChange-Id: Ia88d78aee09fa19bb53a0f163fd19620d0c68743", "target": 0, "func": "Status CompressElement(const std::vector& element,\n CompressedElement* out) {\n // Step 1: Determine the total uncompressed size. This requires serializing\n // non-memcopyable tensors, which we save to use again later.\n std::vector non_memcpy_components;\n int64 total_size = 0;\n for (auto& component : element) {\n if (DataTypeCanUseMemcpy(component.dtype())) {\n const TensorBuffer* buffer = DMAHelper::buffer(&component);\n if (buffer) {\n total_size += buffer->size();\n }\n } else {\n non_memcpy_components.emplace_back();\n component.AsProtoTensorContent(&non_memcpy_components.back());\n total_size += non_memcpy_components.back().ByteSizeLong();\n }\n }\n\n // Step 2: Write the tensor data to a buffer, and compress that buffer.\n // We use tstring for access to resize_uninitialized.\n tstring uncompressed;\n uncompressed.resize_uninitialized(total_size);\n // Position in `uncompressed` to write the next component.\n char* position = uncompressed.mdata();\n int non_memcpy_component_index = 0;\n for (auto& component : element) {\n CompressedComponentMetadata* metadata =\n out->mutable_component_metadata()->Add();\n metadata->set_dtype(component.dtype());\n component.shape().AsProto(metadata->mutable_tensor_shape());\n if (DataTypeCanUseMemcpy(component.dtype())) {\n const TensorBuffer* buffer = DMAHelper::buffer(&component);\n if (buffer) {\n memcpy(position, buffer->data(), buffer->size());\n metadata->set_tensor_size_bytes(buffer->size());\n }\n } else {\n TensorProto& proto = non_memcpy_components[non_memcpy_component_index++];\n proto.SerializeToArray(position, proto.ByteSizeLong());\n metadata->set_tensor_size_bytes(proto.ByteSizeLong());\n }\n position += metadata->tensor_size_bytes();\n }\n DCHECK_EQ(position, uncompressed.mdata() + total_size);\n\n if (!port::Snappy_Compress(uncompressed.mdata(), total_size,\n out->mutable_data())) {\n return errors::Internal(\"Failed to compress using snappy.\");\n }\n VLOG(3) << \"Compressed element from \" << total_size << \" bytes to \"\n << out->data().size() << \" bytes\";\n return Status::OK();\n}", "func_hash": 120050314138160621314070354219764712901, "file_name": "compression_utils.cc", "file_hash": 189908597627405477772937369714565638208, "cwe": ["CWE-125"], "cve": "CVE-2021-37637", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. It is possible to trigger a null pointer dereference in TensorFlow by passing an invalid input to `tf.raw_ops.CompressElement`. The [implementation](https://github.com/tensorflow/tensorflow/blob/47a06f40411a69c99f381495f490536972152ac0/tensorflow/core/data/compression_utils.cc#L34) was accessing the size of a buffer obtained from the return of a separate function call before validating that said buffer is valid. We have patched the issue in GitHub commit 5dc7f6981fdaf74c8c5be41f393df705841fb7c5. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37637"} {"idx": 196857, "project": "tensorflow", "commit_id": "f6fde895ef9c77d848061c0517f19d0ec2682f3a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f6fde895ef9c77d848061c0517f19d0ec2682f3a", "commit_message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373274848\nChange-Id: I3a665ac3a29dee9fb69bdf408a939330cb93ea75", "target": 1, "func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *a_indices_t, *a_values_t, *a_shape_t, *b_indices_t,\n *b_values_t, *b_shape_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape_t));\n\n // Validations.\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsMatrix(a_indices_t->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices_t->shape()),\n errors::InvalidArgument(\"Inputs a_indices and b_indices should be \"\n \"matrices but received shapes: \",\n a_indices_t->shape().DebugString(), \", \",\n b_indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Inputs a_values and b_values should be vectors \"\n \"but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n\n const int64 a_nnz = a_indices_t->dim_size(0);\n const int64 b_nnz = b_indices_t->dim_size(0);\n const auto a_values = a_values_t->vec();\n const auto b_values = b_values_t->vec();\n\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape_t->shape()) &&\n TensorShapeUtils::IsVector(b_shape_t->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape_t->shape().DebugString(), \" and \",\n b_shape_t->shape().DebugString()));\n OP_REQUIRES(ctx, a_shape_t->IsSameSize(*b_shape_t),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape_t->SummarizeValue(10), \" and \",\n b_shape_t->SummarizeValue(10)));\n const auto a_shape = a_shape_t->flat();\n const auto b_shape = b_shape_t->flat();\n for (int i = 0; i < a_shape_t->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape(i) == b_shape(i),\n errors::InvalidArgument(\"Operands' shapes do not match: got \",\n a_shape(i), \" and \", b_shape(i),\n \" for dimension \", i));\n }\n\n OP_REQUIRES(\n ctx, a_indices_t->dim_size(1) == b_indices_t->dim_size(1),\n errors::InvalidArgument(\n \"Indices' dimensions do not match: got \", a_indices_t->dim_size(1),\n \" and \", b_indices_t->dim_size(1), \" for the second dimension.\"));\n const int num_dims = a_indices_t->dim_size(1);\n const auto a_indices_mat = a_indices_t->matrix();\n const auto b_indices_mat = b_indices_t->matrix();\n std::vector a_augmented_values, b_augmented_values;\n std::vector> entries_to_copy; // from_a?, idx\n UnionSparseIndicesAndValues(a_indices_mat, a_values, a_nnz, b_indices_mat,\n b_values, b_nnz, num_dims, &a_augmented_values,\n &b_augmented_values, &entries_to_copy);\n\n // Allocates and fills output tensors.\n const int64 sum_nnz = a_augmented_values.size();\n Tensor *output_indices_t, *output_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &output_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &output_values_t));\n auto output_indices_mat = output_indices_t->matrix();\n\n for (int64 i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n output_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n\n // Performs the functor operation using Eigen.\n //\n // Note that the two stack-allocated std::vector's may not be aligned. Using\n // allocate_temp() would've given us aligned storage, but we do not know\n // their sizes in advance, so we couldn't use allocate_temp() anyway.\n //\n // TODO(zongheng): measure if it's worthwhile to somehow force alignment.\n using UnalignedTensorMap =\n Eigen::TensorMap,\n Eigen::Unaligned>;\n auto a_augmented_values_t =\n UnalignedTensorMap(a_augmented_values.data(), sum_nnz);\n auto b_augmented_values_t =\n UnalignedTensorMap(b_augmented_values.data(), sum_nnz);\n output_values_t->flat().device(ctx->eigen_device()) =\n a_augmented_values_t.binaryExpr(b_augmented_values_t,\n typename Functor::func());\n }", "func_hash": 135024720898975771725934414227586914722, "file_name": "sparse_sparse_binary_op_shared.cc", "file_hash": 143433438690821469588613112492723020511, "cwe": ["CWE-369"], "cve": "CVE-2021-29607", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Incomplete validation in `SparseAdd` results in allowing attackers to exploit undefined behavior (dereferencing null pointers) as well as write outside of bounds of heap allocated data. The implementation(https://github.com/tensorflow/tensorflow/blob/656e7673b14acd7835dc778867f84916c6d1cac2/tensorflow/core/kernels/sparse_sparse_binary_op_shared.cc) has a large set of validation for the two sparse tensor inputs (6 tensors in total), but does not validate that the tensors are not empty or that the second dimension of `*_indices` matches the size of corresponding `*_shape`. This allows attackers to send tensor triples that represent invalid sparse tensors to abuse code assumptions that are not protected by validation. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29607"} {"idx": 246590, "project": "tensorflow", "commit_id": "f6fde895ef9c77d848061c0517f19d0ec2682f3a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f6fde895ef9c77d848061c0517f19d0ec2682f3a", "commit_message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373274848\nChange-Id: I3a665ac3a29dee9fb69bdf408a939330cb93ea75", "target": 0, "func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *a_indices_t, *a_values_t, *a_shape_t, *b_indices_t,\n *b_values_t, *b_shape_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape_t));\n\n // Validations.\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsMatrix(a_indices_t->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices_t->shape()),\n errors::InvalidArgument(\"Inputs a_indices and b_indices should be \"\n \"matrices but received shapes: \",\n a_indices_t->shape().DebugString(), \", \",\n b_indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Inputs a_values and b_values should be vectors \"\n \"but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n\n const int64 a_nnz = a_indices_t->dim_size(0);\n const int64 b_nnz = b_indices_t->dim_size(0);\n\n const auto a_values = a_values_t->vec();\n const auto b_values = b_values_t->vec();\n\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape_t->shape()) &&\n TensorShapeUtils::IsVector(b_shape_t->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape_t->shape().DebugString(), \" and \",\n b_shape_t->shape().DebugString()));\n const int num_dims = a_indices_t->dim_size(1);\n OP_REQUIRES(\n ctx, a_shape_t->NumElements() == num_dims,\n errors::InvalidArgument(\"Second dimension of a_indices and length of \"\n \"a_shape must match, got \",\n num_dims, \" and \", a_shape_t->NumElements()));\n OP_REQUIRES(ctx, num_dims > 0,\n errors::InvalidArgument(\"Tensors must not be empty\"));\n OP_REQUIRES(ctx, a_shape_t->IsSameSize(*b_shape_t),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape_t->SummarizeValue(10), \" and \",\n b_shape_t->SummarizeValue(10)));\n const auto a_shape = a_shape_t->flat();\n const auto b_shape = b_shape_t->flat();\n for (int i = 0; i < a_shape_t->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape(i) == b_shape(i),\n errors::InvalidArgument(\"Operands' shapes do not match: got \",\n a_shape(i), \" and \", b_shape(i),\n \" for dimension \", i));\n }\n\n const auto a_indices_mat = a_indices_t->matrix();\n const auto b_indices_mat = b_indices_t->matrix();\n std::vector a_augmented_values, b_augmented_values;\n std::vector> entries_to_copy; // from_a?, idx\n UnionSparseIndicesAndValues(a_indices_mat, a_values, a_nnz, b_indices_mat,\n b_values, b_nnz, num_dims, &a_augmented_values,\n &b_augmented_values, &entries_to_copy);\n\n // Allocates and fills output tensors.\n const int64 sum_nnz = a_augmented_values.size();\n Tensor *output_indices_t, *output_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &output_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &output_values_t));\n auto output_indices_mat = output_indices_t->matrix();\n\n for (int64 i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n output_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n\n // Performs the functor operation using Eigen.\n //\n // Note that the two stack-allocated std::vector's may not be aligned. Using\n // allocate_temp() would've given us aligned storage, but we do not know\n // their sizes in advance, so we couldn't use allocate_temp() anyway.\n //\n // TODO(zongheng): measure if it's worthwhile to somehow force alignment.\n using UnalignedTensorMap =\n Eigen::TensorMap,\n Eigen::Unaligned>;\n auto a_augmented_values_t =\n UnalignedTensorMap(a_augmented_values.data(), sum_nnz);\n auto b_augmented_values_t =\n UnalignedTensorMap(b_augmented_values.data(), sum_nnz);\n output_values_t->flat().device(ctx->eigen_device()) =\n a_augmented_values_t.binaryExpr(b_augmented_values_t,\n typename Functor::func());\n }", "func_hash": 252667750992733734714665192342607502708, "file_name": "sparse_sparse_binary_op_shared.cc", "file_hash": 81557657454519292663131019408054481925, "cwe": ["CWE-369"], "cve": "CVE-2021-29607", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Incomplete validation in `SparseAdd` results in allowing attackers to exploit undefined behavior (dereferencing null pointers) as well as write outside of bounds of heap allocated data. The implementation(https://github.com/tensorflow/tensorflow/blob/656e7673b14acd7835dc778867f84916c6d1cac2/tensorflow/core/kernels/sparse_sparse_binary_op_shared.cc) has a large set of validation for the two sparse tensor inputs (6 tensors in total), but does not validate that the tensors are not empty or that the second dimension of `*_indices` matches the size of corresponding `*_shape`. This allows attackers to send tensor triples that represent invalid sparse tensors to abuse code assumptions that are not protected by validation. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29607"} {"idx": 196858, "project": "envoy", "commit_id": "9371333230b1a6e1be2eccf4868771e11af6253a", "project_url": "https://github.com/istio/envoy", "commit_url": "https://github.com/envoyproxy/envoy/commit/9371333230b1a6e1be2eccf4868771e11af6253a", "commit_message": "CVE-2021-43824\n\njwt_atuhn: fixed the crash when a CONNECT request is sent to JWT filter\nconfigured with regex match.\n\nSigned-off-by: Yan Avlasov ", "target": 1, "func": " bool matches(const Http::RequestHeaderMap& headers) const override {\n if (BaseMatcherImpl::matchRoute(headers)) {\n const Http::HeaderString& path = headers.Path()->value();\n const absl::string_view query_string = Http::Utility::findQueryStringStart(path);\n absl::string_view path_view = path.getStringView();\n path_view.remove_suffix(query_string.length());\n if (path_matcher_->match(path_view)) {\n ENVOY_LOG(debug, \"Regex requirement '{}' matched.\", regex_str_);\n return true;\n }\n }\n return false;\n }", "func_hash": 220883780313651807212868605412138858861, "file_name": "matcher.cc", "file_hash": 148711647569856549889459343062495155836, "cwe": ["CWE-703"], "cve": "CVE-2021-43824", "cve_desc": "Envoy is an open source edge and service proxy, designed for cloud-native applications. In affected versions a crafted request crashes Envoy when a CONNECT request is sent to JWT filter configured with regex match. This provides a denial of service attack vector. The only workaround is to not use regex in the JWT filter. Users are advised to upgrade.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43824"} {"idx": 246616, "project": "envoy", "commit_id": "9371333230b1a6e1be2eccf4868771e11af6253a", "project_url": "https://github.com/istio/envoy", "commit_url": "https://github.com/envoyproxy/envoy/commit/9371333230b1a6e1be2eccf4868771e11af6253a", "commit_message": "CVE-2021-43824\n\njwt_atuhn: fixed the crash when a CONNECT request is sent to JWT filter\nconfigured with regex match.\n\nSigned-off-by: Yan Avlasov ", "target": 0, "func": " bool matches(const Http::RequestHeaderMap& headers) const override {\n if (BaseMatcherImpl::matchRoute(headers)) {\n if (headers.Path() == nullptr) {\n return false;\n }\n const Http::HeaderString& path = headers.Path()->value();\n const absl::string_view query_string = Http::Utility::findQueryStringStart(path);\n absl::string_view path_view = path.getStringView();\n path_view.remove_suffix(query_string.length());\n if (path_matcher_->match(path_view)) {\n ENVOY_LOG(debug, \"Regex requirement '{}' matched.\", regex_str_);\n return true;\n }\n }\n return false;\n }", "func_hash": 159454018141210410216432641178017307965, "file_name": "matcher.cc", "file_hash": 31125658329761732502750294812742005820, "cwe": ["CWE-703"], "cve": "CVE-2021-43824", "cve_desc": "Envoy is an open source edge and service proxy, designed for cloud-native applications. In affected versions a crafted request crashes Envoy when a CONNECT request is sent to JWT filter configured with regex match. This provides a denial of service attack vector. The only workaround is to not use regex in the JWT filter. Users are advised to upgrade.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43824"} {"idx": 196884, "project": "doom-vanille", "commit_id": "8a6d9a02fa991a91ff90ccdc73b5ceabaa6cb9ec", "project_url": "https://github.com/AXDOOMER/doom-vanille", "commit_url": "https://github.com/AXDOOMER/doom-vanille/commit/8a6d9a02fa991a91ff90ccdc73b5ceabaa6cb9ec", "commit_message": "Fix buffer overflow in M_LoadDefaults\n\nToo much data will most likely result in a crash or freeze, but you can overwrite the stack which can be used to do an arbitrary code execution. (https://twitter.com/notrevenant/status/1268654123903340544)", "target": 1, "func": "void M_LoadDefaults (void)\n{\n int\t\ti;\n int\t\tlen;\n FILE*\tf;\n char\tdef[80];\n char\tstrparm[100];\n char*\tnewstring;\n int\t\tparm;\n boolean\tisstring;\n \n // set everything to base values\n numdefaults = sizeof(defaults)/sizeof(defaults[0]);\n for (i=0 ; i>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n\n constexpr int tensor_in_and_out_dims = 4;\n\n const Tensor& tensor_in = context->input(0);\n OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));\n\n std::vector input_size(tensor_in_and_out_dims);\n std::vector output_size(tensor_in_and_out_dims);\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n input_size[i] = tensor_in.dim_size(i);\n }\n // Output size.\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n output_size[i] =\n static_cast(std::floor(input_size[i] / pooling_ratio_[i]));\n DCHECK_GT(output_size[i], 0);\n }\n\n // Generate pooling sequence.\n std::vector row_cum_seq;\n std::vector col_cum_seq;\n GuardedPhiloxRandom generator;\n generator.Init(seed_, seed2_);\n row_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],\n &generator, pseudo_random_);\n col_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],\n &generator, pseudo_random_);\n\n // Prepare output.\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0,\n TensorShape({output_size[0], output_size[1],\n output_size[2], output_size[3]}),\n &output_tensor));\n Tensor* output_row_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 1, TensorShape({static_cast(row_cum_seq.size())}),\n &output_row_seq_tensor));\n Tensor* output_col_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 2, TensorShape({static_cast(col_cum_seq.size())}),\n &output_col_seq_tensor));\n\n ConstEigenMatrixMap in_mat(tensor_in.flat().data(), input_size[3],\n input_size[2] * input_size[1] * input_size[0]);\n\n EigenMatrixMap out_mat(output_tensor->flat().data(), output_size[3],\n output_size[2] * output_size[1] * output_size[0]);\n // out_count corresponds to number of elements in each pooling cell.\n Eigen::Matrix out_count(out_mat.cols());\n\n // Initializes the output tensor and out_count with 0.\n out_mat.setZero();\n out_count.setZero();\n\n auto output_row_seq_flat = output_row_seq_tensor->flat();\n auto output_col_seq_flat = output_col_seq_tensor->flat();\n\n // Set output tensors.\n for (int i = 0; i < row_cum_seq.size(); ++i) {\n output_row_seq_flat(i) = row_cum_seq[i];\n }\n\n for (int i = 0; i < col_cum_seq.size(); ++i) {\n output_col_seq_flat(i) = col_cum_seq[i];\n }\n\n // For both input and output,\n // 0: batch\n // 1: row / row\n // 2: col / col\n // 3: depth / channel\n const int64 row_max = input_size[1] - 1;\n const int64 col_max = input_size[2] - 1;\n for (int64 b = 0; b < input_size[0]; ++b) {\n // row sequence.\n for (int64 hs = 0; hs < row_cum_seq.size() - 1; ++hs) {\n // row start and end.\n const int64 row_start = row_cum_seq[hs];\n int64 row_end =\n overlapping_ ? row_cum_seq[hs + 1] : row_cum_seq[hs + 1] - 1;\n row_end = std::min(row_end, row_max);\n\n // col sequence.\n for (int64 ws = 0; ws < col_cum_seq.size() - 1; ++ws) {\n const int64 out_offset =\n (b * output_size[1] + hs) * output_size[2] + ws;\n // col start and end.\n const int64 col_start = col_cum_seq[ws];\n int64 col_end =\n overlapping_ ? col_cum_seq[ws + 1] : col_cum_seq[ws + 1] - 1;\n col_end = std::min(col_end, col_max);\n for (int64 h = row_start; h <= row_end; ++h) {\n for (int64 w = col_start; w <= col_end; ++w) {\n const int64 in_offset =\n (b * input_size[1] + h) * input_size[2] + w;\n out_mat.col(out_offset) += in_mat.col(in_offset);\n out_count(out_offset)++;\n }\n }\n }\n }\n }\n DCHECK_GT(out_count.minCoeff(), 0);\n out_mat.array().rowwise() /= out_count.transpose().array();\n }", "func_hash": 216131017455832608801334859353289396717, "file_name": "fractional_avg_pool_op.cc", "file_hash": 79908233111214728219145924268966767884, "cwe": ["CWE-369"], "cve": "CVE-2021-29550", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a runtime division by zero error and denial of service in `tf.raw_ops.FractionalAvgPool`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/acc8ee69f5f46f92a3f1f11230f49c6ac266f10c/tensorflow/core/kernels/fractional_avg_pool_op.cc#L85-L89) computes a divisor quantity by dividing two user controlled values. The user controls the values of `input_size[i]` and `pooling_ratio_[i]` (via the `value.shape()` and `pooling_ratio` arguments). If the value in `input_size[i]` is smaller than the `pooling_ratio_[i]`, then the floor operation results in `output_size[i]` being 0. The `DCHECK_GT` line is a no-op outside of debug mode, so in released versions of TF this does not trigger. Later, these computed values are used as arguments(https://github.com/tensorflow/tensorflow/blob/acc8ee69f5f46f92a3f1f11230f49c6ac266f10c/tensorflow/core/kernels/fractional_avg_pool_op.cc#L96-L99) to `GeneratePoolingSequence`(https://github.com/tensorflow/tensorflow/blob/acc8ee69f5f46f92a3f1f11230f49c6ac266f10c/tensorflow/core/kernels/fractional_pool_common.cc#L100-L108). There, the first computation is a division in a modulo operation. Since `output_length` can be 0, this results in runtime crashing. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29550"} {"idx": 248336, "project": "tensorflow", "commit_id": "548b5eaf23685d86f722233d8fbc21d0a4aecb96", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/548b5eaf23685d86f722233d8fbc21d0a4aecb96", "commit_message": "Fix divide by zero error in `fractional_pool_common.cc`.\n\nPiperOrigin-RevId: 371126221\nChange-Id: Iea4b2f363aaeb116ab460e3bc592c687484af344", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n\n constexpr int tensor_in_and_out_dims = 4;\n\n const Tensor& tensor_in = context->input(0);\n OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));\n\n std::vector input_size(tensor_in_and_out_dims);\n std::vector output_size(tensor_in_and_out_dims);\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n input_size[i] = tensor_in.dim_size(i);\n OP_REQUIRES(\n context, pooling_ratio_[i] <= input_size[i],\n errors::InvalidArgument(\n \"Pooling ratio cannot be bigger than input tensor dim size.\"));\n }\n // Output size.\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n output_size[i] =\n static_cast(std::floor(input_size[i] / pooling_ratio_[i]));\n DCHECK_GT(output_size[i], 0);\n }\n\n // Generate pooling sequence.\n std::vector row_cum_seq;\n std::vector col_cum_seq;\n GuardedPhiloxRandom generator;\n generator.Init(seed_, seed2_);\n row_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],\n &generator, pseudo_random_);\n col_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],\n &generator, pseudo_random_);\n\n // Prepare output.\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0,\n TensorShape({output_size[0], output_size[1],\n output_size[2], output_size[3]}),\n &output_tensor));\n Tensor* output_row_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 1, TensorShape({static_cast(row_cum_seq.size())}),\n &output_row_seq_tensor));\n Tensor* output_col_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 2, TensorShape({static_cast(col_cum_seq.size())}),\n &output_col_seq_tensor));\n\n ConstEigenMatrixMap in_mat(tensor_in.flat().data(), input_size[3],\n input_size[2] * input_size[1] * input_size[0]);\n\n EigenMatrixMap out_mat(output_tensor->flat().data(), output_size[3],\n output_size[2] * output_size[1] * output_size[0]);\n // out_count corresponds to number of elements in each pooling cell.\n Eigen::Matrix out_count(out_mat.cols());\n\n // Initializes the output tensor and out_count with 0.\n out_mat.setZero();\n out_count.setZero();\n\n auto output_row_seq_flat = output_row_seq_tensor->flat();\n auto output_col_seq_flat = output_col_seq_tensor->flat();\n\n // Set output tensors.\n for (int i = 0; i < row_cum_seq.size(); ++i) {\n output_row_seq_flat(i) = row_cum_seq[i];\n }\n\n for (int i = 0; i < col_cum_seq.size(); ++i) {\n output_col_seq_flat(i) = col_cum_seq[i];\n }\n\n // For both input and output,\n // 0: batch\n // 1: row / row\n // 2: col / col\n // 3: depth / channel\n const int64 row_max = input_size[1] - 1;\n const int64 col_max = input_size[2] - 1;\n for (int64 b = 0; b < input_size[0]; ++b) {\n // row sequence.\n for (int64 hs = 0; hs < row_cum_seq.size() - 1; ++hs) {\n // row start and end.\n const int64 row_start = row_cum_seq[hs];\n int64 row_end =\n overlapping_ ? row_cum_seq[hs + 1] : row_cum_seq[hs + 1] - 1;\n row_end = std::min(row_end, row_max);\n\n // col sequence.\n for (int64 ws = 0; ws < col_cum_seq.size() - 1; ++ws) {\n const int64 out_offset =\n (b * output_size[1] + hs) * output_size[2] + ws;\n // col start and end.\n const int64 col_start = col_cum_seq[ws];\n int64 col_end =\n overlapping_ ? col_cum_seq[ws + 1] : col_cum_seq[ws + 1] - 1;\n col_end = std::min(col_end, col_max);\n for (int64 h = row_start; h <= row_end; ++h) {\n for (int64 w = col_start; w <= col_end; ++w) {\n const int64 in_offset =\n (b * input_size[1] + h) * input_size[2] + w;\n out_mat.col(out_offset) += in_mat.col(in_offset);\n out_count(out_offset)++;\n }\n }\n }\n }\n }\n DCHECK_GT(out_count.minCoeff(), 0);\n out_mat.array().rowwise() /= out_count.transpose().array();\n }", "func_hash": 18690751794111129874017944330103607754, "file_name": "fractional_avg_pool_op.cc", "file_hash": 283865613358899377003015554460946711471, "cwe": ["CWE-369"], "cve": "CVE-2021-29550", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a runtime division by zero error and denial of service in `tf.raw_ops.FractionalAvgPool`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/acc8ee69f5f46f92a3f1f11230f49c6ac266f10c/tensorflow/core/kernels/fractional_avg_pool_op.cc#L85-L89) computes a divisor quantity by dividing two user controlled values. The user controls the values of `input_size[i]` and `pooling_ratio_[i]` (via the `value.shape()` and `pooling_ratio` arguments). If the value in `input_size[i]` is smaller than the `pooling_ratio_[i]`, then the floor operation results in `output_size[i]` being 0. The `DCHECK_GT` line is a no-op outside of debug mode, so in released versions of TF this does not trigger. Later, these computed values are used as arguments(https://github.com/tensorflow/tensorflow/blob/acc8ee69f5f46f92a3f1f11230f49c6ac266f10c/tensorflow/core/kernels/fractional_avg_pool_op.cc#L96-L99) to `GeneratePoolingSequence`(https://github.com/tensorflow/tensorflow/blob/acc8ee69f5f46f92a3f1f11230f49c6ac266f10c/tensorflow/core/kernels/fractional_pool_common.cc#L100-L108). There, the first computation is a division in a modulo operation. Since `output_length` can be 0, this results in runtime crashing. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29550"} {"idx": 196935, "project": "tensorflow", "commit_id": "a74768f8e4efbda4def9f16ee7e13cf3922ac5f7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a74768f8e4efbda4def9f16ee7e13cf3922ac5f7", "commit_message": "Prevent heap OOB error in `MaxPoolGrad`\n\nPiperOrigin-RevId: 372424854\nChange-Id: Idac0f23867ad8b0601cafbaaa52d5e64269e63a7", "target": 1, "func": "static void SpatialMaxPoolWithArgMaxHelper(\n OpKernelContext* context, Tensor* output, Tensor* output_arg_max,\n Tensor* input_backprop, const Tensor& tensor_in, const Tensor& out_backprop,\n const PoolParameters& params, const bool include_batch_in_index) {\n if (input_backprop != nullptr) {\n OP_REQUIRES(\n context, include_batch_in_index,\n errors::Internal(\n \"SpatialMaxPoolWithArgMaxHelper requires include_batch_in_index \"\n \"to be True when input_backprop != nullptr\"));\n OP_REQUIRES(\n context, (std::is_same::value),\n errors::Internal(\"SpatialMaxPoolWithArgMaxHelper requires Targmax \"\n \"to be int64 when input_backprop != nullptr\"));\n }\n\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n typedef Eigen::Map>\n EigenIndexMatrixMap;\n\n ConstEigenMatrixMap in_mat(\n tensor_in.flat().data(), params.depth,\n params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch);\n EigenMatrixMap out_mat(\n output->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n EigenIndexMatrixMap out_arg_max_mat(\n output_arg_max->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n // The following code basically does the following:\n // 1. Flattens the input and output tensors into two dimensional arrays.\n // tensor_in_as_matrix:\n // depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)\n // output_as_matrix:\n // depth by (out_width * out_height * tensor_in_batch)\n //\n // 2. Walks through the set of columns in the flattened tensor_in_as_matrix,\n // and updates the corresponding column(s) in output_as_matrix with the\n // max value.\n auto shard = [¶ms, &in_mat, &out_mat, &out_arg_max_mat, &input_backprop,\n &output_arg_max, &out_backprop,\n include_batch_in_index](int64 start, int64 limit) {\n const int32 depth = params.depth;\n const int32 in_rows = params.tensor_in_rows;\n const int32 in_cols = params.tensor_in_cols;\n const int32 pad_top = params.pad_top;\n const int32 pad_left = params.pad_left;\n const int32 window_rows = params.window_rows;\n const int32 window_cols = params.window_cols;\n const int32 row_stride = params.row_stride;\n const int32 col_stride = params.col_stride;\n const int32 out_height = params.out_height;\n const int32 out_width = params.out_width;\n\n {\n // Initializes the output tensor with MIN.\n const int32 output_image_size = out_height * out_width * depth;\n EigenMatrixMap out_shard(out_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_shard.setConstant(Eigen::NumTraits::lowest());\n EigenIndexMatrixMap out_arg_max_shard(\n out_arg_max_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_arg_max_shard.setConstant(kInvalidMaxPoolingIndex);\n }\n\n for (int64 b = start; b < limit; ++b) {\n for (int h = 0; h < in_rows; ++h) {\n for (int w = 0; w < in_cols; ++w) {\n // (h_start, h_end) * (w_start, w_end) is the range that the input\n // vector projects to.\n const int hpad = h + pad_top;\n const int wpad = w + pad_left;\n const int h_start =\n (hpad < window_rows) ? 0 : (hpad - window_rows) / row_stride + 1;\n const int h_end = std::min(hpad / row_stride + 1, out_height);\n const int w_start =\n (wpad < window_cols) ? 0 : (wpad - window_cols) / col_stride + 1;\n const int w_end = std::min(wpad / col_stride + 1, out_width);\n // compute elementwise max\n const int64 in_index = (b * in_rows + h) * in_cols + w;\n for (int ph = h_start; ph < h_end; ++ph) {\n const int64 out_index_base = (b * out_height + ph) * out_width;\n for (int pw = w_start; pw < w_end; ++pw) {\n const int64 out_index = out_index_base + pw;\n /// NOTES(zhengxq): not using the eigen matrix operation for\n /// now.\n for (int d = 0; d < depth; ++d) {\n const T& input_ref = in_mat.coeffRef(d, in_index);\n T& output_ref = out_mat.coeffRef(d, out_index);\n Targmax& out_arg_max_ref =\n out_arg_max_mat.coeffRef(d, out_index);\n if (output_ref < input_ref ||\n out_arg_max_ref == kInvalidMaxPoolingIndex) {\n output_ref = input_ref;\n if (include_batch_in_index) {\n out_arg_max_ref = in_index * depth + d;\n } else {\n out_arg_max_ref = (h * in_cols + w) * depth + d;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (input_backprop != nullptr) {\n auto input_backprop_flat = input_backprop->flat();\n auto out_arg_max_flat = output_arg_max->flat();\n auto out_backprop_flat = out_backprop.flat();\n\n // Initialize output to 0.\n const int64 in_size = in_rows * in_cols * depth;\n const int64 in_start = start * in_size;\n const int64 in_end = limit * in_size;\n EigenMatrixMap in_shard(input_backprop_flat.data() + in_start, 1,\n in_end - in_start);\n in_shard.setConstant(T(0));\n\n // Backpropagate.\n const int out_size = out_height * out_width * depth;\n const int out_start = start * out_size;\n const int out_end = limit * out_size;\n for (int index = out_start; index < out_end; ++index) {\n int input_backprop_index = out_arg_max_flat(index);\n // Although this check is in the inner loop, it is worth its value\n // so we don't end up with memory corruptions. Our benchmark shows that\n // the performance impact is quite small\n // CHECK(input_backprop_index >= in_start && input_backprop_index <\n // in_end)\n FastBoundsCheck(input_backprop_index - in_start, in_end - in_start);\n input_backprop_flat(input_backprop_index) += out_backprop_flat(index);\n }\n }\n };\n\n const int64 shard_cost = params.tensor_in_rows * params.tensor_in_cols *\n params.depth * params.window_rows *\n params.window_cols;\n Shard(worker_threads.num_threads, worker_threads.workers,\n params.tensor_in_batch, shard_cost, shard);\n}", "func_hash": 100942372112380961223737884212137808158, "file_name": "maxpooling_op.cc", "file_hash": 68790224195291456093262869219197591059, "cwe": ["CWE-787"], "cve": "CVE-2021-29579", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.MaxPoolGrad` is vulnerable to a heap buffer overflow. The implementation(https://github.com/tensorflow/tensorflow/blob/ab1e644b48c82cb71493f4362b4dd38f4577a1cf/tensorflow/core/kernels/maxpooling_op.cc#L194-L203) fails to validate that indices used to access elements of input/output arrays are valid. Whereas accesses to `input_backprop_flat` are guarded by `FastBoundsCheck`, the indexing in `out_backprop_flat` can result in OOB access. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29579"} {"idx": 248727, "project": "tensorflow", "commit_id": "a74768f8e4efbda4def9f16ee7e13cf3922ac5f7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a74768f8e4efbda4def9f16ee7e13cf3922ac5f7", "commit_message": "Prevent heap OOB error in `MaxPoolGrad`\n\nPiperOrigin-RevId: 372424854\nChange-Id: Idac0f23867ad8b0601cafbaaa52d5e64269e63a7", "target": 0, "func": "static void SpatialMaxPoolWithArgMaxHelper(\n OpKernelContext* context, Tensor* output, Tensor* output_arg_max,\n Tensor* input_backprop, const Tensor& tensor_in, const Tensor& out_backprop,\n const PoolParameters& params, const bool include_batch_in_index) {\n if (input_backprop != nullptr) {\n OP_REQUIRES(\n context, include_batch_in_index,\n errors::Internal(\n \"SpatialMaxPoolWithArgMaxHelper requires include_batch_in_index \"\n \"to be True when input_backprop != nullptr\"));\n OP_REQUIRES(\n context, (std::is_same::value),\n errors::Internal(\"SpatialMaxPoolWithArgMaxHelper requires Targmax \"\n \"to be int64 when input_backprop != nullptr\"));\n }\n\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n typedef Eigen::Map>\n EigenIndexMatrixMap;\n\n ConstEigenMatrixMap in_mat(\n tensor_in.flat().data(), params.depth,\n params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch);\n EigenMatrixMap out_mat(\n output->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n EigenIndexMatrixMap out_arg_max_mat(\n output_arg_max->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n // The following code basically does the following:\n // 1. Flattens the input and output tensors into two dimensional arrays.\n // tensor_in_as_matrix:\n // depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)\n // output_as_matrix:\n // depth by (out_width * out_height * tensor_in_batch)\n //\n // 2. Walks through the set of columns in the flattened tensor_in_as_matrix,\n // and updates the corresponding column(s) in output_as_matrix with the\n // max value.\n auto shard = [¶ms, &in_mat, &out_mat, &out_arg_max_mat, &input_backprop,\n &output_arg_max, &out_backprop,\n include_batch_in_index](int64 start, int64 limit) {\n const int32 depth = params.depth;\n const int32 in_rows = params.tensor_in_rows;\n const int32 in_cols = params.tensor_in_cols;\n const int32 pad_top = params.pad_top;\n const int32 pad_left = params.pad_left;\n const int32 window_rows = params.window_rows;\n const int32 window_cols = params.window_cols;\n const int32 row_stride = params.row_stride;\n const int32 col_stride = params.col_stride;\n const int32 out_height = params.out_height;\n const int32 out_width = params.out_width;\n\n {\n // Initializes the output tensor with MIN.\n const int32 output_image_size = out_height * out_width * depth;\n EigenMatrixMap out_shard(out_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_shard.setConstant(Eigen::NumTraits::lowest());\n EigenIndexMatrixMap out_arg_max_shard(\n out_arg_max_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_arg_max_shard.setConstant(kInvalidMaxPoolingIndex);\n }\n\n for (int64 b = start; b < limit; ++b) {\n for (int h = 0; h < in_rows; ++h) {\n for (int w = 0; w < in_cols; ++w) {\n // (h_start, h_end) * (w_start, w_end) is the range that the input\n // vector projects to.\n const int hpad = h + pad_top;\n const int wpad = w + pad_left;\n const int h_start =\n (hpad < window_rows) ? 0 : (hpad - window_rows) / row_stride + 1;\n const int h_end = std::min(hpad / row_stride + 1, out_height);\n const int w_start =\n (wpad < window_cols) ? 0 : (wpad - window_cols) / col_stride + 1;\n const int w_end = std::min(wpad / col_stride + 1, out_width);\n // compute elementwise max\n const int64 in_index = (b * in_rows + h) * in_cols + w;\n for (int ph = h_start; ph < h_end; ++ph) {\n const int64 out_index_base = (b * out_height + ph) * out_width;\n for (int pw = w_start; pw < w_end; ++pw) {\n const int64 out_index = out_index_base + pw;\n /// NOTES(zhengxq): not using the eigen matrix operation for\n /// now.\n for (int d = 0; d < depth; ++d) {\n const T& input_ref = in_mat.coeffRef(d, in_index);\n T& output_ref = out_mat.coeffRef(d, out_index);\n Targmax& out_arg_max_ref =\n out_arg_max_mat.coeffRef(d, out_index);\n if (output_ref < input_ref ||\n out_arg_max_ref == kInvalidMaxPoolingIndex) {\n output_ref = input_ref;\n if (include_batch_in_index) {\n out_arg_max_ref = in_index * depth + d;\n } else {\n out_arg_max_ref = (h * in_cols + w) * depth + d;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (input_backprop != nullptr) {\n auto input_backprop_flat = input_backprop->flat();\n auto out_arg_max_flat = output_arg_max->flat();\n auto out_backprop_flat = out_backprop.flat();\n\n // Initialize output to 0.\n const int64 in_size = in_rows * in_cols * depth;\n const int64 in_start = start * in_size;\n const int64 in_end = limit * in_size;\n EigenMatrixMap in_shard(input_backprop_flat.data() + in_start, 1,\n in_end - in_start);\n in_shard.setConstant(T(0));\n\n // Backpropagate.\n const int out_size = out_height * out_width * depth;\n const int out_start = start * out_size;\n const int out_end = limit * out_size;\n for (int index = out_start; index < out_end; ++index) {\n int input_backprop_index = out_arg_max_flat(index);\n // Although this check is in the inner loop, it is worth its value\n // so we don't end up with memory corruptions. Our benchmark shows that\n // the performance impact is quite small\n // CHECK(input_backprop_index >= in_start && input_backprop_index <\n // in_end)\n FastBoundsCheck(input_backprop_index - in_start, in_end - in_start);\n if (index < out_backprop.NumElements()) {\n input_backprop_flat(input_backprop_index) += out_backprop_flat(index);\n }\n }\n }\n };\n\n const int64 shard_cost = params.tensor_in_rows * params.tensor_in_cols *\n params.depth * params.window_rows *\n params.window_cols;\n Shard(worker_threads.num_threads, worker_threads.workers,\n params.tensor_in_batch, shard_cost, shard);\n}", "func_hash": 138820718913662007902327948588454688969, "file_name": "maxpooling_op.cc", "file_hash": 121648353047187600668898428061061875712, "cwe": ["CWE-787"], "cve": "CVE-2021-29579", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.MaxPoolGrad` is vulnerable to a heap buffer overflow. The implementation(https://github.com/tensorflow/tensorflow/blob/ab1e644b48c82cb71493f4362b4dd38f4577a1cf/tensorflow/core/kernels/maxpooling_op.cc#L194-L203) fails to validate that indices used to access elements of input/output arrays are valid. Whereas accesses to `input_backprop_flat` are guarded by `FastBoundsCheck`, the indexing in `out_backprop_flat` can result in OOB access. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29579"} {"idx": 196939, "project": "asylo", "commit_id": "90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "commit_message": "Add sysno check in MessageReader\n\nThe sysno in MessageReader is interpreted from the Message header passed\nfrom the host. A malicious Message header may provide a modified sysno\nto bypass the validation, and overwrites enclave memory. This change\nadds a check for sysno to make sure it matches the expected value.\n\nThis issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and\nKang Li from Baidu Security.\n\nPiperOrigin-RevId: 377328054\nChange-Id: I3ff6f60694d3390f66da89d139cf7cc7b49abaea", "target": 1, "func": "extern \"C\" int64_t enc_untrusted_syscall(int sysno, ...) {\n if (!enc_is_error_handler_set()) {\n enc_set_error_handler(default_error_handler);\n }\n\n asylo::system_call::SystemCallDescriptor descriptor{sysno};\n if (!descriptor.is_valid()) {\n error_handler(\"system_call.cc: Invalid SystemCallDescriptor encountered.\");\n }\n\n // Collect the passed parameter list into an array.\n std::array parameters;\n va_list args;\n va_start(args, sysno);\n for (int i = 0; i < descriptor.parameter_count(); i++) {\n parameters[i] = va_arg(args, uint64_t);\n }\n va_end(args);\n\n // Allocate a buffer for the serialized request.\n asylo::primitives::Extent request;\n asylo::primitives::PrimitiveStatus status;\n status = asylo::system_call::SerializeRequest(sysno, parameters, &request);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Encountered serialization error when serializing \"\n \"syscall parameters.\");\n }\n\n std::unique_ptr request_owner(request.As());\n\n // Invoke the system call dispatch callback to execute the system call.\n uint8_t *response_buffer;\n size_t response_size;\n\n if (!enc_is_syscall_dispatcher_set()) {\n error_handler(\"system_.cc: system call dispatcher not set.\");\n }\n status = global_syscall_callback(request.As(), request.size(),\n &response_buffer, &response_size);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Callback from syscall dispatcher was unsuccessful.\");\n }\n\n std::unique_ptr response_owner(response_buffer);\n\n if (!response_buffer) {\n error_handler(\n \"system_call.cc: null response buffer received for the syscall.\");\n }\n\n // Copy outputs back into pointer parameters.\n auto response_reader =\n asylo::system_call::MessageReader({response_buffer, response_size});\n const asylo::primitives::PrimitiveStatus response_status =\n response_reader.Validate();\n if (!response_status.ok()) {\n error_handler(\n \"system_call.cc: Error deserializing response buffer into response \"\n \"reader.\");\n }\n\n for (int i = 0; i < asylo::system_call::kParameterMax; i++) {\n asylo::system_call::ParameterDescriptor parameter = descriptor.parameter(i);\n if (parameter.is_out()) {\n size_t size;\n if (parameter.is_fixed()) {\n size = parameter.size();\n } else {\n size = parameters[parameter.size()] * parameter.element_size();\n }\n const void *src = response_reader.parameter_address(i);\n void *dst = reinterpret_cast(parameters[i]);\n if (dst != nullptr) {\n memcpy(dst, src, size);\n }\n }\n }\n\n uint64_t result = response_reader.header()->result;\n if (static_cast(result) == -1) {\n int klinux_errno = response_reader.header()->error_number;\n\n // Simply having a return value of -1 from a syscall is not a necessary\n // condition that the syscall failed. Some syscalls can return -1 when\n // successful (eg., lseek). The reliable way to check for syscall failure is\n // to therefore check both return value and presence of a non-zero errno.\n if (klinux_errno != 0) {\n errno = FromkLinuxErrno(klinux_errno);\n }\n }\n return result;\n}", "func_hash": 266679953263994570058871425363447952805, "file_name": "system_call.cc", "file_hash": 79819331317624360846766364095398743533, "cwe": ["CWE-125"], "cve": "CVE-2021-22552", "cve_desc": "An untrusted memory read vulnerability in Asylo versions up to 0.6.1 allows an untrusted attacker to pass a syscall number in MessageReader that is then used by sysno() and can bypass validation. This can allow the attacker to read memory from within the secure enclave. We recommend updating to Asylo 0.6.3 or past https://github.com/google/asylo/commit/90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22552"} {"idx": 248772, "project": "asylo", "commit_id": "90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "commit_message": "Add sysno check in MessageReader\n\nThe sysno in MessageReader is interpreted from the Message header passed\nfrom the host. A malicious Message header may provide a modified sysno\nto bypass the validation, and overwrites enclave memory. This change\nadds a check for sysno to make sure it matches the expected value.\n\nThis issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and\nKang Li from Baidu Security.\n\nPiperOrigin-RevId: 377328054\nChange-Id: I3ff6f60694d3390f66da89d139cf7cc7b49abaea", "target": 0, "func": "extern \"C\" int64_t enc_untrusted_syscall(int sysno, ...) {\n if (!enc_is_error_handler_set()) {\n enc_set_error_handler(default_error_handler);\n }\n\n asylo::system_call::SystemCallDescriptor descriptor{sysno};\n if (!descriptor.is_valid()) {\n error_handler(\"system_call.cc: Invalid SystemCallDescriptor encountered.\");\n }\n\n // Collect the passed parameter list into an array.\n std::array parameters;\n va_list args;\n va_start(args, sysno);\n for (int i = 0; i < descriptor.parameter_count(); i++) {\n parameters[i] = va_arg(args, uint64_t);\n }\n va_end(args);\n\n // Allocate a buffer for the serialized request.\n asylo::primitives::Extent request;\n asylo::primitives::PrimitiveStatus status;\n status = asylo::system_call::SerializeRequest(sysno, parameters, &request);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Encountered serialization error when serializing \"\n \"syscall parameters.\");\n }\n\n std::unique_ptr request_owner(request.As());\n\n // Invoke the system call dispatch callback to execute the system call.\n uint8_t *response_buffer;\n size_t response_size;\n\n if (!enc_is_syscall_dispatcher_set()) {\n error_handler(\"system_.cc: system call dispatcher not set.\");\n }\n status = global_syscall_callback(request.As(), request.size(),\n &response_buffer, &response_size);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Callback from syscall dispatcher was unsuccessful.\");\n }\n\n std::unique_ptr response_owner(response_buffer);\n\n if (!response_buffer) {\n error_handler(\n \"system_call.cc: null response buffer received for the syscall.\");\n }\n\n // Copy outputs back into pointer parameters.\n auto response_reader =\n asylo::system_call::MessageReader({response_buffer, response_size});\n if (response_reader.sysno() != sysno) {\n error_handler(\"system_call.cc: Unexpected sysno in response\");\n }\n const asylo::primitives::PrimitiveStatus response_status =\n response_reader.Validate();\n if (!response_status.ok()) {\n error_handler(\n \"system_call.cc: Error deserializing response buffer into response \"\n \"reader.\");\n }\n\n for (int i = 0; i < asylo::system_call::kParameterMax; i++) {\n asylo::system_call::ParameterDescriptor parameter = descriptor.parameter(i);\n if (parameter.is_out()) {\n size_t size;\n if (parameter.is_fixed()) {\n size = parameter.size();\n } else {\n size = parameters[parameter.size()] * parameter.element_size();\n }\n const void *src = response_reader.parameter_address(i);\n void *dst = reinterpret_cast(parameters[i]);\n if (dst != nullptr) {\n memcpy(dst, src, size);\n }\n }\n }\n\n uint64_t result = response_reader.header()->result;\n if (static_cast(result) == -1) {\n int klinux_errno = response_reader.header()->error_number;\n\n // Simply having a return value of -1 from a syscall is not a necessary\n // condition that the syscall failed. Some syscalls can return -1 when\n // successful (eg., lseek). The reliable way to check for syscall failure is\n // to therefore check both return value and presence of a non-zero errno.\n if (klinux_errno != 0) {\n errno = FromkLinuxErrno(klinux_errno);\n }\n }\n return result;\n}", "func_hash": 305469382436812582629757909623551767239, "file_name": "system_call.cc", "file_hash": 97749642724157804423997036506684723602, "cwe": ["CWE-125"], "cve": "CVE-2021-22552", "cve_desc": "An untrusted memory read vulnerability in Asylo versions up to 0.6.1 allows an untrusted attacker to pass a syscall number in MessageReader that is then used by sysno() and can bypass validation. This can allow the attacker to read memory from within the secure enclave. We recommend updating to Asylo 0.6.3 or past https://github.com/google/asylo/commit/90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22552"} {"idx": 196991, "project": "libiec61850", "commit_id": "cfa94cbf10302bedc779703f874ee2e8387a0721", "project_url": "https://github.com/mz-automation/libiec61850", "commit_url": "https://github.com/mz-automation/libiec61850/commit/cfa94cbf10302bedc779703f874ee2e8387a0721", "commit_message": "- fixed - Bug in presentation layer parser can cause infinite loop (LIB61850-302)", "target": 1, "func": "parseNormalModeParameters(IsoPresentation* self, uint8_t* buffer, int totalLength, int bufPos)\n{\n int endPos = bufPos + totalLength;\n\n self->calledPresentationSelector.size = 0;\n self->callingPresentationSelector.size = 0;\n\n bool hasUserData = false;\n\n while (bufPos < endPos) {\n uint8_t tag = buffer[bufPos++];\n int len;\n\n if (bufPos == endPos) {\n if (DEBUG_PRES)\n printf(\"PRES: invalid message\\n\");\n return -1;\n }\n\n bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, endPos);\n\n if (bufPos < 0) {\n if (DEBUG_PRES)\n printf(\"PRES: wrong parameter length\\n\");\n return -1;\n }\n\n switch (tag) {\n case 0x81: /* calling-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: calling-presentation-sel too large\\n\");\n }\n else {\n self->callingPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->callingPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x82: /* called-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: called-presentation-sel too large\\n\");\n }\n else {\n self->calledPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->calledPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x83: /* responding-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: responding-presentation-sel too large\\n\");\n }\n\n bufPos += len;\n break;\n\n case 0xa4: /* presentation-context-definition list */\n if (DEBUG_PRES)\n printf(\"PRES: pcd list\\n\");\n bufPos = parsePresentationContextDefinitionList(self, buffer, len, bufPos);\n break;\n\n case 0xa5: /* context-definition-result-list */\n\n bufPos += len;\n break;\n\n case 0x61: /* user data */\n if (DEBUG_PRES)\n printf(\"PRES: user-data\\n\");\n\n bufPos = parseFullyEncodedData(self, buffer, len, bufPos);\n\n if (bufPos < 0)\n return -1;\n\n if (self->nextPayload.size > 0)\n hasUserData = true;\n\n break;\n\n case 0x00: /* indefinite length end tag -> ignore */\n break;\n\n default:\n if (DEBUG_PRES)\n printf(\"PRES: unknown tag in normal-mode\\n\");\n bufPos += len;\n break;\n }\n }\n\n if (hasUserData == false) {\n if (DEBUG_PRES)\n printf(\"PRES: user-data is missing\\n\");\n\n return -1;\n }\n\n return bufPos;\n}", "func_hash": 119236758168363766055008162116303946986, "file_name": "iso_presentation.c", "file_hash": 264314714146893751430197637735068366630, "cwe": ["CWE-703"], "cve": "CVE-2022-21159", "cve_desc": "A denial of service vulnerability exists in the parseNormalModeParameters functionality of MZ Automation GmbH libiec61850 1.5.0. A specially-crafted series of network requests can lead to denial of service. An attacker can send a sequence of malformed iec61850 messages to trigger this vulnerability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21159"} {"idx": 249484, "project": "libiec61850", "commit_id": "cfa94cbf10302bedc779703f874ee2e8387a0721", "project_url": "https://github.com/mz-automation/libiec61850", "commit_url": "https://github.com/mz-automation/libiec61850/commit/cfa94cbf10302bedc779703f874ee2e8387a0721", "commit_message": "- fixed - Bug in presentation layer parser can cause infinite loop (LIB61850-302)", "target": 0, "func": "parseNormalModeParameters(IsoPresentation* self, uint8_t* buffer, int totalLength, int bufPos)\n{\n int endPos = bufPos + totalLength;\n\n self->calledPresentationSelector.size = 0;\n self->callingPresentationSelector.size = 0;\n\n bool hasUserData = false;\n\n while (bufPos < endPos) {\n uint8_t tag = buffer[bufPos++];\n int len;\n\n if (bufPos == endPos) {\n if (DEBUG_PRES)\n printf(\"PRES: invalid message\\n\");\n return -1;\n }\n\n bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, endPos);\n\n if (bufPos < 0) {\n if (DEBUG_PRES)\n printf(\"PRES: wrong parameter length\\n\");\n return -1;\n }\n\n switch (tag) {\n case 0x81: /* calling-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: calling-presentation-sel too large\\n\");\n }\n else {\n self->callingPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->callingPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x82: /* called-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: called-presentation-sel too large\\n\");\n }\n else {\n self->calledPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->calledPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x83: /* responding-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: responding-presentation-sel too large\\n\");\n }\n\n bufPos += len;\n break;\n\n case 0xa4: /* presentation-context-definition list */\n if (DEBUG_PRES)\n printf(\"PRES: pcd list\\n\");\n bufPos = parsePresentationContextDefinitionList(self, buffer, len, bufPos);\n\n if (bufPos < 0)\n return -1;\n\n break;\n\n case 0xa5: /* context-definition-result-list */\n\n bufPos += len;\n break;\n\n case 0x61: /* user data */\n if (DEBUG_PRES)\n printf(\"PRES: user-data\\n\");\n\n bufPos = parseFullyEncodedData(self, buffer, len, bufPos);\n\n if (bufPos < 0)\n return -1;\n\n if (self->nextPayload.size > 0)\n hasUserData = true;\n\n break;\n\n case 0x00: /* indefinite length end tag -> ignore */\n break;\n\n default:\n if (DEBUG_PRES)\n printf(\"PRES: unknown tag in normal-mode\\n\");\n bufPos += len;\n break;\n }\n }\n\n if (hasUserData == false) {\n if (DEBUG_PRES)\n printf(\"PRES: user-data is missing\\n\");\n\n return -1;\n }\n\n return bufPos;\n}", "func_hash": 96139389440224821090781161192379972812, "file_name": "iso_presentation.c", "file_hash": 35422293729886185513420882669781558719, "cwe": ["CWE-703"], "cve": "CVE-2022-21159", "cve_desc": "A denial of service vulnerability exists in the parseNormalModeParameters functionality of MZ Automation GmbH libiec61850 1.5.0. A specially-crafted series of network requests can lead to denial of service. An attacker can send a sequence of malformed iec61850 messages to trigger this vulnerability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21159"} {"idx": 196997, "project": "gpac", "commit_id": "ce01bd15f711d4575b7424b54b3a395ec64c1784", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/ce01bd15f711d4575b7424b54b3a395ec64c1784", "commit_message": "fixed #1566", "target": 1, "func": "#ifndef GPAC_DISABLE_ISOM_HINTING\n\nvoid dump_isom_sdp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tconst char *sdp;\n\tu32 size, i;\n\tFILE *dump;\n\n\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) {\n\t\t\tchar *ext = strchr(szBuf, '.');\n\t\t\tif (ext) ext[0] = 0;\n\t\t\tstrcat(szBuf, \"_sdp.txt\");\n\t\t}\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tfprintf(stderr, \"Failed to open %s for dumping\\n\", szBuf);\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t\tfprintf(dump, \"* File SDP content *\\n\\n\");\n\t}\n\t//get the movie SDP\n\tgf_isom_sdp_get(file, &sdp, &size);\n\tfprintf(dump, \"%s\", sdp);\n\tfprintf(dump, \"\\r\\n\");\n\n\t//then tracks\n\tfor (i=0; iinput(0);\n const Tensor& means_tensor = ctx->input(1);\n const Tensor& stddevs_tensor = ctx->input(2);\n const Tensor& minvals_tensor = ctx->input(3);\n const Tensor& maxvals_tensor = ctx->input(4);\n\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(shape_tensor.shape()),\n errors::InvalidArgument(\"Input shape should be a vector, got shape: \",\n shape_tensor.shape().DebugString()));\n int32 num_batches = shape_tensor.flat()(0);\n\n int32 samples_per_batch = 1;\n const int32 num_dims = shape_tensor.dim_size(0);\n for (int32 i = 1; i < num_dims; i++) {\n samples_per_batch *= shape_tensor.flat()(i);\n }\n const int32 num_elements = num_batches * samples_per_batch;\n\n // Allocate the output before fudging num_batches and samples_per_batch.\n auto shape_vec = shape_tensor.flat();\n TensorShape tensor_shape;\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(\n shape_vec.data(), shape_vec.size(), &tensor_shape));\n Tensor* samples_tensor;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, tensor_shape, &samples_tensor));\n\n // Parameters must be 0-d or 1-d.\n OP_REQUIRES(ctx, means_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input means should be a scalar or vector, got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, stddevs_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input stddevs should be a scalar or vector, got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, minvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input minvals should be a scalar or vector, got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, maxvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input maxvals should be a scalar or vector, got shape: \",\n maxvals_tensor.shape().DebugString()));\n\n if ((means_tensor.dims() == 0 || means_tensor.dim_size(0) == 1) &&\n (stddevs_tensor.dims() == 0 || stddevs_tensor.dim_size(0) == 1) &&\n minvals_tensor.dims() == 0 && maxvals_tensor.dims() == 0) {\n // All batches have the same parameters, so we can update the batch size\n // to a reasonable value to improve parallelism (ensure enough batches,\n // and no very small batches which have high overhead).\n int32 size = num_batches * samples_per_batch;\n int32 adjusted_samples = kDesiredBatchSize;\n // Ensure adjusted_batches * adjusted_samples >= size.\n int32 adjusted_batches = Eigen::divup(size, adjusted_samples);\n num_batches = adjusted_batches;\n samples_per_batch = adjusted_samples;\n } else {\n // Parameters must be broadcastable to the shape [num_batches].\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(means_tensor.shape()) ||\n means_tensor.dim_size(0) == 1 ||\n means_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input means should have length 1 or shape[0], got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(stddevs_tensor.shape()) ||\n stddevs_tensor.dim_size(0) == 1 ||\n stddevs_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input stddevs should have length 1 or shape[0], got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(minvals_tensor.shape()) ||\n minvals_tensor.dim_size(0) == 1 ||\n minvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input minvals should have length 1 or shape[0], got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(maxvals_tensor.shape()) ||\n maxvals_tensor.dim_size(0) == 1 ||\n maxvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input maxvals should have length 1 or shape[0], got shape: \",\n maxvals_tensor.shape().DebugString()));\n }\n\n auto truncFunctor = functor::TruncatedNormalFunctor();\n // Each worker has the fudge factor for samples_per_batch, so use it here.\n random::PhiloxRandom rng =\n generator_.ReserveSamples128(num_batches * 2 * functor::kMaxIterations *\n (samples_per_batch + 3) / 4);\n truncFunctor(ctx, ctx->eigen_device(), num_batches,\n samples_per_batch, num_elements, means_tensor.flat(),\n stddevs_tensor.flat(), minvals_tensor.flat(),\n maxvals_tensor.flat(), rng, samples_tensor->flat());\n }", "func_hash": 54099559530803351865281710155928871069, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-29568", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger undefined behavior by binding to null pointer in `tf.raw_ops.ParameterizedTruncatedNormal`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/3f6fe4dfef6f57e768260b48166c27d148f3015f/tensorflow/core/kernels/parameterized_truncated_normal_op.cc#L630) does not validate input arguments before accessing the first element of `shape`. If `shape` argument is empty, then `shape_tensor.flat()` is an empty array. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29568"} {"idx": 251872, "project": "tensorflow", "commit_id": "5e52ef5a461570cfb68f3bdbbebfe972cb4e0fd8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5e52ef5a461570cfb68f3bdbbebfe972cb4e0fd8", "commit_message": "Fix breakage in parameterized_truncated_normal_op.cc\n\nPiperOrigin-RevId: 372041718\nChange-Id: Iff79e77a2bb27032423eefcb84211627b27dfe81", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& shape_tensor = ctx->input(0);\n const Tensor& means_tensor = ctx->input(1);\n const Tensor& stddevs_tensor = ctx->input(2);\n const Tensor& minvals_tensor = ctx->input(3);\n const Tensor& maxvals_tensor = ctx->input(4);\n\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(shape_tensor.shape()),\n errors::InvalidArgument(\"Input shape should be a vector, got shape: \",\n shape_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, shape_tensor.NumElements() > 0,\n errors::InvalidArgument(\"Shape tensor must not be empty, got \",\n shape_tensor.DebugString()));\n int32 num_batches = shape_tensor.flat()(0);\n\n int32 samples_per_batch = 1;\n const int32 num_dims = shape_tensor.dim_size(0);\n for (int32 i = 1; i < num_dims; i++) {\n samples_per_batch *= shape_tensor.flat()(i);\n }\n const int32 num_elements = num_batches * samples_per_batch;\n\n // Allocate the output before fudging num_batches and samples_per_batch.\n auto shape_vec = shape_tensor.flat();\n TensorShape tensor_shape;\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(\n shape_vec.data(), shape_vec.size(), &tensor_shape));\n Tensor* samples_tensor;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, tensor_shape, &samples_tensor));\n\n // Parameters must be 0-d or 1-d.\n OP_REQUIRES(ctx, means_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input means should be a scalar or vector, got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, stddevs_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input stddevs should be a scalar or vector, got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, minvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input minvals should be a scalar or vector, got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, maxvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input maxvals should be a scalar or vector, got shape: \",\n maxvals_tensor.shape().DebugString()));\n\n if ((means_tensor.dims() == 0 || means_tensor.dim_size(0) == 1) &&\n (stddevs_tensor.dims() == 0 || stddevs_tensor.dim_size(0) == 1) &&\n minvals_tensor.dims() == 0 && maxvals_tensor.dims() == 0) {\n // All batches have the same parameters, so we can update the batch size\n // to a reasonable value to improve parallelism (ensure enough batches,\n // and no very small batches which have high overhead).\n int32 size = num_batches * samples_per_batch;\n int32 adjusted_samples = kDesiredBatchSize;\n // Ensure adjusted_batches * adjusted_samples >= size.\n int32 adjusted_batches = Eigen::divup(size, adjusted_samples);\n num_batches = adjusted_batches;\n samples_per_batch = adjusted_samples;\n } else {\n // Parameters must be broadcastable to the shape [num_batches].\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(means_tensor.shape()) ||\n means_tensor.dim_size(0) == 1 ||\n means_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input means should have length 1 or shape[0], got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(stddevs_tensor.shape()) ||\n stddevs_tensor.dim_size(0) == 1 ||\n stddevs_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input stddevs should have length 1 or shape[0], got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(minvals_tensor.shape()) ||\n minvals_tensor.dim_size(0) == 1 ||\n minvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input minvals should have length 1 or shape[0], got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(maxvals_tensor.shape()) ||\n maxvals_tensor.dim_size(0) == 1 ||\n maxvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input maxvals should have length 1 or shape[0], got shape: \",\n maxvals_tensor.shape().DebugString()));\n }\n\n auto truncFunctor = functor::TruncatedNormalFunctor();\n // Each worker has the fudge factor for samples_per_batch, so use it here.\n random::PhiloxRandom rng =\n generator_.ReserveSamples128(num_batches * 2 * functor::kMaxIterations *\n (samples_per_batch + 3) / 4);\n truncFunctor(ctx, ctx->eigen_device(), num_batches,\n samples_per_batch, num_elements, means_tensor.flat(),\n stddevs_tensor.flat(), minvals_tensor.flat(),\n maxvals_tensor.flat(), rng, samples_tensor->flat());\n }", "func_hash": 81939748120016367004260799908977656979, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-29568", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger undefined behavior by binding to null pointer in `tf.raw_ops.ParameterizedTruncatedNormal`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/3f6fe4dfef6f57e768260b48166c27d148f3015f/tensorflow/core/kernels/parameterized_truncated_normal_op.cc#L630) does not validate input arguments before accessing the first element of `shape`. If `shape` argument is empty, then `shape_tensor.flat()` is an empty array. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29568"} {"idx": 197114, "project": "nanopb", "commit_id": "aa9d0d1ca78d6adec3adfeecf3a706c7f9df81f2", "project_url": "https://github.com/nanopb/nanopb", "commit_url": "https://github.com/nanopb/nanopb/commit/aa9d0d1ca78d6adec3adfeecf3a706c7f9df81f2", "commit_message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 1, "func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n PB_UNUSED(wire_type);\n PB_UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n case PB_HTYPE_ONEOF:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_HTYPE(type) == PB_HTYPE_ONEOF)\n {\n *(pb_size_t*)iter->pSize = iter->pos->tag;\n }\n\n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n pb_size_t *size = (pb_size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if ((size_t)*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(char**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n \n if (*size == PB_SIZE_MAX)\n {\n#ifndef PB_NO_ERRMSG\n stream->errmsg = \"too many array entries\";\n#endif\n status = false;\n break;\n }\n \n (*size)++;\n }\n if (!pb_close_string_substream(stream, &substream))\n return false;\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n pb_size_t *size = (pb_size_t*)iter->pSize;\n void *pItem;\n \n if (*size == PB_SIZE_MAX)\n PB_RETURN_ERROR(stream, \"too many array entries\");\n \n (*size)++;\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))\n return false;\n \n pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1);\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n\n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "func_hash": 197024026861839388478611156219036207871, "file_name": "pb_decode.c", "file_hash": 158982902301487802548862656493640508318, "cwe": ["CWE-125"], "cve": "CVE-2020-5235", "cve_desc": "There is a potentially exploitable out of memory condition In Nanopb before 0.4.1, 0.3.9.5, and 0.2.9.4. When nanopb is compiled with PB_ENABLE_MALLOC, the message to be decoded contains a repeated string, bytes or message field and realloc() runs out of memory when expanding the array nanopb can end up calling `free()` on a pointer value that comes from uninitialized memory. Depending on platform this can result in a crash or further memory corruption, which may be exploitable in some cases. This problem is fixed in nanopb-0.4.1, nanopb-0.3.9.5, nanopb-0.2.9.4.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-5235"} {"idx": 252505, "project": "nanopb", "commit_id": "aa9d0d1ca78d6adec3adfeecf3a706c7f9df81f2", "project_url": "https://github.com/nanopb/nanopb", "commit_url": "https://github.com/nanopb/nanopb/commit/aa9d0d1ca78d6adec3adfeecf3a706c7f9df81f2", "commit_message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 0, "func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n PB_UNUSED(wire_type);\n PB_UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n case PB_HTYPE_ONEOF:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_HTYPE(type) == PB_HTYPE_ONEOF)\n {\n *(pb_size_t*)iter->pSize = iter->pos->tag;\n }\n\n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n pb_size_t *size = (pb_size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if ((size_t)*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(char**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n \n if (*size == PB_SIZE_MAX)\n {\n#ifndef PB_NO_ERRMSG\n stream->errmsg = \"too many array entries\";\n#endif\n status = false;\n break;\n }\n \n (*size)++;\n }\n if (!pb_close_string_substream(stream, &substream))\n return false;\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n pb_size_t *size = (pb_size_t*)iter->pSize;\n void *pItem;\n \n if (*size == PB_SIZE_MAX)\n PB_RETURN_ERROR(stream, \"too many array entries\");\n \n if (!allocate_field(stream, iter->pData, iter->pos->data_size, (size_t)(*size + 1)))\n return false;\n \n pItem = *(char**)iter->pData + iter->pos->data_size * (*size);\n (*size)++;\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n\n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "func_hash": 282507665892868857746099821460966868525, "file_name": "pb_decode.c", "file_hash": 259905948831433895536101869181612322302, "cwe": ["CWE-125"], "cve": "CVE-2020-5235", "cve_desc": "There is a potentially exploitable out of memory condition In Nanopb before 0.4.1, 0.3.9.5, and 0.2.9.4. When nanopb is compiled with PB_ENABLE_MALLOC, the message to be decoded contains a repeated string, bytes or message field and realloc() runs out of memory when expanding the array nanopb can end up calling `free()` on a pointer value that comes from uninitialized memory. Depending on platform this can result in a crash or further memory corruption, which may be exploitable in some cases. This problem is fixed in nanopb-0.4.1, nanopb-0.3.9.5, nanopb-0.2.9.4.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-5235"} {"idx": 197133, "project": "tensorflow", "commit_id": "12c727cee857fa19be717f336943d95fca4ffe4f", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/12c727cee857fa19be717f336943d95fca4ffe4f", "commit_message": "Validate inputs of `FractionalAvgPoolGrad`.\n\nPiperOrigin-RevId: 372420640\nChange-Id: Icc583928e6cdc3062e12498e4d2337a8fe3da016", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n // Here's the basic idea:\n // Batch and depth dimension are independent from row and col dimension. And\n // because FractionalAvgPool currently only support pooling along row and\n // col, we can basically think of this 4D tensor backpropagation as\n // operation of a series of 2D planes.\n //\n // For each element of a 'slice' (2D plane) of output_backprop, we need to\n // figure out its contributors when doing FractionalAvgPool operation. This\n // can be done based on row_pooling_sequence, col_pooling_seq and\n // overlapping.\n // Once we figure out the original contributors, we just need to evenly\n // divide the value of this element among these contributors.\n //\n // Internally, we divide the out_backprop tensor and store it in a temporary\n // tensor of double type. And cast it to the corresponding type.\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenDoubleMatrixMap;\n\n // Grab the inputs.\n const Tensor& orig_input_tensor_shape = context->input(0);\n OP_REQUIRES(context,\n orig_input_tensor_shape.dims() == 1 &&\n orig_input_tensor_shape.NumElements() == 4,\n errors::InvalidArgument(\"original input tensor shape must be\"\n \"1-dimensional and 4 elements\"));\n const Tensor& out_backprop = context->input(1);\n const Tensor& row_seq_tensor = context->input(2);\n const Tensor& col_seq_tensor = context->input(3);\n\n const int64 out_batch = out_backprop.dim_size(0);\n const int64 out_rows = out_backprop.dim_size(1);\n const int64 out_cols = out_backprop.dim_size(2);\n const int64 out_depth = out_backprop.dim_size(3);\n\n auto row_seq_tensor_flat = row_seq_tensor.flat();\n auto col_seq_tensor_flat = col_seq_tensor.flat();\n auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n const int64 in_batch = orig_input_tensor_shape_flat(0);\n const int64 in_rows = orig_input_tensor_shape_flat(1);\n const int64 in_cols = orig_input_tensor_shape_flat(2);\n const int64 in_depth = orig_input_tensor_shape_flat(3);\n\n constexpr int tensor_in_and_out_dims = 4;\n // Transform orig_input_tensor_shape into TensorShape\n TensorShape in_shape;\n for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n in_shape.AddDim(orig_input_tensor_shape_flat(i));\n }\n\n // Create intermediate in_backprop.\n Tensor in_backprop_tensor_temp;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n {0}, DataTypeToEnum::v(), in_shape,\n &in_backprop_tensor_temp));\n in_backprop_tensor_temp.flat().setZero();\n // Transform 4D tensor to 2D matrix.\n EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n in_backprop_tensor_temp.flat().data(), in_depth,\n in_cols * in_rows * in_batch);\n ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n out_depth,\n out_cols * out_rows * out_batch);\n // Loop through each element of out_backprop and evenly distribute the\n // element to the corresponding pooling cell.\n const int64 in_max_row_index = in_rows - 1;\n const int64 in_max_col_index = in_cols - 1;\n for (int64 b = 0; b < out_batch; ++b) {\n for (int64 r = 0; r < out_rows; ++r) {\n const int64 in_row_start = row_seq_tensor_flat(r);\n int64 in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n : row_seq_tensor_flat(r + 1) - 1;\n in_row_end = std::min(in_row_end, in_max_row_index);\n for (int64 c = 0; c < out_cols; ++c) {\n const int64 in_col_start = col_seq_tensor_flat(c);\n int64 in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n : col_seq_tensor_flat(c + 1) - 1;\n in_col_end = std::min(in_col_end, in_max_col_index);\n\n const int64 num_elements_in_pooling_cell =\n (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n const int64 out_index = (b * out_rows + r) * out_cols + c;\n // Now we can evenly distribute out_backprop(b, h, w, *) to\n // in_backprop(b, hs:he, ws:we, *).\n for (int64 in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n for (int64 in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n const int64 in_index = (b * in_rows + in_r) * in_cols + in_c;\n // Walk through each channel (depth).\n for (int64 d = 0; d < out_depth; ++d) {\n const double out_backprop_element = static_cast(\n out_backprop_mat.coeffRef(d, out_index));\n double& in_backprop_ref =\n in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n in_backprop_ref +=\n out_backprop_element / num_elements_in_pooling_cell;\n }\n }\n }\n }\n }\n }\n\n // Depending on the type, cast double to type T.\n Tensor* in_backprop_tensor = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 0, in_shape, &in_backprop_tensor));\n auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n for (int64 i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n in_backprop_tensor_flat(i) =\n static_cast(in_backprop_tensor_temp_flat(i));\n }\n }", "func_hash": 320966022522271679966490274814497959175, "file_name": "fractional_avg_pool_op.cc", "file_hash": 265099047389679312668808151671844838843, "cwe": ["CWE-369"], "cve": "CVE-2021-29578", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.FractionalAvgPoolGrad` is vulnerable to a heap buffer overflow. The implementation(https://github.com/tensorflow/tensorflow/blob/dcba796a28364d6d7f003f6fe733d82726dda713/tensorflow/core/kernels/fractional_avg_pool_op.cc#L216) fails to validate that the pooling sequence arguments have enough elements as required by the `out_backprop` tensor shape. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29578"} {"idx": 253652, "project": "tensorflow", "commit_id": "12c727cee857fa19be717f336943d95fca4ffe4f", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/12c727cee857fa19be717f336943d95fca4ffe4f", "commit_message": "Validate inputs of `FractionalAvgPoolGrad`.\n\nPiperOrigin-RevId: 372420640\nChange-Id: Icc583928e6cdc3062e12498e4d2337a8fe3da016", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n // Here's the basic idea:\n // Batch and depth dimension are independent from row and col dimension. And\n // because FractionalAvgPool currently only support pooling along row and\n // col, we can basically think of this 4D tensor backpropagation as\n // operation of a series of 2D planes.\n //\n // For each element of a 'slice' (2D plane) of output_backprop, we need to\n // figure out its contributors when doing FractionalAvgPool operation. This\n // can be done based on row_pooling_sequence, col_pooling_seq and\n // overlapping.\n // Once we figure out the original contributors, we just need to evenly\n // divide the value of this element among these contributors.\n //\n // Internally, we divide the out_backprop tensor and store it in a temporary\n // tensor of double type. And cast it to the corresponding type.\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenDoubleMatrixMap;\n\n // Grab the inputs.\n const Tensor& orig_input_tensor_shape = context->input(0);\n OP_REQUIRES(context,\n orig_input_tensor_shape.dims() == 1 &&\n orig_input_tensor_shape.NumElements() == 4,\n errors::InvalidArgument(\"original input tensor shape must be\"\n \"1-dimensional and 4 elements\"));\n const Tensor& out_backprop = context->input(1);\n const Tensor& row_seq_tensor = context->input(2);\n const Tensor& col_seq_tensor = context->input(3);\n\n const int64 out_batch = out_backprop.dim_size(0);\n const int64 out_rows = out_backprop.dim_size(1);\n const int64 out_cols = out_backprop.dim_size(2);\n const int64 out_depth = out_backprop.dim_size(3);\n\n OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,\n errors::InvalidArgument(\"Given out_backprop shape \",\n out_backprop.shape().DebugString(),\n \", row_seq_tensor must have at least \",\n out_rows + 1, \" elements, but got \",\n row_seq_tensor.NumElements()));\n OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,\n errors::InvalidArgument(\"Given out_backprop shape \",\n out_backprop.shape().DebugString(),\n \", col_seq_tensor must have at least \",\n out_cols + 1, \" elements, but got \",\n col_seq_tensor.NumElements()));\n\n auto row_seq_tensor_flat = row_seq_tensor.flat();\n auto col_seq_tensor_flat = col_seq_tensor.flat();\n auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n const int64 in_batch = orig_input_tensor_shape_flat(0);\n const int64 in_rows = orig_input_tensor_shape_flat(1);\n const int64 in_cols = orig_input_tensor_shape_flat(2);\n const int64 in_depth = orig_input_tensor_shape_flat(3);\n\n constexpr int tensor_in_and_out_dims = 4;\n // Transform orig_input_tensor_shape into TensorShape\n TensorShape in_shape;\n for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n in_shape.AddDim(orig_input_tensor_shape_flat(i));\n }\n\n // Create intermediate in_backprop.\n Tensor in_backprop_tensor_temp;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n {0}, DataTypeToEnum::v(), in_shape,\n &in_backprop_tensor_temp));\n in_backprop_tensor_temp.flat().setZero();\n // Transform 4D tensor to 2D matrix.\n EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n in_backprop_tensor_temp.flat().data(), in_depth,\n in_cols * in_rows * in_batch);\n ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n out_depth,\n out_cols * out_rows * out_batch);\n // Loop through each element of out_backprop and evenly distribute the\n // element to the corresponding pooling cell.\n const int64 in_max_row_index = in_rows - 1;\n const int64 in_max_col_index = in_cols - 1;\n for (int64 b = 0; b < out_batch; ++b) {\n for (int64 r = 0; r < out_rows; ++r) {\n const int64 in_row_start = row_seq_tensor_flat(r);\n int64 in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n : row_seq_tensor_flat(r + 1) - 1;\n in_row_end = std::min(in_row_end, in_max_row_index);\n for (int64 c = 0; c < out_cols; ++c) {\n const int64 in_col_start = col_seq_tensor_flat(c);\n int64 in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n : col_seq_tensor_flat(c + 1) - 1;\n in_col_end = std::min(in_col_end, in_max_col_index);\n\n const int64 num_elements_in_pooling_cell =\n (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n const int64 out_index = (b * out_rows + r) * out_cols + c;\n // Now we can evenly distribute out_backprop(b, h, w, *) to\n // in_backprop(b, hs:he, ws:we, *).\n for (int64 in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n for (int64 in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n const int64 in_index = (b * in_rows + in_r) * in_cols + in_c;\n // Walk through each channel (depth).\n for (int64 d = 0; d < out_depth; ++d) {\n const double out_backprop_element = static_cast(\n out_backprop_mat.coeffRef(d, out_index));\n double& in_backprop_ref =\n in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n in_backprop_ref +=\n out_backprop_element / num_elements_in_pooling_cell;\n }\n }\n }\n }\n }\n }\n\n // Depending on the type, cast double to type T.\n Tensor* in_backprop_tensor = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 0, in_shape, &in_backprop_tensor));\n auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n for (int64 i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n in_backprop_tensor_flat(i) =\n static_cast(in_backprop_tensor_temp_flat(i));\n }\n }", "func_hash": 224160368343188894774248468735082269787, "file_name": "fractional_avg_pool_op.cc", "file_hash": 283865613358899377003015554460946711471, "cwe": ["CWE-369"], "cve": "CVE-2021-29578", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.FractionalAvgPoolGrad` is vulnerable to a heap buffer overflow. The implementation(https://github.com/tensorflow/tensorflow/blob/dcba796a28364d6d7f003f6fe733d82726dda713/tensorflow/core/kernels/fractional_avg_pool_op.cc#L216) fails to validate that the pooling sequence arguments have enough elements as required by the `out_backprop` tensor shape. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29578"} {"idx": 197172, "project": "nanopb", "commit_id": "e2f0ccf939d9f82931d085acb6df8e9a182a4261", "project_url": "https://github.com/nanopb/nanopb", "commit_url": "https://github.com/nanopb/nanopb/commit/e2f0ccf939d9f82931d085acb6df8e9a182a4261", "commit_message": "Fix invalid free() with oneof (#647)\n\nNanopb would call free() or realloc() on an invalid\n(attacker controlled) pointer value when all the following\nconditions are true:\n\n- PB_ENABLE_MALLOC is defined at the compile time\n- Message definition contains an oneof field, and the oneof\n contains at least one pointer type field and at least one\n non-pointer type field.\n- Data being decoded first contains a non-pointer value for\n the oneof field, and later contains an overwriting pointer\n value.\n\nDepending on message layout, the bug may not be exploitable in all\ncases, but it is known to be exploitable at least with string and\nbytes fields. Actual security impact will also depend on the heap\nimplementation used.", "target": 1, "func": "static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field)\n{\n pb_field_iter_t old_field = *field;\n pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */\n pb_size_t new_tag = field->tag; /* New which_ value */\n\n if (old_tag == 0)\n return true; /* Ok, no old data in union */\n\n if (old_tag == new_tag)\n return true; /* Ok, old data is of same type => merge */\n\n /* Release old data. The find can fail if the message struct contains\n * invalid data. */\n if (!pb_field_iter_find(&old_field, old_tag))\n PB_RETURN_ERROR(stream, \"invalid union tag\");\n\n pb_release_single_field(&old_field);\n\n return true;\n}", "func_hash": 229372759713814422524622923398862274970, "file_name": "pb_decode.c", "file_hash": 48108367603645785138818484226191780537, "cwe": ["CWE-763"], "cve": "CVE-2021-21401", "cve_desc": "Nanopb is a small code-size Protocol Buffers implementation in ansi C. In Nanopb before versions 0.3.9.8 and 0.4.5, decoding a specifically formed message can cause invalid `free()` or `realloc()` calls if the message type contains an `oneof` field, and the `oneof` directly contains both a pointer field and a non-pointer field. If the message data first contains the non-pointer field and then the pointer field, the data of the non-pointer field is incorrectly treated as if it was a pointer value. Such message data rarely occurs in normal messages, but it is a concern when untrusted data is parsed. This has been fixed in versions 0.3.9.8 and 0.4.5. See referenced GitHub Security Advisory for more information including workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21401"} {"idx": 254699, "project": "nanopb", "commit_id": "e2f0ccf939d9f82931d085acb6df8e9a182a4261", "project_url": "https://github.com/nanopb/nanopb", "commit_url": "https://github.com/nanopb/nanopb/commit/e2f0ccf939d9f82931d085acb6df8e9a182a4261", "commit_message": "Fix invalid free() with oneof (#647)\n\nNanopb would call free() or realloc() on an invalid\n(attacker controlled) pointer value when all the following\nconditions are true:\n\n- PB_ENABLE_MALLOC is defined at the compile time\n- Message definition contains an oneof field, and the oneof\n contains at least one pointer type field and at least one\n non-pointer type field.\n- Data being decoded first contains a non-pointer value for\n the oneof field, and later contains an overwriting pointer\n value.\n\nDepending on message layout, the bug may not be exploitable in all\ncases, but it is known to be exploitable at least with string and\nbytes fields. Actual security impact will also depend on the heap\nimplementation used.", "target": 0, "func": "static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field)\n{\n pb_field_iter_t old_field = *field;\n pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */\n pb_size_t new_tag = field->tag; /* New which_ value */\n\n if (old_tag == 0)\n return true; /* Ok, no old data in union */\n\n if (old_tag == new_tag)\n return true; /* Ok, old data is of same type => merge */\n\n /* Release old data. The find can fail if the message struct contains\n * invalid data. */\n if (!pb_field_iter_find(&old_field, old_tag))\n PB_RETURN_ERROR(stream, \"invalid union tag\");\n\n pb_release_single_field(&old_field);\n\n if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n {\n /* Initialize the pointer to NULL to make sure it is valid\n * even in case of error return. */\n *(void**)field->pField = NULL;\n field->pData = NULL;\n }\n\n return true;\n}", "func_hash": 64176294146361720637588313764101489820, "file_name": "pb_decode.c", "file_hash": 254404674552774353965172864507752428058, "cwe": ["CWE-763"], "cve": "CVE-2021-21401", "cve_desc": "Nanopb is a small code-size Protocol Buffers implementation in ansi C. In Nanopb before versions 0.3.9.8 and 0.4.5, decoding a specifically formed message can cause invalid `free()` or `realloc()` calls if the message type contains an `oneof` field, and the `oneof` directly contains both a pointer field and a non-pointer field. If the message data first contains the non-pointer field and then the pointer field, the data of the non-pointer field is incorrectly treated as if it was a pointer value. Such message data rarely occurs in normal messages, but it is a concern when untrusted data is parsed. This has been fixed in versions 0.3.9.8 and 0.4.5. See referenced GitHub Security Advisory for more information including workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21401"} {"idx": 197178, "project": "nDPI", "commit_id": "b7e666e465f138ae48ab81976726e67deed12701", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/b7e666e465f138ae48ab81976726e67deed12701", "commit_message": "Added fix to avoid potential heap buffer overflow in H.323 dissector\nModified HTTP report information to make it closer to the HTTP field names", "target": 1, "func": "void ndpi_search_h323(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search H323\\n\");\n\n /*\n The TPKT protocol is used by ISO 8072 (on port 102)\n and H.323. So this check below is to avoid ambiguities\n */\n if((packet->tcp != NULL) && (packet->tcp->dest != ntohs(102))) {\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over tcp\\n\");\n\n /* H323 */\n if(packet->payload_packet_len >= 4\n && (packet->payload[0] == 0x03)\n && (packet->payload[1] == 0x00)) {\n\tstruct tpkt *t = (struct tpkt*)packet->payload;\n\tu_int16_t len = ntohs(t->len);\n\n\tif(packet->payload_packet_len == len) {\n\t /*\n\t We need to check if this packet is in reality\n\t a RDP (Remote Desktop) packet encapsulated on TPTK\n\t */\n\n\t if(packet->payload[4] == (packet->payload_packet_len - sizeof(struct tpkt) - 1)) {\n\t /* ISO 8073/X.224 */\n\t if((packet->payload[5] == 0xE0 /* CC Connect Request */)\n\t || (packet->payload[5] == 0xD0 /* CC Connect Confirm */)) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found RDP\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_RDP, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n\t }\n\n\t flow->l4.tcp.h323_valid_packets++;\n\n\t if(flow->l4.tcp.h323_valid_packets >= 2) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t }\n\t} else {\n\t /* This is not H.323 */\n\t NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\t return;\n\t}\n }\n } else if(packet->udp != NULL) {\n sport = ntohs(packet->udp->source), dport = ntohs(packet->udp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over udp\\n\");\n\n if(packet->payload_packet_len >= 6 && packet->payload[0] == 0x80 && packet->payload[1] == 0x08 &&\n (packet->payload[2] == 0xe7 || packet->payload[2] == 0x26) &&\n packet->payload[4] == 0x00 && packet->payload[5] == 0x00)\n {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n /* H323 */\n if(sport == 1719 || dport == 1719)\n {\n if(packet->payload[0] == 0x16 && packet->payload[1] == 0x80 && packet->payload[4] == 0x06 && packet->payload[5] == 0x00)\n\t {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n else if(packet->payload_packet_len >= 20 && packet->payload_packet_len <= 117)\n\t {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n else\n\t {\n\t NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\t return;\n\t }\n }\n }\n\n}", "func_hash": 75425705243400681989930125626152984706, "file_name": "h323.c", "file_hash": 10809163616517078723681502770999660317, "cwe": ["CWE-125"], "cve": "CVE-2020-15472", "cve_desc": "In nDPI through 3.2, the H.323 dissector is vulnerable to a heap-based buffer over-read in ndpi_search_h323 in lib/protocols/h323.c, as demonstrated by a payload packet length that is too short.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15472"} {"idx": 254869, "project": "nDPI", "commit_id": "b7e666e465f138ae48ab81976726e67deed12701", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/b7e666e465f138ae48ab81976726e67deed12701", "commit_message": "Added fix to avoid potential heap buffer overflow in H.323 dissector\nModified HTTP report information to make it closer to the HTTP field names", "target": 0, "func": "void ndpi_search_h323(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search H323\\n\");\n\n /*\n The TPKT protocol is used by ISO 8072 (on port 102)\n and H.323. So this check below is to avoid ambiguities\n */\n if((packet->tcp != NULL) && (packet->tcp->dest != ntohs(102))) {\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over tcp\\n\");\n\n /* H323 */\n if(packet->payload_packet_len >= 4\n && (packet->payload[0] == 0x03)\n && (packet->payload[1] == 0x00)) {\n struct tpkt *t = (struct tpkt*)packet->payload;\n u_int16_t len = ntohs(t->len);\n\n if(packet->payload_packet_len == len) {\n\t/*\n\t We need to check if this packet is in reality\n\t a RDP (Remote Desktop) packet encapsulated on TPTK\n\t*/\n\n\tif(packet->payload[4] == (packet->payload_packet_len - sizeof(struct tpkt) - 1)) {\n\t /* ISO 8073/X.224 */\n\t if((packet->payload[5] == 0xE0 /* CC Connect Request */)\n\t || (packet->payload[5] == 0xD0 /* CC Connect Confirm */)) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found RDP\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_RDP, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n\t}\n\n\tflow->l4.tcp.h323_valid_packets++;\n\n\tif(flow->l4.tcp.h323_valid_packets >= 2) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t}\n } else {\n\t/* This is not H.323 */\n\tNDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\treturn;\n }\n }\n } else if(packet->udp != NULL) {\n sport = ntohs(packet->udp->source), dport = ntohs(packet->udp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over udp\\n\");\n\n if(packet->payload_packet_len >= 6 && packet->payload[0] == 0x80 && packet->payload[1] == 0x08 &&\n (packet->payload[2] == 0xe7 || packet->payload[2] == 0x26) &&\n packet->payload[4] == 0x00 && packet->payload[5] == 0x00)\n {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n /* H323 */\n if(sport == 1719 || dport == 1719) {\n if((packet->payload_packet_len >= 5)\n\t && (packet->payload[0] == 0x16)\n\t && (packet->payload[1] == 0x80)\n\t && (packet->payload[4] == 0x06)\n\t && (packet->payload[5] == 0x00)) {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n } else if(packet->payload_packet_len >= 20 && packet->payload_packet_len <= 117) {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n } else {\n\tNDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\treturn;\n }\n }\n }\n}", "func_hash": 38311680606270649550628923810986282366, "file_name": "h323.c", "file_hash": 237656741457587827522903907467548435803, "cwe": ["CWE-125"], "cve": "CVE-2020-15472", "cve_desc": "In nDPI through 3.2, the H.323 dissector is vulnerable to a heap-based buffer over-read in ndpi_search_h323 in lib/protocols/h323.c, as demonstrated by a payload packet length that is too short.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15472"} {"idx": 197183, "project": "tensorflow", "commit_id": "fca9874a9b42a2134f907d2fb46ab774a831404a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/fca9874a9b42a2134f907d2fb46ab774a831404a", "commit_message": "Prevent another division by zero.\n\nPiperOrigin-RevId: 369338598\nChange-Id: I55471d363e401fdcf8d259670ad4eef672b731e2", "target": 1, "func": "Status ConvBackpropComputeDimensionsV2(\n StringPiece label, int num_spatial_dims, const TensorShape& input_shape,\n const TensorShape& filter_shape, const TensorShape& out_backprop_shape,\n const gtl::ArraySlice& dilations, const std::vector& strides,\n Padding padding, absl::Span explicit_paddings,\n TensorFormat data_format, ConvBackpropDimensions* dims) {\n // The + 2 in the following line is for the batch and feature dimensions.\n const int num_dims = num_spatial_dims + 2;\n if (input_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": input must be \", num_dims,\n \"-dimensional\");\n }\n if (filter_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": filter must be \", num_dims,\n \"-dimensional\");\n }\n if (out_backprop_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": out_backprop must be \", num_dims,\n \"-dimensional\");\n }\n int batch_dim = GetTensorBatchDimIndex(num_dims, data_format);\n dims->batch_size = input_shape.dim_size(batch_dim);\n if (dims->batch_size != out_backprop_shape.dim_size(batch_dim)) {\n return errors::InvalidArgument(\n label, \": input and out_backprop must have the same batch size.\",\n \" Input batch: \", dims->batch_size,\n \", outbackprop batch: \", out_backprop_shape.dim_size(batch_dim),\n \", batch_dim: \", batch_dim);\n }\n\n int feature_dim = GetTensorFeatureDimIndex(num_dims, data_format);\n dims->in_depth = input_shape.dim_size(feature_dim);\n // The input and output feature dimensions are the second last and last\n // dimensions of the filter Tensor.\n VLOG(2) << \"input vs filter_in depth \" << dims->in_depth << \" \"\n << filter_shape.dim_size(num_dims - 2);\n if (dims->in_depth % filter_shape.dim_size(num_dims - 2)) {\n return errors::InvalidArgument(\n label, \": input depth must be evenly divisible by filter depth\");\n }\n dims->out_depth = filter_shape.dim_size(num_dims - 1);\n if (dims->out_depth != out_backprop_shape.dim_size(feature_dim)) {\n return errors::InvalidArgument(\n label, \": filter and out_backprop must have the same out_depth\");\n }\n dims->spatial_dims.resize(num_spatial_dims);\n for (int i = 0; i < num_spatial_dims; ++i) {\n int image_dim = GetTensorSpatialDimIndex(num_dims, data_format, i);\n int64 padding_before = -1, padding_after = -1;\n if (padding == EXPLICIT) {\n padding_before = explicit_paddings[2 * image_dim];\n padding_after = explicit_paddings[2 * image_dim + 1];\n }\n TF_RETURN_IF_ERROR(ConvBackpropExtractAndVerifyDimension(\n label, input_shape, filter_shape, out_backprop_shape, dilations,\n strides, padding, padding_before, padding_after, image_dim, i,\n &dims->spatial_dims[i]));\n }\n return Status::OK();\n}", "func_hash": 308790408567897944165962327869500863523, "file_name": "conv_grad_shape_utils.cc", "file_hash": 274541989452952422654706114711705815495, "cwe": ["CWE-369"], "cve": "CVE-2021-29524", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a division by 0 in `tf.raw_ops.Conv2DBackpropFilter`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/496c2630e51c1a478f095b084329acedb253db6b/tensorflow/core/kernels/conv_grad_shape_utils.cc#L130) does a modulus operation where the divisor is controlled by the caller. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29524"} {"idx": 255022, "project": "tensorflow", "commit_id": "fca9874a9b42a2134f907d2fb46ab774a831404a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/fca9874a9b42a2134f907d2fb46ab774a831404a", "commit_message": "Prevent another division by zero.\n\nPiperOrigin-RevId: 369338598\nChange-Id: I55471d363e401fdcf8d259670ad4eef672b731e2", "target": 0, "func": "Status ConvBackpropComputeDimensionsV2(\n StringPiece label, int num_spatial_dims, const TensorShape& input_shape,\n const TensorShape& filter_shape, const TensorShape& out_backprop_shape,\n const gtl::ArraySlice& dilations, const std::vector& strides,\n Padding padding, absl::Span explicit_paddings,\n TensorFormat data_format, ConvBackpropDimensions* dims) {\n // The + 2 in the following line is for the batch and feature dimensions.\n const int num_dims = num_spatial_dims + 2;\n if (input_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": input must be \", num_dims,\n \"-dimensional\");\n }\n if (filter_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": filter must be \", num_dims,\n \"-dimensional\");\n }\n if (out_backprop_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": out_backprop must be \", num_dims,\n \"-dimensional\");\n }\n int batch_dim = GetTensorBatchDimIndex(num_dims, data_format);\n dims->batch_size = input_shape.dim_size(batch_dim);\n if (dims->batch_size != out_backprop_shape.dim_size(batch_dim)) {\n return errors::InvalidArgument(\n label, \": input and out_backprop must have the same batch size.\",\n \" Input batch: \", dims->batch_size,\n \", outbackprop batch: \", out_backprop_shape.dim_size(batch_dim),\n \", batch_dim: \", batch_dim);\n }\n\n int feature_dim = GetTensorFeatureDimIndex(num_dims, data_format);\n dims->in_depth = input_shape.dim_size(feature_dim);\n // The input and output feature dimensions are the second last and last\n // dimensions of the filter Tensor.\n VLOG(2) << \"input vs filter_in depth \" << dims->in_depth << \" \"\n << filter_shape.dim_size(num_dims - 2);\n if (filter_shape.dim_size(num_dims - 2) <= 0) {\n return errors ::InvalidArgument(\n label, \": filter depth must be strictly greated than zero\");\n }\n if (dims->in_depth % filter_shape.dim_size(num_dims - 2)) {\n return errors::InvalidArgument(\n label, \": input depth must be evenly divisible by filter depth\");\n }\n dims->out_depth = filter_shape.dim_size(num_dims - 1);\n if (dims->out_depth != out_backprop_shape.dim_size(feature_dim)) {\n return errors::InvalidArgument(\n label, \": filter and out_backprop must have the same out_depth\");\n }\n dims->spatial_dims.resize(num_spatial_dims);\n for (int i = 0; i < num_spatial_dims; ++i) {\n int image_dim = GetTensorSpatialDimIndex(num_dims, data_format, i);\n int64 padding_before = -1, padding_after = -1;\n if (padding == EXPLICIT) {\n padding_before = explicit_paddings[2 * image_dim];\n padding_after = explicit_paddings[2 * image_dim + 1];\n }\n TF_RETURN_IF_ERROR(ConvBackpropExtractAndVerifyDimension(\n label, input_shape, filter_shape, out_backprop_shape, dilations,\n strides, padding, padding_before, padding_after, image_dim, i,\n &dims->spatial_dims[i]));\n }\n return Status::OK();\n}", "func_hash": 169038173761970464390336392718009902651, "file_name": "conv_grad_shape_utils.cc", "file_hash": 320997771561741709610253513233866397643, "cwe": ["CWE-369"], "cve": "CVE-2021-29524", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a division by 0 in `tf.raw_ops.Conv2DBackpropFilter`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/496c2630e51c1a478f095b084329acedb253db6b/tensorflow/core/kernels/conv_grad_shape_utils.cc#L130) does a modulus operation where the divisor is controlled by the caller. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29524"} {"idx": 197202, "project": "openmpt", "commit_id": "7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c", "project_url": "https://github.com/OpenMPT/openmpt", "commit_url": "https://github.com/OpenMPT/openmpt/commit/7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c", "commit_message": "[Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz.\n\ngit-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27", "target": 1, "func": "std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)\n{\n\tstd::vector results;\n\tGetLengthType retval;\n\tretval.startOrder = target.startOrder;\n\tretval.startRow = target.startRow;\n\n\t// Are we trying to reach a certain pattern position?\n\tconst bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;\n\tconst bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;\n\n\tSEQUENCEINDEX sequence = target.sequence;\n\tif(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();\n\tconst ModSequence &orderList = Order(sequence);\n\n\tGetLengthMemory memory(*this);\n\tCSoundFile::PlayState &playState = *memory.state;\n\t// Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time)\n\tRowVisitor visitedRows(*this, sequence);\n\n\tplayState.m_nNextRow = playState.m_nRow = target.startRow;\n\tplayState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder;\n\n\t// Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode.\n\tstd::bitset forbiddenCommands;\n\tstd::bitset forbiddenVolCommands;\n\n\tif(adjustSamplePos)\n\t{\n\t\tforbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);\n\t\tforbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);\n\t\tforbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);\n\n\t\t// Optimize away channels for which it's pointless to adjust sample positions\n\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++)\n\t\t{\n\t\t\tif(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t}\n\t\tif(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size())\n\t\t{\n\t\t\t// If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start.\n\t\t\tconst PATTERNINDEX seekPat = orderList[target.pos.order];\n\t\t\tif(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))\n\t\t\t{\n\t\t\t\tconst ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);\n\t\t\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)\n\t\t\t\t{\n\t\t\t\t\tif(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t\t|| (m->IsNote() && !m->IsPortamento()))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If samples are being synced, force them to resync if tick duration changes\n\tuint32 oldTickDuration = 0;\n\n\tfor (;;)\n\t{\n\t\t// Time target reached.\n\t\tif(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tuint32 rowDelay = 0, tickDelay = 0;\n\t\tplayState.m_nRow = playState.m_nNextRow;\n\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\n\t\tif(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t\tif(m_playBehaviour[kFT2LoopE60Restart])\n\t\t\t{\n\t\t\t\tplayState.m_nRow = playState.m_nNextPatStartRow;\n\t\t\t\tplayState.m_nNextPatStartRow = 0;\n\t\t\t}\n\t\t\tplayState.m_nCurrentOrder = ++playState.m_nNextOrder;\n\t\t}\n\n\t\t// Check if pattern is valid\n\t\tplayState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\tbool positionJumpOnThisRow = false;\n\t\tbool patternBreakOnThisRow = false;\n\t\tbool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;\n\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order)\n\t\t{\n\t\t\t// Early test: Target is inside +++ or non-existing pattern\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\twhile(playState.m_nPattern >= Patterns.Size())\n\t\t{\n\t\t\t// End of song?\n\t\t\tif((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size()))\n\t\t\t{\n\t\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\tplayState.m_nCurrentOrder = orderList.GetRestartPos();\n\t\t\t} else\n\t\t\t{\n\t\t\t\tplayState.m_nCurrentOrder++;\n\t\t\t}\n\t\t\tplayState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder;\n\t\t\tif((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true))\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\n\t\t\t\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\t\t\t\t\tplayState.m_nPattern = orderList[playState.m_nCurrentOrder];\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(playState.m_nNextOrder == ORDERINDEX_INVALID)\n\t\t{\n\t\t\t// GetFirstUnvisitedRow failed, so there is nothing more to play\n\t\t\tbreak;\n\t\t}\n\n\t\t// Skip non-existing patterns\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern))\n\t\t{\n\t\t\t// If there isn't even a tune, we should probably stop here.\n\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\tcontinue;\n\t\t}\n\t\t// Should never happen\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t\tplayState.m_nRow = 0;\n\n\t\t// Check whether target was reached.\n\t\tif(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true))\n\t\t{\n\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t{\n\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\t{\n\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\tresults.push_back(retval);\n\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\tmemory.Reset();\n\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tretval.endOrder = playState.m_nCurrentOrder;\n\t\tretval.endRow = playState.m_nRow;\n\n\t\t// Update next position\n\t\tplayState.m_nNextRow = playState.m_nRow + 1;\n\n\t\t// Jumped to invalid pattern row?\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t}\n\t\t// New pattern?\n\t\tif(!playState.m_nRow)\n\t\t{\n\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t{\n\t\t\t\tmemory.chnSettings[chn].patLoop = memory.elapsedTime;\n\t\t\t\tmemory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t}\n\t\t}\n\n\t\tModChannel *pChn = playState.Chn;\n\t\t\n\t\t// For various effects, we need to know first how many ticks there are in this row.\n\t\tconst ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0);\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tif(p->IsPcNote())\n\t\t\t{\n#ifndef NO_PLUGINS\n\t\t\t\tif((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)\n\t\t\t\t{\n\t\t\t\t\tmemory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();\n\t\t\t\t}\n#endif // NO_PLUGINS\n\t\t\t\tpChn[nChn].rowCommand.Clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpChn[nChn].rowCommand = *p;\n\t\t\tswitch(p->command)\n\t\t\t{\n\t\t\tcase CMD_SPEED:\n\t\t\t\tSetSpeed(playState, p->param);\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\t// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.\n\t\t\t\t\tif(p->param != 0) SetSpeed(playState, p->param);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0x60)\n\t\t\t\t{\n\t\t\t\t\t// Fine Pattern Delay\n\t\t\t\t\ttickDelay += (p->param & 0x0F);\n\t\t\t\t} else if((p->param & 0xF0) == 0xE0 && !rowDelay)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\tif(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),\n\t\t\t\t\t\t// Scream Tracker 3 simply ignores such commands.\n\t\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0xE0)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(rowDelay == 0) rowDelay = 1;\n\t\tconst uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay;\n\t\tconst uint32 nonRowTicks = numTicks - rowDelay;\n\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\tModCommand::NOTE note = pChn->rowCommand.note;\n\n\t\t\tif (pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tpChn->nNewIns = pChn->rowCommand.instr;\n\t\t\t\tpChn->nLastNote = NOTE_NONE;\n\t\t\t\tmemory.chnSettings[nChn].vol = 0xFF;\n\t\t\t}\n\t\t\tif (pChn->rowCommand.IsNote()) pChn->nLastNote = note;\n\n\t\t\t// Update channel panning\n\t\t\tif(pChn->rowCommand.IsNote() || pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tSAMPLEINDEX smp = 0;\n\t\t\t\tif(GetNumInstruments())\n\t\t\t\t{\n\t\t\t\t\tModInstrument *pIns;\n\t\t\t\t\tif(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(pIns->dwFlags[INS_SETPANNING])\n\t\t\t\t\t\t\tpChn->nPan = pIns->nPan;\n\t\t\t\t\t\tif(ModCommand::IsNote(note))\n\t\t\t\t\t\t\tsmp = pIns->Keyboard[note - NOTE_MIN];\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tsmp = pChn->nNewIns;\n\t\t\t\t}\n\t\t\t\tif(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING])\n\t\t\t\t{\n\t\t\t\t\tpChn->nPan = Samples[smp].nPan;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\tif(pChn->rowCommand.vol != 0)\n\t\t\t\t\tpChn->nOldVolParam = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Position Jump\n\t\t\tcase CMD_POSITIONJUMP:\n\t\t\t\tpositionJumpOnThisRow = true;\n\t\t\t\tplayState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn));\n\t\t\t\tplayState.m_nNextPatStartRow = 0; // FT2 E60 bug\n\t\t\t\t// see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx\n\t\t\t\t// Test case: PatternJump.mod\n\t\t\t\tif(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))\n\t\t\t\t\tplayState.m_nNextRow = 0;\n\n\t\t\t\tif (adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Pattern Break\n\t\t\tcase CMD_PATTERNBREAK:\n\t\t\t\t{\n\t\t\t\t\tROWINDEX row = PatternBreak(playState, nChn, param);\n\t\t\t\t\tif(row != ROWINDEX_INVALID)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternBreakOnThisRow = true;\n\t\t\t\t\t\tplayState.m_nNextRow = row;\n\n\t\t\t\t\t\tif(!positionJumpOnThisRow)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Set Tempo\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(!m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\tTEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0);\n\t\t\t\t\tif ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Tempo Slide\n\t\t\t\t\t\tTEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);\n\t\t\t\t\t\tif ((tempo.GetInt() & 0xF0) == 0x10)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nMusicTempo += tempoDiff;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(tempoDiff < playState.m_nMusicTempo)\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo -= tempoDiff;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo.Set(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tTEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();\n\t\t\t\t\tif(m_playBehaviour[kTempoClamp])\t// clamp tempo correctly in compatible mode\n\t\t\t\t\t{\n\t\t\t\t\t\ttempoMax.Set(255);\n\t\t\t\t\t}\n\t\t\t\t\tLimit(playState.m_nMusicTempo, tempoMin, tempoMax);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x90:\n\t\t\t\t\tif(param <= 0x91)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->dwFlags.set(CHN_SURROUND, param == 0x91);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xA0:\n\t\t\t\t\t// High sample offset\n\t\t\t\t\tpChn->nOldHiOffset = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\tcase 0xB0:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tCHANNELINDEX firstChn = nChn, lastChn = nChn;\n\t\t\t\t\t\tif(GetType() == MOD_TYPE_S3M)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// ST3 has only one global loop memory.\n\t\t\t\t\t\t\tfirstChn = 0;\n\t\t\t\t\t\t\tlastChn = GetNumChannels() - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor(CHANNELINDEX c = firstChn; c <= lastChn; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopStart = playState.m_nRow;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x60:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_XFINEPORTAUPDOWN:\n\t\t\t\t// ignore high offset in compatible mode\n\t\t\t\tif(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// The following calculations are not interesting if we just want to get the song length.\n\t\t\tif (!(adjustMode & eAdjust)) continue;\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Portamento Up/Down\n\t\t\tcase CMD_PORTAMENTOUP:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PORTAMENTODOWN:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Tone-Portamento\n\t\t\tcase CMD_TONEPORTAMENTO:\n\t\t\t\tif (param) pChn->nPortamentoSlide = param << 2;\n\t\t\t\tbreak;\n\t\t\t// Offset\n\t\t\tcase CMD_OFFSET:\n\t\t\t\tif (param) pChn->oldOffset = param << 8;\n\t\t\t\tbreak;\n\t\t\t// Volume Slide\n\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tbreak;\n\t\t\t// Set Volume\n\t\t\tcase CMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = param;\n\t\t\t\tbreak;\n\t\t\t// Global Volume\n\t\t\tcase CMD_GLOBALVOLUME:\n\t\t\t\tif(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2;\n\t\t\t\t// IT compatibility 16. ST3 and IT ignore out-of-range values\n\t\t\t\tif(param <= 128)\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = param * 2;\n\t\t\t\t} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = 256;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Global Volume Slide\n\t\t\tcase CMD_GLOBALVOLSLIDE:\n\t\t\t\tif(m_playBehaviour[kPerChannelGlobalVolSlide])\n\t\t\t\t{\n\t\t\t\t\t// IT compatibility 16. Global volume slide params are stored per channel (FT2/IT)\n\t\t\t\t\tif (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide;\n\t\t\t\t}\n\t\t\t\tif (((param & 0x0F) == 0x0F) && (param & 0xF0))\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param << 1;\n\t\t\t\t} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param;\n\t\t\t\t} else if (param & 0xF0)\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tparam <<= 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param * nonRowTicks;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param * nonRowTicks;\n\t\t\t\t}\n\t\t\t\tLimit(playState.m_nGlobalVolume, 0, 256);\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLUME:\n\t\t\t\tif (param <= 64) pChn->nGlobalVol = param;\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLSLIDE:\n\t\t\t\t{\n\t\t\t\t\tif (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;\n\t\t\t\t\tint32 volume = pChn->nGlobalVol;\n\t\t\t\t\tif((param & 0x0F) == 0x0F && (param & 0xF0))\n\t\t\t\t\t\tvolume += (param >> 4);\t\t// Fine Up\n\t\t\t\t\telse if((param & 0xF0) == 0xF0 && (param & 0x0F))\n\t\t\t\t\t\tvolume -= (param & 0x0F);\t// Fine Down\n\t\t\t\t\telse if(param & 0x0F)\t\t\t// Down\n\t\t\t\t\t\tvolume -= (param & 0x0F) * nonRowTicks;\n\t\t\t\t\telse\t\t\t\t\t\t\t// Up\n\t\t\t\t\t\tvolume += ((param & 0xF0) >> 4) * nonRowTicks;\n\t\t\t\t\tLimit(volume, 0, 64);\n\t\t\t\t\tpChn->nGlobalVol = volume;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANNING8:\n\t\t\t\tPanning(pChn, param, Pan8bit);\n\t\t\t\tbreak;\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif(param < 0x10)\n\t\t\t\t{\n\t\t\t\t\t// LED filter\n\t\t\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((param & 0xF0) == 0x80)\n\t\t\t\t{\n\t\t\t\t\tPanning(pChn, (param & 0x0F), Pan4bit);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tparam = 0;\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_VIBRATO:\n\t\t\t\tVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\t\tFineVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tTremolo(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tPanbrello(pChn, param);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_PANNING:\n\t\t\t\tPanning(pChn, pChn->rowCommand.vol, Pan6bit);\n\t\t\t\tbreak;\n\n\t\t\tcase VOLCMD_VIBRATOSPEED:\n\t\t\t\t// FT2 does not automatically enable vibrato with the \"set vibrato speed\" command\n\t\t\t\tif(m_playBehaviour[kFT2VolColVibrato])\n\t\t\t\t\tpChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;\n\t\t\t\telse\n\t\t\t\t\tVibrato(pChn, pChn->rowCommand.vol << 4);\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VIBRATODEPTH:\n\t\t\t\tVibrato(pChn, pChn->rowCommand.vol);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Process vibrato / tremolo / panbrello\n\t\t\tswitch(pChn->rowCommand.command)\n\t\t\t{\n\t\t\tcase CMD_VIBRATO:\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nVibratoSpeed * vibTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nVibratoPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nTremoloSpeed * tremTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nTremoloPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\t// Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row\n\t\t\t\t\tpChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1));\n\t\t\t\t\tProcessPanbrello(pChn);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Interpret F00 effect in XM files as \"stop song\"\n\t\tif(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tplayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;\n\t\tif(Patterns[playState.m_nPattern].GetOverrideSignature())\n\t\t{\n\t\t\tplayState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat();\n\t\t}\n\n\t\tconst uint32 tickDuration = GetTickDuration(playState);\n\t\tconst uint32 rowDuration = tickDuration * numTicks;\n\t\tmemory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq);\n\t\tplayState.m_lTotalSampleCount += rowDuration;\n\n\t\tif(adjustSamplePos)\n\t\t{\n\t\t\t// Super experimental and dirty sample seeking\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)\n\t\t\t{\n\t\t\t\tif(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tuint32 startTick = 0;\n\t\t\t\tconst ModCommand &m = pChn->rowCommand;\n\t\t\t\tuint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;\n\t\t\t\tbool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;\n\t\t\t\tbool stopNote = patternLoopStartedOnThisRow;\t// It's too much trouble to keep those pattern loops in sync...\n\n\t\t\t\tif(m.instr) pChn->proTrackerOffset = 0;\n\t\t\t\tif(m.IsNote())\n\t\t\t\t{\n\t\t\t\t\tif(porta && memory.chnSettings[nChn].incChanged)\n\t\t\t\t\t{\n\t\t\t\t\t\t// If there's a portamento, the current channel increment mustn't be 0 in NoteChange()\n\t\t\t\t\t\tpChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0);\n\t\t\t\t\t}\n\t\t\t\t\tint32 setPan = pChn->nPan;\n\t\t\t\t\tpChn->nNewNote = pChn->nLastNote;\n\t\t\t\t\tif(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);\n\t\t\t\t\tNoteChange(pChn, m.note, porta);\n\t\t\t\t\tmemory.chnSettings[nChn].incChanged = true;\n\n\t\t\t\t\tif((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramLo;\n\t\t\t\t\t} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramHi;\n\t\t\t\t\t}\n\t\t\t\t\tif(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1);\n\t\t\t\t\t}\n\t\t\t\t\tif(!porta) memory.chnSettings[nChn].ticksToRender = 0;\n\n\t\t\t\t\t// Panning commands have to be re-applied after a note change with potential pan change.\n\t\t\t\t\tif(m.command == CMD_PANNING8\n\t\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)\n\t\t\t\t\t\t|| m.volcmd == VOLCMD_PANNING)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->nPan = setPan;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.command == CMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tbool isExtended = false;\n\t\t\t\t\t\tSmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended);\n\t\t\t\t\t\tif(!isExtended)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toffset <<= 8;\n\t\t\t\t\t\t\tif(offset == 0) offset = pChn->oldOffset;\n\t\t\t\t\t\t\toffset += static_cast(pChn->nOldHiOffset) << 16;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t} else if(m.command == CMD_OFFSETPERCENTAGE)\n\t\t\t\t\t{\n\t\t\t\t\t\tSampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255));\n\t\t\t\t\t} else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\tReverseSampleOffset(*pChn, m.param);\n\t\t\t\t\t\tstartTick = playState.m_nMusicSpeed - 1;\n\t\t\t\t\t} else if(m.volcmd == VOLCMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSmpLength offset;\n\t\t\t\t\t\t\tif(m.vol == 0)\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];\n\t\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)\n\t\t\t\t\t|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))\n\t\t\t\t{\n\t\t\t\t\tstopNote = true;\n\t\t\t\t}\n\n\t\t\t\tif(m.command == CMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.param * 4;\n\t\t\t\t} else if(m.volcmd == VOLCMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.vol * 4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(pChn->pModSample && !stopNote)\n\t\t\t\t{\n\t\t\t\t\t// Check if we don't want to emulate some effect and thus stop processing.\n\t\t\t\t\tif(m.command < MAX_EFFECTS)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(forbiddenCommands[m.command])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t} else if(m.command == CMD_MODCMDEX)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Special case: Slides using extended commands\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd])\n\t\t\t\t\t{\n\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(stopNote)\n\t\t\t\t{\n\t\t\t\t\tpChn->Stop();\n\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender = 0;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif(oldTickDuration != tickDuration && oldTickDuration != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch(m.command)\n\t\t\t\t\t{\n\t\t\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\t\t\tif(m.param || (GetType() != MOD_TYPE_MOD))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, m.param);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_MODCMDEX:\n\t\t\t\t\t\tif((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\tcase 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\t\t\tif(m.param == 0x9E)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Play forward\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.reset(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t} else if(m.param == 0x9F)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Reverse\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.set(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t\tif(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if((m.param & 0xF0) == 0x70)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t//ExtendedS3MCommands(nChn, param);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\tswitch(m.volcmd)\n\t\t\t\t\t{\n\t\t\t\t\tcase VOLCMD_FINEVOLUP:\t\tFineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_FINEVOLDOWN:\tFineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// IT Compatibility: Volume column volume slides have their own memory\n\t\t\t\t\t\t\t// Test case: VolColMemory.it\n\t\t\t\t\t\t\tModCommand::VOL vol = m.vol;\n\t\t\t\t\t\t\tif(vol == 0 && m_playBehaviour[kITVolColMemory])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvol = pChn->nOldVolParam;\n\t\t\t\t\t\t\t\tif(vol == 0)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(m.volcmd == VOLCMD_VOLSLIDEUP)\n\t\t\t\t\t\t\t\tvol <<= 4;\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, vol);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(porta)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Portamento needs immediate syncing, as the pitch changes on each tick\n\t\t\t\t\t\tuint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += numTicks;\n\t\t\t\t\t\tmemory.RenderChannel(nChn, tickDuration, portaTick);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += (numTicks - startTick);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toldTickDuration = tickDuration;\n\n\t\t// Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row.\n\t\t// Pattern loop is not executed in IT if there are any position jump commands on the same row.\n\t\t// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm\n\t\t// Test case for IT: exception: LoopBreak.it\n\t\tif(patternLoopEndedOnThisRow\n\t\t\t&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))\n\t\t\t&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))\n\t\t{\n\t\t\tstd::map startTimes;\n\t\t\t// This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row.\n\t\t\t// If one of them starts or ends \"in between\", it will most likely calculate a wrong duration.\n\t\t\t// For S3M files, it's also way off.\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t{\n\t\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\t\tif((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)\n\t\t\t\t\t|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))\n\t\t\t\t{\n\t\t\t\t\tconst double start = memory.chnSettings[nChn].patLoop;\n\t\t\t\t\tif(!startTimes[start]) startTimes[start] = 1;\n\t\t\t\t\tstartTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(const auto &i : startTimes)\n\t\t\t{\n\t\t\t\tmemory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1);\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t\t{\n\t\t\t\t\tif(memory.chnSettings[nChn].patLoop == i.first)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1);\n\t\t\t\t\t\tif(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(GetType() == MOD_TYPE_IT)\n\t\t\t{\n\t\t\t\t// IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0)\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t\t\t{\n\t\t\t\t\tif((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now advance the sample positions for sample seeking on channels that are still playing\n\tif(adjustSamplePos)\n\t{\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t{\n\t\t\tif(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t{\n\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t{\n\t\tretval.lastOrder = playState.m_nCurrentOrder;\n\t\tretval.lastRow = playState.m_nRow;\n\t}\n\tretval.duration = memory.elapsedTime;\n\tresults.push_back(retval);\n\n\t// Store final variables\n\tif(adjustMode & eAdjust)\n\t{\n\t\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t\t{\n\t\t\t// Target found, or there is no target (i.e. play whole song)...\n\t\t\tm_PlayState = std::move(playState);\n\t\t\tm_PlayState.m_nNextRow = m_PlayState.m_nRow;\n\t\t\tm_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;\n\t\t\tm_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;\n\t\t\tm_PlayState.m_bPositionChanged = true;\n\t\t\tfor(CHANNELINDEX n = 0; n < GetNumChannels(); n++)\n\t\t\t{\n\t\t\t\tif(m_PlayState.Chn[n].nLastNote != NOTE_NONE)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote;\n\t\t\t\t}\n\t\t\t\tif(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4;\n\t\t\t\t}\n\t\t\t}\n\n#ifndef NO_PLUGINS\n\t\t\t// If there were any PC events, update plugin parameters to their latest value.\n\t\t\tstd::bitset plugSetProgram;\n\t\t\tfor(const auto ¶m : memory.plugParams)\n\t\t\t{\n\t\t\t\tPLUGINDEX plug = param.first.first - 1;\n\t\t\t\tIMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;\n\t\t\t\tif(plugin != nullptr)\n\t\t\t\t{\n\t\t\t\t\tif(!plugSetProgram[plug])\n\t\t\t\t\t{\n\t\t\t\t\t\t// Used for bridged plugins to avoid sending out individual messages for each parameter.\n\t\t\t\t\t\tplugSetProgram.set(plug);\n\t\t\t\t\t\tplugin->BeginSetProgram();\n\t\t\t\t\t}\n\t\t\t\t\tplugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(plugSetProgram.any())\n\t\t\t{\n\t\t\t\tfor(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)\n\t\t\t\t{\n\t\t\t\t\tif(plugSetProgram[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tm_MixPlugins[i].pMixPlugin->EndSetProgram();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#endif // NO_PLUGINS\n\t\t} else if(adjustMode != eAdjustOnSuccess)\n\t\t{\n\t\t\t// Target not found (e.g. when jumping to a hidden sub song), reset global variables...\n\t\t\tm_PlayState.m_nMusicSpeed = m_nDefaultSpeed;\n\t\t\tm_PlayState.m_nMusicTempo = m_nDefaultTempo;\n\t\t\tm_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;\n\t\t}\n\t\t// When adjusting the playback status, we will also want to update the visited rows vector according to the current position.\n\t\tif(sequence != Order.GetCurrentSequenceIndex())\n\t\t{\n\t\t\tOrder.SetSequence(sequence);\n\t\t}\n\t\tvisitedSongRows.Set(visitedRows);\n\t}\n\n\treturn results;\n\n}", "func_hash": 36412420505433519515927473229886569852, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2018-10017", "cve_desc": "soundlib/Snd_fx.cpp in OpenMPT before 1.27.07.00 and libopenmpt before 0.3.8 allows remote attackers to cause a denial of service (out-of-bounds read) via an IT or MO3 file with many nested pattern loops.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-10017"} {"idx": 255181, "project": "openmpt", "commit_id": "7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c", "project_url": "https://github.com/OpenMPT/openmpt", "commit_url": "https://github.com/OpenMPT/openmpt/commit/7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c", "commit_message": "[Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz.\n\ngit-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27", "target": 0, "func": "std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)\n{\n\tstd::vector results;\n\tGetLengthType retval;\n\tretval.startOrder = target.startOrder;\n\tretval.startRow = target.startRow;\n\n\t// Are we trying to reach a certain pattern position?\n\tconst bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;\n\tconst bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;\n\n\tSEQUENCEINDEX sequence = target.sequence;\n\tif(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();\n\tconst ModSequence &orderList = Order(sequence);\n\n\tGetLengthMemory memory(*this);\n\tCSoundFile::PlayState &playState = *memory.state;\n\t// Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time)\n\tRowVisitor visitedRows(*this, sequence);\n\n\tplayState.m_nNextRow = playState.m_nRow = target.startRow;\n\tplayState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder;\n\n\t// Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode.\n\tstd::bitset forbiddenCommands;\n\tstd::bitset forbiddenVolCommands;\n\n\tif(adjustSamplePos)\n\t{\n\t\tforbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);\n\t\tforbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);\n\t\tforbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);\n\n\t\t// Optimize away channels for which it's pointless to adjust sample positions\n\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++)\n\t\t{\n\t\t\tif(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t}\n\t\tif(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size())\n\t\t{\n\t\t\t// If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start.\n\t\t\tconst PATTERNINDEX seekPat = orderList[target.pos.order];\n\t\t\tif(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))\n\t\t\t{\n\t\t\t\tconst ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);\n\t\t\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)\n\t\t\t\t{\n\t\t\t\t\tif(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t\t|| (m->IsNote() && !m->IsPortamento()))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If samples are being synced, force them to resync if tick duration changes\n\tuint32 oldTickDuration = 0;\n\n\tfor (;;)\n\t{\n\t\t// Time target reached.\n\t\tif(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tuint32 rowDelay = 0, tickDelay = 0;\n\t\tplayState.m_nRow = playState.m_nNextRow;\n\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\n\t\tif(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t\tif(m_playBehaviour[kFT2LoopE60Restart])\n\t\t\t{\n\t\t\t\tplayState.m_nRow = playState.m_nNextPatStartRow;\n\t\t\t\tplayState.m_nNextPatStartRow = 0;\n\t\t\t}\n\t\t\tplayState.m_nCurrentOrder = ++playState.m_nNextOrder;\n\t\t}\n\n\t\t// Check if pattern is valid\n\t\tplayState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\tbool positionJumpOnThisRow = false;\n\t\tbool patternBreakOnThisRow = false;\n\t\tbool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;\n\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order)\n\t\t{\n\t\t\t// Early test: Target is inside +++ or non-existing pattern\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\twhile(playState.m_nPattern >= Patterns.Size())\n\t\t{\n\t\t\t// End of song?\n\t\t\tif((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size()))\n\t\t\t{\n\t\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\tplayState.m_nCurrentOrder = orderList.GetRestartPos();\n\t\t\t} else\n\t\t\t{\n\t\t\t\tplayState.m_nCurrentOrder++;\n\t\t\t}\n\t\t\tplayState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder;\n\t\t\tif((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true))\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\n\t\t\t\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\t\t\t\t\tplayState.m_nPattern = orderList[playState.m_nCurrentOrder];\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(playState.m_nNextOrder == ORDERINDEX_INVALID)\n\t\t{\n\t\t\t// GetFirstUnvisitedRow failed, so there is nothing more to play\n\t\t\tbreak;\n\t\t}\n\n\t\t// Skip non-existing patterns\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern))\n\t\t{\n\t\t\t// If there isn't even a tune, we should probably stop here.\n\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\tcontinue;\n\t\t}\n\t\t// Should never happen\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t\tplayState.m_nRow = 0;\n\n\t\t// Check whether target was reached.\n\t\tif(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true))\n\t\t{\n\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t{\n\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\t{\n\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\tresults.push_back(retval);\n\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\tmemory.Reset();\n\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tretval.endOrder = playState.m_nCurrentOrder;\n\t\tretval.endRow = playState.m_nRow;\n\n\t\t// Update next position\n\t\tplayState.m_nNextRow = playState.m_nRow + 1;\n\n\t\t// Jumped to invalid pattern row?\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t}\n\t\t// New pattern?\n\t\tif(!playState.m_nRow)\n\t\t{\n\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t{\n\t\t\t\tmemory.chnSettings[chn].patLoop = memory.elapsedTime;\n\t\t\t\tmemory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t}\n\t\t}\n\n\t\tModChannel *pChn = playState.Chn;\n\t\t\n\t\t// For various effects, we need to know first how many ticks there are in this row.\n\t\tconst ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0);\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tif(p->IsPcNote())\n\t\t\t{\n#ifndef NO_PLUGINS\n\t\t\t\tif((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)\n\t\t\t\t{\n\t\t\t\t\tmemory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();\n\t\t\t\t}\n#endif // NO_PLUGINS\n\t\t\t\tpChn[nChn].rowCommand.Clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpChn[nChn].rowCommand = *p;\n\t\t\tswitch(p->command)\n\t\t\t{\n\t\t\tcase CMD_SPEED:\n\t\t\t\tSetSpeed(playState, p->param);\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\t// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.\n\t\t\t\t\tif(p->param != 0) SetSpeed(playState, p->param);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0x60)\n\t\t\t\t{\n\t\t\t\t\t// Fine Pattern Delay\n\t\t\t\t\ttickDelay += (p->param & 0x0F);\n\t\t\t\t} else if((p->param & 0xF0) == 0xE0 && !rowDelay)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\tif(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),\n\t\t\t\t\t\t// Scream Tracker 3 simply ignores such commands.\n\t\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0xE0)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(rowDelay == 0) rowDelay = 1;\n\t\tconst uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay;\n\t\tconst uint32 nonRowTicks = numTicks - rowDelay;\n\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\tModCommand::NOTE note = pChn->rowCommand.note;\n\n\t\t\tif (pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tpChn->nNewIns = pChn->rowCommand.instr;\n\t\t\t\tpChn->nLastNote = NOTE_NONE;\n\t\t\t\tmemory.chnSettings[nChn].vol = 0xFF;\n\t\t\t}\n\t\t\tif (pChn->rowCommand.IsNote()) pChn->nLastNote = note;\n\n\t\t\t// Update channel panning\n\t\t\tif(pChn->rowCommand.IsNote() || pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tSAMPLEINDEX smp = 0;\n\t\t\t\tif(GetNumInstruments())\n\t\t\t\t{\n\t\t\t\t\tModInstrument *pIns;\n\t\t\t\t\tif(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(pIns->dwFlags[INS_SETPANNING])\n\t\t\t\t\t\t\tpChn->nPan = pIns->nPan;\n\t\t\t\t\t\tif(ModCommand::IsNote(note))\n\t\t\t\t\t\t\tsmp = pIns->Keyboard[note - NOTE_MIN];\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tsmp = pChn->nNewIns;\n\t\t\t\t}\n\t\t\t\tif(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING])\n\t\t\t\t{\n\t\t\t\t\tpChn->nPan = Samples[smp].nPan;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\tif(pChn->rowCommand.vol != 0)\n\t\t\t\t\tpChn->nOldVolParam = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Position Jump\n\t\t\tcase CMD_POSITIONJUMP:\n\t\t\t\tpositionJumpOnThisRow = true;\n\t\t\t\tplayState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn));\n\t\t\t\tplayState.m_nNextPatStartRow = 0; // FT2 E60 bug\n\t\t\t\t// see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx\n\t\t\t\t// Test case: PatternJump.mod\n\t\t\t\tif(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))\n\t\t\t\t\tplayState.m_nNextRow = 0;\n\n\t\t\t\tif (adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Pattern Break\n\t\t\tcase CMD_PATTERNBREAK:\n\t\t\t\t{\n\t\t\t\t\tROWINDEX row = PatternBreak(playState, nChn, param);\n\t\t\t\t\tif(row != ROWINDEX_INVALID)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternBreakOnThisRow = true;\n\t\t\t\t\t\tplayState.m_nNextRow = row;\n\n\t\t\t\t\t\tif(!positionJumpOnThisRow)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Set Tempo\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(!m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\tTEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0);\n\t\t\t\t\tif ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Tempo Slide\n\t\t\t\t\t\tTEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);\n\t\t\t\t\t\tif ((tempo.GetInt() & 0xF0) == 0x10)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nMusicTempo += tempoDiff;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(tempoDiff < playState.m_nMusicTempo)\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo -= tempoDiff;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo.Set(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tTEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();\n\t\t\t\t\tif(m_playBehaviour[kTempoClamp])\t// clamp tempo correctly in compatible mode\n\t\t\t\t\t{\n\t\t\t\t\t\ttempoMax.Set(255);\n\t\t\t\t\t}\n\t\t\t\t\tLimit(playState.m_nMusicTempo, tempoMin, tempoMax);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x90:\n\t\t\t\t\tif(param <= 0x91)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->dwFlags.set(CHN_SURROUND, param == 0x91);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xA0:\n\t\t\t\t\t// High sample offset\n\t\t\t\t\tpChn->nOldHiOffset = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\tcase 0xB0:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tCHANNELINDEX firstChn = nChn, lastChn = nChn;\n\t\t\t\t\t\tif(GetType() == MOD_TYPE_S3M)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// ST3 has only one global loop memory.\n\t\t\t\t\t\t\tfirstChn = 0;\n\t\t\t\t\t\t\tlastChn = GetNumChannels() - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor(CHANNELINDEX c = firstChn; c <= lastChn; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopStart = playState.m_nRow;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x60:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_XFINEPORTAUPDOWN:\n\t\t\t\t// ignore high offset in compatible mode\n\t\t\t\tif(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// The following calculations are not interesting if we just want to get the song length.\n\t\t\tif (!(adjustMode & eAdjust)) continue;\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Portamento Up/Down\n\t\t\tcase CMD_PORTAMENTOUP:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PORTAMENTODOWN:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Tone-Portamento\n\t\t\tcase CMD_TONEPORTAMENTO:\n\t\t\t\tif (param) pChn->nPortamentoSlide = param << 2;\n\t\t\t\tbreak;\n\t\t\t// Offset\n\t\t\tcase CMD_OFFSET:\n\t\t\t\tif (param) pChn->oldOffset = param << 8;\n\t\t\t\tbreak;\n\t\t\t// Volume Slide\n\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tbreak;\n\t\t\t// Set Volume\n\t\t\tcase CMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = param;\n\t\t\t\tbreak;\n\t\t\t// Global Volume\n\t\t\tcase CMD_GLOBALVOLUME:\n\t\t\t\tif(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2;\n\t\t\t\t// IT compatibility 16. ST3 and IT ignore out-of-range values\n\t\t\t\tif(param <= 128)\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = param * 2;\n\t\t\t\t} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = 256;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Global Volume Slide\n\t\t\tcase CMD_GLOBALVOLSLIDE:\n\t\t\t\tif(m_playBehaviour[kPerChannelGlobalVolSlide])\n\t\t\t\t{\n\t\t\t\t\t// IT compatibility 16. Global volume slide params are stored per channel (FT2/IT)\n\t\t\t\t\tif (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide;\n\t\t\t\t}\n\t\t\t\tif (((param & 0x0F) == 0x0F) && (param & 0xF0))\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param << 1;\n\t\t\t\t} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param;\n\t\t\t\t} else if (param & 0xF0)\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tparam <<= 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param * nonRowTicks;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param * nonRowTicks;\n\t\t\t\t}\n\t\t\t\tLimit(playState.m_nGlobalVolume, 0, 256);\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLUME:\n\t\t\t\tif (param <= 64) pChn->nGlobalVol = param;\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLSLIDE:\n\t\t\t\t{\n\t\t\t\t\tif (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;\n\t\t\t\t\tint32 volume = pChn->nGlobalVol;\n\t\t\t\t\tif((param & 0x0F) == 0x0F && (param & 0xF0))\n\t\t\t\t\t\tvolume += (param >> 4);\t\t// Fine Up\n\t\t\t\t\telse if((param & 0xF0) == 0xF0 && (param & 0x0F))\n\t\t\t\t\t\tvolume -= (param & 0x0F);\t// Fine Down\n\t\t\t\t\telse if(param & 0x0F)\t\t\t// Down\n\t\t\t\t\t\tvolume -= (param & 0x0F) * nonRowTicks;\n\t\t\t\t\telse\t\t\t\t\t\t\t// Up\n\t\t\t\t\t\tvolume += ((param & 0xF0) >> 4) * nonRowTicks;\n\t\t\t\t\tLimit(volume, 0, 64);\n\t\t\t\t\tpChn->nGlobalVol = volume;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANNING8:\n\t\t\t\tPanning(pChn, param, Pan8bit);\n\t\t\t\tbreak;\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif(param < 0x10)\n\t\t\t\t{\n\t\t\t\t\t// LED filter\n\t\t\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((param & 0xF0) == 0x80)\n\t\t\t\t{\n\t\t\t\t\tPanning(pChn, (param & 0x0F), Pan4bit);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tparam = 0;\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_VIBRATO:\n\t\t\t\tVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\t\tFineVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tTremolo(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tPanbrello(pChn, param);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_PANNING:\n\t\t\t\tPanning(pChn, pChn->rowCommand.vol, Pan6bit);\n\t\t\t\tbreak;\n\n\t\t\tcase VOLCMD_VIBRATOSPEED:\n\t\t\t\t// FT2 does not automatically enable vibrato with the \"set vibrato speed\" command\n\t\t\t\tif(m_playBehaviour[kFT2VolColVibrato])\n\t\t\t\t\tpChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;\n\t\t\t\telse\n\t\t\t\t\tVibrato(pChn, pChn->rowCommand.vol << 4);\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VIBRATODEPTH:\n\t\t\t\tVibrato(pChn, pChn->rowCommand.vol);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Process vibrato / tremolo / panbrello\n\t\t\tswitch(pChn->rowCommand.command)\n\t\t\t{\n\t\t\tcase CMD_VIBRATO:\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nVibratoSpeed * vibTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nVibratoPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nTremoloSpeed * tremTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nTremoloPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\t// Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row\n\t\t\t\t\tpChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1));\n\t\t\t\t\tProcessPanbrello(pChn);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Interpret F00 effect in XM files as \"stop song\"\n\t\tif(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tplayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;\n\t\tif(Patterns[playState.m_nPattern].GetOverrideSignature())\n\t\t{\n\t\t\tplayState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat();\n\t\t}\n\n\t\tconst uint32 tickDuration = GetTickDuration(playState);\n\t\tconst uint32 rowDuration = tickDuration * numTicks;\n\t\tmemory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq);\n\t\tplayState.m_lTotalSampleCount += rowDuration;\n\n\t\tif(adjustSamplePos)\n\t\t{\n\t\t\t// Super experimental and dirty sample seeking\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)\n\t\t\t{\n\t\t\t\tif(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tuint32 startTick = 0;\n\t\t\t\tconst ModCommand &m = pChn->rowCommand;\n\t\t\t\tuint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;\n\t\t\t\tbool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;\n\t\t\t\tbool stopNote = patternLoopStartedOnThisRow;\t// It's too much trouble to keep those pattern loops in sync...\n\n\t\t\t\tif(m.instr) pChn->proTrackerOffset = 0;\n\t\t\t\tif(m.IsNote())\n\t\t\t\t{\n\t\t\t\t\tif(porta && memory.chnSettings[nChn].incChanged)\n\t\t\t\t\t{\n\t\t\t\t\t\t// If there's a portamento, the current channel increment mustn't be 0 in NoteChange()\n\t\t\t\t\t\tpChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0);\n\t\t\t\t\t}\n\t\t\t\t\tint32 setPan = pChn->nPan;\n\t\t\t\t\tpChn->nNewNote = pChn->nLastNote;\n\t\t\t\t\tif(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);\n\t\t\t\t\tNoteChange(pChn, m.note, porta);\n\t\t\t\t\tmemory.chnSettings[nChn].incChanged = true;\n\n\t\t\t\t\tif((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramLo;\n\t\t\t\t\t} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramHi;\n\t\t\t\t\t}\n\t\t\t\t\tif(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1);\n\t\t\t\t\t}\n\t\t\t\t\tif(!porta) memory.chnSettings[nChn].ticksToRender = 0;\n\n\t\t\t\t\t// Panning commands have to be re-applied after a note change with potential pan change.\n\t\t\t\t\tif(m.command == CMD_PANNING8\n\t\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)\n\t\t\t\t\t\t|| m.volcmd == VOLCMD_PANNING)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->nPan = setPan;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.command == CMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tbool isExtended = false;\n\t\t\t\t\t\tSmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended);\n\t\t\t\t\t\tif(!isExtended)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toffset <<= 8;\n\t\t\t\t\t\t\tif(offset == 0) offset = pChn->oldOffset;\n\t\t\t\t\t\t\toffset += static_cast(pChn->nOldHiOffset) << 16;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t} else if(m.command == CMD_OFFSETPERCENTAGE)\n\t\t\t\t\t{\n\t\t\t\t\t\tSampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255));\n\t\t\t\t\t} else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\tReverseSampleOffset(*pChn, m.param);\n\t\t\t\t\t\tstartTick = playState.m_nMusicSpeed - 1;\n\t\t\t\t\t} else if(m.volcmd == VOLCMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSmpLength offset;\n\t\t\t\t\t\t\tif(m.vol == 0)\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];\n\t\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)\n\t\t\t\t\t|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))\n\t\t\t\t{\n\t\t\t\t\tstopNote = true;\n\t\t\t\t}\n\n\t\t\t\tif(m.command == CMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.param * 4;\n\t\t\t\t} else if(m.volcmd == VOLCMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.vol * 4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(pChn->pModSample && !stopNote)\n\t\t\t\t{\n\t\t\t\t\t// Check if we don't want to emulate some effect and thus stop processing.\n\t\t\t\t\tif(m.command < MAX_EFFECTS)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(forbiddenCommands[m.command])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t} else if(m.command == CMD_MODCMDEX)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Special case: Slides using extended commands\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd])\n\t\t\t\t\t{\n\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(stopNote)\n\t\t\t\t{\n\t\t\t\t\tpChn->Stop();\n\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender = 0;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif(oldTickDuration != tickDuration && oldTickDuration != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch(m.command)\n\t\t\t\t\t{\n\t\t\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\t\t\tif(m.param || (GetType() != MOD_TYPE_MOD))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, m.param);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_MODCMDEX:\n\t\t\t\t\t\tif((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\tcase 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\t\t\tif(m.param == 0x9E)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Play forward\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.reset(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t} else if(m.param == 0x9F)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Reverse\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.set(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t\tif(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if((m.param & 0xF0) == 0x70)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t//ExtendedS3MCommands(nChn, param);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\tswitch(m.volcmd)\n\t\t\t\t\t{\n\t\t\t\t\tcase VOLCMD_FINEVOLUP:\t\tFineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_FINEVOLDOWN:\tFineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// IT Compatibility: Volume column volume slides have their own memory\n\t\t\t\t\t\t\t// Test case: VolColMemory.it\n\t\t\t\t\t\t\tModCommand::VOL vol = m.vol;\n\t\t\t\t\t\t\tif(vol == 0 && m_playBehaviour[kITVolColMemory])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvol = pChn->nOldVolParam;\n\t\t\t\t\t\t\t\tif(vol == 0)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(m.volcmd == VOLCMD_VOLSLIDEUP)\n\t\t\t\t\t\t\t\tvol <<= 4;\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, vol);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(porta)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Portamento needs immediate syncing, as the pitch changes on each tick\n\t\t\t\t\t\tuint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += numTicks;\n\t\t\t\t\t\tmemory.RenderChannel(nChn, tickDuration, portaTick);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += (numTicks - startTick);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toldTickDuration = tickDuration;\n\n\t\t// Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row.\n\t\t// Pattern loop is not executed in IT if there are any position jump commands on the same row.\n\t\t// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm\n\t\t// Test case for IT: exception: LoopBreak.it\n\t\tif(patternLoopEndedOnThisRow\n\t\t\t&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))\n\t\t\t&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))\n\t\t{\n\t\t\tstd::map startTimes;\n\t\t\t// This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row.\n\t\t\t// If one of them starts or ends \"in between\", it will most likely calculate a wrong duration.\n\t\t\t// For S3M files, it's also way off.\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t{\n\t\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\t\tif((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)\n\t\t\t\t\t|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))\n\t\t\t\t{\n\t\t\t\t\tconst double start = memory.chnSettings[nChn].patLoop;\n\t\t\t\t\tif(!startTimes[start]) startTimes[start] = 1;\n\t\t\t\t\tstartTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(const auto &i : startTimes)\n\t\t\t{\n\t\t\t\tmemory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1);\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t\t{\n\t\t\t\t\tif(memory.chnSettings[nChn].patLoop == i.first)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1);\n\t\t\t\t\t\tif(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(GetType() == MOD_TYPE_IT)\n\t\t\t{\n\t\t\t\t// IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0)\n\t\t\t\tpChn = playState.Chn;\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t\t{\n\t\t\t\t\tif((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now advance the sample positions for sample seeking on channels that are still playing\n\tif(adjustSamplePos)\n\t{\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t{\n\t\t\tif(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t{\n\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t{\n\t\tretval.lastOrder = playState.m_nCurrentOrder;\n\t\tretval.lastRow = playState.m_nRow;\n\t}\n\tretval.duration = memory.elapsedTime;\n\tresults.push_back(retval);\n\n\t// Store final variables\n\tif(adjustMode & eAdjust)\n\t{\n\t\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t\t{\n\t\t\t// Target found, or there is no target (i.e. play whole song)...\n\t\t\tm_PlayState = std::move(playState);\n\t\t\tm_PlayState.m_nNextRow = m_PlayState.m_nRow;\n\t\t\tm_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;\n\t\t\tm_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;\n\t\t\tm_PlayState.m_bPositionChanged = true;\n\t\t\tfor(CHANNELINDEX n = 0; n < GetNumChannels(); n++)\n\t\t\t{\n\t\t\t\tif(m_PlayState.Chn[n].nLastNote != NOTE_NONE)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote;\n\t\t\t\t}\n\t\t\t\tif(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4;\n\t\t\t\t}\n\t\t\t}\n\n#ifndef NO_PLUGINS\n\t\t\t// If there were any PC events, update plugin parameters to their latest value.\n\t\t\tstd::bitset plugSetProgram;\n\t\t\tfor(const auto ¶m : memory.plugParams)\n\t\t\t{\n\t\t\t\tPLUGINDEX plug = param.first.first - 1;\n\t\t\t\tIMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;\n\t\t\t\tif(plugin != nullptr)\n\t\t\t\t{\n\t\t\t\t\tif(!plugSetProgram[plug])\n\t\t\t\t\t{\n\t\t\t\t\t\t// Used for bridged plugins to avoid sending out individual messages for each parameter.\n\t\t\t\t\t\tplugSetProgram.set(plug);\n\t\t\t\t\t\tplugin->BeginSetProgram();\n\t\t\t\t\t}\n\t\t\t\t\tplugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(plugSetProgram.any())\n\t\t\t{\n\t\t\t\tfor(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)\n\t\t\t\t{\n\t\t\t\t\tif(plugSetProgram[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tm_MixPlugins[i].pMixPlugin->EndSetProgram();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#endif // NO_PLUGINS\n\t\t} else if(adjustMode != eAdjustOnSuccess)\n\t\t{\n\t\t\t// Target not found (e.g. when jumping to a hidden sub song), reset global variables...\n\t\t\tm_PlayState.m_nMusicSpeed = m_nDefaultSpeed;\n\t\t\tm_PlayState.m_nMusicTempo = m_nDefaultTempo;\n\t\t\tm_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;\n\t\t}\n\t\t// When adjusting the playback status, we will also want to update the visited rows vector according to the current position.\n\t\tif(sequence != Order.GetCurrentSequenceIndex())\n\t\t{\n\t\t\tOrder.SetSequence(sequence);\n\t\t}\n\t\tvisitedSongRows.Set(visitedRows);\n\t}\n\n\treturn results;\n\n}", "func_hash": 69324091200318539203706793155024173964, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2018-10017", "cve_desc": "soundlib/Snd_fx.cpp in OpenMPT before 1.27.07.00 and libopenmpt before 0.3.8 allows remote attackers to cause a denial of service (out-of-bounds read) via an IT or MO3 file with many nested pattern loops.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-10017"} {"idx": 197204, "project": "nanopb", "commit_id": "7b396821ddd06df8e39143f16e1dc0a4645b89a3", "project_url": "https://github.com/nanopb/nanopb", "commit_url": "https://github.com/nanopb/nanopb/commit/7b396821ddd06df8e39143f16e1dc0a4645b89a3", "commit_message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 1, "func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n UNUSED(wire_type);\n UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n size_t *size = (size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if (*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n (*size)++;\n }\n pb_close_string_substream(stream, &substream);\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n size_t *size = (size_t*)iter->pSize;\n void *pItem;\n \n (*size)++;\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))\n return false;\n \n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size - 1);\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n \n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "func_hash": 136851498746232944091397559952935912126, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-5235", "cve_desc": "There is a potentially exploitable out of memory condition In Nanopb before 0.4.1, 0.3.9.5, and 0.2.9.4. When nanopb is compiled with PB_ENABLE_MALLOC, the message to be decoded contains a repeated string, bytes or message field and realloc() runs out of memory when expanding the array nanopb can end up calling `free()` on a pointer value that comes from uninitialized memory. Depending on platform this can result in a crash or further memory corruption, which may be exploitable in some cases. This problem is fixed in nanopb-0.4.1, nanopb-0.3.9.5, nanopb-0.2.9.4.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-5235"} {"idx": 255326, "project": "nanopb", "commit_id": "7b396821ddd06df8e39143f16e1dc0a4645b89a3", "project_url": "https://github.com/nanopb/nanopb", "commit_url": "https://github.com/nanopb/nanopb/commit/7b396821ddd06df8e39143f16e1dc0a4645b89a3", "commit_message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 0, "func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n UNUSED(wire_type);\n UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n size_t *size = (size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if (*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n (*size)++;\n }\n pb_close_string_substream(stream, &substream);\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n size_t *size = (size_t*)iter->pSize;\n void *pItem;\n \n if (!allocate_field(stream, iter->pData, iter->pos->data_size, (size_t)(*size + 1)))\n return false;\n \n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);\n (*size)++;\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n \n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "func_hash": 168106183763787560906347934656413621072, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-5235", "cve_desc": "There is a potentially exploitable out of memory condition In Nanopb before 0.4.1, 0.3.9.5, and 0.2.9.4. When nanopb is compiled with PB_ENABLE_MALLOC, the message to be decoded contains a repeated string, bytes or message field and realloc() runs out of memory when expanding the array nanopb can end up calling `free()` on a pointer value that comes from uninitialized memory. Depending on platform this can result in a crash or further memory corruption, which may be exploitable in some cases. This problem is fixed in nanopb-0.4.1, nanopb-0.3.9.5, nanopb-0.2.9.4.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-5235"} {"idx": 197240, "project": "gpac", "commit_id": "da69ad1f970a7e17c865eaec9af98cc84df10d5b", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/da69ad1f970a7e17c865eaec9af98cc84df10d5b", "commit_message": "fixed 1718", "target": 1, "func": "GF_Err flac_dmx_process(GF_Filter *filter)\n{\n\tGF_FLACDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu8 *output;\n\tu8 *start;\n\tBool final_flush=GF_FALSE;\n\tu32 pck_size, remain, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\tFLACHeader hdr;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tflac_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t\tfinal_flush = GF_TRUE;\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t}\n\n\tprev_pck_size = ctx->flac_buffer_size;\n\tif (pck && !ctx->resume_from) {\n\t\tu8 *data = (u8 *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\tu64 byte_offset = gf_filter_pck_get_byte_offset(pck);\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tctx->byte_offset = byte_offset;\n\t\t\t} else if (ctx->byte_offset + ctx->flac_buffer_size != byte_offset) {\n\t\t\t\tctx->byte_offset = GF_FILTER_NO_BO;\n\t\t\t\tif ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->flac_buffer_size) ) {\n\t\t\t\t\tctx->byte_offset = byte_offset - ctx->flac_buffer_size;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->flac_buffer_size + pck_size > ctx->flac_buffer_alloc) {\n\t\t\tctx->flac_buffer_alloc = ctx->flac_buffer_size + pck_size;\n\t\t\tctx->flac_buffer = gf_realloc(ctx->flac_buffer, ctx->flac_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->flac_buffer + ctx->flac_buffer_size, data, pck_size);\n\t\tctx->flac_buffer_size += pck_size;\n\t}\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tif (cts == GF_FILTER_NO_TS) {\n\t\t//avoids updating cts\n\t\tprev_pck_size = 0;\n\t}\n\n\tremain = ctx->flac_buffer_size;\n\tstart = ctx->flac_buffer;\n\n\tif (ctx->resume_from) {\n\t\tstart += ctx->resume_from - 1;\n\t\tremain -= ctx->resume_from - 1;\n\t\tctx->resume_from = 0;\n\t}\n\n\twhile (remain>2) {\n\t\tu32 next_frame=0, nb_samp;\n\t\tu32 cur_size = remain-2;\n\t\tu8 *cur_buf = start+2;\n\t\tu8 *hdr_start = NULL;\n\n\t\tif (final_flush) {\n\t\t\tnext_frame = remain;\n\t\t} else {\n\t\t\twhile (cur_size) {\n\t\t\t\t//wait till we have a frame header\n\t\t\t\thdr_start = memchr(cur_buf, 0xFF, cur_size);\n\t\t\t\tif (!hdr_start) break;\n\t\t\t\tnext_frame = (u32) (hdr_start-start);\n\t\t\t\tif (next_frame == remain)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif ((hdr_start[1]&0xFC) == 0xF8) {\n\t\t\t\t\tif (flac_parse_header(ctx, hdr_start, (u32) remain - next_frame, &hdr))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcur_buf = hdr_start+1;\n\t\t\t\tcur_size = (u32) (cur_buf - start);\n\t\t\t\tassert(cur_size<=remain);\n\t\t\t\tcur_size = remain - cur_size;\n\t\t\t\thdr_start = NULL;\n\t\t\t}\n\t\t\tif (!hdr_start) break;\n\t\t\tif (next_frame == remain)\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tif (!ctx->initialized) {\n\t\t\tu32 size = next_frame;\n\t\t\tu32 dsi_end = 0;\n\t\t\t//we have a header\n\t\t\tgf_bs_reassign_buffer(ctx->bs, ctx->flac_buffer, size);\n\t\t\tu32 magic = gf_bs_read_u32(ctx->bs);\n\t\t\tif (magic != GF_4CC('f','L','a','C')) {\n\n\t\t\t}\n\t\t\twhile (gf_bs_available(ctx->bs)) {\n\t\t\t\tBool last = gf_bs_read_int(ctx->bs, 1);\n\t\t\t\tu32 type = gf_bs_read_int(ctx->bs, 7);\n\t\t\t\tu32 len = gf_bs_read_int(ctx->bs, 24);\n\n\t\t\t\tif (type==0) {\n\t\t\t\t\tu16 min_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\tu16 max_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\t/*u32 min_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\t/*u32 max_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\tctx->sample_rate = gf_bs_read_int(ctx->bs, 20);\n\t\t\t\t\tctx->nb_channels = 1 + gf_bs_read_int(ctx->bs, 3);\n\t\t\t\t\tctx->bits_per_sample = 1 + gf_bs_read_int(ctx->bs, 5);\n\t\t\t\t\tif (min_block_size==max_block_size) ctx->block_size = min_block_size;\n\t\t\t\t\telse ctx->block_size = 0;\n\n\t\t\t\t\tctx->duration.num = gf_bs_read_long_int(ctx->bs, 36);\n\t\t\t\t\tctx->duration.den = ctx->sample_rate;\n\t\t\t\t\t//ignore the rest\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, 16);\n\t\t\t\t\tdsi_end = (u32) gf_bs_get_position(ctx->bs);\n\n\t\t\t\t} else {\n\t\t\t\t\t//ignore the rest for now\n\t\t\t\t\t//TODO: expose metadata, pictures and co\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, len);\n\t\t\t\t}\n\t\t\t\tif (last) break;\n\t\t\t}\n\t\t\tflac_dmx_check_pid(filter, ctx, ctx->flac_buffer+4, dsi_end-4);\n\t\t\tremain -= size;\n\t\t\tstart += size;\n\t\t\tctx->initialized = GF_TRUE;\n\t\t\tif (!ctx->is_playing) break;\n\t\t\tcontinue;\n\t\t}\n\n\t\t//we have a next frame, check we are synchronize\n\t\tif ((start[0] != 0xFF) && ((start[1]&0xFC) != 0xF8)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[FLACDmx] invalid frame, droping %d bytes and resyncing\\n\", next_frame));\n\t\t\tstart += next_frame;\n\t\t\tremain -= next_frame;\n\t\t\tcontinue;\n\t\t}\n\n\t\tflac_parse_header(ctx,start, next_frame, &hdr);\n\t\tif (hdr.sample_rate != ctx->sample_rate) {\n\t\t\tctx->sample_rate = hdr.sample_rate;\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAMPLE_RATE, & PROP_UINT(ctx->sample_rate));\n\t\t}\n\n\t\tnb_samp = hdr.block_size;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * ctx->sample_rate);\n\t\t\tif (ctx->cts + nb_samp >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + nb_samp ) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) {\n\t\t\tctx->cts = cts;\n\t\t\tcts = GF_FILTER_NO_TS;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, next_frame, &output);\n\t\t\tmemcpy(output, start, next_frame);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tif (!ctx->timescale || (ctx->timescale==ctx->sample_rate) )\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, nb_samp);\n\t\t\telse {\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, (nb_samp * ctx->timescale) / ctx->sample_rate);\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset);\n\t\t\t}\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tflac_dmx_update_cts(ctx, nb_samp);\n\n\t\tassert (start[0] == 0xFF);\n\t\tassert((start[1]&0xFC) == 0xF8);\n\n\t\tstart += next_frame;\n\t\tassert(remain >= next_frame);\n\t\tremain -= next_frame;\n\n\t}\n\n\tif (!pck) {\n\t\tctx->flac_buffer_size = 0;\n\t\treturn flac_dmx_process(filter);\n\t} else {\n\t\tif (remain < ctx->flac_buffer_size) {\n\t\t\tmemmove(ctx->flac_buffer, start, remain);\n\t\t}\n\t\tctx->flac_buffer_size = remain;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t}\n\treturn GF_OK;\n}", "func_hash": 323785917459606598765086099632153926503, "file_name": "reframe_flac.c", "file_hash": 270657332798976199872934434049460312254, "cwe": ["CWE-787"], "cve": "CVE-2021-29279", "cve_desc": "There is a integer overflow in function filter_core/filter_props.c:gf_props_assign_value in GPAC 1.0.1. In which, the arg const GF_PropertyValue *value,maybe value->value.data.size is a negative number. In result, memcpy in gf_props_assign_value failed.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29279"} {"idx": 255791, "project": "gpac", "commit_id": "da69ad1f970a7e17c865eaec9af98cc84df10d5b", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/da69ad1f970a7e17c865eaec9af98cc84df10d5b", "commit_message": "fixed 1718", "target": 0, "func": "GF_Err flac_dmx_process(GF_Filter *filter)\n{\n\tGF_FLACDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu8 *output;\n\tu8 *start;\n\tBool final_flush=GF_FALSE;\n\tu32 pck_size, remain, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\tFLACHeader hdr;\n\n\tif (ctx->in_error)\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tflac_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t\tfinal_flush = GF_TRUE;\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t}\n\n\tprev_pck_size = ctx->flac_buffer_size;\n\tif (pck && !ctx->resume_from) {\n\t\tu8 *data = (u8 *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\tu64 byte_offset = gf_filter_pck_get_byte_offset(pck);\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tctx->byte_offset = byte_offset;\n\t\t\t} else if (ctx->byte_offset + ctx->flac_buffer_size != byte_offset) {\n\t\t\t\tctx->byte_offset = GF_FILTER_NO_BO;\n\t\t\t\tif ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->flac_buffer_size) ) {\n\t\t\t\t\tctx->byte_offset = byte_offset - ctx->flac_buffer_size;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->flac_buffer_size + pck_size > ctx->flac_buffer_alloc) {\n\t\t\tctx->flac_buffer_alloc = ctx->flac_buffer_size + pck_size;\n\t\t\tctx->flac_buffer = gf_realloc(ctx->flac_buffer, ctx->flac_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->flac_buffer + ctx->flac_buffer_size, data, pck_size);\n\t\tctx->flac_buffer_size += pck_size;\n\t}\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tif (cts == GF_FILTER_NO_TS) {\n\t\t//avoids updating cts\n\t\tprev_pck_size = 0;\n\t}\n\n\tremain = ctx->flac_buffer_size;\n\tstart = ctx->flac_buffer;\n\n\tif (ctx->resume_from) {\n\t\tstart += ctx->resume_from - 1;\n\t\tremain -= ctx->resume_from - 1;\n\t\tctx->resume_from = 0;\n\t}\n\n\twhile (remain>2) {\n\t\tu32 next_frame=0, nb_samp;\n\t\tu32 cur_size = remain-2;\n\t\tu8 *cur_buf = start+2;\n\t\tu8 *hdr_start = NULL;\n\n\t\tif (final_flush) {\n\t\t\tnext_frame = remain;\n\t\t} else {\n\t\t\twhile (cur_size) {\n\t\t\t\t//wait till we have a frame header\n\t\t\t\thdr_start = memchr(cur_buf, 0xFF, cur_size);\n\t\t\t\tif (!hdr_start) break;\n\t\t\t\tnext_frame = (u32) (hdr_start-start);\n\t\t\t\tif (next_frame == remain)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif ((hdr_start[1]&0xFC) == 0xF8) {\n\t\t\t\t\tif (flac_parse_header(ctx, hdr_start, (u32) remain - next_frame, &hdr))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcur_buf = hdr_start+1;\n\t\t\t\tcur_size = (u32) (cur_buf - start);\n\t\t\t\tassert(cur_size<=remain);\n\t\t\t\tcur_size = remain - cur_size;\n\t\t\t\thdr_start = NULL;\n\t\t\t}\n\t\t\tif (!hdr_start) break;\n\t\t\tif (next_frame == remain)\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tif (!ctx->initialized) {\n\t\t\tu32 size = next_frame;\n\t\t\tu32 dsi_end = 0;\n\t\t\t//we have a header\n\t\t\tgf_bs_reassign_buffer(ctx->bs, ctx->flac_buffer, size);\n\t\t\tu32 magic = gf_bs_read_u32(ctx->bs);\n\t\t\tif (magic != GF_4CC('f','L','a','C')) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[FLACDmx] invalid FLAC magic\\n\"));\n\t\t\t\tctx->in_error = GF_TRUE;\n\t\t\t\tctx->flac_buffer_size = 0;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\twhile (gf_bs_available(ctx->bs)) {\n\t\t\t\tBool last = gf_bs_read_int(ctx->bs, 1);\n\t\t\t\tu32 type = gf_bs_read_int(ctx->bs, 7);\n\t\t\t\tu32 len = gf_bs_read_int(ctx->bs, 24);\n\n\t\t\t\tif (type==0) {\n\t\t\t\t\tu16 min_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\tu16 max_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\t/*u32 min_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\t/*u32 max_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\tctx->sample_rate = gf_bs_read_int(ctx->bs, 20);\n\t\t\t\t\tctx->nb_channels = 1 + gf_bs_read_int(ctx->bs, 3);\n\t\t\t\t\tctx->bits_per_sample = 1 + gf_bs_read_int(ctx->bs, 5);\n\t\t\t\t\tif (min_block_size==max_block_size) ctx->block_size = min_block_size;\n\t\t\t\t\telse ctx->block_size = 0;\n\n\t\t\t\t\tctx->duration.num = gf_bs_read_long_int(ctx->bs, 36);\n\t\t\t\t\tctx->duration.den = ctx->sample_rate;\n\t\t\t\t\t//ignore the rest\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, 16);\n\t\t\t\t\tdsi_end = (u32) gf_bs_get_position(ctx->bs);\n\n\t\t\t\t} else {\n\t\t\t\t\t//ignore the rest for now\n\t\t\t\t\t//TODO: expose metadata, pictures and co\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, len);\n\t\t\t\t}\n\t\t\t\tif (last) break;\n\t\t\t}\n\t\t\tif (!dsi_end) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[FLACDmx] invalid FLAC header\\n\"));\n\t\t\t\tctx->in_error = GF_TRUE;\n\t\t\t\tctx->flac_buffer_size = 0;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\tflac_dmx_check_pid(filter, ctx, ctx->flac_buffer+4, dsi_end-4);\n\t\t\tremain -= size;\n\t\t\tstart += size;\n\t\t\tctx->initialized = GF_TRUE;\n\t\t\tif (!ctx->is_playing) break;\n\t\t\tcontinue;\n\t\t}\n\n\t\t//we have a next frame, check we are synchronize\n\t\tif ((start[0] != 0xFF) && ((start[1]&0xFC) != 0xF8)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[FLACDmx] invalid frame, droping %d bytes and resyncing\\n\", next_frame));\n\t\t\tstart += next_frame;\n\t\t\tremain -= next_frame;\n\t\t\tcontinue;\n\t\t}\n\n\t\tflac_parse_header(ctx,start, next_frame, &hdr);\n\t\tif (hdr.sample_rate != ctx->sample_rate) {\n\t\t\tctx->sample_rate = hdr.sample_rate;\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAMPLE_RATE, & PROP_UINT(ctx->sample_rate));\n\t\t}\n\n\t\tnb_samp = hdr.block_size;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * ctx->sample_rate);\n\t\t\tif (ctx->cts + nb_samp >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + nb_samp ) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) {\n\t\t\tctx->cts = cts;\n\t\t\tcts = GF_FILTER_NO_TS;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, next_frame, &output);\n\t\t\tmemcpy(output, start, next_frame);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tif (!ctx->timescale || (ctx->timescale==ctx->sample_rate) )\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, nb_samp);\n\t\t\telse {\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, (nb_samp * ctx->timescale) / ctx->sample_rate);\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset);\n\t\t\t}\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tflac_dmx_update_cts(ctx, nb_samp);\n\n\t\tassert (start[0] == 0xFF);\n\t\tassert((start[1]&0xFC) == 0xF8);\n\n\t\tstart += next_frame;\n\t\tassert(remain >= next_frame);\n\t\tremain -= next_frame;\n\n\t}\n\n\tif (!pck) {\n\t\tctx->flac_buffer_size = 0;\n\t\treturn flac_dmx_process(filter);\n\t} else {\n\t\tif (remain < ctx->flac_buffer_size) {\n\t\t\tmemmove(ctx->flac_buffer, start, remain);\n\t\t}\n\t\tctx->flac_buffer_size = remain;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t}\n\treturn GF_OK;\n}", "func_hash": 37406677278036946231944481891751055513, "file_name": "reframe_flac.c", "file_hash": 215917421738013429565522266606358218654, "cwe": ["CWE-787"], "cve": "CVE-2021-29279", "cve_desc": "There is a integer overflow in function filter_core/filter_props.c:gf_props_assign_value in GPAC 1.0.1. In which, the arg const GF_PropertyValue *value,maybe value->value.data.size is a negative number. In result, memcpy in gf_props_assign_value failed.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29279"} {"idx": 197260, "project": "flatpak", "commit_id": "a7401e638bf0c03102039e216ab1081922f140ae", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/a7401e638bf0c03102039e216ab1081922f140ae", "commit_message": "dir: Refuse to export .desktop files with suspicious uses of @@ tokens\n\nThis is either a malicious/compromised app trying to do an attack, or\na mistake that will break handling of %f, %u and so on. Either way,\nif we refuse to export the .desktop file, resulting in installation\nfailing, then it makes the rejection more obvious than quietly\nremoving the magic tokens.\n\nSigned-off-by: Simon McVittie \n(cherry picked from commit 46b3ede5241561c7d588951048c687c5075a3eac)", "target": 1, "func": "export_desktop_file (const char *app,\n const char *branch,\n const char *arch,\n GKeyFile *metadata,\n const char * const *previous_ids,\n int parent_fd,\n const char *name,\n struct stat *stat_buf,\n char **target,\n GCancellable *cancellable,\n GError **error)\n{\n gboolean ret = FALSE;\n glnx_autofd int desktop_fd = -1;\n g_autofree char *tmpfile_name = g_strdup_printf (\"export-desktop-XXXXXX\");\n g_autoptr(GOutputStream) out_stream = NULL;\n g_autofree gchar *data = NULL;\n gsize data_len;\n g_autofree gchar *new_data = NULL;\n gsize new_data_len;\n g_autoptr(GKeyFile) keyfile = NULL;\n g_autofree gchar *old_exec = NULL;\n gint old_argc;\n g_auto(GStrv) old_argv = NULL;\n g_auto(GStrv) groups = NULL;\n GString *new_exec = NULL;\n g_autofree char *escaped_app = maybe_quote (app);\n g_autofree char *escaped_branch = maybe_quote (branch);\n g_autofree char *escaped_arch = maybe_quote (arch);\n int i;\n\n if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error))\n goto out;\n\n if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error))\n goto out;\n\n keyfile = g_key_file_new ();\n if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error))\n goto out;\n\n if (g_str_has_suffix (name, \".service\"))\n {\n g_autofree gchar *dbus_name = NULL;\n g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen (\".service\"));\n\n dbus_name = g_key_file_get_string (keyfile, \"D-BUS Service\", \"Name\", NULL);\n\n if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0)\n {\n return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED,\n _(\"D-Bus service file '%s' has wrong name\"), name);\n }\n }\n\n if (g_str_has_suffix (name, \".desktop\"))\n {\n gsize length;\n g_auto(GStrv) tags = g_key_file_get_string_list (metadata,\n \"Application\",\n \"tags\", &length,\n NULL);\n\n if (tags != NULL)\n {\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n \"X-Flatpak-Tags\",\n (const char * const *) tags, length);\n }\n\n /* Add a marker so consumers can easily find out that this launches a sandbox */\n g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, \"X-Flatpak\", app);\n\n /* If the app has been renamed, add its old .desktop filename to\n * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to\n * introduce duplicates.\n */\n if (previous_ids != NULL)\n {\n const char *X_FLATPAK_RENAMED_FROM = \"X-Flatpak-RenamedFrom\";\n g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n NULL, NULL);\n g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free);\n g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal);\n const char *new_suffix;\n\n for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++)\n {\n if (!g_hash_table_contains (seen, renamed_from[i]))\n {\n gchar *copy = g_strdup (renamed_from[i]);\n g_hash_table_insert (seen, copy, copy);\n g_ptr_array_add (merged, g_steal_pointer (©));\n }\n }\n\n /* If an app was renamed from com.example.Foo to net.example.Bar, and\n * the new version exports net.example.Bar-suffix.desktop, we assume the\n * old version exported com.example.Foo-suffix.desktop.\n *\n * This assertion is true because\n * flatpak_name_matches_one_wildcard_prefix() is called on all\n * exported files before we get here.\n */\n g_assert (g_str_has_prefix (name, app));\n /* \".desktop\" for the \"main\" desktop file; something like\n * \"-suffix.desktop\" for extra ones.\n */\n new_suffix = name + strlen (app);\n\n for (i = 0; previous_ids[i] != NULL; i++)\n {\n g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL);\n if (!g_hash_table_contains (seen, previous_desktop))\n {\n g_hash_table_insert (seen, previous_desktop, previous_desktop);\n g_ptr_array_add (merged, g_steal_pointer (&previous_desktop));\n }\n }\n\n if (merged->len > 0)\n {\n g_ptr_array_add (merged, NULL);\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n (const char * const *) merged->pdata,\n merged->len - 1);\n }\n }\n }\n\n groups = g_key_file_get_groups (keyfile, NULL);\n\n for (i = 0; groups[i] != NULL; i++)\n {\n g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL, NULL);\n g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts);\n\n g_key_file_remove_key (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL);\n g_key_file_remove_key (keyfile, groups[i], \"TryExec\", NULL);\n\n /* Remove this to make sure nothing tries to execute it outside the sandbox*/\n g_key_file_remove_key (keyfile, groups[i], \"X-GNOME-Bugzilla-ExtraInfoScript\", NULL);\n\n new_exec = g_string_new (\"\");\n g_string_append_printf (new_exec,\n FLATPAK_BINDIR \"/flatpak run --branch=%s --arch=%s\",\n escaped_branch,\n escaped_arch);\n\n if (flatpak_run_args != NULL)\n g_string_append_printf (new_exec, \"%s\", flatpak_run_args);\n\n old_exec = g_key_file_get_string (keyfile, groups[i], \"Exec\", NULL);\n if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1)\n {\n int j;\n g_autofree char *command = maybe_quote (old_argv[0]);\n\n g_string_append_printf (new_exec, \" --command=%s\", command);\n\n for (j = 1; j < old_argc; j++)\n {\n if (strcasecmp (old_argv[j], \"%f\") == 0 ||\n strcasecmp (old_argv[j], \"%u\") == 0)\n {\n g_string_append (new_exec, \" --file-forwarding\");\n break;\n }\n }\n\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n\n for (j = 1; j < old_argc; j++)\n {\n g_autofree char *arg = maybe_quote (old_argv[j]);\n\n if (strcasecmp (arg, \"%f\") == 0)\n g_string_append_printf (new_exec, \" @@ %s @@\", arg);\n else if (strcasecmp (arg, \"%u\") == 0)\n g_string_append_printf (new_exec, \" @@u %s @@\", arg);\n else if (g_str_has_prefix (arg, \"@@\"))\n g_print (_(\"Skipping invalid Exec argument %s\\n\"), arg);\n else\n g_string_append_printf (new_exec, \" %s\", arg);\n }\n }\n else\n {\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n }\n\n g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str);\n }\n\n new_data = g_key_file_to_data (keyfile, &new_data_len, error);\n if (new_data == NULL)\n goto out;\n\n if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error))\n goto out;\n\n if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error))\n goto out;\n\n if (!g_output_stream_close (out_stream, cancellable, error))\n goto out;\n\n if (target)\n *target = g_steal_pointer (&tmpfile_name);\n\n ret = TRUE;\nout:\n\n if (new_exec != NULL)\n g_string_free (new_exec, TRUE);\n\n return ret;\n}", "func_hash": 40358228263089164850802986169998993504, "file_name": "flatpak-dir.c", "file_hash": 71812989109100532072905075762540290909, "cwe": ["CWE-94"], "cve": "CVE-2021-21381", "cve_desc": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. In Flatpack since version 0.9.4 and before version 1.10.2 has a vulnerability in the \"file forwarding\" feature which can be used by an attacker to gain access to files that would not ordinarily be allowed by the app's permissions. By putting the special tokens `@@` and/or `@@u` in the Exec field of a Flatpak app's .desktop file, a malicious app publisher can trick flatpak into behaving as though the user had chosen to open a target file with their Flatpak app, which automatically makes that file available to the Flatpak app. This is fixed in version 1.10.2. A minimal solution is the first commit \"`Disallow @@ and @@U usage in desktop files`\". The follow-up commits \"`dir: Reserve the whole @@ prefix`\" and \"`dir: Refuse to export .desktop files with suspicious uses of @@ tokens`\" are recommended, but not strictly required. As a workaround, avoid installing Flatpak apps from untrusted sources, or check the contents of the exported `.desktop` files in `exports/share/applications/*.desktop` (typically `~/.local/share/flatpak/exports/share/applications/*.desktop` and `/var/lib/flatpak/exports/share/applications/*.desktop`) to make sure that literal filenames do not follow `@@` or `@@u`.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21381"} {"idx": 256099, "project": "flatpak", "commit_id": "a7401e638bf0c03102039e216ab1081922f140ae", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/a7401e638bf0c03102039e216ab1081922f140ae", "commit_message": "dir: Refuse to export .desktop files with suspicious uses of @@ tokens\n\nThis is either a malicious/compromised app trying to do an attack, or\na mistake that will break handling of %f, %u and so on. Either way,\nif we refuse to export the .desktop file, resulting in installation\nfailing, then it makes the rejection more obvious than quietly\nremoving the magic tokens.\n\nSigned-off-by: Simon McVittie \n(cherry picked from commit 46b3ede5241561c7d588951048c687c5075a3eac)", "target": 0, "func": "export_desktop_file (const char *app,\n const char *branch,\n const char *arch,\n GKeyFile *metadata,\n const char * const *previous_ids,\n int parent_fd,\n const char *name,\n struct stat *stat_buf,\n char **target,\n GCancellable *cancellable,\n GError **error)\n{\n gboolean ret = FALSE;\n glnx_autofd int desktop_fd = -1;\n g_autofree char *tmpfile_name = g_strdup_printf (\"export-desktop-XXXXXX\");\n g_autoptr(GOutputStream) out_stream = NULL;\n g_autofree gchar *data = NULL;\n gsize data_len;\n g_autofree gchar *new_data = NULL;\n gsize new_data_len;\n g_autoptr(GKeyFile) keyfile = NULL;\n g_autofree gchar *old_exec = NULL;\n gint old_argc;\n g_auto(GStrv) old_argv = NULL;\n g_auto(GStrv) groups = NULL;\n GString *new_exec = NULL;\n g_autofree char *escaped_app = maybe_quote (app);\n g_autofree char *escaped_branch = maybe_quote (branch);\n g_autofree char *escaped_arch = maybe_quote (arch);\n int i;\n\n if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error))\n goto out;\n\n if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error))\n goto out;\n\n keyfile = g_key_file_new ();\n if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error))\n goto out;\n\n if (g_str_has_suffix (name, \".service\"))\n {\n g_autofree gchar *dbus_name = NULL;\n g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen (\".service\"));\n\n dbus_name = g_key_file_get_string (keyfile, \"D-BUS Service\", \"Name\", NULL);\n\n if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0)\n {\n return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED,\n _(\"D-Bus service file '%s' has wrong name\"), name);\n }\n }\n\n if (g_str_has_suffix (name, \".desktop\"))\n {\n gsize length;\n g_auto(GStrv) tags = g_key_file_get_string_list (metadata,\n \"Application\",\n \"tags\", &length,\n NULL);\n\n if (tags != NULL)\n {\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n \"X-Flatpak-Tags\",\n (const char * const *) tags, length);\n }\n\n /* Add a marker so consumers can easily find out that this launches a sandbox */\n g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, \"X-Flatpak\", app);\n\n /* If the app has been renamed, add its old .desktop filename to\n * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to\n * introduce duplicates.\n */\n if (previous_ids != NULL)\n {\n const char *X_FLATPAK_RENAMED_FROM = \"X-Flatpak-RenamedFrom\";\n g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n NULL, NULL);\n g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free);\n g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal);\n const char *new_suffix;\n\n for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++)\n {\n if (!g_hash_table_contains (seen, renamed_from[i]))\n {\n gchar *copy = g_strdup (renamed_from[i]);\n g_hash_table_insert (seen, copy, copy);\n g_ptr_array_add (merged, g_steal_pointer (©));\n }\n }\n\n /* If an app was renamed from com.example.Foo to net.example.Bar, and\n * the new version exports net.example.Bar-suffix.desktop, we assume the\n * old version exported com.example.Foo-suffix.desktop.\n *\n * This assertion is true because\n * flatpak_name_matches_one_wildcard_prefix() is called on all\n * exported files before we get here.\n */\n g_assert (g_str_has_prefix (name, app));\n /* \".desktop\" for the \"main\" desktop file; something like\n * \"-suffix.desktop\" for extra ones.\n */\n new_suffix = name + strlen (app);\n\n for (i = 0; previous_ids[i] != NULL; i++)\n {\n g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL);\n if (!g_hash_table_contains (seen, previous_desktop))\n {\n g_hash_table_insert (seen, previous_desktop, previous_desktop);\n g_ptr_array_add (merged, g_steal_pointer (&previous_desktop));\n }\n }\n\n if (merged->len > 0)\n {\n g_ptr_array_add (merged, NULL);\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n (const char * const *) merged->pdata,\n merged->len - 1);\n }\n }\n }\n\n groups = g_key_file_get_groups (keyfile, NULL);\n\n for (i = 0; groups[i] != NULL; i++)\n {\n g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL, NULL);\n g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts);\n\n g_key_file_remove_key (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL);\n g_key_file_remove_key (keyfile, groups[i], \"TryExec\", NULL);\n\n /* Remove this to make sure nothing tries to execute it outside the sandbox*/\n g_key_file_remove_key (keyfile, groups[i], \"X-GNOME-Bugzilla-ExtraInfoScript\", NULL);\n\n new_exec = g_string_new (\"\");\n g_string_append_printf (new_exec,\n FLATPAK_BINDIR \"/flatpak run --branch=%s --arch=%s\",\n escaped_branch,\n escaped_arch);\n\n if (flatpak_run_args != NULL)\n g_string_append_printf (new_exec, \"%s\", flatpak_run_args);\n\n old_exec = g_key_file_get_string (keyfile, groups[i], \"Exec\", NULL);\n if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1)\n {\n int j;\n g_autofree char *command = maybe_quote (old_argv[0]);\n\n g_string_append_printf (new_exec, \" --command=%s\", command);\n\n for (j = 1; j < old_argc; j++)\n {\n if (strcasecmp (old_argv[j], \"%f\") == 0 ||\n strcasecmp (old_argv[j], \"%u\") == 0)\n {\n g_string_append (new_exec, \" --file-forwarding\");\n break;\n }\n }\n\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n\n for (j = 1; j < old_argc; j++)\n {\n g_autofree char *arg = maybe_quote (old_argv[j]);\n\n if (strcasecmp (arg, \"%f\") == 0)\n g_string_append_printf (new_exec, \" @@ %s @@\", arg);\n else if (strcasecmp (arg, \"%u\") == 0)\n g_string_append_printf (new_exec, \" @@u %s @@\", arg);\n else if (g_str_has_prefix (arg, \"@@\"))\n {\n flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED,\n _(\"Invalid Exec argument %s\"), arg);\n goto out;\n }\n else\n g_string_append_printf (new_exec, \" %s\", arg);\n }\n }\n else\n {\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n }\n\n g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str);\n }\n\n new_data = g_key_file_to_data (keyfile, &new_data_len, error);\n if (new_data == NULL)\n goto out;\n\n if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error))\n goto out;\n\n if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error))\n goto out;\n\n if (!g_output_stream_close (out_stream, cancellable, error))\n goto out;\n\n if (target)\n *target = g_steal_pointer (&tmpfile_name);\n\n ret = TRUE;\nout:\n\n if (new_exec != NULL)\n g_string_free (new_exec, TRUE);\n\n return ret;\n}", "func_hash": 185448239288866534156501366190938058633, "file_name": "flatpak-dir.c", "file_hash": 244889468632293836579096904931255849539, "cwe": ["CWE-94"], "cve": "CVE-2021-21381", "cve_desc": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. In Flatpack since version 0.9.4 and before version 1.10.2 has a vulnerability in the \"file forwarding\" feature which can be used by an attacker to gain access to files that would not ordinarily be allowed by the app's permissions. By putting the special tokens `@@` and/or `@@u` in the Exec field of a Flatpak app's .desktop file, a malicious app publisher can trick flatpak into behaving as though the user had chosen to open a target file with their Flatpak app, which automatically makes that file available to the Flatpak app. This is fixed in version 1.10.2. A minimal solution is the first commit \"`Disallow @@ and @@U usage in desktop files`\". The follow-up commits \"`dir: Reserve the whole @@ prefix`\" and \"`dir: Refuse to export .desktop files with suspicious uses of @@ tokens`\" are recommended, but not strictly required. As a workaround, avoid installing Flatpak apps from untrusted sources, or check the contents of the exported `.desktop` files in `exports/share/applications/*.desktop` (typically `~/.local/share/flatpak/exports/share/applications/*.desktop` and `/var/lib/flatpak/exports/share/applications/*.desktop`) to make sure that literal filenames do not follow `@@` or `@@u`.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21381"} {"idx": 197301, "project": "tensorflow", "commit_id": "1e922ccdf6bf46a3a52641f99fd47d54c1decd13", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/1e922ccdf6bf46a3a52641f99fd47d54c1decd13", "commit_message": "Fix crash in `SparseTensorToCSRSparseMatrixCPUFunctor`\n\nPiperOrigin-RevId: 370110290\nChange-Id: I4451e92661a55c2180f80d38b67a9b50bf5edec5", "target": 1, "func": "Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()(\n const int64 batch_size, const int num_rows,\n TTypes::ConstMatrix indices, TTypes::Vec batch_ptr,\n TTypes::Vec csr_row_ptr, TTypes::Vec csr_col_ind) {\n // Validate inputs.\n if (batch_ptr.size() != batch_size + 1) {\n return errors::InvalidArgument(\n \"Expected batch_ptr.size() == batch_size + 1. Got: \", batch_ptr.size(),\n \" vs. \", batch_size + 1);\n }\n if (csr_row_ptr.size() != batch_size * (num_rows + 1)) {\n return errors::InvalidArgument(\n \"Expected csr_row_ptr.size() == batch_size * (num_rows + 1). Got: \",\n csr_row_ptr.size(), \" vs. \", batch_size * (num_rows + 1));\n }\n\n const int64 total_nnz = indices.dimension(0);\n const int rank = indices.dimension(1);\n if (rank == 2 && batch_size != 1) {\n return errors::InvalidArgument(\n \"Expected batch_size == 1 when rank is 2. Got batch_size: \",\n batch_size);\n }\n if (csr_col_ind.size() != total_nnz) {\n return errors::InvalidArgument(\n \"Expected csr_col_ind.size() == total_nnz. Got: \", csr_col_ind.size(),\n \" vs. \", total_nnz);\n }\n\n int prev_batch = -1;\n if (rank == 2) {\n // For a single batch, the batch_ptrs are {0, total_nnz}.\n batch_ptr(0) = 0;\n ++prev_batch;\n\n for (int64 i = 0; i < total_nnz; ++i) {\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(indices(i, 0) + 1) += 1;\n csr_col_ind(i) = indices(i, 1);\n }\n } else { // rank == 3\n for (int64 i = 0; i < total_nnz; ++i) {\n const int cur_batch = indices(i, 0);\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(cur_batch * (num_rows + 1) + indices(i, 1) + 1) += 1;\n csr_col_ind(i) = indices(i, 2);\n\n // We're at a new batch and might have skipped over empty batches.\n while (prev_batch < cur_batch) {\n // The previous batch ends at position i.\n batch_ptr(prev_batch + 1) = i;\n ++prev_batch;\n }\n }\n }\n // Set the last element of batch_ptr and account for trailing empty batches.\n while (prev_batch < batch_size) {\n batch_ptr(prev_batch + 1) = total_nnz;\n ++prev_batch;\n }\n\n // Compute the cumulative row counts for each batch.\n for (int batch_idx = 0; batch_idx < batch_size; ++batch_idx) {\n auto* row_ptr_batch = csr_row_ptr.data() + batch_idx * (num_rows + 1);\n std::partial_sum(row_ptr_batch, row_ptr_batch + num_rows + 1,\n row_ptr_batch);\n }\n return Status::OK();\n}", "func_hash": 39280245793073834327644484895303763533, "file_name": "kernels.cc", "file_hash": 294680081119943017384889089948962236294, "cwe": ["CWE-369"], "cve": "CVE-2021-29545", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a denial of service via a `CHECK`-fail in converting sparse tensors to CSR Sparse matrices. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/800346f2c03a27e182dd4fba48295f65e7790739/tensorflow/core/kernels/sparse/kernels.cc#L66) does a double redirection to access an element of an array allocated on the heap. If the value at `indices(i, 0)` is such that `indices(i, 0) + 1` is outside the bounds of `csr_row_ptr`, this results in writing outside of bounds of heap allocated data. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29545"} {"idx": 256387, "project": "tensorflow", "commit_id": "1e922ccdf6bf46a3a52641f99fd47d54c1decd13", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/1e922ccdf6bf46a3a52641f99fd47d54c1decd13", "commit_message": "Fix crash in `SparseTensorToCSRSparseMatrixCPUFunctor`\n\nPiperOrigin-RevId: 370110290\nChange-Id: I4451e92661a55c2180f80d38b67a9b50bf5edec5", "target": 0, "func": "Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()(\n const int64 batch_size, const int num_rows,\n TTypes::ConstMatrix indices, TTypes::Vec batch_ptr,\n TTypes::Vec csr_row_ptr, TTypes::Vec csr_col_ind) {\n // Validate inputs.\n if (batch_ptr.size() != batch_size + 1) {\n return errors::InvalidArgument(\n \"Expected batch_ptr.size() == batch_size + 1. Got: \", batch_ptr.size(),\n \" vs. \", batch_size + 1);\n }\n if (csr_row_ptr.size() != batch_size * (num_rows + 1)) {\n return errors::InvalidArgument(\n \"Expected csr_row_ptr.size() == batch_size * (num_rows + 1). Got: \",\n csr_row_ptr.size(), \" vs. \", batch_size * (num_rows + 1));\n }\n\n const int64 total_nnz = indices.dimension(0);\n const int rank = indices.dimension(1);\n if (rank == 2 && batch_size != 1) {\n return errors::InvalidArgument(\n \"Expected batch_size == 1 when rank is 2. Got batch_size: \",\n batch_size);\n }\n if (csr_col_ind.size() != total_nnz) {\n return errors::InvalidArgument(\n \"Expected csr_col_ind.size() == total_nnz. Got: \", csr_col_ind.size(),\n \" vs. \", total_nnz);\n }\n\n int prev_batch = -1;\n if (rank == 2) {\n // For a single batch, the batch_ptrs are {0, total_nnz}.\n batch_ptr(0) = 0;\n ++prev_batch;\n\n for (int64 i = 0; i < total_nnz; ++i) {\n // For now, the rows pointers store the corresponding row counts.\n int64 ix = indices(i, 0) + 1;\n if (ix >= csr_row_ptr.size()) {\n return errors::InvalidArgument(\"Got an index \", ix,\n \" that is outside of csr_row_ptr\");\n }\n csr_row_ptr(indices(i, 0) + 1) += 1;\n csr_col_ind(i) = indices(i, 1);\n }\n } else { // rank == 3\n for (int64 i = 0; i < total_nnz; ++i) {\n const int cur_batch = indices(i, 0);\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(cur_batch * (num_rows + 1) + indices(i, 1) + 1) += 1;\n csr_col_ind(i) = indices(i, 2);\n\n // We're at a new batch and might have skipped over empty batches.\n while (prev_batch < cur_batch) {\n // The previous batch ends at position i.\n batch_ptr(prev_batch + 1) = i;\n ++prev_batch;\n }\n }\n }\n // Set the last element of batch_ptr and account for trailing empty batches.\n while (prev_batch < batch_size) {\n batch_ptr(prev_batch + 1) = total_nnz;\n ++prev_batch;\n }\n\n // Compute the cumulative row counts for each batch.\n for (int batch_idx = 0; batch_idx < batch_size; ++batch_idx) {\n auto* row_ptr_batch = csr_row_ptr.data() + batch_idx * (num_rows + 1);\n std::partial_sum(row_ptr_batch, row_ptr_batch + num_rows + 1,\n row_ptr_batch);\n }\n return Status::OK();\n}", "func_hash": 301413604230811602511860638183892507509, "file_name": "kernels.cc", "file_hash": 334965645996645396768549967872774695033, "cwe": ["CWE-369"], "cve": "CVE-2021-29545", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a denial of service via a `CHECK`-fail in converting sparse tensors to CSR Sparse matrices. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/800346f2c03a27e182dd4fba48295f65e7790739/tensorflow/core/kernels/sparse/kernels.cc#L66) does a double redirection to access an element of an array allocated on the heap. If the value at `indices(i, 0)` is such that `indices(i, 0) + 1` is outside the bounds of `csr_row_ptr`, this results in writing outside of bounds of heap allocated data. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29545"} {"idx": 197303, "project": "tensorflow", "commit_id": "f61c57bd425878be108ec787f4d96390579fb83e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f61c57bd425878be108ec787f4d96390579fb83e", "commit_message": "Prevent division by 0\n\nPiperOrigin-RevId: 370966645\nChange-Id: I831bfd96c7eb77b02d7ebb744335f59f6e5728cb", "target": 1, "func": "TfLiteStatus EvalSimple(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* lookup, const TfLiteTensor* value,\n TfLiteTensor* output) {\n const int row_size = SizeOfDimension(value, 0);\n const int row_bytes = value->bytes / row_size;\n\n char* output_raw = GetTensorData(output);\n const char* value_raw = GetTensorData(value);\n const int32_t* lookup_data = GetTensorData(lookup);\n for (int i = 0; i < SizeOfDimension(lookup, 0); i++) {\n int idx = lookup_data[i];\n if (idx >= row_size || idx < 0) {\n context->ReportError(context,\n \"Embedding Lookup: index out of bounds. \"\n \"Got %d, and bounds are [0, %d]\",\n idx, row_size - 1);\n return kTfLiteError;\n } else {\n std::memcpy(output_raw + i * row_bytes, value_raw + idx * row_bytes,\n row_bytes);\n }\n }\n\n return kTfLiteOk;\n}", "func_hash": 99119810548761958092126756546127706322, "file_name": "embedding_lookup.cc", "file_hash": 169192025447226172521529008009380994700, "cwe": ["CWE-369"], "cve": "CVE-2021-29596", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of the `EmbeddingLookup` TFLite operator is vulnerable to a division by zero error(https://github.com/tensorflow/tensorflow/blob/e4b29809543b250bc9b19678ec4776299dd569ba/tensorflow/lite/kernels/embedding_lookup.cc#L73-L74). An attacker can craft a model such that the first dimension of the `value` input is 0. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29596"} {"idx": 256405, "project": "tensorflow", "commit_id": "f61c57bd425878be108ec787f4d96390579fb83e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f61c57bd425878be108ec787f4d96390579fb83e", "commit_message": "Prevent division by 0\n\nPiperOrigin-RevId: 370966645\nChange-Id: I831bfd96c7eb77b02d7ebb744335f59f6e5728cb", "target": 0, "func": "TfLiteStatus EvalSimple(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* lookup, const TfLiteTensor* value,\n TfLiteTensor* output) {\n const int row_size = SizeOfDimension(value, 0);\n if (row_size == 0) {\n // Propagate empty tensor if input is empty\n return kTfLiteOk;\n }\n const int row_bytes = value->bytes / row_size;\n\n char* output_raw = GetTensorData(output);\n const char* value_raw = GetTensorData(value);\n const int32_t* lookup_data = GetTensorData(lookup);\n for (int i = 0; i < SizeOfDimension(lookup, 0); i++) {\n int idx = lookup_data[i];\n if (idx >= row_size || idx < 0) {\n context->ReportError(context,\n \"Embedding Lookup: index out of bounds. \"\n \"Got %d, and bounds are [0, %d]\",\n idx, row_size - 1);\n return kTfLiteError;\n } else {\n std::memcpy(output_raw + i * row_bytes, value_raw + idx * row_bytes,\n row_bytes);\n }\n }\n\n return kTfLiteOk;\n}", "func_hash": 85751146722188577407404581668850455506, "file_name": "embedding_lookup.cc", "file_hash": 65223595450655215010450939118170575514, "cwe": ["CWE-369"], "cve": "CVE-2021-29596", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of the `EmbeddingLookup` TFLite operator is vulnerable to a division by zero error(https://github.com/tensorflow/tensorflow/blob/e4b29809543b250bc9b19678ec4776299dd569ba/tensorflow/lite/kernels/embedding_lookup.cc#L73-L74). An attacker can craft a model such that the first dimension of the `value` input is 0. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29596"} {"idx": 197404, "project": "tensorflow", "commit_id": "ecf768cbe50cedc0a45ce1ee223146a3d3d26d23", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ecf768cbe50cedc0a45ce1ee223146a3d3d26d23", "commit_message": "Add missing validations to reverse_sequence_op\n\nPiperOrigin-RevId: 372178683\nChange-Id: Iac97ebab5b342f1262c77a7d9bcb4267b305ce5b", "target": 1, "func": " explicit ReverseSequenceOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"batch_dim\", &batch_dim_));\n OP_REQUIRES_OK(context, context->GetAttr(\"seq_dim\", &seq_dim_));\n }", "func_hash": 5948582312496195656462916695436327209, "file_name": "reverse_sequence_op.cc", "file_hash": 181466370148571985706195279869538359425, "cwe": ["CWE-787"], "cve": "CVE-2021-29575", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.ReverseSequence` allows for stack overflow and/or `CHECK`-fail based denial of service. The implementation(https://github.com/tensorflow/tensorflow/blob/5b3b071975e01f0d250c928b2a8f901cd53b90a7/tensorflow/core/kernels/reverse_sequence_op.cc#L114-L118) fails to validate that `seq_dim` and `batch_dim` arguments are valid. Negative values for `seq_dim` can result in stack overflow or `CHECK`-failure, depending on the version of Eigen code used to implement the operation. Similar behavior can be exhibited by invalid values of `batch_dim`. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29575"} {"idx": 258254, "project": "tensorflow", "commit_id": "ecf768cbe50cedc0a45ce1ee223146a3d3d26d23", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ecf768cbe50cedc0a45ce1ee223146a3d3d26d23", "commit_message": "Add missing validations to reverse_sequence_op\n\nPiperOrigin-RevId: 372178683\nChange-Id: Iac97ebab5b342f1262c77a7d9bcb4267b305ce5b", "target": 0, "func": " explicit ReverseSequenceOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"batch_dim\", &batch_dim_));\n OP_REQUIRES_OK(context, context->GetAttr(\"seq_dim\", &seq_dim_));\n OP_REQUIRES(context, batch_dim_ >= 0,\n errors::InvalidArgument(\"Invalid batch_dim \", batch_dim_));\n OP_REQUIRES(context, seq_dim_ >= 0,\n errors::InvalidArgument(\"Invalid seq_dim \", seq_dim_));\n }", "func_hash": 258800459709810373752808324953515234281, "file_name": "reverse_sequence_op.cc", "file_hash": 16052429149914873254774409585901022405, "cwe": ["CWE-787"], "cve": "CVE-2021-29575", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.ReverseSequence` allows for stack overflow and/or `CHECK`-fail based denial of service. The implementation(https://github.com/tensorflow/tensorflow/blob/5b3b071975e01f0d250c928b2a8f901cd53b90a7/tensorflow/core/kernels/reverse_sequence_op.cc#L114-L118) fails to validate that `seq_dim` and `batch_dim` arguments are valid. Negative values for `seq_dim` can result in stack overflow or `CHECK`-failure, depending on the version of Eigen code used to implement the operation. Similar behavior can be exhibited by invalid values of `batch_dim`. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29575"} {"idx": 197415, "project": "openfortivpn", "commit_id": "6328a070ddaab16faaf008cb9a8a62439c30f2a8", "project_url": "https://github.com/adrienverge/openfortivpn", "commit_url": "https://github.com/adrienverge/openfortivpn/commit/6328a070ddaab16faaf008cb9a8a62439c30f2a8", "commit_message": "fix TLS Certificate CommonName NULL Byte Vulnerability\n\nCVE-2020-7043 TLS Certificate CommonName NULL Byte Vulnerability is fixed\nwith this commit\n\nwith #8 hostname validation for the certificate was introduced\nbut unfortunately strncasecmp() was used to compare the byte array\nagainst the expected hostname. This does not correctly treat a CN\nwhich contains a NULL byte. In order to fix this vulnerability\nthe reference implementation from iSECPartners has been included\ninto the code.", "target": 1, "func": "static int ssl_verify_cert(struct tunnel *tunnel)\n{\n\tint ret = -1;\n\tint cert_valid = 0;\n\tunsigned char digest[SHA256LEN];\n\tunsigned int len;\n\tstruct x509_digest *elem;\n\tchar digest_str[SHA256STRLEN], *subject, *issuer;\n\tchar *line;\n\tint i;\n\tX509_NAME *subj;\n\n\tSSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);\n\n\tX509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);\n\tif (cert == NULL) {\n\t\tlog_error(\"Unable to get gateway certificate.\\n\");\n\t\treturn 1;\n\t}\n\n\tsubj = X509_get_subject_name(cert);\n\n#ifdef HAVE_X509_CHECK_HOST\n\t// Use OpenSSL native host validation if v >= 1.0.2.\n\t// compare against gateway_host and correctly check return value\n\t// to fix piror Incorrect use of X509_check_host\n\tif (X509_check_host(cert, tunnel->config->gateway_host,\n\t 0, 0, NULL) == 1)\n\t\tcert_valid = 1;\n#else\n\tchar common_name[FIELD_SIZE + 1];\n\t// Use explicit Common Name check if native validation not available.\n\t// Note: this will ignore Subject Alternative Name fields.\n\tif (subj\n\t && X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,\n\t FIELD_SIZE) > 0\n\t && strncasecmp(common_name, tunnel->config->gateway_host,\n\t FIELD_SIZE) == 0)\n\t\tcert_valid = 1;\n#endif\n\n\t// Try to validate certificate using local PKI\n\tif (cert_valid\n\t && SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {\n\t\tlog_debug(\"Gateway certificate validation succeeded.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\tlog_debug(\"Gateway certificate validation failed.\\n\");\n\n\t// If validation failed, check if cert is in the white list\n\tif (X509_digest(cert, EVP_sha256(), digest, &len) <= 0\n\t || len != SHA256LEN) {\n\t\tlog_error(\"Could not compute certificate sha256 digest.\\n\");\n\t\tgoto free_cert;\n\t}\n\t// Encode digest in base16\n\tfor (i = 0; i < SHA256LEN; i++)\n\t\tsprintf(&digest_str[2 * i], \"%02x\", digest[i]);\n\tdigest_str[SHA256STRLEN - 1] = '\\0';\n\t// Is it in whitelist?\n\tfor (elem = tunnel->config->cert_whitelist; elem != NULL;\n\t elem = elem->next)\n\t\tif (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)\n\t\t\tbreak;\n\tif (elem != NULL) { // break before end of loop\n\t\tlog_debug(\"Gateway certificate digest found in white list.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\n\tsubject = X509_NAME_oneline(subj, NULL, 0);\n\tissuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n\n\tlog_error(\"Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\\n\");\n\tlog_error(\" --trusted-cert %s\\n\", digest_str);\n\tlog_error(\"or add this line to your config file:\\n\");\n\tlog_error(\" trusted-cert = %s\\n\", digest_str);\n\tlog_error(\"Gateway certificate:\\n\");\n\tlog_error(\" subject:\\n\");\n\tfor (line = strtok(subject, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" issuer:\\n\");\n\tfor (line = strtok(issuer, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" sha256 digest:\\n\");\n\tlog_error(\" %s\\n\", digest_str);\n\nfree_cert:\n\tX509_free(cert);\n\treturn ret;\n}", "func_hash": 336518491467505713024184864187116782024, "file_name": "None", "file_hash": null, "cwe": ["CWE-295"], "cve": "CVE-2020-7043", "cve_desc": "An issue was discovered in openfortivpn 1.11.0 when used with OpenSSL before 1.0.2. tunnel.c mishandles certificate validation because hostname comparisons do not consider '\\0' characters, as demonstrated by a good.example.com\\x00evil.example.com attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7043"} {"idx": 258435, "project": "openfortivpn", "commit_id": "6328a070ddaab16faaf008cb9a8a62439c30f2a8", "project_url": "https://github.com/adrienverge/openfortivpn", "commit_url": "https://github.com/adrienverge/openfortivpn/commit/6328a070ddaab16faaf008cb9a8a62439c30f2a8", "commit_message": "fix TLS Certificate CommonName NULL Byte Vulnerability\n\nCVE-2020-7043 TLS Certificate CommonName NULL Byte Vulnerability is fixed\nwith this commit\n\nwith #8 hostname validation for the certificate was introduced\nbut unfortunately strncasecmp() was used to compare the byte array\nagainst the expected hostname. This does not correctly treat a CN\nwhich contains a NULL byte. In order to fix this vulnerability\nthe reference implementation from iSECPartners has been included\ninto the code.", "target": 0, "func": "static int ssl_verify_cert(struct tunnel *tunnel)\n{\n\tint ret = -1;\n\tint cert_valid = 0;\n\tunsigned char digest[SHA256LEN];\n\tunsigned int len;\n\tstruct x509_digest *elem;\n\tchar digest_str[SHA256STRLEN], *subject, *issuer;\n\tchar *line;\n\tint i;\n\tX509_NAME *subj;\n\n\tSSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);\n\n\tX509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);\n\tif (cert == NULL) {\n\t\tlog_error(\"Unable to get gateway certificate.\\n\");\n\t\treturn 1;\n\t}\n\n\tsubj = X509_get_subject_name(cert);\n\n#ifdef HAVE_X509_CHECK_HOST\n\t// Use OpenSSL native host validation if v >= 1.0.2.\n\t// compare against gateway_host and correctly check return value\n\t// to fix piror Incorrect use of X509_check_host\n\tif (X509_check_host(cert, tunnel->config->gateway_host,\n\t 0, 0, NULL) == 1)\n\t\tcert_valid = 1;\n#else\n\t// Use validate_hostname form iSECPartners if native validation not available\n\t// in order to avoid TLS Certificate CommonName NULL Byte Vulnerability\n\tif (validate_hostname(tunnel->config->gateway_host, cert) == MatchFound)\n \t\tcert_valid = 1;\n#endif\n\n\t// Try to validate certificate using local PKI\n\tif (cert_valid\n\t && SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {\n\t\tlog_debug(\"Gateway certificate validation succeeded.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\tlog_debug(\"Gateway certificate validation failed.\\n\");\n\n\t// If validation failed, check if cert is in the white list\n\tif (X509_digest(cert, EVP_sha256(), digest, &len) <= 0\n\t || len != SHA256LEN) {\n\t\tlog_error(\"Could not compute certificate sha256 digest.\\n\");\n\t\tgoto free_cert;\n\t}\n\t// Encode digest in base16\n\tfor (i = 0; i < SHA256LEN; i++)\n\t\tsprintf(&digest_str[2 * i], \"%02x\", digest[i]);\n\tdigest_str[SHA256STRLEN - 1] = '\\0';\n\t// Is it in whitelist?\n\tfor (elem = tunnel->config->cert_whitelist; elem != NULL;\n\t elem = elem->next)\n\t\tif (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)\n\t\t\tbreak;\n\tif (elem != NULL) { // break before end of loop\n\t\tlog_debug(\"Gateway certificate digest found in white list.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\n\tsubject = X509_NAME_oneline(subj, NULL, 0);\n\tissuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n\n\tlog_error(\"Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\\n\");\n\tlog_error(\" --trusted-cert %s\\n\", digest_str);\n\tlog_error(\"or add this line to your config file:\\n\");\n\tlog_error(\" trusted-cert = %s\\n\", digest_str);\n\tlog_error(\"Gateway certificate:\\n\");\n\tlog_error(\" subject:\\n\");\n\tfor (line = strtok(subject, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" issuer:\\n\");\n\tfor (line = strtok(issuer, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" sha256 digest:\\n\");\n\tlog_error(\" %s\\n\", digest_str);\n\nfree_cert:\n\tX509_free(cert);\n\treturn ret;\n}", "func_hash": 40713904292106712785484150787893397974, "file_name": "None", "file_hash": null, "cwe": ["CWE-295"], "cve": "CVE-2020-7043", "cve_desc": "An issue was discovered in openfortivpn 1.11.0 when used with OpenSSL before 1.0.2. tunnel.c mishandles certificate validation because hostname comparisons do not consider '\\0' characters, as demonstrated by a good.example.com\\x00evil.example.com attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7043"} {"idx": 197417, "project": "gpac", "commit_id": "5aba27604d957e960d8069d85ccaf868f8a7b07a", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/5aba27604d957e960d8069d85ccaf868f8a7b07a", "commit_message": "fixed #1661", "target": 1, "func": "void CleanWriters(GF_List *writers)\n{\n\twhile (gf_list_count(writers)) {\n\t\tTrackWriter *writer = (TrackWriter*)gf_list_get(writers, 0);\n\t\tgf_isom_box_del(writer->stco);\n\t\tgf_isom_box_del((GF_Box *)writer->stsc);\n\t\tgf_free(writer);\n\t\tgf_list_rem(writers, 0);\n\t}\n}", "func_hash": 121452612481286418299631099668174467689, "file_name": "isom_store.c", "file_hash": 338457397792726647767624897587669032469, "cwe": ["CWE-416"], "cve": "CVE-2020-35980", "cve_desc": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is a use-after-free in the function gf_isom_box_del() in isomedia/box_funcs.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35980"} {"idx": 258460, "project": "gpac", "commit_id": "5aba27604d957e960d8069d85ccaf868f8a7b07a", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/5aba27604d957e960d8069d85ccaf868f8a7b07a", "commit_message": "fixed #1661", "target": 0, "func": "void CleanWriters(GF_List *writers)\n{\n\twhile (gf_list_count(writers)) {\n\t\tTrackWriter *writer = (TrackWriter*)gf_list_get(writers, 0);\n\t\t//in case we have an error in the middle of file write, remove our created stco and stsc from sample table\n\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stco);\n\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stsc);\n\t\tgf_isom_box_del(writer->stco);\n\t\tgf_isom_box_del((GF_Box *)writer->stsc);\n\t\tgf_free(writer);\n\t\tgf_list_rem(writers, 0);\n\t}\n}", "func_hash": 81939705768680503398925286425910329694, "file_name": "isom_store.c", "file_hash": 8944833003799279989947131987357453368, "cwe": ["CWE-416"], "cve": "CVE-2020-35980", "cve_desc": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is a use-after-free in the function gf_isom_box_del() in isomedia/box_funcs.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35980"} {"idx": 197433, "project": "gpac", "commit_id": "2da2f68bffd51d89b1d272d22aa8cc023c1c066e", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/2da2f68bffd51d89b1d272d22aa8cc023c1c066e", "commit_message": "fixed #1705", "target": 1, "func": "GF_Err stbl_GetSampleInfos(GF_SampleTableBox *stbl, u32 sampleNumber, u64 *offset, u32 *chunkNumber, u32 *descIndex, GF_StscEntry **out_ent)\n{\n\tGF_Err e;\n\tu32 i, k, offsetInChunk, size, chunk_num;\n\tGF_ChunkOffsetBox *stco;\n\tGF_ChunkLargeOffsetBox *co64;\n\tGF_StscEntry *ent;\n\n\t(*offset) = 0;\n\t(*chunkNumber) = (*descIndex) = 0;\n\tif (out_ent) (*out_ent) = NULL;\n\tif (!stbl || !sampleNumber) return GF_BAD_PARAM;\n\tif (!stbl->ChunkOffset || !stbl->SampleToChunk || !stbl->SampleSize) return GF_ISOM_INVALID_FILE;\n\n\tif (stbl->SampleSize && stbl->SampleToChunk->nb_entries == stbl->SampleSize->sampleCount) {\n\t\tent = &stbl->SampleToChunk->entries[sampleNumber-1];\n\t\tif (!ent) return GF_BAD_PARAM;\n\t\t(*descIndex) = ent->sampleDescriptionIndex;\n\t\t(*chunkNumber) = sampleNumber;\n\t\tif (out_ent) *out_ent = ent;\n\t\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!stco->offsets) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = (u64) stco->offsets[sampleNumber - 1];\n\t\t} else {\n\t\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!co64->offsets) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = co64->offsets[sampleNumber - 1];\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\t//check our cache: if desired sample is at or above current cache entry, start from here\n\tif (stbl->SampleToChunk->firstSampleInCurrentChunk &&\n\t (stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber)) {\n\n\t\ti = stbl->SampleToChunk->currentIndex;\n\t\tent = &stbl->SampleToChunk->entries[stbl->SampleToChunk->currentIndex];\n\t\tGetGhostNum(ent, i, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\t//otherwise start from first entry\n\telse {\n\t\ti = 0;\n\t\tstbl->SampleToChunk->currentIndex = 0;\n\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\tstbl->SampleToChunk->ghostNumber = 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk = 1;\n\t\tent = &stbl->SampleToChunk->entries[0];\n\t\tGetGhostNum(ent, 0, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\n\t//first get the chunk\n\tfor (; i < stbl->SampleToChunk->nb_entries; i++) {\n\t\tassert(stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber);\n\t\t//corrupted file (less sample2chunk info than sample count\n\t\tif (k > stbl->SampleToChunk->ghostNumber) {\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\n\t\t//check if sample is in current chunk\n\t\tu32 max_chunks_in_entry = stbl->SampleToChunk->ghostNumber - k;\n\t\tu32 nb_chunks_for_sample = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\tif (ent->samplesPerChunk) \n\t\t\tnb_chunks_for_sample /= ent->samplesPerChunk;\n\n\t\tif (\n\t\t\t(nb_chunks_for_sample <= max_chunks_in_entry)\n\t\t\t&& (stbl->SampleToChunk->firstSampleInCurrentChunk + (nb_chunks_for_sample+1) * ent->samplesPerChunk > sampleNumber)\n\t\t) {\n\n\t\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += nb_chunks_for_sample * ent->samplesPerChunk;\n\t\t\tstbl->SampleToChunk->currentChunk += nb_chunks_for_sample;\n\t\t\tgoto sample_found;\n\t\t}\n\t\tmax_chunks_in_entry += 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += max_chunks_in_entry * ent->samplesPerChunk;\n\t\tstbl->SampleToChunk->currentChunk += max_chunks_in_entry;\n\n\t\t//not in this entry, get the next entry if not the last one\n\t\tif (i+1 != stbl->SampleToChunk->nb_entries) {\n\t\t\tent = &stbl->SampleToChunk->entries[i+1];\n\t\t\t//update the GhostNumber\n\t\t\tGetGhostNum(ent, i+1, stbl->SampleToChunk->nb_entries, stbl);\n\t\t\t//update the entry in our cache\n\t\t\tstbl->SampleToChunk->currentIndex = i+1;\n\t\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\t\tk = 1;\n\t\t}\n\t}\n\t//if we get here, gasp, the sample was not found\n\treturn GF_ISOM_INVALID_FILE;\n\nsample_found:\n\n\t(*descIndex) = ent->sampleDescriptionIndex;\n\t(*chunkNumber) = chunk_num = ent->firstChunk + stbl->SampleToChunk->currentChunk - 1;\n\tif (out_ent) *out_ent = ent;\n\tif (! *chunkNumber)\n\t\treturn GF_ISOM_INVALID_FILE;\n\t\n\t//ok, get the size of all the previous samples in the chunk\n\toffsetInChunk = 0;\n\t//constant size\n\tif (stbl->SampleSize && stbl->SampleSize->sampleSize) {\n\t\tu32 diff = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\toffsetInChunk += diff * stbl->SampleSize->sampleSize;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num == sampleNumber)) {\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num + 1 == sampleNumber)) {\n\t\te = stbl_GetSampleSize(stbl->SampleSize, stbl->r_last_sample_num, &size);\n\t\tif (e) return e;\n\t\tstbl->r_last_offset_in_chunk += size;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else {\n\t\t//warning, firstSampleInChunk is at least 1 - not 0\n\t\tfor (i = stbl->SampleToChunk->firstSampleInCurrentChunk; i < sampleNumber; i++) {\n\t\t\te = stbl_GetSampleSize(stbl->SampleSize, i, &size);\n\t\t\tif (e) return e;\n\t\t\toffsetInChunk += size;\n\t\t}\n\t\tstbl->r_last_chunk_num = chunk_num;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\tstbl->r_last_offset_in_chunk = offsetInChunk;\n\t}\n\t//OK, that's the size of our offset in the chunk\n\t//now get the chunk\n\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\tif (stco->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = (u64) stco->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t} else {\n\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\tif (co64->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = co64->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t}\n\treturn GF_OK;\n}", "func_hash": 160915137715994750835684574667945977691, "file_name": "stbl_read.c", "file_hash": 126250742115371105366851881073074299292, "cwe": ["CWE-416"], "cve": "CVE-2021-31256", "cve_desc": "Memory leak in the stbl_GetSampleInfos function in MP4Box in GPAC 1.0.1 allows attackers to read memory via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31256"} {"idx": 258553, "project": "gpac", "commit_id": "2da2f68bffd51d89b1d272d22aa8cc023c1c066e", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/2da2f68bffd51d89b1d272d22aa8cc023c1c066e", "commit_message": "fixed #1705", "target": 0, "func": "GF_Err stbl_GetSampleInfos(GF_SampleTableBox *stbl, u32 sampleNumber, u64 *offset, u32 *chunkNumber, u32 *descIndex, GF_StscEntry **out_ent)\n{\n\tGF_Err e;\n\tu32 i, k, offsetInChunk, size, chunk_num;\n\tGF_ChunkOffsetBox *stco;\n\tGF_ChunkLargeOffsetBox *co64;\n\tGF_StscEntry *ent;\n\n\t(*offset) = 0;\n\t(*chunkNumber) = (*descIndex) = 0;\n\tif (out_ent) (*out_ent) = NULL;\n\tif (!stbl || !sampleNumber) return GF_BAD_PARAM;\n\tif (!stbl->ChunkOffset || !stbl->SampleToChunk || !stbl->SampleSize) return GF_ISOM_INVALID_FILE;\n\n\tif (stbl->SampleSize && stbl->SampleToChunk->nb_entries == stbl->SampleSize->sampleCount) {\n\t\tent = &stbl->SampleToChunk->entries[sampleNumber-1];\n\t\tif (!ent) return GF_BAD_PARAM;\n\t\t(*descIndex) = ent->sampleDescriptionIndex;\n\t\t(*chunkNumber) = sampleNumber;\n\t\tif (out_ent) *out_ent = ent;\n\t\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!stco->offsets) return GF_ISOM_INVALID_FILE;\n\t\t\tif (stco->nb_entries < sampleNumber) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = (u64) stco->offsets[sampleNumber - 1];\n\t\t} else {\n\t\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!co64->offsets) return GF_ISOM_INVALID_FILE;\n\t\t\tif (co64->nb_entries < sampleNumber) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = co64->offsets[sampleNumber - 1];\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\t//check our cache: if desired sample is at or above current cache entry, start from here\n\tif (stbl->SampleToChunk->firstSampleInCurrentChunk &&\n\t (stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber)) {\n\n\t\ti = stbl->SampleToChunk->currentIndex;\n\t\tent = &stbl->SampleToChunk->entries[stbl->SampleToChunk->currentIndex];\n\t\tGetGhostNum(ent, i, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\t//otherwise start from first entry\n\telse {\n\t\ti = 0;\n\t\tstbl->SampleToChunk->currentIndex = 0;\n\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\tstbl->SampleToChunk->ghostNumber = 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk = 1;\n\t\tent = &stbl->SampleToChunk->entries[0];\n\t\tGetGhostNum(ent, 0, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\n\t//first get the chunk\n\tfor (; i < stbl->SampleToChunk->nb_entries; i++) {\n\t\tassert(stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber);\n\t\t//corrupted file (less sample2chunk info than sample count\n\t\tif (k > stbl->SampleToChunk->ghostNumber) {\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\n\t\t//check if sample is in current chunk\n\t\tu32 max_chunks_in_entry = stbl->SampleToChunk->ghostNumber - k;\n\t\tu32 nb_chunks_for_sample = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\tif (ent->samplesPerChunk) \n\t\t\tnb_chunks_for_sample /= ent->samplesPerChunk;\n\n\t\tif (\n\t\t\t(nb_chunks_for_sample <= max_chunks_in_entry)\n\t\t\t&& (stbl->SampleToChunk->firstSampleInCurrentChunk + (nb_chunks_for_sample+1) * ent->samplesPerChunk > sampleNumber)\n\t\t) {\n\n\t\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += nb_chunks_for_sample * ent->samplesPerChunk;\n\t\t\tstbl->SampleToChunk->currentChunk += nb_chunks_for_sample;\n\t\t\tgoto sample_found;\n\t\t}\n\t\tmax_chunks_in_entry += 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += max_chunks_in_entry * ent->samplesPerChunk;\n\t\tstbl->SampleToChunk->currentChunk += max_chunks_in_entry;\n\n\t\t//not in this entry, get the next entry if not the last one\n\t\tif (i+1 != stbl->SampleToChunk->nb_entries) {\n\t\t\tent = &stbl->SampleToChunk->entries[i+1];\n\t\t\t//update the GhostNumber\n\t\t\tGetGhostNum(ent, i+1, stbl->SampleToChunk->nb_entries, stbl);\n\t\t\t//update the entry in our cache\n\t\t\tstbl->SampleToChunk->currentIndex = i+1;\n\t\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\t\tk = 1;\n\t\t}\n\t}\n\t//if we get here, gasp, the sample was not found\n\treturn GF_ISOM_INVALID_FILE;\n\nsample_found:\n\n\t(*descIndex) = ent->sampleDescriptionIndex;\n\t(*chunkNumber) = chunk_num = ent->firstChunk + stbl->SampleToChunk->currentChunk - 1;\n\tif (out_ent) *out_ent = ent;\n\tif (! *chunkNumber)\n\t\treturn GF_ISOM_INVALID_FILE;\n\t\n\t//ok, get the size of all the previous samples in the chunk\n\toffsetInChunk = 0;\n\t//constant size\n\tif (stbl->SampleSize && stbl->SampleSize->sampleSize) {\n\t\tu32 diff = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\toffsetInChunk += diff * stbl->SampleSize->sampleSize;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num == sampleNumber)) {\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num + 1 == sampleNumber)) {\n\t\te = stbl_GetSampleSize(stbl->SampleSize, stbl->r_last_sample_num, &size);\n\t\tif (e) return e;\n\t\tstbl->r_last_offset_in_chunk += size;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else {\n\t\t//warning, firstSampleInChunk is at least 1 - not 0\n\t\tfor (i = stbl->SampleToChunk->firstSampleInCurrentChunk; i < sampleNumber; i++) {\n\t\t\te = stbl_GetSampleSize(stbl->SampleSize, i, &size);\n\t\t\tif (e) return e;\n\t\t\toffsetInChunk += size;\n\t\t}\n\t\tstbl->r_last_chunk_num = chunk_num;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\tstbl->r_last_offset_in_chunk = offsetInChunk;\n\t}\n\t//OK, that's the size of our offset in the chunk\n\t//now get the chunk\n\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\tif (stco->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = (u64) stco->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t} else {\n\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\tif (co64->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = co64->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t}\n\treturn GF_OK;\n}", "func_hash": 190210457362100569482246599043587791041, "file_name": "stbl_read.c", "file_hash": 272972149996696841982184365511641332455, "cwe": ["CWE-416"], "cve": "CVE-2021-31256", "cve_desc": "Memory leak in the stbl_GetSampleInfos function in MP4Box in GPAC 1.0.1 allows attackers to read memory via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31256"} {"idx": 197465, "project": "mpv", "commit_id": "d0c530919d8cd4d7a774e38ab064e0fabdae34e6", "project_url": "https://github.com/mpv-player/mpv", "commit_url": "https://github.com/mpv-player/mpv/commit/d0c530919d8cd4d7a774e38ab064e0fabdae34e6", "commit_message": "demux_mf: improve format string processing\n\nBefore this commit, the user could specify a printf format string\nwhich wasn't verified, and could result in:\n- Undefined behavior due to missing or non-matching arguments.\n- Buffer overflow due to untested result length.\n\nThe offending code was added at commit 103a9609 (2002, mplayer svn):\ngit-svn-id: svn://svn.mplayerhq.hu/mplayer/trunk@4566 b3059339-0415-0410-9bf9-f77b7e298cf2\n\nIt moved around but was not modified meaningfully until now.\n\nNow we reject all conversion specifiers at the format except %%\nand a simple subset of the valid specifiers. Also, we now use\nsnprintf to avoid buffer overflow.\n\nThe format string is provided by the user as part of mf:// URI.\n\nReport and initial patch by Stefan Schiller.\nPatch reviewed by @jeeb, @sfan5, Stefan Schiller.", "target": 1, "func": "static mf_t *open_mf_pattern(void *talloc_ctx, struct demuxer *d, char *filename)\n{\n struct mp_log *log = d->log;\n int error_count = 0;\n int count = 0;\n\n mf_t *mf = talloc_zero(talloc_ctx, mf_t);\n mf->log = log;\n\n if (filename[0] == '@') {\n struct stream *s = stream_create(filename + 1,\n d->stream_origin | STREAM_READ, d->cancel, d->global);\n if (s) {\n while (1) {\n char buf[512];\n int len = stream_read_peek(s, buf, sizeof(buf));\n if (!len)\n break;\n bstr data = (bstr){buf, len};\n int pos = bstrchr(data, '\\n');\n data = bstr_splice(data, 0, pos < 0 ? data.len : pos + 1);\n bstr fname = bstr_strip(data);\n if (fname.len) {\n if (bstrchr(fname, '\\0') >= 0) {\n mp_err(log, \"invalid filename\\n\");\n break;\n }\n char *entry = bstrto0(mf, fname);\n if (!mp_path_exists(entry)) {\n mp_verbose(log, \"file not found: '%s'\\n\", entry);\n } else {\n MP_TARRAY_APPEND(mf, mf->names, mf->nr_of_files, entry);\n }\n }\n stream_seek_skip(s, stream_tell(s) + data.len);\n }\n free_stream(s);\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n goto exit_mf;\n }\n mp_info(log, \"%s is not indirect filelist\\n\", filename + 1);\n }\n\n if (strchr(filename, ',')) {\n mp_info(log, \"filelist: %s\\n\", filename);\n bstr bfilename = bstr0(filename);\n\n while (bfilename.len) {\n bstr bfname;\n bstr_split_tok(bfilename, \",\", &bfname, &bfilename);\n char *fname2 = bstrdup0(mf, bfname);\n\n if (!mp_path_exists(fname2))\n mp_verbose(log, \"file not found: '%s'\\n\", fname2);\n else {\n mf_add(mf, fname2);\n }\n talloc_free(fname2);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\n goto exit_mf;\n }\n\n char *fname = talloc_size(mf, strlen(filename) + 32);\n\n#if HAVE_GLOB\n if (!strchr(filename, '%')) {\n strcpy(fname, filename);\n if (!strchr(filename, '*'))\n strcat(fname, \"*\");\n\n mp_info(log, \"search expr: %s\\n\", fname);\n\n glob_t gg;\n if (glob(fname, 0, NULL, &gg)) {\n talloc_free(mf);\n return NULL;\n }\n\n for (int i = 0; i < gg.gl_pathc; i++) {\n if (mp_path_isdir(gg.gl_pathv[i]))\n continue;\n mf_add(mf, gg.gl_pathv[i]);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n globfree(&gg);\n goto exit_mf;\n }\n#endif\n\n mp_info(log, \"search expr: %s\\n\", filename);\n\n while (error_count < 5) {\n sprintf(fname, filename, count++);\n if (!mp_path_exists(fname)) {\n error_count++;\n mp_verbose(log, \"file not found: '%s'\\n\", fname);\n } else {\n mf_add(mf, fname);\n }\n }\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\nexit_mf:\n return mf;\n}", "func_hash": 304764368265976283042185246858897259939, "file_name": "demux_mf.c", "file_hash": 305755919765663619983328890438805441070, "cwe": ["CWE-134"], "cve": "CVE-2021-30145", "cve_desc": "A format string vulnerability in mpv through 0.33.0 allows user-assisted remote attackers to achieve code execution via a crafted m3u playlist file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30145"} {"idx": 259078, "project": "mpv", "commit_id": "d0c530919d8cd4d7a774e38ab064e0fabdae34e6", "project_url": "https://github.com/mpv-player/mpv", "commit_url": "https://github.com/mpv-player/mpv/commit/d0c530919d8cd4d7a774e38ab064e0fabdae34e6", "commit_message": "demux_mf: improve format string processing\n\nBefore this commit, the user could specify a printf format string\nwhich wasn't verified, and could result in:\n- Undefined behavior due to missing or non-matching arguments.\n- Buffer overflow due to untested result length.\n\nThe offending code was added at commit 103a9609 (2002, mplayer svn):\ngit-svn-id: svn://svn.mplayerhq.hu/mplayer/trunk@4566 b3059339-0415-0410-9bf9-f77b7e298cf2\n\nIt moved around but was not modified meaningfully until now.\n\nNow we reject all conversion specifiers at the format except %%\nand a simple subset of the valid specifiers. Also, we now use\nsnprintf to avoid buffer overflow.\n\nThe format string is provided by the user as part of mf:// URI.\n\nReport and initial patch by Stefan Schiller.\nPatch reviewed by @jeeb, @sfan5, Stefan Schiller.", "target": 0, "func": "static mf_t *open_mf_pattern(void *talloc_ctx, struct demuxer *d, char *filename)\n{\n struct mp_log *log = d->log;\n int error_count = 0;\n int count = 0;\n\n mf_t *mf = talloc_zero(talloc_ctx, mf_t);\n mf->log = log;\n\n if (filename[0] == '@') {\n struct stream *s = stream_create(filename + 1,\n d->stream_origin | STREAM_READ, d->cancel, d->global);\n if (s) {\n while (1) {\n char buf[512];\n int len = stream_read_peek(s, buf, sizeof(buf));\n if (!len)\n break;\n bstr data = (bstr){buf, len};\n int pos = bstrchr(data, '\\n');\n data = bstr_splice(data, 0, pos < 0 ? data.len : pos + 1);\n bstr fname = bstr_strip(data);\n if (fname.len) {\n if (bstrchr(fname, '\\0') >= 0) {\n mp_err(log, \"invalid filename\\n\");\n break;\n }\n char *entry = bstrto0(mf, fname);\n if (!mp_path_exists(entry)) {\n mp_verbose(log, \"file not found: '%s'\\n\", entry);\n } else {\n MP_TARRAY_APPEND(mf, mf->names, mf->nr_of_files, entry);\n }\n }\n stream_seek_skip(s, stream_tell(s) + data.len);\n }\n free_stream(s);\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n goto exit_mf;\n }\n mp_info(log, \"%s is not indirect filelist\\n\", filename + 1);\n }\n\n if (strchr(filename, ',')) {\n mp_info(log, \"filelist: %s\\n\", filename);\n bstr bfilename = bstr0(filename);\n\n while (bfilename.len) {\n bstr bfname;\n bstr_split_tok(bfilename, \",\", &bfname, &bfilename);\n char *fname2 = bstrdup0(mf, bfname);\n\n if (!mp_path_exists(fname2))\n mp_verbose(log, \"file not found: '%s'\\n\", fname2);\n else {\n mf_add(mf, fname2);\n }\n talloc_free(fname2);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\n goto exit_mf;\n }\n\n size_t fname_avail = strlen(filename) + 32;\n char *fname = talloc_size(mf, fname_avail);\n\n#if HAVE_GLOB\n if (!strchr(filename, '%')) {\n strcpy(fname, filename);\n if (!strchr(filename, '*'))\n strcat(fname, \"*\");\n\n mp_info(log, \"search expr: %s\\n\", fname);\n\n glob_t gg;\n if (glob(fname, 0, NULL, &gg)) {\n talloc_free(mf);\n return NULL;\n }\n\n for (int i = 0; i < gg.gl_pathc; i++) {\n if (mp_path_isdir(gg.gl_pathv[i]))\n continue;\n mf_add(mf, gg.gl_pathv[i]);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n globfree(&gg);\n goto exit_mf;\n }\n#endif\n\n // We're using arbitrary user input as printf format with 1 int argument.\n // Any format which uses exactly 1 int argument would be valid, but for\n // simplicity we reject all conversion specifiers except %% and simple\n // integer specifier: %[.][NUM]d where NUM is 1-3 digits (%.d is valid)\n const char *f = filename;\n int MAXDIGS = 3, nspec = 0, bad_spec = 0, c;\n\n while (nspec < 2 && (c = *f++)) {\n if (c != '%')\n continue;\n if (*f != '%') {\n nspec++; // conversion specifier which isn't %%\n if (*f == '.')\n f++;\n for (int ndig = 0; mp_isdigit(*f) && ndig < MAXDIGS; ndig++, f++)\n /* no-op */;\n if (*f != 'd') {\n bad_spec++; // not int, or beyond our validation capacity\n break;\n }\n }\n // *f is '%' or 'd'\n f++;\n }\n\n // nspec==0 (zero specifiers) is rejected because fname wouldn't advance.\n if (bad_spec || nspec != 1) {\n mp_err(log, \"unsupported expr format: '%s'\\n\", filename);\n goto exit_mf;\n }\n\n mp_info(log, \"search expr: %s\\n\", filename);\n\n while (error_count < 5) {\n if (snprintf(fname, fname_avail, filename, count++) >= fname_avail) {\n mp_err(log, \"format result too long: '%s'\\n\", filename);\n goto exit_mf;\n }\n if (!mp_path_exists(fname)) {\n error_count++;\n mp_verbose(log, \"file not found: '%s'\\n\", fname);\n } else {\n mf_add(mf, fname);\n }\n }\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\nexit_mf:\n return mf;\n}", "func_hash": 261876196693293576017295450405726481245, "file_name": "demux_mf.c", "file_hash": 197578774368000154694316497619820943172, "cwe": ["CWE-134"], "cve": "CVE-2021-30145", "cve_desc": "A format string vulnerability in mpv through 0.33.0 allows user-assisted remote attackers to achieve code execution via a crafted m3u playlist file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30145"} {"idx": 197476, "project": "hermes", "commit_id": "8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0", "commit_message": "Handle set where internalSetter and Proxy are both true\n\nSummary:\nIf putComputed is called on a proxy whose target's prototype\nis an array with a propname of 'length', then internalSetter will be\ntrue, and the receiver will be a proxy. In that case, proxy needs to\nwin; the behavior may assert or be UB otherwise.\n\nReviewed By: tmikov\n\nDifferential Revision: D23916279\n\nfbshipit-source-id: c760356d48a02ece565fb4bc1acdafd7ccad7c68", "target": 1, "func": "CallResult JSObject::putComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() &&\n \"mustExist flag cannot be used with computed properties\");\n\n // Try the fast-path first: has \"index-like\" properties, the \"name\"\n // already is a valid integer index, selfHandle and receiver are the\n // same, and it is present in storage.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n \"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Look for the property in this object or along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.\n\n if (LLVM_LIKELY(\n selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(selfHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n // Is it an accessor?\n if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to property \",\n nameValPrimitiveHandle,\n \" which has only a getter\");\n }\n return false;\n }\n\n // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n valueHandle.get()) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult setRes =\n JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy trap returned false for property\"));\n }\n return setRes;\n }\n\n if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(id));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to read-only property \", nameValPrimitiveHandle, \"\");\n }\n return false;\n }\n\n if (selfHandle == propObj && desc.flags.internalSetter) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return internalSetter(\n selfHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n }\n\n // The property does not exist as an conventional own property on\n // this object.\n\n MutableHandle receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }\n\n if (LLVM_LIKELY(\n !desc.flags.internalSetter && !receiverHandle->isHostObject() &&\n !receiverHandle->isProxyObject())) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(\n receiverHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n }\n\n if (LLVM_UNLIKELY(\n desc.flags.internalSetter || receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n if (desc.flags.internalSetter) {\n return internalSetter(\n receiverHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n } else if (receiverHandle->isHostObject()) {\n return vmcast(receiverHandle.get())->set(id, *valueHandle);\n }\n assert(\n receiverHandle->isProxyObject() && \"descriptor flags are impossible\");\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle,\n runtime,\n nameValPrimitiveHandle,\n dpf,\n valueHandle,\n opFlags);\n }\n }\n\n /// Can we add more properties?\n if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }\n\n // If we have indexed storage we must check whether the property is an index,\n // and if it is, store it in indexed storage.\n if (receiverHandle->flags_.indexedStorage) {\n OptValue arrayIndex;\n MutableHandle strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n if (arrayIndex) {\n // Check whether we need to update array's \".length\" property.\n if (auto *array = dyn_vmcast(receiverHandle.get())) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) {\n auto cr = putNamed_RJS(\n receiverHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n runtime->makeHandle(\n HermesValue::encodeNumberValue(*arrayIndex + 1)),\n opFlags);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_UNLIKELY(!*cr))\n return false;\n }\n }\n\n auto result =\n setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n\n // Add a new named property.\n return addOwnProperty(\n receiverHandle,\n runtime,\n id,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "func_hash": 236966743101147887136562731364722597761, "file_name": "JSObject.cpp", "file_hash": 114944590920835284847205698428247648692, "cwe": ["CWE-125"], "cve": "CVE-2020-1915", "cve_desc": "An out-of-bounds read in the JavaScript Interpreter in Facebook Hermes prior to commit 8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0 allows attackers to cause a denial of service attack or possible further memory corruption via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1915"} {"idx": 259369, "project": "hermes", "commit_id": "8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0", "commit_message": "Handle set where internalSetter and Proxy are both true\n\nSummary:\nIf putComputed is called on a proxy whose target's prototype\nis an array with a propname of 'length', then internalSetter will be\ntrue, and the receiver will be a proxy. In that case, proxy needs to\nwin; the behavior may assert or be UB otherwise.\n\nReviewed By: tmikov\n\nDifferential Revision: D23916279\n\nfbshipit-source-id: c760356d48a02ece565fb4bc1acdafd7ccad7c68", "target": 0, "func": "CallResult JSObject::putComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() &&\n \"mustExist flag cannot be used with computed properties\");\n\n // Try the fast-path first: has \"index-like\" properties, the \"name\"\n // already is a valid integer index, selfHandle and receiver are the\n // same, and it is present in storage.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n \"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Look for the property in this object or along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.\n\n if (LLVM_LIKELY(\n selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(selfHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n // Is it an accessor?\n if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to property \",\n nameValPrimitiveHandle,\n \" which has only a getter\");\n }\n return false;\n }\n\n // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n valueHandle.get()) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult setRes =\n JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy trap returned false for property\"));\n }\n return setRes;\n }\n\n if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(id));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to read-only property \", nameValPrimitiveHandle, \"\");\n }\n return false;\n }\n\n if (selfHandle == propObj && desc.flags.internalSetter) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return internalSetter(\n selfHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n }\n\n // The property does not exist as an conventional own property on\n // this object.\n\n MutableHandle receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }\n\n if (LLVM_LIKELY(\n !desc.flags.internalSetter && !receiverHandle->isHostObject() &&\n !receiverHandle->isProxyObject())) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(\n receiverHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n }\n\n if (LLVM_UNLIKELY(\n desc.flags.internalSetter || receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n // If putComputed is called on a proxy whose target's prototype\n // is an array with a propname of 'length', then internalSetter\n // will be true, and the receiver will be a proxy. In that case,\n // proxy wins.\n if (receiverHandle->isProxyObject()) {\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle,\n runtime,\n nameValPrimitiveHandle,\n dpf,\n valueHandle,\n opFlags);\n }\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n if (desc.flags.internalSetter) {\n return internalSetter(\n receiverHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n assert(\n receiverHandle->isHostObject() && \"descriptor flags are impossible\");\n return vmcast(receiverHandle.get())->set(id, *valueHandle);\n }\n }\n\n /// Can we add more properties?\n if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }\n\n // If we have indexed storage we must check whether the property is an index,\n // and if it is, store it in indexed storage.\n if (receiverHandle->flags_.indexedStorage) {\n OptValue arrayIndex;\n MutableHandle strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n if (arrayIndex) {\n // Check whether we need to update array's \".length\" property.\n if (auto *array = dyn_vmcast(receiverHandle.get())) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) {\n auto cr = putNamed_RJS(\n receiverHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n runtime->makeHandle(\n HermesValue::encodeNumberValue(*arrayIndex + 1)),\n opFlags);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_UNLIKELY(!*cr))\n return false;\n }\n }\n\n auto result =\n setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n\n // Add a new named property.\n return addOwnProperty(\n receiverHandle,\n runtime,\n id,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "func_hash": 180879736034706790851138958847125901987, "file_name": "JSObject.cpp", "file_hash": 313398634736354939038310130415553970557, "cwe": ["CWE-125"], "cve": "CVE-2020-1915", "cve_desc": "An out-of-bounds read in the JavaScript Interpreter in Facebook Hermes prior to commit 8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0 allows attackers to cause a denial of service attack or possible further memory corruption via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1915"} {"idx": 197512, "project": "tensorflow", "commit_id": "77dd114513d7796e1e2b8aece214a380af26fbf4", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/77dd114513d7796e1e2b8aece214a380af26fbf4", "commit_message": "Fix a check fail\n\nPiperOrigin-RevId: 372011072\nChange-Id: I1062cfaed0aa16884e9a16312483794d188db76f", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n // Checks what we're remapping and inverts the relevant remapping Tensors to\n // be maps with key = old ID, value = new ID.\n std::unordered_map old_row_to_new_row_map;\n std::vector row_id_present;\n const Tensor* row_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"row_remapping\", &row_remapping_t));\n const auto row_remapping = row_remapping_t->vec();\n OP_REQUIRES(context, row_remapping.size() == num_rows_,\n errors::InvalidArgument(strings::StrCat(\n \"Size of row_remapping is \", row_remapping.size(),\n \" instead of being equal to num_rows=\", num_rows_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(row_remapping, &row_id_present,\n &old_row_to_new_row_map));\n\n // Calculates the min/max old row ID that we need to read, to save us from\n // reading some unnecessary slices of the old tensor.\n int64 min_old_row = -1;\n int64 max_old_row = -1;\n for (int i = 0; i < row_remapping.size(); ++i) {\n if (min_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) < min_old_row)) {\n min_old_row = row_remapping(i);\n }\n if (max_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) > max_old_row)) {\n max_old_row = row_remapping(i);\n }\n }\n\n // Processes the remapping for columns.\n std::unordered_map old_col_to_new_col_map;\n std::vector col_id_present;\n const Tensor* col_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"col_remapping\", &col_remapping_t));\n const auto col_remapping = col_remapping_t->vec();\n // Note that we always \"remap rows\", even when the row vocabulary does\n // not change, because partitioning requires a mapping from partitioned\n // Variables to the full checkpoints we load.\n const bool remap_cols = col_remapping.size() > 0;\n if (remap_cols) {\n OP_REQUIRES(\n context, col_remapping.size() == num_cols_,\n errors::InvalidArgument(strings::StrCat(\n \"Provided col_remapping, but its size is \", col_remapping.size(),\n \" instead of being equal to num_cols=\", num_cols_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(col_remapping, &col_id_present,\n &old_col_to_new_col_map));\n } else {\n col_id_present.clear();\n col_id_present.resize(num_cols_, true);\n }\n\n // Processes the checkpoint source and the provided Tensor name.\n const Tensor* ckpt_path_t;\n OP_REQUIRES_OK(context, context->input(\"ckpt_path\", &ckpt_path_t));\n const string& ckpt_path = ckpt_path_t->scalar()();\n const Tensor* old_tensor_name_t;\n OP_REQUIRES_OK(context,\n context->input(\"old_tensor_name\", &old_tensor_name_t));\n const string& old_tensor_name = old_tensor_name_t->scalar()();\n\n LOG(INFO) << \"Processing checkpoint : \" << ckpt_path;\n BundleReader reader(context->env(), ckpt_path);\n OP_REQUIRES_OK(context, reader.status());\n\n DataType tensor_type;\n TensorShape tensor_shape;\n OP_REQUIRES_OK(context, reader.LookupDtypeAndShape(\n old_tensor_name, &tensor_type, &tensor_shape));\n OP_REQUIRES(context, tensor_type == DT_FLOAT,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has invalid type \",\n DataTypeString(tensor_type), \" instead of expected type \",\n DataTypeString(DT_FLOAT))));\n // This op is limited to loading Tensors of rank 2 (matrices).\n OP_REQUIRES(\n context, tensor_shape.dims() == 2,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(), \" of invalid rank \",\n tensor_shape.dims(), \" instead of expected shape of rank 2.\")));\n\n if (!remap_cols) {\n // TODO(weiho): Consider relaxing this restriction to allow partial column\n // loading (even when no column remapping is specified) if there turns out\n // to be a use case for it.\n OP_REQUIRES(context, num_cols_ == tensor_shape.dim_size(1),\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(),\n \", where the size of its 2nd dimension is \",\n tensor_shape.dim_size(1),\n \" instead of being equal to num_cols=\", num_cols_)));\n }\n\n // Uses TensorSlice to potentially load the old tensor in chunks in case\n // memory usage is a concern.\n std::vector tensor_slices;\n TensorSlice slice(tensor_shape.dims());\n if (min_old_row >= 0 && max_old_row >= 0) {\n int64 row_start = min_old_row;\n // TODO(weiho): Given the list of old row IDs of interest (the keys of\n // old_row_to_new_row_map), we could also try something smarter to\n // find some minimal set of covering ranges for the list of old row IDs\n // such that the size of each range is less than max_rows_in_memory_.\n while (row_start <= max_old_row) {\n const int64 slice_length =\n max_rows_in_memory_ <= 0\n // If max_rows_in_memory_ <= 0, we just load the entire chunk.\n ? max_old_row - row_start + 1\n : std::min(max_rows_in_memory_, max_old_row - row_start + 1);\n slice.set_start(0, row_start);\n slice.set_length(0, slice_length);\n tensor_slices.push_back(slice);\n row_start += slice_length;\n }\n }\n\n // Allocates the output matrix.\n Tensor* output_matrix_t = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"output_matrix\",\n TensorShape({num_rows_, num_cols_}),\n &output_matrix_t));\n auto output_matrix = output_matrix_t->matrix();\n\n // Iterates through tensor slices and copies over values from the old tensor\n // to the output matrix.\n int64 row_index = min_old_row;\n int64 rows_copied = 0;\n Tensor loaded_tensor_t;\n for (const TensorSlice& tensor_slice : tensor_slices) {\n LOG(INFO) << \"Loading slice \" << tensor_slice.DebugString();\n TensorShape slice_shape;\n OP_REQUIRES_OK(context,\n tensor_slice.SliceTensorShape(tensor_shape, &slice_shape));\n // Potentially re-allocates the tensor buffer since the last slice may\n // have fewer rows than the other slices.\n if (loaded_tensor_t.shape() != slice_shape) {\n loaded_tensor_t = Tensor(DT_FLOAT, slice_shape);\n }\n OP_REQUIRES_OK(context, reader.LookupSlice(old_tensor_name, tensor_slice,\n &loaded_tensor_t));\n\n // Iterates through the old loaded tensor slice row-by-row.\n for (int row = 0; row < loaded_tensor_t.dim_size(0); ++row, ++row_index) {\n if (row_index % 500000 == min_old_row) {\n LOG(INFO) << \"Processing old row \" << row_index;\n }\n\n // If the old row ID is not found in old_row_to_new_row_map, continue\n // to the next row; otherwise, copy it to the output matrix.\n const int64* new_row_ptr =\n gtl::FindOrNull(old_row_to_new_row_map, row_index);\n if (new_row_ptr == nullptr) {\n continue;\n }\n ++rows_copied;\n const int64 new_row = *new_row_ptr;\n\n // Copies over the row element-by-element, in case remapping is needed\n // along the column axis.\n const auto& loaded_tensor = loaded_tensor_t.matrix();\n for (int old_col = 0; old_col < loaded_tensor_t.dim_size(1);\n ++old_col) {\n int64 new_col = old_col;\n if (remap_cols) {\n const int64* new_col_ptr =\n gtl::FindOrNull(old_col_to_new_col_map, old_col);\n if (new_col_ptr == nullptr) {\n // Column remapping is specified, but this column is not found in\n // old_col_to_new_col_map, so we leave it uninitialized, to be\n // filled in with initializing_values later.\n continue;\n }\n new_col = *new_col_ptr;\n }\n\n OP_REQUIRES(context,\n new_row < num_rows_ && new_col < num_cols_ &&\n new_row >= 0 && new_col >= 0,\n errors::Internal(strings::StrCat(\n \"new_row=\", new_row, \" and new_col=\", new_col,\n \" should have been less than num_rows_=\", num_rows_,\n \" and num_cols_=\", num_cols_,\n \" and non-negative. This should never have happened \"\n \"if the code were correct. Please file a bug.\")));\n output_matrix(new_row, new_col) = loaded_tensor(row, old_col);\n }\n }\n }\n LOG(INFO) << \"Copied \" << rows_copied << \" rows from old matrix (with \"\n << tensor_shape.dim_size(0) << \" rows) to new matrix (with \"\n << num_rows_ << \" rows).\";\n\n // At this point, there are potentially whole rows/columns uninitialized\n // (corresponding to the indices where row_id_present/col_id_present are\n // false). We fill this in cell-by-cell using row_id_present and\n // col_id_present while dequeuing from the initializing_values vector.\n const Tensor* initializing_values_t;\n OP_REQUIRES_OK(\n context, context->input(\"initializing_values\", &initializing_values_t));\n const auto initializing_values = initializing_values_t->flat();\n int64 initializing_values_index = 0;\n for (int i = 0; i < num_rows_; ++i) {\n for (int j = 0; j < num_cols_; ++j) {\n if (row_id_present[i] && col_id_present[j]) continue;\n OP_REQUIRES(\n context, initializing_values_index < initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but more missing values remain.\"));\n output_matrix(i, j) = initializing_values(initializing_values_index);\n ++initializing_values_index;\n }\n }\n\n // Checks that we used all the given initializing values.\n OP_REQUIRES(\n context, initializing_values_index == initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but only \", initializing_values_index,\n \" elements were used to fill in missing values.\"));\n }", "func_hash": 80875128026884430703598016991593176887, "file_name": "load_and_remap_matrix_op.cc", "file_hash": 294248211774345343220661731671890857803, "cwe": ["CWE-369"], "cve": "CVE-2021-29561", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service by exploiting a `CHECK`-failure coming from `tf.raw_ops.LoadAndRemapMatrix`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/d94227d43aa125ad8b54115c03cece54f6a1977b/tensorflow/core/kernels/ragged_tensor_to_tensor_op.cc#L219-L222) assumes that the `ckpt_path` is always a valid scalar. However, an attacker can send any other tensor as the first argument of `LoadAndRemapMatrix`. This would cause the rank `CHECK` in `scalar()()` to trigger and terminate the process. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29561"} {"idx": 259623, "project": "tensorflow", "commit_id": "77dd114513d7796e1e2b8aece214a380af26fbf4", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/77dd114513d7796e1e2b8aece214a380af26fbf4", "commit_message": "Fix a check fail\n\nPiperOrigin-RevId: 372011072\nChange-Id: I1062cfaed0aa16884e9a16312483794d188db76f", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n // Checks what we're remapping and inverts the relevant remapping Tensors to\n // be maps with key = old ID, value = new ID.\n std::unordered_map old_row_to_new_row_map;\n std::vector row_id_present;\n const Tensor* row_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"row_remapping\", &row_remapping_t));\n const auto row_remapping = row_remapping_t->vec();\n OP_REQUIRES(context, row_remapping.size() == num_rows_,\n errors::InvalidArgument(strings::StrCat(\n \"Size of row_remapping is \", row_remapping.size(),\n \" instead of being equal to num_rows=\", num_rows_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(row_remapping, &row_id_present,\n &old_row_to_new_row_map));\n\n // Calculates the min/max old row ID that we need to read, to save us from\n // reading some unnecessary slices of the old tensor.\n int64 min_old_row = -1;\n int64 max_old_row = -1;\n for (int i = 0; i < row_remapping.size(); ++i) {\n if (min_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) < min_old_row)) {\n min_old_row = row_remapping(i);\n }\n if (max_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) > max_old_row)) {\n max_old_row = row_remapping(i);\n }\n }\n\n // Processes the remapping for columns.\n std::unordered_map old_col_to_new_col_map;\n std::vector col_id_present;\n const Tensor* col_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"col_remapping\", &col_remapping_t));\n const auto col_remapping = col_remapping_t->vec();\n // Note that we always \"remap rows\", even when the row vocabulary does\n // not change, because partitioning requires a mapping from partitioned\n // Variables to the full checkpoints we load.\n const bool remap_cols = col_remapping.size() > 0;\n if (remap_cols) {\n OP_REQUIRES(\n context, col_remapping.size() == num_cols_,\n errors::InvalidArgument(strings::StrCat(\n \"Provided col_remapping, but its size is \", col_remapping.size(),\n \" instead of being equal to num_cols=\", num_cols_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(col_remapping, &col_id_present,\n &old_col_to_new_col_map));\n } else {\n col_id_present.clear();\n col_id_present.resize(num_cols_, true);\n }\n\n // Processes the checkpoint source and the provided Tensor name.\n const Tensor* ckpt_path_t;\n OP_REQUIRES_OK(context, context->input(\"ckpt_path\", &ckpt_path_t));\n OP_REQUIRES(\n context, ckpt_path_t->NumElements() == 1,\n errors::InvalidArgument(\"The `ckpt_path` tensor must have exactly one \"\n \"element, got tensor of shape \",\n ckpt_path_t->shape().DebugString()));\n const string& ckpt_path = ckpt_path_t->scalar()();\n const Tensor* old_tensor_name_t;\n OP_REQUIRES_OK(context,\n context->input(\"old_tensor_name\", &old_tensor_name_t));\n const string& old_tensor_name = old_tensor_name_t->scalar()();\n\n LOG(INFO) << \"Processing checkpoint : \" << ckpt_path;\n BundleReader reader(context->env(), ckpt_path);\n OP_REQUIRES_OK(context, reader.status());\n\n DataType tensor_type;\n TensorShape tensor_shape;\n OP_REQUIRES_OK(context, reader.LookupDtypeAndShape(\n old_tensor_name, &tensor_type, &tensor_shape));\n OP_REQUIRES(context, tensor_type == DT_FLOAT,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has invalid type \",\n DataTypeString(tensor_type), \" instead of expected type \",\n DataTypeString(DT_FLOAT))));\n // This op is limited to loading Tensors of rank 2 (matrices).\n OP_REQUIRES(\n context, tensor_shape.dims() == 2,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(), \" of invalid rank \",\n tensor_shape.dims(), \" instead of expected shape of rank 2.\")));\n\n if (!remap_cols) {\n // TODO(weiho): Consider relaxing this restriction to allow partial column\n // loading (even when no column remapping is specified) if there turns out\n // to be a use case for it.\n OP_REQUIRES(context, num_cols_ == tensor_shape.dim_size(1),\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(),\n \", where the size of its 2nd dimension is \",\n tensor_shape.dim_size(1),\n \" instead of being equal to num_cols=\", num_cols_)));\n }\n\n // Uses TensorSlice to potentially load the old tensor in chunks in case\n // memory usage is a concern.\n std::vector tensor_slices;\n TensorSlice slice(tensor_shape.dims());\n if (min_old_row >= 0 && max_old_row >= 0) {\n int64 row_start = min_old_row;\n // TODO(weiho): Given the list of old row IDs of interest (the keys of\n // old_row_to_new_row_map), we could also try something smarter to\n // find some minimal set of covering ranges for the list of old row IDs\n // such that the size of each range is less than max_rows_in_memory_.\n while (row_start <= max_old_row) {\n const int64 slice_length =\n max_rows_in_memory_ <= 0\n // If max_rows_in_memory_ <= 0, we just load the entire chunk.\n ? max_old_row - row_start + 1\n : std::min(max_rows_in_memory_, max_old_row - row_start + 1);\n slice.set_start(0, row_start);\n slice.set_length(0, slice_length);\n tensor_slices.push_back(slice);\n row_start += slice_length;\n }\n }\n\n // Allocates the output matrix.\n Tensor* output_matrix_t = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"output_matrix\",\n TensorShape({num_rows_, num_cols_}),\n &output_matrix_t));\n auto output_matrix = output_matrix_t->matrix();\n\n // Iterates through tensor slices and copies over values from the old tensor\n // to the output matrix.\n int64 row_index = min_old_row;\n int64 rows_copied = 0;\n Tensor loaded_tensor_t;\n for (const TensorSlice& tensor_slice : tensor_slices) {\n LOG(INFO) << \"Loading slice \" << tensor_slice.DebugString();\n TensorShape slice_shape;\n OP_REQUIRES_OK(context,\n tensor_slice.SliceTensorShape(tensor_shape, &slice_shape));\n // Potentially re-allocates the tensor buffer since the last slice may\n // have fewer rows than the other slices.\n if (loaded_tensor_t.shape() != slice_shape) {\n loaded_tensor_t = Tensor(DT_FLOAT, slice_shape);\n }\n OP_REQUIRES_OK(context, reader.LookupSlice(old_tensor_name, tensor_slice,\n &loaded_tensor_t));\n\n // Iterates through the old loaded tensor slice row-by-row.\n for (int row = 0; row < loaded_tensor_t.dim_size(0); ++row, ++row_index) {\n if (row_index % 500000 == min_old_row) {\n LOG(INFO) << \"Processing old row \" << row_index;\n }\n\n // If the old row ID is not found in old_row_to_new_row_map, continue\n // to the next row; otherwise, copy it to the output matrix.\n const int64* new_row_ptr =\n gtl::FindOrNull(old_row_to_new_row_map, row_index);\n if (new_row_ptr == nullptr) {\n continue;\n }\n ++rows_copied;\n const int64 new_row = *new_row_ptr;\n\n // Copies over the row element-by-element, in case remapping is needed\n // along the column axis.\n const auto& loaded_tensor = loaded_tensor_t.matrix();\n for (int old_col = 0; old_col < loaded_tensor_t.dim_size(1);\n ++old_col) {\n int64 new_col = old_col;\n if (remap_cols) {\n const int64* new_col_ptr =\n gtl::FindOrNull(old_col_to_new_col_map, old_col);\n if (new_col_ptr == nullptr) {\n // Column remapping is specified, but this column is not found in\n // old_col_to_new_col_map, so we leave it uninitialized, to be\n // filled in with initializing_values later.\n continue;\n }\n new_col = *new_col_ptr;\n }\n\n OP_REQUIRES(context,\n new_row < num_rows_ && new_col < num_cols_ &&\n new_row >= 0 && new_col >= 0,\n errors::Internal(strings::StrCat(\n \"new_row=\", new_row, \" and new_col=\", new_col,\n \" should have been less than num_rows_=\", num_rows_,\n \" and num_cols_=\", num_cols_,\n \" and non-negative. This should never have happened \"\n \"if the code were correct. Please file a bug.\")));\n output_matrix(new_row, new_col) = loaded_tensor(row, old_col);\n }\n }\n }\n LOG(INFO) << \"Copied \" << rows_copied << \" rows from old matrix (with \"\n << tensor_shape.dim_size(0) << \" rows) to new matrix (with \"\n << num_rows_ << \" rows).\";\n\n // At this point, there are potentially whole rows/columns uninitialized\n // (corresponding to the indices where row_id_present/col_id_present are\n // false). We fill this in cell-by-cell using row_id_present and\n // col_id_present while dequeuing from the initializing_values vector.\n const Tensor* initializing_values_t;\n OP_REQUIRES_OK(\n context, context->input(\"initializing_values\", &initializing_values_t));\n const auto initializing_values = initializing_values_t->flat();\n int64 initializing_values_index = 0;\n for (int i = 0; i < num_rows_; ++i) {\n for (int j = 0; j < num_cols_; ++j) {\n if (row_id_present[i] && col_id_present[j]) continue;\n OP_REQUIRES(\n context, initializing_values_index < initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but more missing values remain.\"));\n output_matrix(i, j) = initializing_values(initializing_values_index);\n ++initializing_values_index;\n }\n }\n\n // Checks that we used all the given initializing values.\n OP_REQUIRES(\n context, initializing_values_index == initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but only \", initializing_values_index,\n \" elements were used to fill in missing values.\"));\n }", "func_hash": 201106216742697676716998543927546938287, "file_name": "load_and_remap_matrix_op.cc", "file_hash": 128878311543448227786848710599905533022, "cwe": ["CWE-369"], "cve": "CVE-2021-29561", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service by exploiting a `CHECK`-failure coming from `tf.raw_ops.LoadAndRemapMatrix`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/d94227d43aa125ad8b54115c03cece54f6a1977b/tensorflow/core/kernels/ragged_tensor_to_tensor_op.cc#L219-L222) assumes that the `ckpt_path` is always a valid scalar. However, an attacker can send any other tensor as the first argument of `LoadAndRemapMatrix`. This would cause the rank `CHECK` in `scalar()()` to trigger and terminate the process. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29561"} {"idx": 197575, "project": "tensorflow", "commit_id": "ef0c008ee84bad91ec6725ddc42091e19a30cf0e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ef0c008ee84bad91ec6725ddc42091e19a30cf0e", "commit_message": "Fix out of bound read in requantization_range_op.cc\n\nPiperOrigin-RevId: 372129031\nChange-Id: Ie684ab98a3840c5186ead3eafffc0e0ed0e8030d", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const float input_min_float = ctx->input(1).flat()(0);\n const float input_max_float = ctx->input(2).flat()(0);\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output_min));\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_max));\n\n qint32 used_min_quantized;\n qint32 used_max_quantized;\n CalculateUsedRange(input, &used_min_quantized, &used_max_quantized);\n\n // We want to make sure that the minimum is no larger than zero, so that the\n // convolution operation can run efficiently.\n const float used_min_float = std::min(\n 0.0f,\n QuantizedToFloat(used_min_quantized, input_min_float, input_max_float));\n const float used_max_float =\n QuantizedToFloat(used_max_quantized, input_min_float, input_max_float);\n\n output_min->flat().setConstant(used_min_float);\n output_max->flat().setConstant(used_max_float);\n }", "func_hash": 30261531077942356400936795936344876892, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-29569", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.MaxPoolGradWithArgmax` can cause reads outside of bounds of heap allocated data if attacker supplies specially crafted inputs. The implementation(https://github.com/tensorflow/tensorflow/blob/ac328eaa3870491ababc147822cd04e91a790643/tensorflow/core/kernels/requantization_range_op.cc#L49-L50) assumes that the `input_min` and `input_max` tensors have at least one element, as it accesses the first element in two arrays. If the tensors are empty, `.flat()` is an empty object, backed by an empty array. Hence, accesing even the 0th element is a read outside the bounds. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29569"} {"idx": 261456, "project": "tensorflow", "commit_id": "ef0c008ee84bad91ec6725ddc42091e19a30cf0e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ef0c008ee84bad91ec6725ddc42091e19a30cf0e", "commit_message": "Fix out of bound read in requantization_range_op.cc\n\nPiperOrigin-RevId: 372129031\nChange-Id: Ie684ab98a3840c5186ead3eafffc0e0ed0e8030d", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n OP_REQUIRES(ctx, ctx->input(1).NumElements() > 0,\n errors::InvalidArgument(\"Input min must not be empty.\"));\n OP_REQUIRES(ctx, ctx->input(2).NumElements() > 0,\n errors::InvalidArgument(\"Input max must not be empty.\"));\n const float input_min_float = ctx->input(1).flat()(0);\n const float input_max_float = ctx->input(2).flat()(0);\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output_min));\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_max));\n\n qint32 used_min_quantized;\n qint32 used_max_quantized;\n CalculateUsedRange(input, &used_min_quantized, &used_max_quantized);\n\n // We want to make sure that the minimum is no larger than zero, so that the\n // convolution operation can run efficiently.\n const float used_min_float = std::min(\n 0.0f,\n QuantizedToFloat(used_min_quantized, input_min_float, input_max_float));\n const float used_max_float =\n QuantizedToFloat(used_max_quantized, input_min_float, input_max_float);\n\n output_min->flat().setConstant(used_min_float);\n output_max->flat().setConstant(used_max_float);\n }", "func_hash": 55917900542893971683927073159431047742, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-29569", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of `tf.raw_ops.MaxPoolGradWithArgmax` can cause reads outside of bounds of heap allocated data if attacker supplies specially crafted inputs. The implementation(https://github.com/tensorflow/tensorflow/blob/ac328eaa3870491ababc147822cd04e91a790643/tensorflow/core/kernels/requantization_range_op.cc#L49-L50) assumes that the `input_min` and `input_max` tensors have at least one element, as it accesses the first element in two arrays. If the tensors are empty, `.flat()` is an empty object, backed by an empty array. Hence, accesing even the 0th element is a read outside the bounds. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29569"} {"idx": 197649, "project": "tensorflow", "commit_id": "27b417360cbd671ef55915e4bb6bb06af8b8a832", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/27b417360cbd671ef55915e4bb6bb06af8b8a832", "commit_message": "Prevent `int64` to `int` truncation in `Shard` API usage.\n\nThe function argument in `Shard` must be a function of two `int64` arguments. However, we are passing in a function with two `int` arguments. Thus, for large workloads, these arguments get truncated from positive `int64` values to negative `int` ones, resulting in a buffer out of bounds write.\n\nPiperOrigin-RevId: 332557334\nChange-Id: I236c9a2e7f53580e520571da8ba941a3aa9fa0b5", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& shape_t = ctx->input(0);\n const Tensor& alpha_t = ctx->input(1);\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(shape_t.shape()) &&\n (shape_t.dtype() == DataType::DT_INT32 ||\n shape_t.dtype() == DataType::DT_INT64),\n errors::InvalidArgument(\n \"shape must be a vector of {int32,int64}, got shape: \",\n shape_t.DebugString()));\n TensorShape samples_shape;\n if (shape_t.dtype() == DataType::DT_INT32) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n } else if (shape_t.dtype() == DataType::DT_INT64) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n }\n const int64 samples_per_alpha = samples_shape.num_elements();\n\n samples_shape.AppendShape(alpha_t.shape());\n // Allocate output samples.\n Tensor* samples_t = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, samples_shape, &samples_t));\n\n if (samples_shape.num_elements() == 0) return;\n\n using random::PhiloxRandom;\n\n typedef random::NormalDistribution Normal;\n typedef random::UniformDistribution Uniform;\n#define UNIFORM(X) \\\n if (uniform_remaining == 0) { \\\n uniform_remaining = Uniform::kResultElementCount; \\\n uniform_result = uniform(&gen); \\\n } \\\n uniform_remaining--; \\\n double X = uniform_result[uniform_remaining]\n\n // Each attempt is 95+% successful, and requires 1-2 normal + 1 uniform\n static constexpr int kReservedSamplesPerOutput = 256;\n\n const auto alpha_flat = alpha_t.flat().data();\n const int64 num_alphas = alpha_t.NumElements();\n OP_REQUIRES(ctx, num_alphas > 0,\n errors::InvalidArgument(\n \"Input alpha should have non-zero element count, got: \",\n num_alphas));\n auto samples_flat = samples_t->flat().data();\n PhiloxRandom rng = generator_.ReserveRandomOutputs(\n samples_per_alpha * num_alphas, kReservedSamplesPerOutput);\n\n // We partition work first across alphas then across samples-per-alpha to\n // avoid a couple flops which can be done on a per-alpha basis.\n\n auto DoWork = [samples_per_alpha, num_alphas, &rng, samples_flat,\n alpha_flat](int start_output, int limit_output) {\n using Eigen::numext::exp;\n using Eigen::numext::log;\n using Eigen::numext::log1p;\n using Eigen::numext::pow;\n\n // Capturing \"rng\" by-value would only make a copy for the _shared_\n // lambda. Since we want to let each worker have its own copy, we pass\n // \"rng\" by reference and explicitly do a copy assignment.\n\n Normal normal;\n Uniform uniform;\n typename Normal::ResultType norm_result;\n typename Uniform::ResultType uniform_result;\n for (int64 output_idx = start_output; output_idx < limit_output;\n /* output_idx incremented within inner loop below */) {\n int64 alpha_idx = output_idx / samples_per_alpha;\n\n // Instead of +alpha_idx for each sample, we offset the pointer once.\n T* const samples_alpha_offset = samples_flat + alpha_idx;\n\n // Several calculations can be done on a per-alpha basis.\n const double alpha = static_cast(alpha_flat[alpha_idx]);\n\n DISABLE_FLOAT_EQUALITY_WARNING\n if (alpha == static_cast(1.0)) {\n ENABLE_FLOAT_EQUALITY_WARNING\n // Sample from an exponential distribution.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // As we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 uniform_remaining = 0;\n UNIFORM(u);\n const double res = -log1p(-u);\n samples_alpha_offset[sample_idx * num_alphas] = static_cast(res);\n } // for (sample_idx)\n } else { // if alpha != 1.0\n // Transformation-rejection from pairs of uniform and normal random\n // variables. http://dl.acm.org/citation.cfm?id=358414\n //\n // The algorithm has an acceptance rate of ~95% for small alpha (~1),\n // and higher accept rates for higher alpha, so runtime is\n // O(NumAlphas * NumSamples * k) with k ~ 1 / 0.95.\n //\n // For alpha<1, we add one to d=alpha-1/3, and multiply the final\n // result by uniform()^(1/alpha)\n const bool alpha_less_than_one = alpha < 1;\n const double d = alpha + (alpha_less_than_one ? 2.0 / 3 : -1.0 / 3);\n const double c = 1.0 / 3 / sqrt(d);\n\n // Compute the rest of the samples for the current alpha value.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // Since each sample may use a variable number of normal/uniform\n // samples, and we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 norm_remaining = 0;\n int16 uniform_remaining = 0;\n\n // Keep trying until we don't reject a sample. In practice, we will\n // only reject ~5% at worst, for low alpha near 1.\n while (true) {\n if (norm_remaining == 0) {\n norm_remaining = Normal::kResultElementCount;\n norm_result = normal(&gen);\n }\n norm_remaining--;\n const double x = norm_result[norm_remaining];\n double v = 1 + c * x;\n if (v <= 0) {\n continue;\n }\n v = v * v * v;\n UNIFORM(u);\n // The first option in the if is a \"squeeze\" short-circuit to\n // dodge the two logs. Magic constant sourced from the paper\n // linked above. Upward of .91 of the area covered by the log\n // inequality is covered by the squeeze as well (larger coverage\n // for smaller values of alpha).\n if ((u < 1 - 0.0331 * (x * x) * (x * x)) ||\n (log(u) < 0.5 * x * x + d * (1 - v + log(v)))) {\n double res = d * v;\n if (alpha_less_than_one) {\n UNIFORM(b);\n res *= pow(b, 1 / alpha);\n }\n samples_alpha_offset[sample_idx * num_alphas] =\n static_cast(res);\n break;\n }\n } // while: true\n } // for: sample_idx\n } // if (alpha == 1.0)\n } // for: output_idx\n }; // DoWork\n#undef UNIFORM\n // Two calls to log only occur for ~10% of samples reaching the log line.\n // 2 x 100 (64-bit cycles per log) x 0.10 = ~20.\n // Other ops: sqrt, +, *, /, %... something like 15 of these, at 3-6 cycles\n // each = ~60.\n // All of this /0.95 due to the rejection possibility = ~85.\n static const int kElementCost = 85 + 2 * Normal::kElementCost +\n Uniform::kElementCost +\n 3 * PhiloxRandom::kElementCost;\n auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());\n Shard(worker_threads.num_threads, worker_threads.workers,\n num_alphas * samples_per_alpha, kElementCost, DoWork);\n }", "func_hash": 283913710136392978354162182489065189735, "file_name": "random_op.cc", "file_hash": 180578547057084176103520608657808019643, "cwe": ["CWE-703"], "cve": "CVE-2020-15202", "cve_desc": "In Tensorflow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, the `Shard` API in TensorFlow expects the last argument to be a function taking two `int64` (i.e., `long long`) arguments. However, there are several places in TensorFlow where a lambda taking `int` or `int32` arguments is being used. In these cases, if the amount of work to be parallelized is large enough, integer truncation occurs. Depending on how the two arguments of the lambda are used, this can result in segfaults, read/write outside of heap allocated arrays, stack overflows, or data corruption. The issue is patched in commits 27b417360cbd671ef55915e4bb6bb06af8b8a832 and ca8c013b5e97b1373b3bb1c97ea655e69f31a575, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15202"} {"idx": 262651, "project": "tensorflow", "commit_id": "27b417360cbd671ef55915e4bb6bb06af8b8a832", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/27b417360cbd671ef55915e4bb6bb06af8b8a832", "commit_message": "Prevent `int64` to `int` truncation in `Shard` API usage.\n\nThe function argument in `Shard` must be a function of two `int64` arguments. However, we are passing in a function with two `int` arguments. Thus, for large workloads, these arguments get truncated from positive `int64` values to negative `int` ones, resulting in a buffer out of bounds write.\n\nPiperOrigin-RevId: 332557334\nChange-Id: I236c9a2e7f53580e520571da8ba941a3aa9fa0b5", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& shape_t = ctx->input(0);\n const Tensor& alpha_t = ctx->input(1);\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(shape_t.shape()) &&\n (shape_t.dtype() == DataType::DT_INT32 ||\n shape_t.dtype() == DataType::DT_INT64),\n errors::InvalidArgument(\n \"shape must be a vector of {int32,int64}, got shape: \",\n shape_t.DebugString()));\n TensorShape samples_shape;\n if (shape_t.dtype() == DataType::DT_INT32) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n } else if (shape_t.dtype() == DataType::DT_INT64) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n }\n const int64 samples_per_alpha = samples_shape.num_elements();\n\n samples_shape.AppendShape(alpha_t.shape());\n // Allocate output samples.\n Tensor* samples_t = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, samples_shape, &samples_t));\n\n if (samples_shape.num_elements() == 0) return;\n\n using random::PhiloxRandom;\n\n typedef random::NormalDistribution Normal;\n typedef random::UniformDistribution Uniform;\n#define UNIFORM(X) \\\n if (uniform_remaining == 0) { \\\n uniform_remaining = Uniform::kResultElementCount; \\\n uniform_result = uniform(&gen); \\\n } \\\n uniform_remaining--; \\\n double X = uniform_result[uniform_remaining]\n\n // Each attempt is 95+% successful, and requires 1-2 normal + 1 uniform\n static constexpr int kReservedSamplesPerOutput = 256;\n\n const auto alpha_flat = alpha_t.flat().data();\n const int64 num_alphas = alpha_t.NumElements();\n OP_REQUIRES(ctx, num_alphas > 0,\n errors::InvalidArgument(\n \"Input alpha should have non-zero element count, got: \",\n num_alphas));\n auto samples_flat = samples_t->flat().data();\n PhiloxRandom rng = generator_.ReserveRandomOutputs(\n samples_per_alpha * num_alphas, kReservedSamplesPerOutput);\n\n // We partition work first across alphas then across samples-per-alpha to\n // avoid a couple flops which can be done on a per-alpha basis.\n\n auto DoWork = [samples_per_alpha, num_alphas, &rng, samples_flat,\n alpha_flat](int64 start_output, int64 limit_output) {\n using Eigen::numext::exp;\n using Eigen::numext::log;\n using Eigen::numext::log1p;\n using Eigen::numext::pow;\n\n // Capturing \"rng\" by-value would only make a copy for the _shared_\n // lambda. Since we want to let each worker have its own copy, we pass\n // \"rng\" by reference and explicitly do a copy assignment.\n\n Normal normal;\n Uniform uniform;\n typename Normal::ResultType norm_result;\n typename Uniform::ResultType uniform_result;\n for (int64 output_idx = start_output; output_idx < limit_output;\n /* output_idx incremented within inner loop below */) {\n int64 alpha_idx = output_idx / samples_per_alpha;\n\n // Instead of +alpha_idx for each sample, we offset the pointer once.\n T* const samples_alpha_offset = samples_flat + alpha_idx;\n\n // Several calculations can be done on a per-alpha basis.\n const double alpha = static_cast(alpha_flat[alpha_idx]);\n\n DISABLE_FLOAT_EQUALITY_WARNING\n if (alpha == static_cast(1.0)) {\n ENABLE_FLOAT_EQUALITY_WARNING\n // Sample from an exponential distribution.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // As we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 uniform_remaining = 0;\n UNIFORM(u);\n const double res = -log1p(-u);\n samples_alpha_offset[sample_idx * num_alphas] = static_cast(res);\n } // for (sample_idx)\n } else { // if alpha != 1.0\n // Transformation-rejection from pairs of uniform and normal random\n // variables. http://dl.acm.org/citation.cfm?id=358414\n //\n // The algorithm has an acceptance rate of ~95% for small alpha (~1),\n // and higher accept rates for higher alpha, so runtime is\n // O(NumAlphas * NumSamples * k) with k ~ 1 / 0.95.\n //\n // For alpha<1, we add one to d=alpha-1/3, and multiply the final\n // result by uniform()^(1/alpha)\n const bool alpha_less_than_one = alpha < 1;\n const double d = alpha + (alpha_less_than_one ? 2.0 / 3 : -1.0 / 3);\n const double c = 1.0 / 3 / sqrt(d);\n\n // Compute the rest of the samples for the current alpha value.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // Since each sample may use a variable number of normal/uniform\n // samples, and we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 norm_remaining = 0;\n int16 uniform_remaining = 0;\n\n // Keep trying until we don't reject a sample. In practice, we will\n // only reject ~5% at worst, for low alpha near 1.\n while (true) {\n if (norm_remaining == 0) {\n norm_remaining = Normal::kResultElementCount;\n norm_result = normal(&gen);\n }\n norm_remaining--;\n const double x = norm_result[norm_remaining];\n double v = 1 + c * x;\n if (v <= 0) {\n continue;\n }\n v = v * v * v;\n UNIFORM(u);\n // The first option in the if is a \"squeeze\" short-circuit to\n // dodge the two logs. Magic constant sourced from the paper\n // linked above. Upward of .91 of the area covered by the log\n // inequality is covered by the squeeze as well (larger coverage\n // for smaller values of alpha).\n if ((u < 1 - 0.0331 * (x * x) * (x * x)) ||\n (log(u) < 0.5 * x * x + d * (1 - v + log(v)))) {\n double res = d * v;\n if (alpha_less_than_one) {\n UNIFORM(b);\n res *= pow(b, 1 / alpha);\n }\n samples_alpha_offset[sample_idx * num_alphas] =\n static_cast(res);\n break;\n }\n } // while: true\n } // for: sample_idx\n } // if (alpha == 1.0)\n } // for: output_idx\n }; // DoWork\n#undef UNIFORM\n // Two calls to log only occur for ~10% of samples reaching the log line.\n // 2 x 100 (64-bit cycles per log) x 0.10 = ~20.\n // Other ops: sqrt, +, *, /, %... something like 15 of these, at 3-6 cycles\n // each = ~60.\n // All of this /0.95 due to the rejection possibility = ~85.\n static const int kElementCost = 85 + 2 * Normal::kElementCost +\n Uniform::kElementCost +\n 3 * PhiloxRandom::kElementCost;\n auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());\n Shard(worker_threads.num_threads, worker_threads.workers,\n num_alphas * samples_per_alpha, kElementCost, DoWork);\n }", "func_hash": 137310656871269739780074394670147467359, "file_name": "random_op.cc", "file_hash": 40732238126201314905151657428456113385, "cwe": ["CWE-703"], "cve": "CVE-2020-15202", "cve_desc": "In Tensorflow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, the `Shard` API in TensorFlow expects the last argument to be a function taking two `int64` (i.e., `long long`) arguments. However, there are several places in TensorFlow where a lambda taking `int` or `int32` arguments is being used. In these cases, if the amount of work to be parallelized is large enough, integer truncation occurs. Depending on how the two arguments of the lambda are used, this can result in segfaults, read/write outside of heap allocated arrays, stack overflows, or data corruption. The issue is patched in commits 27b417360cbd671ef55915e4bb6bb06af8b8a832 and ca8c013b5e97b1373b3bb1c97ea655e69f31a575, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15202"} {"idx": 197652, "project": "FFmpeg", "commit_id": "26d3c81bc5ef2f8c3f09d45eaeacfb4b1139a777", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/26d3c81bc5ef2f8c3f09d45eaeacfb4b1139a777", "commit_message": "avcodec/exr: More strictly check dc_count\n\nFixes: out of array access\nFixes: exr/deneme\n\nFound-by: Burak \u00c7ar\u0131k\u00e7\u0131 \nSigned-off-by: Michael Niedermayer ", "target": 1, "func": "static int dwa_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,\n int uncompressed_size, EXRThreadData *td)\n{\n int64_t version, lo_usize, lo_size;\n int64_t ac_size, dc_size, rle_usize, rle_csize, rle_raw_size;\n int64_t ac_count, dc_count, ac_compression;\n const int dc_w = td->xsize >> 3;\n const int dc_h = td->ysize >> 3;\n GetByteContext gb, agb;\n int skip, ret;\n\n if (compressed_size <= 88)\n return AVERROR_INVALIDDATA;\n\n version = AV_RL64(src + 0);\n if (version != 2)\n return AVERROR_INVALIDDATA;\n\n lo_usize = AV_RL64(src + 8);\n lo_size = AV_RL64(src + 16);\n ac_size = AV_RL64(src + 24);\n dc_size = AV_RL64(src + 32);\n rle_csize = AV_RL64(src + 40);\n rle_usize = AV_RL64(src + 48);\n rle_raw_size = AV_RL64(src + 56);\n ac_count = AV_RL64(src + 64);\n dc_count = AV_RL64(src + 72);\n ac_compression = AV_RL64(src + 80);\n\n if (compressed_size < 88LL + lo_size + ac_size + dc_size + rle_csize)\n return AVERROR_INVALIDDATA;\n\n bytestream2_init(&gb, src + 88, compressed_size - 88);\n skip = bytestream2_get_le16(&gb);\n if (skip < 2)\n return AVERROR_INVALIDDATA;\n\n bytestream2_skip(&gb, skip - 2);\n\n if (lo_size > 0) {\n if (lo_usize > uncompressed_size)\n return AVERROR_INVALIDDATA;\n bytestream2_skip(&gb, lo_size);\n }\n\n if (ac_size > 0) {\n unsigned long dest_len = ac_count * 2LL;\n GetByteContext agb = gb;\n\n if (ac_count > 3LL * td->xsize * s->scan_lines_per_block)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->ac_data, &td->ac_size, dest_len);\n if (!td->ac_data)\n return AVERROR(ENOMEM);\n\n switch (ac_compression) {\n case 0:\n ret = huf_uncompress(s, td, &agb, (int16_t *)td->ac_data, ac_count);\n if (ret < 0)\n return ret;\n break;\n case 1:\n if (uncompress(td->ac_data, &dest_len, agb.buffer, ac_size) != Z_OK ||\n dest_len != ac_count * 2LL)\n return AVERROR_INVALIDDATA;\n break;\n default:\n return AVERROR_INVALIDDATA;\n }\n\n bytestream2_skip(&gb, ac_size);\n }\n\n if (dc_size > 0) {\n unsigned long dest_len = dc_count * 2LL;\n GetByteContext agb = gb;\n\n if (dc_count > (6LL * td->xsize * td->ysize + 63) / 64)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->dc_data, &td->dc_size, FFALIGN(dest_len, 64) * 2);\n if (!td->dc_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->dc_data + FFALIGN(dest_len, 64), &dest_len, agb.buffer, dc_size) != Z_OK ||\n (dest_len != dc_count * 2LL))\n return AVERROR_INVALIDDATA;\n\n s->dsp.predictor(td->dc_data + FFALIGN(dest_len, 64), dest_len);\n s->dsp.reorder_pixels(td->dc_data, td->dc_data + FFALIGN(dest_len, 64), dest_len);\n\n bytestream2_skip(&gb, dc_size);\n }\n\n if (rle_raw_size > 0 && rle_csize > 0 && rle_usize > 0) {\n unsigned long dest_len = rle_usize;\n\n av_fast_padded_malloc(&td->rle_data, &td->rle_size, rle_usize);\n if (!td->rle_data)\n return AVERROR(ENOMEM);\n\n av_fast_padded_malloc(&td->rle_raw_data, &td->rle_raw_size, rle_raw_size);\n if (!td->rle_raw_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->rle_data, &dest_len, gb.buffer, rle_csize) != Z_OK ||\n (dest_len != rle_usize))\n return AVERROR_INVALIDDATA;\n\n ret = rle(td->rle_raw_data, td->rle_data, rle_usize, rle_raw_size);\n if (ret < 0)\n return ret;\n bytestream2_skip(&gb, rle_csize);\n }\n\n bytestream2_init(&agb, td->ac_data, ac_count * 2);\n\n for (int y = 0; y < td->ysize; y += 8) {\n for (int x = 0; x < td->xsize; x += 8) {\n memset(td->block, 0, sizeof(td->block));\n\n for (int j = 0; j < 3; j++) {\n float *block = td->block[j];\n const int idx = (x >> 3) + (y >> 3) * dc_w + dc_w * dc_h * j;\n uint16_t *dc = (uint16_t *)td->dc_data;\n union av_intfloat32 dc_val;\n\n dc_val.i = half2float(dc[idx], s->mantissatable,\n s->exponenttable, s->offsettable);\n\n block[0] = dc_val.f;\n ac_uncompress(s, &agb, block);\n dct_inverse(block);\n }\n\n {\n const float scale = s->pixel_type == EXR_FLOAT ? 2.f : 1.f;\n const int o = s->nb_channels == 4;\n float *bo = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 0) + x;\n float *go = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 1) + x;\n float *ro = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 2) + x;\n float *yb = td->block[0];\n float *ub = td->block[1];\n float *vb = td->block[2];\n\n for (int yy = 0; yy < 8; yy++) {\n for (int xx = 0; xx < 8; xx++) {\n const int idx = xx + yy * 8;\n\n convert(yb[idx], ub[idx], vb[idx], &bo[xx], &go[xx], &ro[xx]);\n\n bo[xx] = to_linear(bo[xx], scale);\n go[xx] = to_linear(go[xx], scale);\n ro[xx] = to_linear(ro[xx], scale);\n }\n\n bo += td->xsize * s->nb_channels;\n go += td->xsize * s->nb_channels;\n ro += td->xsize * s->nb_channels;\n }\n }\n }\n }\n\n if (s->nb_channels < 4)\n return 0;\n\n for (int y = 0; y < td->ysize && td->rle_raw_data; y++) {\n uint32_t *ao = ((uint32_t *)td->uncompressed_data) + y * td->xsize * s->nb_channels;\n uint8_t *ai0 = td->rle_raw_data + y * td->xsize;\n uint8_t *ai1 = td->rle_raw_data + y * td->xsize + rle_raw_size / 2;\n\n for (int x = 0; x < td->xsize; x++) {\n uint16_t ha = ai0[x] | (ai1[x] << 8);\n\n ao[x] = half2float(ha, s->mantissatable, s->exponenttable, s->offsettable);\n }\n }\n\n return 0;\n}", "func_hash": 142878928467885775153253517177050654455, "file_name": "exr.c", "file_hash": 79360806882273413511520772128732682473, "cwe": ["CWE-20"], "cve": "CVE-2021-33815", "cve_desc": "dwa_uncompress in libavcodec/exr.c in FFmpeg 4.4 allows an out-of-bounds array access because dc_count is not strictly checked.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33815"} {"idx": 262684, "project": "FFmpeg", "commit_id": "26d3c81bc5ef2f8c3f09d45eaeacfb4b1139a777", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/26d3c81bc5ef2f8c3f09d45eaeacfb4b1139a777", "commit_message": "avcodec/exr: More strictly check dc_count\n\nFixes: out of array access\nFixes: exr/deneme\n\nFound-by: Burak \u00c7ar\u0131k\u00e7\u0131 \nSigned-off-by: Michael Niedermayer ", "target": 0, "func": "static int dwa_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,\n int uncompressed_size, EXRThreadData *td)\n{\n int64_t version, lo_usize, lo_size;\n int64_t ac_size, dc_size, rle_usize, rle_csize, rle_raw_size;\n int64_t ac_count, dc_count, ac_compression;\n const int dc_w = td->xsize >> 3;\n const int dc_h = td->ysize >> 3;\n GetByteContext gb, agb;\n int skip, ret;\n\n if (compressed_size <= 88)\n return AVERROR_INVALIDDATA;\n\n version = AV_RL64(src + 0);\n if (version != 2)\n return AVERROR_INVALIDDATA;\n\n lo_usize = AV_RL64(src + 8);\n lo_size = AV_RL64(src + 16);\n ac_size = AV_RL64(src + 24);\n dc_size = AV_RL64(src + 32);\n rle_csize = AV_RL64(src + 40);\n rle_usize = AV_RL64(src + 48);\n rle_raw_size = AV_RL64(src + 56);\n ac_count = AV_RL64(src + 64);\n dc_count = AV_RL64(src + 72);\n ac_compression = AV_RL64(src + 80);\n\n if (compressed_size < 88LL + lo_size + ac_size + dc_size + rle_csize)\n return AVERROR_INVALIDDATA;\n\n bytestream2_init(&gb, src + 88, compressed_size - 88);\n skip = bytestream2_get_le16(&gb);\n if (skip < 2)\n return AVERROR_INVALIDDATA;\n\n bytestream2_skip(&gb, skip - 2);\n\n if (lo_size > 0) {\n if (lo_usize > uncompressed_size)\n return AVERROR_INVALIDDATA;\n bytestream2_skip(&gb, lo_size);\n }\n\n if (ac_size > 0) {\n unsigned long dest_len = ac_count * 2LL;\n GetByteContext agb = gb;\n\n if (ac_count > 3LL * td->xsize * s->scan_lines_per_block)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->ac_data, &td->ac_size, dest_len);\n if (!td->ac_data)\n return AVERROR(ENOMEM);\n\n switch (ac_compression) {\n case 0:\n ret = huf_uncompress(s, td, &agb, (int16_t *)td->ac_data, ac_count);\n if (ret < 0)\n return ret;\n break;\n case 1:\n if (uncompress(td->ac_data, &dest_len, agb.buffer, ac_size) != Z_OK ||\n dest_len != ac_count * 2LL)\n return AVERROR_INVALIDDATA;\n break;\n default:\n return AVERROR_INVALIDDATA;\n }\n\n bytestream2_skip(&gb, ac_size);\n }\n\n {\n unsigned long dest_len = dc_count * 2LL;\n GetByteContext agb = gb;\n\n if (dc_count != dc_w * dc_h * 3)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->dc_data, &td->dc_size, FFALIGN(dest_len, 64) * 2);\n if (!td->dc_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->dc_data + FFALIGN(dest_len, 64), &dest_len, agb.buffer, dc_size) != Z_OK ||\n (dest_len != dc_count * 2LL))\n return AVERROR_INVALIDDATA;\n\n s->dsp.predictor(td->dc_data + FFALIGN(dest_len, 64), dest_len);\n s->dsp.reorder_pixels(td->dc_data, td->dc_data + FFALIGN(dest_len, 64), dest_len);\n\n bytestream2_skip(&gb, dc_size);\n }\n\n if (rle_raw_size > 0 && rle_csize > 0 && rle_usize > 0) {\n unsigned long dest_len = rle_usize;\n\n av_fast_padded_malloc(&td->rle_data, &td->rle_size, rle_usize);\n if (!td->rle_data)\n return AVERROR(ENOMEM);\n\n av_fast_padded_malloc(&td->rle_raw_data, &td->rle_raw_size, rle_raw_size);\n if (!td->rle_raw_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->rle_data, &dest_len, gb.buffer, rle_csize) != Z_OK ||\n (dest_len != rle_usize))\n return AVERROR_INVALIDDATA;\n\n ret = rle(td->rle_raw_data, td->rle_data, rle_usize, rle_raw_size);\n if (ret < 0)\n return ret;\n bytestream2_skip(&gb, rle_csize);\n }\n\n bytestream2_init(&agb, td->ac_data, ac_count * 2);\n\n for (int y = 0; y < td->ysize; y += 8) {\n for (int x = 0; x < td->xsize; x += 8) {\n memset(td->block, 0, sizeof(td->block));\n\n for (int j = 0; j < 3; j++) {\n float *block = td->block[j];\n const int idx = (x >> 3) + (y >> 3) * dc_w + dc_w * dc_h * j;\n uint16_t *dc = (uint16_t *)td->dc_data;\n union av_intfloat32 dc_val;\n\n dc_val.i = half2float(dc[idx], s->mantissatable,\n s->exponenttable, s->offsettable);\n\n block[0] = dc_val.f;\n ac_uncompress(s, &agb, block);\n dct_inverse(block);\n }\n\n {\n const float scale = s->pixel_type == EXR_FLOAT ? 2.f : 1.f;\n const int o = s->nb_channels == 4;\n float *bo = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 0) + x;\n float *go = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 1) + x;\n float *ro = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 2) + x;\n float *yb = td->block[0];\n float *ub = td->block[1];\n float *vb = td->block[2];\n\n for (int yy = 0; yy < 8; yy++) {\n for (int xx = 0; xx < 8; xx++) {\n const int idx = xx + yy * 8;\n\n convert(yb[idx], ub[idx], vb[idx], &bo[xx], &go[xx], &ro[xx]);\n\n bo[xx] = to_linear(bo[xx], scale);\n go[xx] = to_linear(go[xx], scale);\n ro[xx] = to_linear(ro[xx], scale);\n }\n\n bo += td->xsize * s->nb_channels;\n go += td->xsize * s->nb_channels;\n ro += td->xsize * s->nb_channels;\n }\n }\n }\n }\n\n if (s->nb_channels < 4)\n return 0;\n\n for (int y = 0; y < td->ysize && td->rle_raw_data; y++) {\n uint32_t *ao = ((uint32_t *)td->uncompressed_data) + y * td->xsize * s->nb_channels;\n uint8_t *ai0 = td->rle_raw_data + y * td->xsize;\n uint8_t *ai1 = td->rle_raw_data + y * td->xsize + rle_raw_size / 2;\n\n for (int x = 0; x < td->xsize; x++) {\n uint16_t ha = ai0[x] | (ai1[x] << 8);\n\n ao[x] = half2float(ha, s->mantissatable, s->exponenttable, s->offsettable);\n }\n }\n\n return 0;\n}", "func_hash": 322842465407150042463191303772987242359, "file_name": "exr.c", "file_hash": 315144144928517405887700569057224337426, "cwe": ["CWE-20"], "cve": "CVE-2021-33815", "cve_desc": "dwa_uncompress in libavcodec/exr.c in FFmpeg 4.4 allows an out-of-bounds array access because dc_count is not strictly checked.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33815"} {"idx": 197664, "project": "tensorflow", "commit_id": "b1b323042264740c398140da32e93fb9c2c9f33e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/b1b323042264740c398140da32e93fb9c2c9f33e", "commit_message": "Fix SEGV in CTC ops\n\nPiperOrigin-RevId: 372430279\nChange-Id: I7ec2ad9d6f4d0980c33de45d27c6b17df5c6e26f", "target": 1, "func": " Status ValidateInputsGenerateOutputs(\n OpKernelContext* ctx, const Tensor** inputs, const Tensor** seq_len,\n Tensor** log_prob, OpOutputList* decoded_indices,\n OpOutputList* decoded_values, OpOutputList* decoded_shape) const {\n Status status = ctx->input(\"inputs\", inputs);\n if (!status.ok()) return status;\n status = ctx->input(\"sequence_length\", seq_len);\n if (!status.ok()) return status;\n\n const TensorShape& inputs_shape = (*inputs)->shape();\n\n if (inputs_shape.dims() != 3) {\n return errors::InvalidArgument(\"inputs is not a 3-Tensor\");\n }\n\n const int64 max_time = inputs_shape.dim_size(0);\n const int64 batch_size = inputs_shape.dim_size(1);\n\n if (max_time == 0) {\n return errors::InvalidArgument(\"max_time is 0\");\n }\n if (!TensorShapeUtils::IsVector((*seq_len)->shape())) {\n return errors::InvalidArgument(\"sequence_length is not a vector\");\n }\n\n if (!(batch_size == (*seq_len)->dim_size(0))) {\n return errors::FailedPrecondition(\n \"len(sequence_length) != batch_size. \",\n \"len(sequence_length): \", (*seq_len)->dim_size(0),\n \" batch_size: \", batch_size);\n }\n\n auto seq_len_t = (*seq_len)->vec();\n\n for (int b = 0; b < batch_size; ++b) {\n if (!(seq_len_t(b) <= max_time)) {\n return errors::FailedPrecondition(\"sequence_length(\", b,\n \") <= \", max_time);\n }\n }\n\n Status s = ctx->allocate_output(\n \"log_probability\", TensorShape({batch_size, top_paths_}), log_prob);\n if (!s.ok()) return s;\n\n s = ctx->output_list(\"decoded_indices\", decoded_indices);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_values\", decoded_values);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_shape\", decoded_shape);\n if (!s.ok()) return s;\n\n return Status::OK();\n }", "func_hash": 71441406844977995036613788368762616499, "file_name": "ctc_decoder_ops.cc", "file_hash": 266784141974934021077049125535569452745, "cwe": ["CWE-369"], "cve": "CVE-2021-29581", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Due to lack of validation in `tf.raw_ops.CTCBeamSearchDecoder`, an attacker can trigger denial of service via segmentation faults. The implementation(https://github.com/tensorflow/tensorflow/blob/a74768f8e4efbda4def9f16ee7e13cf3922ac5f7/tensorflow/core/kernels/ctc_decoder_ops.cc#L68-L79) fails to detect cases when the input tensor is empty and proceeds to read data from a null buffer. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29581"} {"idx": 262711, "project": "tensorflow", "commit_id": "b1b323042264740c398140da32e93fb9c2c9f33e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/b1b323042264740c398140da32e93fb9c2c9f33e", "commit_message": "Fix SEGV in CTC ops\n\nPiperOrigin-RevId: 372430279\nChange-Id: I7ec2ad9d6f4d0980c33de45d27c6b17df5c6e26f", "target": 0, "func": " Status ValidateInputsGenerateOutputs(\n OpKernelContext* ctx, const Tensor** inputs, const Tensor** seq_len,\n Tensor** log_prob, OpOutputList* decoded_indices,\n OpOutputList* decoded_values, OpOutputList* decoded_shape) const {\n Status status = ctx->input(\"inputs\", inputs);\n if (!status.ok()) return status;\n status = ctx->input(\"sequence_length\", seq_len);\n if (!status.ok()) return status;\n\n const TensorShape& inputs_shape = (*inputs)->shape();\n\n if (inputs_shape.dims() != 3) {\n return errors::InvalidArgument(\"inputs is not a 3-Tensor\");\n }\n if (inputs_shape.num_elements() == 0) {\n return errors::InvalidArgument(\"inputs must not be empty\");\n }\n\n const int64 max_time = inputs_shape.dim_size(0);\n const int64 batch_size = inputs_shape.dim_size(1);\n\n if (max_time == 0) {\n return errors::InvalidArgument(\"max_time is 0\");\n }\n if (!TensorShapeUtils::IsVector((*seq_len)->shape())) {\n return errors::InvalidArgument(\"sequence_length is not a vector\");\n }\n\n if (!(batch_size == (*seq_len)->dim_size(0))) {\n return errors::FailedPrecondition(\n \"len(sequence_length) != batch_size. \",\n \"len(sequence_length): \", (*seq_len)->dim_size(0),\n \" batch_size: \", batch_size);\n }\n\n auto seq_len_t = (*seq_len)->vec();\n\n for (int b = 0; b < batch_size; ++b) {\n if (!(seq_len_t(b) <= max_time)) {\n return errors::FailedPrecondition(\"sequence_length(\", b,\n \") <= \", max_time);\n }\n }\n\n Status s = ctx->allocate_output(\n \"log_probability\", TensorShape({batch_size, top_paths_}), log_prob);\n if (!s.ok()) return s;\n\n s = ctx->output_list(\"decoded_indices\", decoded_indices);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_values\", decoded_values);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_shape\", decoded_shape);\n if (!s.ok()) return s;\n\n return Status::OK();\n }", "func_hash": 242197615639407058758314636706266165291, "file_name": "ctc_decoder_ops.cc", "file_hash": 305766485693993039725348685958596370867, "cwe": ["CWE-369"], "cve": "CVE-2021-29581", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Due to lack of validation in `tf.raw_ops.CTCBeamSearchDecoder`, an attacker can trigger denial of service via segmentation faults. The implementation(https://github.com/tensorflow/tensorflow/blob/a74768f8e4efbda4def9f16ee7e13cf3922ac5f7/tensorflow/core/kernels/ctc_decoder_ops.cc#L68-L79) fails to detect cases when the input tensor is empty and proceeds to read data from a null buffer. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29581"} {"idx": 197715, "project": "tensorflow", "commit_id": "e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd", "commit_message": "Remove `OP_REQUIRES` call from helper function.\n\nSince `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway.\n\nPiperOrigin-RevId: 369524386\nChange-Id: I54f6cf9328445675ccc392e661b04336b229c9da", "target": 1, "func": " void ValidateInputs(OpKernelContext* ctx,\n const CSRSparseMatrix& sparse_matrix,\n const Tensor& permutation_indices, int* batch_size,\n int64* num_rows) {\n OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum::value,\n errors::InvalidArgument(\n \"Asked for a CSRSparseMatrix of type \",\n DataTypeString(DataTypeToEnum::value),\n \" but saw dtype: \", DataTypeString(sparse_matrix.dtype())));\n\n const Tensor& dense_shape = sparse_matrix.dense_shape();\n const int rank = dense_shape.dim_size(0);\n OP_REQUIRES(ctx, rank == 2 || rank == 3,\n errors::InvalidArgument(\"sparse matrix must have rank 2 or 3; \",\n \"but dense_shape has size \", rank));\n const int row_dim = (rank == 2) ? 0 : 1;\n auto dense_shape_vec = dense_shape.vec();\n *num_rows = dense_shape_vec(row_dim);\n const int64 num_cols = dense_shape_vec(row_dim + 1);\n OP_REQUIRES(ctx, *num_rows == num_cols,\n errors::InvalidArgument(\"sparse matrix must be square; got: \",\n *num_rows, \" != \", num_cols));\n const TensorShape& perm_shape = permutation_indices.shape();\n OP_REQUIRES(\n ctx, perm_shape.dims() + 1 == rank,\n errors::InvalidArgument(\n \"sparse matrix must have the same rank as permutation; got: \", rank,\n \" != \", perm_shape.dims(), \" + 1.\"));\n OP_REQUIRES(\n ctx, perm_shape.dim_size(rank - 2) == *num_rows,\n errors::InvalidArgument(\n \"permutation must have the same number of elements in each batch \"\n \"as the number of rows in sparse matrix; got: \",\n perm_shape.dim_size(rank - 2), \" != \", *num_rows));\n\n *batch_size = sparse_matrix.batch_size();\n if (*batch_size > 1) {\n OP_REQUIRES(\n ctx, perm_shape.dim_size(0) == *batch_size,\n errors::InvalidArgument(\"permutation must have the same batch size \"\n \"as sparse matrix; got: \",\n perm_shape.dim_size(0), \" != \", *batch_size));\n }\n }", "func_hash": 207716032934062484843236754460475741571, "file_name": "sparse_cholesky_op.cc", "file_hash": 317827167598950333029494517682845030815, "cwe": ["CWE-476"], "cve": "CVE-2021-29530", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a null pointer dereference by providing an invalid `permutation` to `tf.raw_ops.SparseMatrixSparseCholesky`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/kernels/sparse/sparse_cholesky_op.cc#L85-L86) fails to properly validate the input arguments. Although `ValidateInputs` is called and there are checks in the body of this function, the code proceeds to the next line in `ValidateInputs` since `OP_REQUIRES`(https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/framework/op_requires.h#L41-L48) is a macro that only exits the current function. Thus, the first validation condition that fails in `ValidateInputs` will cause an early return from that function. However, the caller will continue execution from the next line. The fix is to either explicitly check `context->status()` or to convert `ValidateInputs` to return a `Status`. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29530"} {"idx": 262772, "project": "tensorflow", "commit_id": "e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd", "commit_message": "Remove `OP_REQUIRES` call from helper function.\n\nSince `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway.\n\nPiperOrigin-RevId: 369524386\nChange-Id: I54f6cf9328445675ccc392e661b04336b229c9da", "target": 0, "func": " Status ValidateInputs(const CSRSparseMatrix& sparse_matrix,\n const Tensor& permutation_indices, int* batch_size,\n int64* num_rows) {\n if (sparse_matrix.dtype() != DataTypeToEnum::value)\n return errors::InvalidArgument(\n \"Asked for a CSRSparseMatrix of type \",\n DataTypeString(DataTypeToEnum::value),\n \" but saw dtype: \", DataTypeString(sparse_matrix.dtype()));\n\n const Tensor& dense_shape = sparse_matrix.dense_shape();\n const int rank = dense_shape.dim_size(0);\n if (rank < 2 || rank > 3)\n return errors::InvalidArgument(\"sparse matrix must have rank 2 or 3; \",\n \"but dense_shape has size \", rank);\n const int row_dim = (rank == 2) ? 0 : 1;\n auto dense_shape_vec = dense_shape.vec();\n *num_rows = dense_shape_vec(row_dim);\n const int64 num_cols = dense_shape_vec(row_dim + 1);\n if (*num_rows != num_cols)\n return errors::InvalidArgument(\n \"sparse matrix must be square; got: \", *num_rows, \" != \", num_cols);\n const TensorShape& perm_shape = permutation_indices.shape();\n if (perm_shape.dims() + 1 != rank)\n return errors::InvalidArgument(\n \"sparse matrix must have the same rank as permutation; got: \", rank,\n \" != \", perm_shape.dims(), \" + 1.\");\n if (perm_shape.dim_size(rank - 2) != *num_rows)\n return errors::InvalidArgument(\n \"permutation must have the same number of elements in each batch \"\n \"as the number of rows in sparse matrix; got: \",\n perm_shape.dim_size(rank - 2), \" != \", *num_rows);\n\n *batch_size = sparse_matrix.batch_size();\n if (*batch_size > 1) {\n if (perm_shape.dim_size(0) != *batch_size)\n return errors::InvalidArgument(\n \"permutation must have the same batch size \"\n \"as sparse matrix; got: \",\n perm_shape.dim_size(0), \" != \", *batch_size);\n }\n\n return Status::OK();\n }", "func_hash": 120237585409331637113577076552167637086, "file_name": "sparse_cholesky_op.cc", "file_hash": 139632759565090329593684401737049417891, "cwe": ["CWE-476"], "cve": "CVE-2021-29530", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a null pointer dereference by providing an invalid `permutation` to `tf.raw_ops.SparseMatrixSparseCholesky`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/kernels/sparse/sparse_cholesky_op.cc#L85-L86) fails to properly validate the input arguments. Although `ValidateInputs` is called and there are checks in the body of this function, the code proceeds to the next line in `ValidateInputs` since `OP_REQUIRES`(https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/framework/op_requires.h#L41-L48) is a macro that only exits the current function. Thus, the first validation condition that fails in `ValidateInputs` will cause an early return from that function. However, the caller will continue execution from the next line. The fix is to either explicitly check `context->status()` or to convert `ValidateInputs` to return a `Status`. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29530"} {"idx": 197721, "project": "acrn-hypervisor", "commit_id": "25c0e3817eb332660dd63d1d4522e63dcc94e79a", "project_url": "https://github.com/projectacrn/acrn-hypervisor", "commit_url": "https://github.com/projectacrn/acrn-hypervisor/commit/25c0e3817eb332660dd63d1d4522e63dcc94e79a", "commit_message": "hv: validate input for dmar_free_irte function\n\n Malicious input 'index' may trigger buffer\n overflow on array 'irte_alloc_bitmap[]'.\n\n This patch validate that 'index' shall be\n less than 'CONFIG_MAX_IR_ENTRIES' and also\n remove unnecessary check on 'index' in\n 'ptirq_free_irte()' function with this fix.\n\nTracked-On: #6132\nSigned-off-by: Yonghua Huang ", "target": 1, "func": "void dmar_free_irte(const struct intr_source *intr_src, uint16_t index)\n{\n\tstruct dmar_drhd_rt *dmar_unit;\n\tunion dmar_ir_entry *ir_table, *ir_entry;\n\tunion pci_bdf sid;\n\n\tif (intr_src->is_msi) {\n\t\tdmar_unit = device_to_dmaru((uint8_t)intr_src->src.msi.bits.b, intr_src->src.msi.fields.devfun);\n\t} else {\n\t\tdmar_unit = ioapic_to_dmaru(intr_src->src.ioapic_id, &sid);\n\t}\n\n\tif (is_dmar_unit_valid(dmar_unit, sid)) {\n\t\tir_table = (union dmar_ir_entry *)hpa2hva(dmar_unit->ir_table_addr);\n\t\tir_entry = ir_table + index;\n\t\tir_entry->bits.remap.present = 0x0UL;\n\n\t\tiommu_flush_cache(ir_entry, sizeof(union dmar_ir_entry));\n\t\tdmar_invalid_iec(dmar_unit, index, 0U, false);\n\n\t\tif (!is_irte_reserved(dmar_unit, index)) {\n\t\t\tspinlock_obtain(&dmar_unit->lock);\n\t\t\tbitmap_clear_nolock(index & 0x3FU, &dmar_unit->irte_alloc_bitmap[index >> 6U]);\n\t\t\tspinlock_release(&dmar_unit->lock);\n\t\t}\n\t}\n\n}", "func_hash": 106352965449834945718151925530540549590, "file_name": "vtd.c", "file_hash": 153372670473212858231940127682997028064, "cwe": ["CWE-787"], "cve": "CVE-2021-36148", "cve_desc": "An issue was discovered in ACRN before 2.5. dmar_free_irte in hypervisor/arch/x86/vtd.c allows an irte_alloc_bitmap buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36148"} {"idx": 262864, "project": "acrn-hypervisor", "commit_id": "25c0e3817eb332660dd63d1d4522e63dcc94e79a", "project_url": "https://github.com/projectacrn/acrn-hypervisor", "commit_url": "https://github.com/projectacrn/acrn-hypervisor/commit/25c0e3817eb332660dd63d1d4522e63dcc94e79a", "commit_message": "hv: validate input for dmar_free_irte function\n\n Malicious input 'index' may trigger buffer\n overflow on array 'irte_alloc_bitmap[]'.\n\n This patch validate that 'index' shall be\n less than 'CONFIG_MAX_IR_ENTRIES' and also\n remove unnecessary check on 'index' in\n 'ptirq_free_irte()' function with this fix.\n\nTracked-On: #6132\nSigned-off-by: Yonghua Huang ", "target": 0, "func": "void dmar_free_irte(const struct intr_source *intr_src, uint16_t index)\n{\n\tstruct dmar_drhd_rt *dmar_unit;\n\tunion dmar_ir_entry *ir_table, *ir_entry;\n\tunion pci_bdf sid;\n\n\tif (intr_src->is_msi) {\n\t\tdmar_unit = device_to_dmaru((uint8_t)intr_src->src.msi.bits.b, intr_src->src.msi.fields.devfun);\n\t} else {\n\t\tdmar_unit = ioapic_to_dmaru(intr_src->src.ioapic_id, &sid);\n\t}\n\n\tif (is_dmar_unit_valid(dmar_unit, sid) && (index < CONFIG_MAX_IR_ENTRIES)) {\n\t\tir_table = (union dmar_ir_entry *)hpa2hva(dmar_unit->ir_table_addr);\n\t\tir_entry = ir_table + index;\n\t\tir_entry->bits.remap.present = 0x0UL;\n\n\t\tiommu_flush_cache(ir_entry, sizeof(union dmar_ir_entry));\n\t\tdmar_invalid_iec(dmar_unit, index, 0U, false);\n\n\t\tif (!is_irte_reserved(dmar_unit, index)) {\n\t\t\tspinlock_obtain(&dmar_unit->lock);\n\t\t\tbitmap_clear_nolock(index & 0x3FU, &dmar_unit->irte_alloc_bitmap[index >> 6U]);\n\t\t\tspinlock_release(&dmar_unit->lock);\n\t\t}\n\t}\n\n}", "func_hash": 90974058547894076190273333284621933382, "file_name": "vtd.c", "file_hash": 332372204312052317334421379047093601695, "cwe": ["CWE-787"], "cve": "CVE-2021-36148", "cve_desc": "An issue was discovered in ACRN before 2.5. dmar_free_irte in hypervisor/arch/x86/vtd.c allows an irte_alloc_bitmap buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36148"} {"idx": 197747, "project": "nDPI", "commit_id": "6a9f5e4f7c3fd5ddab3e6727b071904d76773952", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/6a9f5e4f7c3fd5ddab3e6727b071904d76773952", "commit_message": "Fixed use after free caused by dangling pointer\n\n * This fix also improved RCE Injection detection\n\nSigned-off-by: Toni Uhlig ", "target": 1, "func": "static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}", "func_hash": 55698524150275344961286550816040843749, "file_name": "ndpi_main.c", "file_hash": 195878556414950733083169233258475616968, "cwe": ["CWE-787"], "cve": "CVE-2020-15475", "cve_desc": "In nDPI through 3.2, ndpi_reset_packet_line_info in lib/ndpi_main.c omits certain reinitialization, leading to a use-after-free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15475"} {"idx": 263377, "project": "nDPI", "commit_id": "6a9f5e4f7c3fd5ddab3e6727b071904d76773952", "project_url": "https://github.com/ntop/nDPI", "commit_url": "https://github.com/ntop/nDPI/commit/6a9f5e4f7c3fd5ddab3e6727b071904d76773952", "commit_message": "Fixed use after free caused by dangling pointer\n\n * This fix also improved RCE Injection detection\n\nSigned-off-by: Toni Uhlig ", "target": 0, "func": "static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL,\n packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}", "func_hash": 254433194213981168811138730361928545389, "file_name": "ndpi_main.c", "file_hash": 296519856225272093146805222016819646473, "cwe": ["CWE-787"], "cve": "CVE-2020-15475", "cve_desc": "In nDPI through 3.2, ndpi_reset_packet_line_info in lib/ndpi_main.c omits certain reinitialization, leading to a use-after-free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15475"} {"idx": 197757, "project": "asylo", "commit_id": "bda9772e7872b0d2b9bee32930cf7a4983837b39", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/bda9772e7872b0d2b9bee32930cf7a4983837b39", "commit_message": "Check input length in FromLinuxSockAddr\n\nPiperOrigin-RevId: 333785506\nChange-Id: I1d68fb8954665eebc1018d80ff995cbe9e7ed6a9", "target": 1, "func": "bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,\n socklen_t input_len, struct sockaddr *output,\n socklen_t *output_len,\n void (*abort_handler)(const char *)) {\n if (!input || !output || !output_len || input_len == 0) {\n output = nullptr;\n return false;\n }\n\n int16_t klinux_family = input->klinux_sa_family;\n if (klinux_family == kLinux_AF_UNIX) {\n struct klinux_sockaddr_un *klinux_sockaddr_un_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_un sockaddr_un_out;\n sockaddr_un_out.sun_family = AF_UNIX;\n InitializeToZeroArray(sockaddr_un_out.sun_path);\n ReinterpretCopyArray(\n sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,\n std::min(sizeof(sockaddr_un_out.sun_path),\n sizeof(klinux_sockaddr_un_in->klinux_sun_path)));\n CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET) {\n struct klinux_sockaddr_in *klinux_sockaddr_in_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in sockaddr_in_out;\n sockaddr_in_out.sin_family = AF_INET;\n sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;\n InitializeToZeroSingle(&sockaddr_in_out.sin_addr);\n ReinterpretCopySingle(&sockaddr_in_out.sin_addr,\n &klinux_sockaddr_in_in->klinux_sin_addr);\n InitializeToZeroArray(sockaddr_in_out.sin_zero);\n ReinterpretCopyArray(sockaddr_in_out.sin_zero,\n klinux_sockaddr_in_in->klinux_sin_zero);\n CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET6) {\n struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in6 sockaddr_in6_out;\n sockaddr_in6_out.sin6_family = AF_INET6;\n sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;\n sockaddr_in6_out.sin6_flowinfo =\n klinux_sockaddr_in6_in->klinux_sin6_flowinfo;\n sockaddr_in6_out.sin6_scope_id =\n klinux_sockaddr_in6_in->klinux_sin6_scope_id;\n InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);\n ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,\n &klinux_sockaddr_in6_in->klinux_sin6_addr);\n CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,\n output_len);\n } else if (klinux_family == kLinux_AF_UNSPEC) {\n output = nullptr;\n *output_len = 0;\n } else {\n if (abort_handler != nullptr) {\n std::string message = absl::StrCat(\n \"Type conversion error - Unsupported AF family: \", klinux_family);\n abort_handler(message.c_str());\n } else {\n abort();\n }\n }\n return true;\n}", "func_hash": 188602023715829590048173881617728168836, "file_name": "manual_types_functions.cc", "file_hash": 201245110528442385495504648260197275317, "cwe": ["CWE-787"], "cve": "CVE-2020-8938", "cve_desc": "An arbitrary memory overwrite vulnerability in Asylo versions up to 0.6.0 allows an attacker to make a host call to FromkLinuxSockAddr with attacker controlled content and size of klinux_addr which allows an attacker to write memory values from within the enclave. We recommend upgrading past commit a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8938"} {"idx": 263436, "project": "asylo", "commit_id": "bda9772e7872b0d2b9bee32930cf7a4983837b39", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/bda9772e7872b0d2b9bee32930cf7a4983837b39", "commit_message": "Check input length in FromLinuxSockAddr\n\nPiperOrigin-RevId: 333785506\nChange-Id: I1d68fb8954665eebc1018d80ff995cbe9e7ed6a9", "target": 0, "func": "bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,\n socklen_t input_len, struct sockaddr *output,\n socklen_t *output_len,\n void (*abort_handler)(const char *)) {\n if (!input || !output || !output_len || input_len == 0) {\n output = nullptr;\n return false;\n }\n\n int16_t klinux_family = input->klinux_sa_family;\n if (klinux_family == kLinux_AF_UNIX) {\n if (input_len < sizeof(struct klinux_sockaddr_un)) {\n return false;\n }\n\n struct klinux_sockaddr_un *klinux_sockaddr_un_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_un sockaddr_un_out;\n sockaddr_un_out.sun_family = AF_UNIX;\n InitializeToZeroArray(sockaddr_un_out.sun_path);\n ReinterpretCopyArray(\n sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,\n std::min(sizeof(sockaddr_un_out.sun_path),\n sizeof(klinux_sockaddr_un_in->klinux_sun_path)));\n CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET) {\n if (input_len < sizeof(struct klinux_sockaddr_in)) {\n return false;\n }\n struct klinux_sockaddr_in *klinux_sockaddr_in_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in sockaddr_in_out;\n sockaddr_in_out.sin_family = AF_INET;\n sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;\n InitializeToZeroSingle(&sockaddr_in_out.sin_addr);\n ReinterpretCopySingle(&sockaddr_in_out.sin_addr,\n &klinux_sockaddr_in_in->klinux_sin_addr);\n InitializeToZeroArray(sockaddr_in_out.sin_zero);\n ReinterpretCopyArray(sockaddr_in_out.sin_zero,\n klinux_sockaddr_in_in->klinux_sin_zero);\n CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET6) {\n if (input_len < sizeof(struct klinux_sockaddr_in6)) {\n return false;\n }\n\n struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in6 sockaddr_in6_out;\n sockaddr_in6_out.sin6_family = AF_INET6;\n sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;\n sockaddr_in6_out.sin6_flowinfo =\n klinux_sockaddr_in6_in->klinux_sin6_flowinfo;\n sockaddr_in6_out.sin6_scope_id =\n klinux_sockaddr_in6_in->klinux_sin6_scope_id;\n InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);\n ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,\n &klinux_sockaddr_in6_in->klinux_sin6_addr);\n CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,\n output_len);\n } else if (klinux_family == kLinux_AF_UNSPEC) {\n output = nullptr;\n *output_len = 0;\n } else {\n if (abort_handler != nullptr) {\n std::string message = absl::StrCat(\n \"Type conversion error - Unsupported AF family: \", klinux_family);\n abort_handler(message.c_str());\n } else {\n abort();\n }\n }\n return true;\n}", "func_hash": 201940672553315255224046732541792997627, "file_name": "manual_types_functions.cc", "file_hash": 188340427456901480339701702448748912209, "cwe": ["CWE-787"], "cve": "CVE-2020-8938", "cve_desc": "An arbitrary memory overwrite vulnerability in Asylo versions up to 0.6.0 allows an attacker to make a host call to FromkLinuxSockAddr with attacker controlled content and size of klinux_addr which allows an attacker to write memory values from within the enclave. We recommend upgrading past commit a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8938"} {"idx": 197761, "project": "tensorflow", "commit_id": "d6ed5bcfe1dcab9e85a4d39931bd18d99018e75b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/d6ed5bcfe1dcab9e85a4d39931bd18d99018e75b", "commit_message": "Add missing validation in `QuantizedBatchNormWithGlobalNormalization`\n\nPiperOrigin-RevId: 370123451\nChange-Id: Id234d6dab1ec21230bb8e503dba30f899af87f33", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const float input_min = context->input(1).flat()(0);\n const float input_max = context->input(2).flat()(0);\n const Tensor& mean = context->input(3);\n const float mean_min = context->input(4).flat()(0);\n const float mean_max = context->input(5).flat()(0);\n const Tensor& var = context->input(6);\n const float var_min = context->input(7).flat()(0);\n const float var_max = context->input(8).flat()(0);\n const Tensor& beta = context->input(9);\n const float beta_min = context->input(10).flat()(0);\n const float beta_max = context->input(11).flat()(0);\n const Tensor& gamma = context->input(12);\n const float gamma_min = context->input(13).flat()(0);\n const float gamma_max = context->input(14).flat()(0);\n\n OP_REQUIRES(context, input.dims() == 4,\n errors::InvalidArgument(\"input must be 4-dimensional\",\n input.shape().DebugString()));\n OP_REQUIRES(context, mean.dims() == 1,\n errors::InvalidArgument(\"mean must be 1-dimensional\",\n mean.shape().DebugString()));\n OP_REQUIRES(context, var.dims() == 1,\n errors::InvalidArgument(\"var must be 1-dimensional\",\n var.shape().DebugString()));\n OP_REQUIRES(context, beta.dims() == 1,\n errors::InvalidArgument(\"beta must be 1-dimensional\",\n beta.shape().DebugString()));\n OP_REQUIRES(context, gamma.dims() == 1,\n errors::InvalidArgument(\"gamma must be 1-dimensional\",\n gamma.shape().DebugString()));\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input.shape(), &output));\n float output_min;\n float output_max;\n FixedPointBatchNorm(input, input_min, input_max, mean, mean_min,\n mean_max, var, var_min, var_max, beta, beta_min,\n beta_max, gamma, gamma_min, gamma_max,\n variance_epsilon_, scale_after_normalization_,\n output, &output_min, &output_max);\n\n Tensor* output_min_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(1, {}, &output_min_tensor));\n output_min_tensor->flat()(0) = output_min;\n\n Tensor* output_max_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(2, {}, &output_max_tensor));\n output_max_tensor->flat()(0) = output_max;\n }", "func_hash": 1241482450187694621098595834398852720, "file_name": "quantized_batch_norm_op.cc", "file_hash": 324521549903328782290266648367483232425, "cwe": ["CWE-369"], "cve": "CVE-2021-29547", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a segfault and denial of service via accessing data outside of bounds in `tf.raw_ops.QuantizedBatchNormWithGlobalNormalization`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/55a97caa9e99c7f37a0bbbeb414dc55553d3ae7f/tensorflow/core/kernels/quantized_batch_norm_op.cc#L176-L189) assumes the inputs are not empty. If any of these inputs is empty, `.flat()` is an empty buffer, so accessing the element at index 0 is accessing data outside of bounds. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29547"} {"idx": 263524, "project": "tensorflow", "commit_id": "d6ed5bcfe1dcab9e85a4d39931bd18d99018e75b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/d6ed5bcfe1dcab9e85a4d39931bd18d99018e75b", "commit_message": "Add missing validation in `QuantizedBatchNormWithGlobalNormalization`\n\nPiperOrigin-RevId: 370123451\nChange-Id: Id234d6dab1ec21230bb8e503dba30f899af87f33", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const auto& input_min_tensor = context->input(1);\n OP_REQUIRES(context, input_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"input_min must have 1 element\"));\n const float input_min = input_min_tensor.flat()(0);\n const auto& input_max_tensor = context->input(2);\n OP_REQUIRES(context, input_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"input_max must have 1 element\"));\n const float input_max = input_max_tensor.flat()(0);\n const Tensor& mean = context->input(3);\n const auto& mean_min_tensor = context->input(4);\n OP_REQUIRES(context, mean_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"mean_min must have 1 element\"));\n const float mean_min = mean_min_tensor.flat()(0);\n const auto& mean_max_tensor = context->input(5);\n OP_REQUIRES(context, mean_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"mean_max must have 1 element\"));\n const float mean_max = mean_max_tensor.flat()(0);\n const Tensor& var = context->input(6);\n const auto& var_min_tensor = context->input(7);\n OP_REQUIRES(context, var_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"var_min must have 1 element\"));\n const float var_min = var_min_tensor.flat()(0);\n const auto& var_max_tensor = context->input(8);\n OP_REQUIRES(context, var_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"var_max must have 1 element\"));\n const float var_max = var_max_tensor.flat()(0);\n const Tensor& beta = context->input(9);\n const auto& beta_min_tensor = context->input(10);\n OP_REQUIRES(context, beta_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"beta_min must have 1 element\"));\n const float beta_min = beta_min_tensor.flat()(0);\n const auto& beta_max_tensor = context->input(11);\n OP_REQUIRES(context, beta_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"beta_max must have 1 element\"));\n const float beta_max = beta_max_tensor.flat()(0);\n const Tensor& gamma = context->input(12);\n const auto& gamma_min_tensor = context->input(13);\n OP_REQUIRES(context, gamma_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"gamma_min must have 1 element\"));\n const float gamma_min = gamma_min_tensor.flat()(0);\n const auto& gamma_max_tensor = context->input(14);\n OP_REQUIRES(context, gamma_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"gamma_max must have 1 element\"));\n const float gamma_max = gamma_max_tensor.flat()(0);\n\n OP_REQUIRES(context, input.dims() == 4,\n errors::InvalidArgument(\"input must be 4-dimensional\",\n input.shape().DebugString()));\n OP_REQUIRES(context, mean.dims() == 1,\n errors::InvalidArgument(\"mean must be 1-dimensional\",\n mean.shape().DebugString()));\n OP_REQUIRES(context, var.dims() == 1,\n errors::InvalidArgument(\"var must be 1-dimensional\",\n var.shape().DebugString()));\n OP_REQUIRES(context, beta.dims() == 1,\n errors::InvalidArgument(\"beta must be 1-dimensional\",\n beta.shape().DebugString()));\n OP_REQUIRES(context, gamma.dims() == 1,\n errors::InvalidArgument(\"gamma must be 1-dimensional\",\n gamma.shape().DebugString()));\n OP_REQUIRES(context, mean.NumElements() > 1,\n errors::InvalidArgument(\"Must have at least a mean value\",\n gamma.shape().DebugString()));\n OP_REQUIRES(context, mean.NumElements() > 1,\n errors::InvalidArgument(\"Must have at least a mean value\"));\n const auto last_dim = input.shape().dims() - 1;\n OP_REQUIRES(context,\n mean.shape().dim_size(0) == input.shape().dim_size(last_dim),\n errors::InvalidArgument(\"Must provide as many means as the \"\n \"last dimension of the input tensor: \",\n mean.shape().DebugString(), \" vs. \",\n input.shape().DebugString()));\n OP_REQUIRES(\n context, mean.shape().dim_size(0) == var.shape().dim_size(0),\n errors::InvalidArgument(\n \"Mean and variance tensors must have the same shape: \",\n mean.shape().DebugString(), \" vs. \", var.shape().DebugString()));\n OP_REQUIRES(\n context, mean.shape().dim_size(0) == beta.shape().dim_size(0),\n errors::InvalidArgument(\n \"Mean and beta tensors must have the same shape: \",\n mean.shape().DebugString(), \" vs. \", beta.shape().DebugString()));\n OP_REQUIRES(\n context, mean.shape().dim_size(0) == gamma.shape().dim_size(0),\n errors::InvalidArgument(\n \"Mean and gamma tensors must have the same shape: \",\n mean.shape().DebugString(), \" vs. \", gamma.shape().DebugString()));\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input.shape(), &output));\n float output_min;\n float output_max;\n FixedPointBatchNorm(input, input_min, input_max, mean, mean_min,\n mean_max, var, var_min, var_max, beta, beta_min,\n beta_max, gamma, gamma_min, gamma_max,\n variance_epsilon_, scale_after_normalization_,\n output, &output_min, &output_max);\n\n Tensor* output_min_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(1, {}, &output_min_tensor));\n output_min_tensor->flat()(0) = output_min;\n\n Tensor* output_max_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(2, {}, &output_max_tensor));\n output_max_tensor->flat()(0) = output_max;\n }", "func_hash": 159711476986257703058516395032495614016, "file_name": "quantized_batch_norm_op.cc", "file_hash": 169617773940428611353453440751458853103, "cwe": ["CWE-369"], "cve": "CVE-2021-29547", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a segfault and denial of service via accessing data outside of bounds in `tf.raw_ops.QuantizedBatchNormWithGlobalNormalization`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/55a97caa9e99c7f37a0bbbeb414dc55553d3ae7f/tensorflow/core/kernels/quantized_batch_norm_op.cc#L176-L189) assumes the inputs are not empty. If any of these inputs is empty, `.flat()` is an empty buffer, so accessing the element at index 0 is accessing data outside of bounds. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29547"} {"idx": 197806, "project": "tensorflow", "commit_id": "4f663d4b8f0bec1b48da6fa091a7d29609980fa4", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4f663d4b8f0bec1b48da6fa091a7d29609980fa4", "commit_message": "Allowlist certain data types to avoid a seg fault.\n\nPiperOrigin-RevId: 356326671\nChange-Id: I23b65b52e93798cb5a6744632d31b0f88c6b6b31", "target": 1, "func": "ImmutableConstantOp::ImmutableConstantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context,\n context->GetAttr(kMemoryRegionNameAttr, ®ion_name_));\n OP_REQUIRES_OK(context, context->GetAttr(kDTypeAttr, &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(kShapeAttr, &shape_));\n}", "func_hash": 175422434799737301895630436276365186451, "file_name": "immutable_constant_op.cc", "file_hash": 324964758469908684145057205337900692185, "cwe": ["CWE-703"], "cve": "CVE-2021-29539", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Calling `tf.raw_ops.ImmutableConst`(https://www.tensorflow.org/api_docs/python/tf/raw_ops/ImmutableConst) with a `dtype` of `tf.resource` or `tf.variant` results in a segfault in the implementation as code assumes that the tensor contents are pure scalars. We have patched the issue in 4f663d4b8f0bec1b48da6fa091a7d29609980fa4 and will release TensorFlow 2.5.0 containing the patch. TensorFlow nightly packages after this commit will also have the issue resolved. If using `tf.raw_ops.ImmutableConst` in code, you can prevent the segfault by inserting a filter for the `dtype` argument.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29539"} {"idx": 264414, "project": "tensorflow", "commit_id": "4f663d4b8f0bec1b48da6fa091a7d29609980fa4", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4f663d4b8f0bec1b48da6fa091a7d29609980fa4", "commit_message": "Allowlist certain data types to avoid a seg fault.\n\nPiperOrigin-RevId: 356326671\nChange-Id: I23b65b52e93798cb5a6744632d31b0f88c6b6b31", "target": 0, "func": "ImmutableConstantOp::ImmutableConstantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context,\n context->GetAttr(kMemoryRegionNameAttr, ®ion_name_));\n OP_REQUIRES_OK(context, context->GetAttr(kDTypeAttr, &dtype_));\n OP_REQUIRES(context, dtype_ != DT_RESOURCE && dtype_ != DT_VARIANT,\n errors::InvalidArgument(\n \"Resource and variant dtypes are invalid for this op.\"));\n OP_REQUIRES_OK(context, context->GetAttr(kShapeAttr, &shape_));\n}", "func_hash": 221315840751104478142536762734452612024, "file_name": "immutable_constant_op.cc", "file_hash": 309514468328058558963685973025166446073, "cwe": ["CWE-703"], "cve": "CVE-2021-29539", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Calling `tf.raw_ops.ImmutableConst`(https://www.tensorflow.org/api_docs/python/tf/raw_ops/ImmutableConst) with a `dtype` of `tf.resource` or `tf.variant` results in a segfault in the implementation as code assumes that the tensor contents are pure scalars. We have patched the issue in 4f663d4b8f0bec1b48da6fa091a7d29609980fa4 and will release TensorFlow 2.5.0 containing the patch. TensorFlow nightly packages after this commit will also have the issue resolved. If using `tf.raw_ops.ImmutableConst` in code, you can prevent the segfault by inserting a filter for the `dtype` argument.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29539"} {"idx": 197832, "project": "asylo", "commit_id": "a47ef55db2337d29de19c50cd29b0deb2871d31c", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/a47ef55db2337d29de19c50cd29b0deb2871d31c", "commit_message": "Fix vulnerability in UntrustedCacheMalloc\n\nThe pointer array is stored in untrusted memory, so we cannot trust the\nvalue even after validation. We should validate the pointer is pointing\nto untrusted memory after it's stored inside the enclave.\n\nPiperOrigin-RevId: 358474391\nChange-Id: I63cf6c251bdaf1b491dbf06cc0dcf77f7b141756", "target": 1, "func": "void *UntrustedCacheMalloc::GetBuffer() {\n void **buffers = nullptr;\n void *buffer;\n bool is_pool_empty;\n\n {\n LockGuard spin_lock(&lock_);\n is_pool_empty = buffer_pool_.empty();\n if (is_pool_empty) {\n buffers =\n primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize);\n for (int i = 0; i < kPoolIncrement; i++) {\n if (!buffers[i] ||\n !TrustedPrimitives::IsOutsideEnclave(buffers[i], kPoolEntrySize)) {\n abort();\n }\n buffer_pool_.push(buffers[i]);\n }\n }\n buffer = buffer_pool_.top();\n buffer_pool_.pop();\n busy_buffers_.insert(buffer);\n }\n\n if (is_pool_empty) {\n // Free memory held by the array of buffer pointers returned by\n // AllocateUntrustedBuffers.\n Free(buffers);\n }\n return buffer;\n}", "func_hash": 318544625816530458883546440933957546126, "file_name": "untrusted_cache_malloc.cc", "file_hash": 250331028132802305658090145538678750540, "cwe": ["CWE-200"], "cve": "CVE-2021-22550", "cve_desc": "An attacker can modify the pointers in enclave memory to overwrite arbitrary memory addresses within the secure enclave. It is recommended to update past 0.6.3 or git commit https://github.com/google/asylo/commit/a47ef55db2337d29de19c50cd29b0deb2871d31c", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22550"} {"idx": 264754, "project": "asylo", "commit_id": "a47ef55db2337d29de19c50cd29b0deb2871d31c", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/a47ef55db2337d29de19c50cd29b0deb2871d31c", "commit_message": "Fix vulnerability in UntrustedCacheMalloc\n\nThe pointer array is stored in untrusted memory, so we cannot trust the\nvalue even after validation. We should validate the pointer is pointing\nto untrusted memory after it's stored inside the enclave.\n\nPiperOrigin-RevId: 358474391\nChange-Id: I63cf6c251bdaf1b491dbf06cc0dcf77f7b141756", "target": 0, "func": "void *UntrustedCacheMalloc::GetBuffer() {\n void **buffers = nullptr;\n void *buffer;\n bool is_pool_empty;\n\n {\n LockGuard spin_lock(&lock_);\n is_pool_empty = buffer_pool_.empty();\n if (is_pool_empty) {\n buffers =\n primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize);\n for (int i = 0; i < kPoolIncrement; i++) {\n void *buf = buffers[i];\n if (!buf || !TrustedPrimitives::IsOutsideEnclave(buf, kPoolEntrySize)) {\n TrustedPrimitives::BestEffortAbort(\n \"Cached buffer is not outside the enclave\");\n }\n buffer_pool_.push(buf);\n }\n }\n buffer = buffer_pool_.top();\n buffer_pool_.pop();\n busy_buffers_.insert(buffer);\n }\n\n if (is_pool_empty) {\n // Free memory held by the array of buffer pointers returned by\n // AllocateUntrustedBuffers.\n Free(buffers);\n }\n return buffer;\n}", "func_hash": 46090269348625475856862158670640407102, "file_name": "untrusted_cache_malloc.cc", "file_hash": 310238975396390984529837067178373923074, "cwe": ["CWE-200"], "cve": "CVE-2021-22550", "cve_desc": "An attacker can modify the pointers in enclave memory to overwrite arbitrary memory addresses within the secure enclave. It is recommended to update past 0.6.3 or git commit https://github.com/google/asylo/commit/a47ef55db2337d29de19c50cd29b0deb2871d31c", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22550"} {"idx": 197848, "project": "Pillow", "commit_id": "6a83e4324738bb0452fbe8074a995b1c73f08de7", "project_url": "https://github.com/python-pillow/Pillow", "commit_url": "https://github.com/python-pillow/Pillow/commit/6a83e4324738bb0452fbe8074a995b1c73f08de7#diff-9478f2787e3ae9668a15123b165c23ac", "commit_message": "Fix OOB Access on PcxDecode.c", "target": 1, "func": "ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 n;\n UINT8* ptr;\n\n if (strcmp(im->mode, \"1\") == 0 && state->xsize > state->bytes * 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n } else if (strcmp(im->mode, \"P\") == 0 && state->xsize > state->bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n ptr = buf;\n\n for (;;) {\n\n\tif (bytes < 1)\n\t return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t /* Run */\n\t if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t n = ptr[0] & 0x3F;\n\n\t while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t }\n\n\t ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t /* Literal */\n\t state->buffer[state->x++] = ptr[0];\n\t ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n if (state->bytes % state->xsize && state->bytes > state->xsize) {\n int bands = state->bytes / state->xsize;\n int stride = state->bytes / bands;\n int i;\n for (i=1; i< bands; i++) { // note -- skipping first band\n memmove(&state->buffer[i*state->xsize],\n &state->buffer[i*stride],\n state->xsize);\n }\n }\n\t /* Got a full line, unpack it */\n\t state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t state->xoff * im->pixelsize, state->buffer,\n\t\t\t state->xsize);\n\n\t state->x = 0;\n\n\t if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t }\n\t}\n\n }\n}", "func_hash": 143873595391817729679500419080772302964, "file_name": "PcxDecode.c", "file_hash": 23050918028233146900672463352839911866, "cwe": ["CWE-125"], "cve": "CVE-2020-10378", "cve_desc": "In libImaging/PcxDecode.c in Pillow before 7.1.0, an out-of-bounds read can occur when reading PCX files where state->shuffle is instructed to read beyond state->buffer.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10378"} {"idx": 265040, "project": "Pillow", "commit_id": "6a83e4324738bb0452fbe8074a995b1c73f08de7", "project_url": "https://github.com/python-pillow/Pillow", "commit_url": "https://github.com/python-pillow/Pillow/commit/6a83e4324738bb0452fbe8074a995b1c73f08de7#diff-9478f2787e3ae9668a15123b165c23ac", "commit_message": "Fix OOB Access on PcxDecode.c", "target": 0, "func": "ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 n;\n UINT8* ptr;\n\n if ((state->xsize * state->bits + 7) / 8 > state->bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n ptr = buf;\n\n for (;;) {\n\n\tif (bytes < 1)\n\t return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t /* Run */\n\t if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t n = ptr[0] & 0x3F;\n\n\t while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t }\n\n\t ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t /* Literal */\n\t state->buffer[state->x++] = ptr[0];\n\t ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n if (state->bytes % state->xsize && state->bytes > state->xsize) {\n int bands = state->bytes / state->xsize;\n int stride = state->bytes / bands;\n int i;\n for (i=1; i< bands; i++) { // note -- skipping first band\n memmove(&state->buffer[i*state->xsize],\n &state->buffer[i*stride],\n state->xsize);\n }\n }\n\t /* Got a full line, unpack it */\n\t state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t state->xoff * im->pixelsize, state->buffer,\n\t\t\t state->xsize);\n\n\t state->x = 0;\n\n\t if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t }\n\t}\n\n }\n}", "func_hash": 66523386479742628747449146209741933785, "file_name": "PcxDecode.c", "file_hash": 333465392432706025704119135976753939637, "cwe": ["CWE-125"], "cve": "CVE-2020-10378", "cve_desc": "In libImaging/PcxDecode.c in Pillow before 7.1.0, an out-of-bounds read can occur when reading PCX files where state->shuffle is instructed to read beyond state->buffer.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10378"} {"idx": 197890, "project": "gpac", "commit_id": "f0ba83717b6e4d7a15a1676d1fe06152e199b011", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/f0ba83717b6e4d7a15a1676d1fe06152e199b011", "commit_message": "fixed #1772 (fuzz)", "target": 1, "func": "GF_Err Media_RewriteODFrame(GF_MediaBox *mdia, GF_ISOSample *sample)\n{\n\tGF_Err e;\n\tGF_ODCodec *ODdecode;\n\tGF_ODCodec *ODencode;\n\tGF_ODCom *com;\n\n\t//the commands we proceed\n\tGF_ESDUpdate *esdU, *esdU2;\n\tGF_ESDRemove *esdR, *esdR2;\n\tGF_ODUpdate *odU, *odU2;\n\n\t//the desc they contain\n\tGF_ObjectDescriptor *od;\n\tGF_IsomObjectDescriptor *isom_od;\n\tGF_ESD *esd;\n\tGF_ES_ID_Ref *ref;\n\tGF_Descriptor *desc;\n\tGF_TrackReferenceTypeBox *mpod;\n\tu32 i, j, skipped;\n\n\tif (!mdia || !sample || !sample->data || !sample->dataLength) return GF_BAD_PARAM;\n\n\tmpod = NULL;\n\te = Track_FindRef(mdia->mediaTrack, GF_ISOM_BOX_TYPE_MPOD, &mpod);\n\tif (e) return e;\n\t//no references, nothing to do...\n\tif (!mpod || !mpod->trackIDs) return GF_OK;\n\n\tODdecode = gf_odf_codec_new();\n\tif (!ODdecode) return GF_OUT_OF_MEM;\n\tODencode = gf_odf_codec_new();\n\tif (!ODencode) {\n\t\tgf_odf_codec_del(ODdecode);\n\t\treturn GF_OUT_OF_MEM;\n\t}\n\te = gf_odf_codec_set_au(ODdecode, sample->data, sample->dataLength);\n\tif (e) goto err_exit;\n\te = gf_odf_codec_decode(ODdecode);\n\tif (e) goto err_exit;\n\n\twhile (1) {\n\t\tcom = gf_odf_codec_get_com(ODdecode);\n\t\tif (!com) break;\n\n\t\t//we only need to rewrite commands with ESDs inside: ESDUpdate and ODUpdate\n\t\tswitch (com->tag) {\n\t\tcase GF_ODF_OD_UPDATE_TAG:\n\t\t\todU = (GF_ODUpdate *) com;\n\t\t\todU2 = (GF_ODUpdate *) gf_odf_com_new(GF_ODF_OD_UPDATE_TAG);\n\n\t\t\ti=0;\n\t\t\twhile ((desc = (GF_Descriptor*)gf_list_enum(odU->objectDescriptors, &i))) {\n\t\t\t\tswitch (desc->tag) {\n\t\t\t\tcase GF_ODF_OD_TAG:\n\t\t\t\tcase GF_ODF_ISOM_OD_TAG:\n\t\t\t\t//IOD can be used in OD streams\n\t\t\t\tcase GF_ODF_ISOM_IOD_TAG:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t\t}\n\t\t\t\te = gf_odf_desc_copy(desc, (GF_Descriptor **)&isom_od);\n\t\t\t\tif (e) goto err_exit;\n\n\t\t\t\t//create our OD...\n\t\t\t\tif (desc->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_InitialObjectDescriptor));\n\t\t\t\t} else {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_ObjectDescriptor));\n\t\t\t\t}\n\t\t\t\tif (!od) {\n\t\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tod->ESDescriptors = gf_list_new();\n\t\t\t\t//and duplicate...\n\t\t\t\tod->objectDescriptorID = isom_od->objectDescriptorID;\n\t\t\t\tod->tag = GF_ODF_OD_TAG;\n\t\t\t\tod->URLString = isom_od->URLString;\n\t\t\t\tisom_od->URLString = NULL;\n\t\t\t\tod->extensionDescriptors = isom_od->extensionDescriptors;\n\t\t\t\tisom_od->extensionDescriptors = NULL;\n\t\t\t\tod->IPMP_Descriptors = isom_od->IPMP_Descriptors;\n\t\t\t\tisom_od->IPMP_Descriptors = NULL;\n\t\t\t\tod->OCIDescriptors = isom_od->OCIDescriptors;\n\t\t\t\tisom_od->OCIDescriptors = NULL;\n\n\t\t\t\t//init as IOD\n\t\t\t\tif (isom_od->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->audio_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->audio_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->inlineProfileFlag = ((GF_IsomInitialObjectDescriptor *)isom_od)->inlineProfileFlag;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->graphics_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->graphics_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->OD_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->OD_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->scene_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->scene_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->visual_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->visual_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->IPMPToolList = ((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList;\n\t\t\t\t\t((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList = NULL;\n\t\t\t\t}\n\n\t\t\t\t//then rewrite the ESDesc\n\t\t\t\tj=0;\n\t\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(isom_od->ES_ID_RefDescriptors, &j))) {\n\t\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\t\tif (!mpod->trackIDs || gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t\t//OK, get the esd\n\t\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\t\tif (!e) e = gf_odf_desc_add_desc((GF_Descriptor *) od, (GF_Descriptor *) esd);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU2);\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\t\t\t\tgoto err_exit;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t//delete our desc\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\tgf_list_add(odU2->objectDescriptors, od);\n\t\t\t}\n\t\t\t//clean a bit\n\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)odU2);\n\t\t\tbreak;\n\n\t\tcase GF_ODF_ESD_UPDATE_TAG:\n\t\t\tesdU = (GF_ESDUpdate *) com;\n\t\t\tesdU2 = (GF_ESDUpdate *) gf_odf_com_new(GF_ODF_ESD_UPDATE_TAG);\n\t\t\tesdU2->ODID = esdU->ODID;\n\t\t\ti=0;\n\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(esdU->ESDescriptors, &i))) {\n\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t//OK, get the esd\n\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tgf_list_add(esdU2->ESDescriptors, esd);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdU2);\n\t\t\tbreak;\n\n\t\t//brand new case: the ESRemove follows the same principle according to the spec...\n\t\tcase GF_ODF_ESD_REMOVE_REF_TAG:\n\t\t\t//both commands have the same structure, only the tags change\n\t\t\tesdR = (GF_ESDRemove *) com;\n\t\t\tesdR2 = (GF_ESDRemove *) gf_odf_com_new(GF_ODF_ESD_REMOVE_TAG);\n\t\t\tesdR2->ODID = esdR->ODID;\n\t\t\tesdR2->NbESDs = esdR->NbESDs;\n\t\t\t//alloc our stuff\n\t\t\tesdR2->ES_ID = (unsigned short*)gf_malloc(sizeof(u32) * esdR->NbESDs);\n\t\t\tif (!esdR2->ES_ID) {\n\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\tskipped = 0;\n\t\t\t//get the ES_ID in the mpod indicated in the ES_ID[]\n\t\t\tfor (i = 0; i < esdR->NbESDs; i++) {\n\t\t\t\t//if the ref index is not valid, remove this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[esdR->ES_ID[i] - 1]) == NULL) {\n\t\t\t\t\tskipped ++;\n\t\t\t\t} else {\n\t\t\t\t\t//the command in the file has the ref index of the trackID in the mpod\n\t\t\t\t\tesdR2->ES_ID[i - skipped] = mpod->trackIDs[esdR->ES_ID[i] - 1];\n\t\t\t\t}\n\t\t\t}\n\t\t\t//gf_realloc...\n\t\t\tif (skipped && (skipped != esdR2->NbESDs) ) {\n\t\t\t\tesdR2->NbESDs -= skipped;\n\t\t\t\tesdR2->ES_ID = (unsigned short*)gf_realloc(esdR2->ES_ID, sizeof(u32) * esdR2->NbESDs);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdR);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdR2);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\te = gf_odf_codec_add_com(ODencode, com);\n\t\t\tif (e) goto err_exit;\n\t\t}\n\t}\n\t//encode our new AU\n\te = gf_odf_codec_encode(ODencode, 1);\n\tif (e) goto err_exit;\n\n\t//and set the buffer in the sample\n\tgf_free(sample->data);\n\tsample->data = NULL;\n\tsample->dataLength = 0;\n\te = gf_odf_codec_get_au(ODencode, &sample->data, &sample->dataLength);\n\nerr_exit:\n\tgf_odf_codec_del(ODdecode);\n\tgf_odf_codec_del(ODencode);\n\treturn e;\n}", "func_hash": 169545290828552418750876349362579438656, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-32440", "cve_desc": "The Media_RewriteODFrame function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32440"} {"idx": 265416, "project": "gpac", "commit_id": "f0ba83717b6e4d7a15a1676d1fe06152e199b011", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/f0ba83717b6e4d7a15a1676d1fe06152e199b011", "commit_message": "fixed #1772 (fuzz)", "target": 0, "func": "GF_Err Media_RewriteODFrame(GF_MediaBox *mdia, GF_ISOSample *sample)\n{\n\tGF_Err e;\n\tGF_ODCodec *ODdecode;\n\tGF_ODCodec *ODencode;\n\tGF_ODCom *com;\n\n\t//the commands we proceed\n\tGF_ESDUpdate *esdU, *esdU2;\n\tGF_ESDRemove *esdR, *esdR2;\n\tGF_ODUpdate *odU, *odU2;\n\n\t//the desc they contain\n\tGF_ObjectDescriptor *od;\n\tGF_IsomObjectDescriptor *isom_od;\n\tGF_ESD *esd;\n\tGF_ES_ID_Ref *ref;\n\tGF_Descriptor *desc;\n\tGF_TrackReferenceTypeBox *mpod;\n\tu32 i, j, skipped;\n\n\tif (!mdia || !sample || !sample->data || !sample->dataLength) return GF_BAD_PARAM;\n\n\tmpod = NULL;\n\te = Track_FindRef(mdia->mediaTrack, GF_ISOM_BOX_TYPE_MPOD, &mpod);\n\tif (e) return e;\n\t//no references, nothing to do...\n\tif (!mpod || !mpod->trackIDs) return GF_OK;\n\n\tODdecode = gf_odf_codec_new();\n\tif (!ODdecode) return GF_OUT_OF_MEM;\n\tODencode = gf_odf_codec_new();\n\tif (!ODencode) {\n\t\tgf_odf_codec_del(ODdecode);\n\t\treturn GF_OUT_OF_MEM;\n\t}\n\te = gf_odf_codec_set_au(ODdecode, sample->data, sample->dataLength);\n\tif (e) goto err_exit;\n\te = gf_odf_codec_decode(ODdecode);\n\tif (e) goto err_exit;\n\n\twhile (1) {\n\t\tcom = gf_odf_codec_get_com(ODdecode);\n\t\tif (!com) break;\n\n\t\t//we only need to rewrite commands with ESDs inside: ESDUpdate and ODUpdate\n\t\tswitch (com->tag) {\n\t\tcase GF_ODF_OD_UPDATE_TAG:\n\t\t\todU = (GF_ODUpdate *) com;\n\t\t\todU2 = (GF_ODUpdate *) gf_odf_com_new(GF_ODF_OD_UPDATE_TAG);\n\n\t\t\ti=0;\n\t\t\twhile ((desc = (GF_Descriptor*)gf_list_enum(odU->objectDescriptors, &i))) {\n\t\t\t\tswitch (desc->tag) {\n\t\t\t\tcase GF_ODF_OD_TAG:\n\t\t\t\tcase GF_ODF_ISOM_OD_TAG:\n\t\t\t\t//IOD can be used in OD streams\n\t\t\t\tcase GF_ODF_ISOM_IOD_TAG:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t\t}\n\t\t\t\te = gf_odf_desc_copy(desc, (GF_Descriptor **)&isom_od);\n\t\t\t\tif (e) goto err_exit;\n\n\t\t\t\t//create our OD...\n\t\t\t\tif (desc->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_InitialObjectDescriptor));\n\t\t\t\t} else {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_ObjectDescriptor));\n\t\t\t\t}\n\t\t\t\tif (!od) {\n\t\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tod->ESDescriptors = gf_list_new();\n\t\t\t\t//and duplicate...\n\t\t\t\tod->objectDescriptorID = isom_od->objectDescriptorID;\n\t\t\t\tod->tag = GF_ODF_OD_TAG;\n\t\t\t\tod->URLString = isom_od->URLString;\n\t\t\t\tisom_od->URLString = NULL;\n\t\t\t\tod->extensionDescriptors = isom_od->extensionDescriptors;\n\t\t\t\tisom_od->extensionDescriptors = NULL;\n\t\t\t\tod->IPMP_Descriptors = isom_od->IPMP_Descriptors;\n\t\t\t\tisom_od->IPMP_Descriptors = NULL;\n\t\t\t\tod->OCIDescriptors = isom_od->OCIDescriptors;\n\t\t\t\tisom_od->OCIDescriptors = NULL;\n\n\t\t\t\t//init as IOD\n\t\t\t\tif (isom_od->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->audio_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->audio_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->inlineProfileFlag = ((GF_IsomInitialObjectDescriptor *)isom_od)->inlineProfileFlag;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->graphics_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->graphics_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->OD_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->OD_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->scene_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->scene_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->visual_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->visual_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->IPMPToolList = ((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList;\n\t\t\t\t\t((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList = NULL;\n\t\t\t\t}\n\n\t\t\t\t//then rewrite the ESDesc\n\t\t\t\tj=0;\n\t\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(isom_od->ES_ID_RefDescriptors, &j))) {\n\t\t\t\t\tif (!mpod->trackIDs || !ref->trackRef || (ref->trackRef>mpod->trackIDCount)) continue;\n\t\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t\t//OK, get the esd\n\t\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\t\tif (!e) e = gf_odf_desc_add_desc((GF_Descriptor *) od, (GF_Descriptor *) esd);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU2);\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\t\t\t\tgoto err_exit;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t//delete our desc\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\tgf_list_add(odU2->objectDescriptors, od);\n\t\t\t}\n\t\t\t//clean a bit\n\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)odU2);\n\t\t\tbreak;\n\n\t\tcase GF_ODF_ESD_UPDATE_TAG:\n\t\t\tesdU = (GF_ESDUpdate *) com;\n\t\t\tesdU2 = (GF_ESDUpdate *) gf_odf_com_new(GF_ODF_ESD_UPDATE_TAG);\n\t\t\tesdU2->ODID = esdU->ODID;\n\t\t\ti=0;\n\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(esdU->ESDescriptors, &i))) {\n\t\t\t\tif (!mpod->trackIDs || !ref->trackRef || (ref->trackRef>mpod->trackIDCount)) continue;\n\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t//OK, get the esd\n\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tgf_list_add(esdU2->ESDescriptors, esd);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdU2);\n\t\t\tbreak;\n\n\t\t//brand new case: the ESRemove follows the same principle according to the spec...\n\t\tcase GF_ODF_ESD_REMOVE_REF_TAG:\n\t\t\t//both commands have the same structure, only the tags change\n\t\t\tesdR = (GF_ESDRemove *) com;\n\t\t\tesdR2 = (GF_ESDRemove *) gf_odf_com_new(GF_ODF_ESD_REMOVE_TAG);\n\t\t\tesdR2->ODID = esdR->ODID;\n\t\t\tesdR2->NbESDs = esdR->NbESDs;\n\t\t\t//alloc our stuff\n\t\t\tesdR2->ES_ID = (unsigned short*)gf_malloc(sizeof(u32) * esdR->NbESDs);\n\t\t\tif (!esdR2->ES_ID) {\n\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\tskipped = 0;\n\t\t\t//get the ES_ID in the mpod indicated in the ES_ID[]\n\t\t\tfor (i = 0; i < esdR->NbESDs; i++) {\n\t\t\t\tif (!mpod->trackIDs || !esdR->ES_ID[i] || (esdR->ES_ID[i]>mpod->trackIDCount)) continue;\n\t\t\t\t//if the ref index is not valid, remove this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[esdR->ES_ID[i] - 1]) == NULL) {\n\t\t\t\t\tskipped ++;\n\t\t\t\t} else {\n\t\t\t\t\t//the command in the file has the ref index of the trackID in the mpod\n\t\t\t\t\tesdR2->ES_ID[i - skipped] = mpod->trackIDs[esdR->ES_ID[i] - 1];\n\t\t\t\t}\n\t\t\t}\n\t\t\t//gf_realloc...\n\t\t\tif (skipped && (skipped != esdR2->NbESDs) ) {\n\t\t\t\tesdR2->NbESDs -= skipped;\n\t\t\t\tesdR2->ES_ID = (unsigned short*)gf_realloc(esdR2->ES_ID, sizeof(u32) * esdR2->NbESDs);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdR);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdR2);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\te = gf_odf_codec_add_com(ODencode, com);\n\t\t\tif (e) goto err_exit;\n\t\t}\n\t}\n\t//encode our new AU\n\te = gf_odf_codec_encode(ODencode, 1);\n\tif (e) goto err_exit;\n\n\t//and set the buffer in the sample\n\tgf_free(sample->data);\n\tsample->data = NULL;\n\tsample->dataLength = 0;\n\te = gf_odf_codec_get_au(ODencode, &sample->data, &sample->dataLength);\n\nerr_exit:\n\tgf_odf_codec_del(ODdecode);\n\tgf_odf_codec_del(ODencode);\n\treturn e;\n}", "func_hash": 277984426061127219707588128655592306818, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-32440", "cve_desc": "The Media_RewriteODFrame function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32440"} {"idx": 197892, "project": "tensorflow", "commit_id": "801c1c6be5324219689c98e1bd3e0ca365ee834d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/801c1c6be5324219689c98e1bd3e0ca365ee834d", "commit_message": "Fix another division by 0 in TFLite\n\nPiperOrigin-RevId: 370800181\nChange-Id: I924809166a6131f5075e6d45c455106538d755f9", "target": 1, "func": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n // Retrieve tensors (All should be allocated by now)\n const TfLiteTensor* output_shape;\n TF_LITE_ENSURE_OK(\n context, GetInputSafe(context, node, kOutputShapeTensor, &output_shape));\n const TfLiteTensor* weights;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kWeightsTensor, &weights));\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kDataInputTensor, &input));\n const TfLiteTensor* bias =\n (NumInputs(node) == 4)\n ? GetOptionalInputTensor(context, node, kBiasTensor)\n : nullptr;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n OpData* data = reinterpret_cast(node->user_data);\n TfLiteTensor* col2im = data->has_col2im\n ? GetTemporary(context, node, data->col2im_index)\n : nullptr;\n TfLiteTensor* transposed_weights =\n data->weights_are_transposed\n ? GetTemporary(context, node, data->transposed_weights_index)\n : nullptr;\n const auto* params =\n reinterpret_cast(node->builtin_data);\n\n // Resize any deferred dynamic tensors\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));\n }\n if (data->has_col2im && IsDynamicTensor(col2im)) {\n TF_LITE_ENSURE_OK(context, ResizeCol2ImTensor(context, output_shape,\n weights, input, col2im));\n }\n\n // Get height and width of the output image.\n const int width = SizeOfDimension(output, 2);\n const int height = SizeOfDimension(output, 1);\n const int filter_width = SizeOfDimension(weights, 2);\n const int filter_height = SizeOfDimension(weights, 1);\n\n int unused_output_height, unused_output_width;\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n filter_height, filter_width, params->padding, &unused_output_height,\n &unused_output_width);\n\n // Currently support float32, uint8, int8, int16.\n switch (input->type) {\n case kTfLiteFloat32: {\n // Only for GenericOptimized path, we use transposed weights.\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalFloat(context, params, data, input, weights, bias,\n transposed_weights, col2im, output);\n break;\n }\n case kTfLiteUInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalQuantized(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n case kTfLiteInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel(context, params, data, input,\n weights, transposed_weights, bias,\n col2im, output, scratch_buffer);\n break;\n }\n case kTfLiteInt16: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel16x8(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n default:\n context->ReportError(context, \"Type '%s' is not currently supported.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "func_hash": 30542501178687739244904227716328852360, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29588", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The optimized implementation of the `TransposeConv` TFLite operator is [vulnerable to a division by zero error](https://github.com/tensorflow/tensorflow/blob/0d45ea1ca641b21b73bcf9c00e0179cda284e7e7/tensorflow/lite/kernels/internal/optimized/optimized_ops.h#L5221-L5222). An attacker can craft a model such that `stride_{h,w}` values are 0. Code calling this function must validate these arguments. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29588"} {"idx": 265428, "project": "tensorflow", "commit_id": "801c1c6be5324219689c98e1bd3e0ca365ee834d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/801c1c6be5324219689c98e1bd3e0ca365ee834d", "commit_message": "Fix another division by 0 in TFLite\n\nPiperOrigin-RevId: 370800181\nChange-Id: I924809166a6131f5075e6d45c455106538d755f9", "target": 0, "func": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n // Retrieve tensors (All should be allocated by now)\n const TfLiteTensor* output_shape;\n TF_LITE_ENSURE_OK(\n context, GetInputSafe(context, node, kOutputShapeTensor, &output_shape));\n const TfLiteTensor* weights;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kWeightsTensor, &weights));\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kDataInputTensor, &input));\n const TfLiteTensor* bias =\n (NumInputs(node) == 4)\n ? GetOptionalInputTensor(context, node, kBiasTensor)\n : nullptr;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n OpData* data = reinterpret_cast(node->user_data);\n TfLiteTensor* col2im = data->has_col2im\n ? GetTemporary(context, node, data->col2im_index)\n : nullptr;\n TfLiteTensor* transposed_weights =\n data->weights_are_transposed\n ? GetTemporary(context, node, data->transposed_weights_index)\n : nullptr;\n const auto* params =\n reinterpret_cast(node->builtin_data);\n\n // Prevent divisions by 0\n TF_LITE_ENSURE(context, params->stride_height > 0);\n TF_LITE_ENSURE(context, params->stride_width > 0);\n\n // Resize any deferred dynamic tensors\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));\n }\n if (data->has_col2im && IsDynamicTensor(col2im)) {\n TF_LITE_ENSURE_OK(context, ResizeCol2ImTensor(context, output_shape,\n weights, input, col2im));\n }\n\n // Get height and width of the output image.\n const int width = SizeOfDimension(output, 2);\n const int height = SizeOfDimension(output, 1);\n const int filter_width = SizeOfDimension(weights, 2);\n const int filter_height = SizeOfDimension(weights, 1);\n\n int unused_output_height, unused_output_width;\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n filter_height, filter_width, params->padding, &unused_output_height,\n &unused_output_width);\n\n // Currently support float32, uint8, int8, int16.\n switch (input->type) {\n case kTfLiteFloat32: {\n // Only for GenericOptimized path, we use transposed weights.\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalFloat(context, params, data, input, weights, bias,\n transposed_weights, col2im, output);\n break;\n }\n case kTfLiteUInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalQuantized(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n case kTfLiteInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel(context, params, data, input,\n weights, transposed_weights, bias,\n col2im, output, scratch_buffer);\n break;\n }\n case kTfLiteInt16: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel16x8(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n default:\n context->ReportError(context, \"Type '%s' is not currently supported.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "func_hash": 17172995054397793046191492804967558780, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29588", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The optimized implementation of the `TransposeConv` TFLite operator is [vulnerable to a division by zero error](https://github.com/tensorflow/tensorflow/blob/0d45ea1ca641b21b73bcf9c00e0179cda284e7e7/tensorflow/lite/kernels/internal/optimized/optimized_ops.h#L5221-L5222). An attacker can craft a model such that `stride_{h,w}` values are 0. Code calling this function must validate these arguments. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29588"} {"idx": 197910, "project": "asylo", "commit_id": "382da2b8b09cbf928668a2445efb778f76bd9c8a", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/382da2b8b09cbf928668a2445efb778f76bd9c8a", "commit_message": "Check output of ecall_restore is outside enclave\n\nPiperOrigin-RevId: 334265380\nChange-Id: Ifbaead6bce56f01b2a4d69f53ca508d0138f6f61", "target": 1, "func": "int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(\n output_len, sizeof(uint64_t))) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input/output found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n}", "func_hash": 5120789648516904544874225583525524317, "file_name": "ecalls.cc", "file_hash": 129384299980105655491932483673774824011, "cwe": ["CWE-787"], "cve": "CVE-2020-8944", "cve_desc": "An arbitrary memory write vulnerability in Asylo versions up to 0.6.0 allows an untrusted attacker to make a call to ecall_restore using the attribute output which fails to check the range of a pointer. An attacker can use this pointer to write to arbitrary memory addresses including those within the secure enclave We recommend upgrading past commit 382da2b8b09cbf928668a2445efb778f76bd9c8a", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8944"} {"idx": 265529, "project": "asylo", "commit_id": "382da2b8b09cbf928668a2445efb778f76bd9c8a", "project_url": "https://github.com/google/asylo", "commit_url": "https://github.com/google/asylo/commit/382da2b8b09cbf928668a2445efb778f76bd9c8a", "commit_message": "Check output of ecall_restore is outside enclave\n\nPiperOrigin-RevId: 334265380\nChange-Id: Ifbaead6bce56f01b2a4d69f53ca508d0138f6f61", "target": 0, "func": "int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(\n output_len, sizeof(uint64_t)) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(output,\n *output_len)) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input/output found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n}", "func_hash": 263208674062185681680063567908187832873, "file_name": "ecalls.cc", "file_hash": 134421748399709934154161949188451565618, "cwe": ["CWE-787"], "cve": "CVE-2020-8944", "cve_desc": "An arbitrary memory write vulnerability in Asylo versions up to 0.6.0 allows an untrusted attacker to make a call to ecall_restore using the attribute output which fails to check the range of a pointer. An attacker can use this pointer to write to arbitrary memory addresses including those within the secure enclave We recommend upgrading past commit 382da2b8b09cbf928668a2445efb778f76bd9c8a", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8944"} {"idx": 197927, "project": "znc", "commit_id": "a4a5aeeb17d32937d8c7d743dae9a4cc755ce773", "project_url": "https://github.com/znc/znc", "commit_url": "https://github.com/znc/znc/commit/a4a5aeeb17d32937d8c7d743dae9a4cc755ce773", "commit_message": "Don't let web skin name ../../../../ access files outside of usual skins directories.\n\nThanks for Jeriko One for finding and reporting this.", "target": 1, "func": "CString CWebSock::GetSkinPath(const CString& sSkinName) {\n CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkinName;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkinName;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CString(_SKINDIR_) + \"/\" + sSkinName;\n }\n }\n\n return sRet + \"/\";\n}", "func_hash": 105778916665681223864629284532223037569, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2018-14056", "cve_desc": "ZNC before 1.7.1-rc1 is prone to a path traversal flaw via ../ in a web skin name to access files outside of the intended skins directories.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14056"} {"idx": 265791, "project": "znc", "commit_id": "a4a5aeeb17d32937d8c7d743dae9a4cc755ce773", "project_url": "https://github.com/znc/znc", "commit_url": "https://github.com/znc/znc/commit/a4a5aeeb17d32937d8c7d743dae9a4cc755ce773", "commit_message": "Don't let web skin name ../../../../ access files outside of usual skins directories.\n\nThanks for Jeriko One for finding and reporting this.", "target": 0, "func": "CString CWebSock::GetSkinPath(const CString& sSkinName) {\n const CString sSkin = sSkinName.Replace_n(\"/\", \"_\").Replace_n(\".\", \"_\");\n\n CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkin;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkin;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CString(_SKINDIR_) + \"/\" + sSkin;\n }\n }\n\n return sRet + \"/\";\n}", "func_hash": 73822411145922058132571110211930081796, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2018-14056", "cve_desc": "ZNC before 1.7.1-rc1 is prone to a path traversal flaw via ../ in a web skin name to access files outside of the intended skins directories.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14056"} {"idx": 197972, "project": "gpac", "commit_id": "ebfa346eff05049718f7b80041093b4c5581c24e", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/ebfa346eff05049718f7b80041093b4c5581c24e", "commit_message": "fixed #1706", "target": 1, "func": "GF_Err gf_isom_set_extraction_slc(GF_ISOFile *the_file, u32 trackNumber, u32 StreamDescriptionIndex, const GF_SLConfig *slConfig)\n{\n\tGF_TrackBox *trak;\n\tGF_SampleEntryBox *entry;\n\tGF_Err e;\n\tGF_SLConfig **slc;\n\n\ttrak = gf_isom_get_track_from_file(the_file, trackNumber);\n\tif (!trak) return GF_BAD_PARAM;\n\n\te = Media_GetSampleDesc(trak->Media, StreamDescriptionIndex, &entry, NULL);\n\tif (e) return e;\n\n\t//we must be sure we are not using a remote ESD\n\tswitch (entry->type) {\n\tcase GF_ISOM_BOX_TYPE_MP4S:\n\t\tif (((GF_MPEGSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = & ((GF_MPEGSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4A:\n\t\tif (((GF_MPEGAudioSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = & ((GF_MPEGAudioSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4V:\n\t\tif (((GF_MPEGVisualSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = & ((GF_MPEGVisualSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_BAD_PARAM;\n\t}\n\n\tif (*slc) {\n\t\tgf_odf_desc_del((GF_Descriptor *)*slc);\n\t\t*slc = NULL;\n\t}\n\tif (!slConfig) return GF_OK;\n\t//finally duplicate the SL\n\treturn gf_odf_desc_copy((GF_Descriptor *) slConfig, (GF_Descriptor **) slc);\n}", "func_hash": 184731129482944775879819994176932367646, "file_name": "isom_write.c", "file_hash": 256983831904192174076501126567311270167, "cwe": ["CWE-476"], "cve": "CVE-2021-31258", "cve_desc": "The gf_isom_set_extraction_slc function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31258"} {"idx": 267342, "project": "gpac", "commit_id": "ebfa346eff05049718f7b80041093b4c5581c24e", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/ebfa346eff05049718f7b80041093b4c5581c24e", "commit_message": "fixed #1706", "target": 0, "func": "GF_Err gf_isom_get_extraction_slc(GF_ISOFile *the_file, u32 trackNumber, u32 StreamDescriptionIndex, GF_SLConfig **slConfig)\n{\n\tGF_TrackBox *trak;\n\tGF_SampleEntryBox *entry;\n\tGF_Err e;\n\tGF_SLConfig *slc;\n\n\ttrak = gf_isom_get_track_from_file(the_file, trackNumber);\n\tif (!trak) return GF_BAD_PARAM;\n\n\te = Media_GetSampleDesc(trak->Media, StreamDescriptionIndex, &entry, NULL);\n\tif (e) return e;\n\n\t//we must be sure we are not using a remote ESD\n\tslc = NULL;\n\t*slConfig = NULL;\n\tswitch (entry->type) {\n\tcase GF_ISOM_BOX_TYPE_MP4S:\n\t\tif (((GF_MPEGSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = ((GF_MPEGSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4A:\n\t\tif (((GF_MPEGAudioSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = ((GF_MPEGAudioSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4V:\n\t\tif (((GF_MPEGVisualSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = ((GF_MPEGVisualSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_BAD_PARAM;\n\t}\n\n\tif (!slc) return GF_OK;\n\t//finally duplicate the SL\n\treturn gf_odf_desc_copy((GF_Descriptor *) slc, (GF_Descriptor **) slConfig);\n}", "func_hash": 109639109888544538026435171116212127960, "file_name": "isom_write.c", "file_hash": 282403932169763893947360360802804463352, "cwe": ["CWE-476"], "cve": "CVE-2021-31258", "cve_desc": "The gf_isom_set_extraction_slc function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31258"} {"idx": 197987, "project": "cpp-peglib", "commit_id": "b3b29ce8f3acf3a32733d930105a17d7b0ba347e", "project_url": "https://github.com/yhirose/cpp-peglib", "commit_url": "https://github.com/yhirose/cpp-peglib/commit/b3b29ce8f3acf3a32733d930105a17d7b0ba347e", "commit_message": "Fix #122", "target": 1, "func": "inline size_t codepoint_length(const char *s8, size_t l) {\n if (l) {\n auto b = static_cast(s8[0]);\n if ((b & 0x80) == 0) {\n return 1;\n } else if ((b & 0xE0) == 0xC0) {\n return 2;\n } else if ((b & 0xF0) == 0xE0) {\n return 3;\n } else if ((b & 0xF8) == 0xF0) {\n return 4;\n }\n }\n return 0;\n}", "func_hash": 328501512882637178600198262398191644384, "file_name": "peglib.h", "file_hash": 140476493305589985699450440915588987282, "cwe": ["CWE-125"], "cve": "CVE-2020-23915", "cve_desc": "An issue was discovered in cpp-peglib through v0.1.12. peg::resolve_escape_sequence() in peglib.h has a heap-based buffer over-read.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-23915"} {"idx": 267830, "project": "cpp-peglib", "commit_id": "b3b29ce8f3acf3a32733d930105a17d7b0ba347e", "project_url": "https://github.com/yhirose/cpp-peglib", "commit_url": "https://github.com/yhirose/cpp-peglib/commit/b3b29ce8f3acf3a32733d930105a17d7b0ba347e", "commit_message": "Fix #122", "target": 0, "func": "inline size_t codepoint_length(const char *s8, size_t l) {\n if (l) {\n auto b = static_cast(s8[0]);\n if ((b & 0x80) == 0) {\n return 1;\n } else if ((b & 0xE0) == 0xC0 && l >= 2) {\n return 2;\n } else if ((b & 0xF0) == 0xE0 && l >= 3) {\n return 3;\n } else if ((b & 0xF8) == 0xF0 && l >= 4) {\n return 4;\n }\n }\n return 0;\n}", "func_hash": 57092079656666454069555466858351211295, "file_name": "peglib.h", "file_hash": 168591356101478982559161876726245931915, "cwe": ["CWE-125"], "cve": "CVE-2020-23915", "cve_desc": "An issue was discovered in cpp-peglib through v0.1.12. peg::resolve_escape_sequence() in peglib.h has a heap-based buffer over-read.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-23915"} {"idx": 197988, "project": "tensorflow", "commit_id": "390611e0d45c5793c7066110af37c8514e6a6c54", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/390611e0d45c5793c7066110af37c8514e6a6c54", "commit_message": "Fix heap buffer overflow in `tf.raw_ops.SparseFillEmptyRowsGrad`.\n\nAlso add tests as they were lacking\n\nPiperOrigin-RevId: 332566071\nChange-Id: I44277578e26ff5fb3fdb0dcbba6e91b2ec3e7859", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor* reverse_index_map_t;\n const Tensor* grad_values_t;\n OP_REQUIRES_OK(context,\n context->input(\"reverse_index_map\", &reverse_index_map_t));\n OP_REQUIRES_OK(context, context->input(\"grad_values\", &grad_values_t));\n\n const CPUDevice& d = context->eigen_device();\n\n OP_REQUIRES(\n context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()),\n errors::InvalidArgument(\"reverse_index_map must be a vector, saw: \",\n reverse_index_map_t->shape().DebugString()));\n\n const auto reverse_index_map = reverse_index_map_t->vec();\n const auto grad_values = grad_values_t->vec();\n\n const int64 N = reverse_index_map_t->shape().dim_size(0);\n const int64 N_full = grad_values_t->shape().dim_size(0);\n\n Tensor* d_values_t;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"d_values\", TensorShape({N}), &d_values_t));\n auto d_values = d_values_t->vec();\n Tensor* d_default_value_t;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"d_default_value\", TensorShape({}),\n &d_default_value_t));\n T& d_default_value = d_default_value_t->scalar()();\n d_default_value = T();\n\n Tensor visited_t;\n OP_REQUIRES_OK(context, context->allocate_temp(\n DT_BOOL, TensorShape({N_full}), &visited_t));\n auto visited = visited_t.vec();\n visited.device(d) = visited.constant(false);\n\n for (int i = 0; i < N; ++i) {\n // Locate the index of the output of the forward prop associated\n // with this location in the input of the forward prop. Copy\n // the gradient into it. Mark it as visited.\n d_values(i) = grad_values(reverse_index_map(i));\n visited(reverse_index_map(i)) = true;\n }\n for (int j = 0; j < N_full; ++j) {\n // The default value gradient gets the accumulated remainder of\n // the backprop values (since the default value was used to fill\n // in these slots in the forward calculation).\n if (!visited(j)) {\n d_default_value += grad_values(j);\n }\n }\n }", "func_hash": 245279904927503876946687660273585137284, "file_name": "sparse_fill_empty_rows_op.cc", "file_hash": 134974129627694538649582621193985633125, "cwe": ["CWE-703"], "cve": "CVE-2020-15194", "cve_desc": "In Tensorflow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, the `SparseFillEmptyRowsGrad` implementation has incomplete validation of the shapes of its arguments. Although `reverse_index_map_t` and `grad_values_t` are accessed in a similar pattern, only `reverse_index_map_t` is validated to be of proper shape. Hence, malicious users can pass a bad `grad_values_t` to trigger an assertion failure in `vec`, causing denial of service in serving installations. The issue is patched in commit 390611e0d45c5793c7066110af37c8514e6a6c54, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.\"", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15194"} {"idx": 267831, "project": "tensorflow", "commit_id": "390611e0d45c5793c7066110af37c8514e6a6c54", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/390611e0d45c5793c7066110af37c8514e6a6c54", "commit_message": "Fix heap buffer overflow in `tf.raw_ops.SparseFillEmptyRowsGrad`.\n\nAlso add tests as they were lacking\n\nPiperOrigin-RevId: 332566071\nChange-Id: I44277578e26ff5fb3fdb0dcbba6e91b2ec3e7859", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor* reverse_index_map_t;\n const Tensor* grad_values_t;\n OP_REQUIRES_OK(context,\n context->input(\"reverse_index_map\", &reverse_index_map_t));\n OP_REQUIRES_OK(context, context->input(\"grad_values\", &grad_values_t));\n\n const CPUDevice& d = context->eigen_device();\n\n OP_REQUIRES(\n context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()),\n errors::InvalidArgument(\"reverse_index_map must be a vector, saw: \",\n reverse_index_map_t->shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()),\n errors::InvalidArgument(\"grad_values must be a vector, saw: \",\n grad_values_t->shape().DebugString()));\n\n const auto reverse_index_map = reverse_index_map_t->vec();\n const auto grad_values = grad_values_t->vec();\n\n const int64 N = reverse_index_map_t->shape().dim_size(0);\n const int64 N_full = grad_values_t->shape().dim_size(0);\n\n Tensor* d_values_t;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"d_values\", TensorShape({N}), &d_values_t));\n auto d_values = d_values_t->vec();\n Tensor* d_default_value_t;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"d_default_value\", TensorShape({}),\n &d_default_value_t));\n T& d_default_value = d_default_value_t->scalar()();\n d_default_value = T();\n\n Tensor visited_t;\n OP_REQUIRES_OK(context, context->allocate_temp(\n DT_BOOL, TensorShape({N_full}), &visited_t));\n auto visited = visited_t.vec();\n visited.device(d) = visited.constant(false);\n\n for (int i = 0; i < N; ++i) {\n // Locate the index of the output of the forward prop associated\n // with this location in the input of the forward prop. Copy\n // the gradient into it. Mark it as visited.\n int64 reverse_index = reverse_index_map(i);\n OP_REQUIRES(\n context, 0 <= reverse_index && reverse_index < N_full,\n errors::InvalidArgument(\"Elements in reverse index must be in [0, \",\n N_full, \") but got \", reverse_index));\n d_values(i) = grad_values(reverse_index);\n visited(reverse_index) = true;\n }\n for (int j = 0; j < N_full; ++j) {\n // The default value gradient gets the accumulated remainder of\n // the backprop values (since the default value was used to fill\n // in these slots in the forward calculation).\n if (!visited(j)) {\n d_default_value += grad_values(j);\n }\n }\n }", "func_hash": 60349116575418886863085596069752274981, "file_name": "sparse_fill_empty_rows_op.cc", "file_hash": 151633134804476299872427829626476441044, "cwe": ["CWE-703"], "cve": "CVE-2020-15194", "cve_desc": "In Tensorflow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, the `SparseFillEmptyRowsGrad` implementation has incomplete validation of the shapes of its arguments. Although `reverse_index_map_t` and `grad_values_t` are accessed in a similar pattern, only `reverse_index_map_t` is validated to be of proper shape. Hence, malicious users can pass a bad `grad_values_t` to trigger an assertion failure in `vec`, causing denial of service in serving installations. The issue is patched in commit 390611e0d45c5793c7066110af37c8514e6a6c54, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.\"", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15194"} {"idx": 197993, "project": "gpac", "commit_id": "77ed81c069e10b3861d88f72e1c6be1277ee7eae", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/77ed81c069e10b3861d88f72e1c6be1277ee7eae", "commit_message": "fixed #1774 (fuzz)", "target": 1, "func": "GF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack)\n{\n\tu32 i;\n\tif (!nb_pack) nb_pack = 1;\n\n\tif (!stbl->SampleSize->sampleCount) {\n\t\tstbl->SampleSize->sampleSize = size;\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\tif (stbl->SampleSize->sampleSize && (stbl->SampleSize->sampleSize==size)) {\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\tif (!stbl->SampleSize->sizes || (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)) {\n\t\tBool init_table = (stbl->SampleSize->sizes==NULL) ? 1 : 0;\n\t\tALLOC_INC(stbl->SampleSize->alloc_size);\n\t\tif (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)\n\t\t\tstbl->SampleSize->alloc_size = stbl->SampleSize->sampleCount+nb_pack;\n\n\t\tstbl->SampleSize->sizes = (u32 *)gf_realloc(stbl->SampleSize->sizes, sizeof(u32)*stbl->SampleSize->alloc_size);\n\t\tif (!stbl->SampleSize->sizes) return GF_OUT_OF_MEM;\n\t\tmemset(&stbl->SampleSize->sizes[stbl->SampleSize->sampleCount], 0, sizeof(u32) * (stbl->SampleSize->alloc_size - stbl->SampleSize->sampleCount) );\n\n\t\tif (init_table) {\n\t\t\tfor (i=0; iSampleSize->sampleCount; i++)\n\t\t\t\tstbl->SampleSize->sizes[i] = stbl->SampleSize->sampleSize;\n\t\t}\n\t}\n\tstbl->SampleSize->sampleSize = 0;\n\tfor (i=0; iSampleSize->sizes[stbl->SampleSize->sampleCount+i] = size;\n\t}\n\tstbl->SampleSize->sampleCount += nb_pack;\n\tif (size > stbl->SampleSize->max_size)\n\t\tstbl->SampleSize->max_size = size;\n\tstbl->SampleSize->total_size += size;\n\tstbl->SampleSize->total_samples += nb_pack;\n\treturn GF_OK;\n}", "func_hash": 62798505757740469990874876462718925341, "file_name": "stbl_write.c", "file_hash": 105559088213322021567527149864707025859, "cwe": ["CWE-787"], "cve": "CVE-2021-32439", "cve_desc": "Buffer overflow in the stbl_AppendSize function in MP4Box in GPAC 1.0.1 allows attackers to cause a denial of service or execute arbitrary code via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32439"} {"idx": 267899, "project": "gpac", "commit_id": "77ed81c069e10b3861d88f72e1c6be1277ee7eae", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/77ed81c069e10b3861d88f72e1c6be1277ee7eae", "commit_message": "fixed #1774 (fuzz)", "target": 0, "func": "GF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack)\n{\n\tu32 i;\n\tCHECK_PACK(GF_ISOM_INVALID_FILE)\n\n\tif (!stbl->SampleSize->sampleCount) {\n\t\tstbl->SampleSize->sampleSize = size;\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\tif (stbl->SampleSize->sampleSize && (stbl->SampleSize->sampleSize==size)) {\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\n\tif (!stbl->SampleSize->sizes || (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)) {\n\t\tBool init_table = (stbl->SampleSize->sizes==NULL) ? 1 : 0;\n\t\tALLOC_INC(stbl->SampleSize->alloc_size);\n\t\tif (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size) {\n\t\t\tstbl->SampleSize->alloc_size = stbl->SampleSize->sampleCount+nb_pack;\n\t\t}\n\n\t\tstbl->SampleSize->sizes = (u32 *)gf_realloc(stbl->SampleSize->sizes, sizeof(u32)*stbl->SampleSize->alloc_size);\n\t\tif (!stbl->SampleSize->sizes) return GF_OUT_OF_MEM;\n\t\tmemset(&stbl->SampleSize->sizes[stbl->SampleSize->sampleCount], 0, sizeof(u32) * (stbl->SampleSize->alloc_size - stbl->SampleSize->sampleCount) );\n\n\t\tif (init_table) {\n\t\t\tfor (i=0; iSampleSize->sampleCount; i++)\n\t\t\t\tstbl->SampleSize->sizes[i] = stbl->SampleSize->sampleSize;\n\t\t}\n\t}\n\tstbl->SampleSize->sampleSize = 0;\n\tfor (i=0; iSampleSize->sizes[stbl->SampleSize->sampleCount+i] = size;\n\t}\n\tstbl->SampleSize->sampleCount += nb_pack;\n\tif (size > stbl->SampleSize->max_size)\n\t\tstbl->SampleSize->max_size = size;\n\tstbl->SampleSize->total_size += size;\n\tstbl->SampleSize->total_samples += nb_pack;\n\treturn GF_OK;\n}", "func_hash": 311529664055604176581120701952532765020, "file_name": "stbl_write.c", "file_hash": 269360063276341489225403956942155517712, "cwe": ["CWE-787"], "cve": "CVE-2021-32439", "cve_desc": "Buffer overflow in the stbl_AppendSize function in MP4Box in GPAC 1.0.1 allows attackers to cause a denial of service or execute arbitrary code via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32439"} {"idx": 198002, "project": "tensorflow", "commit_id": "744009c9e5cc5d0447f0dc39d055f917e1fd9e16", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/744009c9e5cc5d0447f0dc39d055f917e1fd9e16", "commit_message": "Validate work in `QuantizedAdd`, ensure at least one element.\n\nPiperOrigin-RevId: 370127996\nChange-Id: I57c6f3e01afdeada84737820a131590137463855", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n const float min_x = context->input(2).flat()(0);\n const float max_x = context->input(3).flat()(0);\n const float min_y = context->input(4).flat()(0);\n const float max_y = context->input(5).flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_x.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_y must be larger than min_y.\"));\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n // We want the range of the output to be symmetrical around zero so that\n // adding zero leaves the result unchanged, and to contain the largest of\n // the two input values with some room to spare.\n const float smallest_min = std::min(min_x, min_y);\n const float largest_max = std::max(max_x, max_y);\n const float biggest_range =\n std::max(std::abs(smallest_min), std::abs(largest_max));\n const float output_range = (biggest_range * (1 << 14));\n const float min_z_value = -output_range;\n const float max_z_value = output_range;\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarAddition(context, y_data, min_y, max_y,\n y.NumElements(), x_data[0], min_x, max_x,\n min_z_value, max_z_value, z_data);\n } else if (y.NumElements() == 1) {\n ScalarAddition(context, x_data, min_x, max_x,\n x.NumElements(), y_data[0], min_y, max_y,\n min_z_value, max_z_value, z_data);\n } else {\n VectorAddition(context, x_data, min_x, max_x, y_data, min_y,\n max_y, x.NumElements(), min_z_value,\n max_z_value, z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n float vector_min;\n float vector_max;\n const T* tensor_data;\n int64 tensor_num_elements;\n float tensor_min;\n float tensor_max;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_min = min_x;\n vector_max = max_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_min = min_y;\n tensor_max = max_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_min = min_y;\n vector_max = max_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_min = min_x;\n tensor_max = max_x;\n }\n VectorTensorAddition(\n vector_data, vector_min, vector_max, vector_num_elements, tensor_data,\n tensor_min, tensor_max, tensor_num_elements, min_z_value, max_z_value,\n z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "func_hash": 35604858474136916607313323733382769755, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29549", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a runtime division by zero error and denial of service in `tf.raw_ops.QuantizedBatchNormWithGlobalNormalization`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/6f26b3f3418201479c264f2a02000880d8df151c/tensorflow/core/kernels/quantized_add_op.cc#L289-L295) computes a modulo operation without validating that the divisor is not zero. Since `vector_num_elements` is determined based on input shapes(https://github.com/tensorflow/tensorflow/blob/6f26b3f3418201479c264f2a02000880d8df151c/tensorflow/core/kernels/quantized_add_op.cc#L522-L544), a user can trigger scenarios where this quantity is 0. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29549"} {"idx": 267926, "project": "tensorflow", "commit_id": "744009c9e5cc5d0447f0dc39d055f917e1fd9e16", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/744009c9e5cc5d0447f0dc39d055f917e1fd9e16", "commit_message": "Validate work in `QuantizedAdd`, ensure at least one element.\n\nPiperOrigin-RevId: 370127996\nChange-Id: I57c6f3e01afdeada84737820a131590137463855", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n const float min_x = context->input(2).flat()(0);\n const float max_x = context->input(3).flat()(0);\n const float min_y = context->input(4).flat()(0);\n const float max_y = context->input(5).flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_x.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_y must be larger than min_y.\"));\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n // We want the range of the output to be symmetrical around zero so that\n // adding zero leaves the result unchanged, and to contain the largest of\n // the two input values with some room to spare.\n const float smallest_min = std::min(min_x, min_y);\n const float largest_max = std::max(max_x, max_y);\n const float biggest_range =\n std::max(std::abs(smallest_min), std::abs(largest_max));\n const float output_range = (biggest_range * (1 << 14));\n const float min_z_value = -output_range;\n const float max_z_value = output_range;\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarAddition(context, y_data, min_y, max_y,\n y.NumElements(), x_data[0], min_x, max_x,\n min_z_value, max_z_value, z_data);\n } else if (y.NumElements() == 1) {\n ScalarAddition(context, x_data, min_x, max_x,\n x.NumElements(), y_data[0], min_y, max_y,\n min_z_value, max_z_value, z_data);\n } else {\n VectorAddition(context, x_data, min_x, max_x, y_data, min_y,\n max_y, x.NumElements(), min_z_value,\n max_z_value, z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n float vector_min;\n float vector_max;\n const T* tensor_data;\n int64 tensor_num_elements;\n float tensor_min;\n float tensor_max;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_min = min_x;\n vector_max = max_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_min = min_y;\n tensor_max = max_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_min = min_y;\n vector_max = max_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_min = min_x;\n tensor_max = max_x;\n }\n OP_REQUIRES(context, vector_num_elements > 0,\n errors::InvalidArgument(\"Must have some elements to add\"));\n VectorTensorAddition(\n vector_data, vector_min, vector_max, vector_num_elements, tensor_data,\n tensor_min, tensor_max, tensor_num_elements, min_z_value, max_z_value,\n z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "func_hash": 43722487695514546988911883075758194457, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29549", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a runtime division by zero error and denial of service in `tf.raw_ops.QuantizedBatchNormWithGlobalNormalization`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/6f26b3f3418201479c264f2a02000880d8df151c/tensorflow/core/kernels/quantized_add_op.cc#L289-L295) computes a modulo operation without validating that the divisor is not zero. Since `vector_num_elements` is determined based on input shapes(https://github.com/tensorflow/tensorflow/blob/6f26b3f3418201479c264f2a02000880d8df151c/tensorflow/core/kernels/quantized_add_op.cc#L522-L544), a user can trigger scenarios where this quantity is 0. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29549"} {"idx": 198007, "project": "tensorflow", "commit_id": "3ebedd7e345453d68e279cfc3e4072648e5e12e5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/3ebedd7e345453d68e279cfc3e4072648e5e12e5", "commit_message": "Prevent division by 0 in OneHot implementation\n\nIf input indices is degenerate, the implementation would do a divide by zero. See https://github.com/tensorflow/tensorflow/blob/745d57df6d5e9bc568666a2a48ed8dd629c27241/tensorflow/lite/kernels/one_hot.cc#L68-L72\n\nPiperOrigin-RevId: 370966870\nChange-Id: Ie018337811c8016b5a1d3a277d00d5f2e19a2058", "target": 1, "func": "void OneHotComputeImpl(const OneHotContext& op_context) {\n // prefix_dim_size == # of elements before the axis\n // depth == # of elements per axis\n // suffix_dim_size == # of elements after the axis\n int prefix_dim_size = 1;\n for (int i = 0; i < op_context.axis; ++i) {\n prefix_dim_size *= op_context.indices->dims->data[i];\n }\n const int suffix_dim_size = NumElements(op_context.indices) / prefix_dim_size;\n const int depth = *op_context.depth->data.i32;\n\n const T on_value = *GetTensorData(op_context.on_value);\n const T off_value = *GetTensorData(op_context.off_value);\n\n // View the indices as a matrix of size:\n // prefix_dim_size x suffix_dim_size\n // View the output as a matrix of size:\n // prefix_dim_size x depth x suffix_dim_size\n // Then the output is:\n // output(i, j, k) == (indices(i, k) == j) ? on : off\n T* output = GetTensorData(op_context.output);\n const TI* indices = GetTensorData(op_context.indices);\n for (int i = 0; i < prefix_dim_size; ++i) {\n for (int j = 0; j < depth; ++j) {\n for (int k = 0; k < suffix_dim_size; ++k, ++output) {\n *output = static_cast(indices[i * suffix_dim_size + k]) == j\n ? on_value\n : off_value;\n }\n }\n }\n}", "func_hash": 250564437365152896995349048419381657522, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29600", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of the `OneHot` TFLite operator is vulnerable to a division by zero error(https://github.com/tensorflow/tensorflow/blob/f61c57bd425878be108ec787f4d96390579fb83e/tensorflow/lite/kernels/one_hot.cc#L68-L72). An attacker can craft a model such that at least one of the dimensions of `indices` would be 0. In turn, the `prefix_dim_size` value would become 0. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29600"} {"idx": 267934, "project": "tensorflow", "commit_id": "3ebedd7e345453d68e279cfc3e4072648e5e12e5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/3ebedd7e345453d68e279cfc3e4072648e5e12e5", "commit_message": "Prevent division by 0 in OneHot implementation\n\nIf input indices is degenerate, the implementation would do a divide by zero. See https://github.com/tensorflow/tensorflow/blob/745d57df6d5e9bc568666a2a48ed8dd629c27241/tensorflow/lite/kernels/one_hot.cc#L68-L72\n\nPiperOrigin-RevId: 370966870\nChange-Id: Ie018337811c8016b5a1d3a277d00d5f2e19a2058", "target": 0, "func": "void OneHotComputeImpl(const OneHotContext& op_context) {\n // prefix_dim_size == # of elements before the axis\n // depth == # of elements per axis\n // suffix_dim_size == # of elements after the axis\n int prefix_dim_size = 1;\n for (int i = 0; i < op_context.axis; ++i) {\n prefix_dim_size *= op_context.indices->dims->data[i];\n }\n if (prefix_dim_size == 0) {\n // If indices tensor is degenerate, return a degenerate tensor, just like\n // TensorFlow does.\n return;\n }\n const int suffix_dim_size = NumElements(op_context.indices) / prefix_dim_size;\n const int depth = *op_context.depth->data.i32;\n\n const T on_value = *GetTensorData(op_context.on_value);\n const T off_value = *GetTensorData(op_context.off_value);\n\n // View the indices as a matrix of size:\n // prefix_dim_size x suffix_dim_size\n // View the output as a matrix of size:\n // prefix_dim_size x depth x suffix_dim_size\n // Then the output is:\n // output(i, j, k) == (indices(i, k) == j) ? on : off\n T* output = GetTensorData(op_context.output);\n const TI* indices = GetTensorData(op_context.indices);\n for (int i = 0; i < prefix_dim_size; ++i) {\n for (int j = 0; j < depth; ++j) {\n for (int k = 0; k < suffix_dim_size; ++k, ++output) {\n *output = static_cast(indices[i * suffix_dim_size + k]) == j\n ? on_value\n : off_value;\n }\n }\n }\n}", "func_hash": 184353264085211869912796363433734473300, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29600", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The implementation of the `OneHot` TFLite operator is vulnerable to a division by zero error(https://github.com/tensorflow/tensorflow/blob/f61c57bd425878be108ec787f4d96390579fb83e/tensorflow/lite/kernels/one_hot.cc#L68-L72). An attacker can craft a model such that at least one of the dimensions of `indices` would be 0. In turn, the `prefix_dim_size` value would become 0. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29600"} {"idx": 198015, "project": "tensorflow", "commit_id": "4c0ee937c0f61c4fc5f5d32d9bb4c67428012a60", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4c0ee937c0f61c4fc5f5d32d9bb4c67428012a60", "commit_message": "Prevent overflow in sparse op\n\nPiperOrigin-RevId: 372442006\nChange-Id: I60fe31cd7e56fb3501e97c63500caf902ddeee96", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const int64 axis_input = context->input(0).scalar()();\n const Tensor& input_indices = context->input(1);\n const Tensor& input_values = context->input(2);\n const Tensor& input_shape = context->input(3);\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices.shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values.shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape.shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape.shape().DebugString()));\n\n const int64 input_rank = input_shape.vec().size();\n const int64 axis = (axis_input < 0) ? input_rank + axis_input : axis_input;\n\n OP_REQUIRES(\n context, axis >= 0 && axis < input_rank,\n errors::InvalidArgument(\"Input axis should be in range [\", -input_rank,\n \", \", input_rank, \"), got \", axis_input));\n\n OP_REQUIRES(context,\n num_split_ >= 1 && num_split_ <= input_shape.vec()(axis),\n errors::InvalidArgument(\"Input num_split should be between 1 \"\n \"and the splitting dimension size (\",\n input_shape.vec()(axis),\n \"), got \", num_split_));\n\n sparse::SparseTensor sparse_tensor;\n OP_REQUIRES_OK(context,\n sparse::SparseTensor::Create(\n input_indices, input_values,\n TensorShape(input_shape.vec()), &sparse_tensor));\n\n std::vector outputs;\n OP_REQUIRES_OK(context, sparse::SparseTensor::Split(\n sparse_tensor, axis, num_split_, &outputs));\n\n for (int slice_index = 0; slice_index < num_split_; ++slice_index) {\n context->set_output(slice_index, outputs[slice_index].indices());\n context->set_output(slice_index + num_split_,\n outputs[slice_index].values());\n Tensor* shape = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n slice_index + 2 * num_split_,\n {outputs[slice_index].dims()}, &shape));\n auto output_shape = outputs[slice_index].shape();\n for (int dim = 0; dim < outputs[slice_index].dims(); ++dim) {\n shape->vec()(dim) = output_shape[dim];\n }\n }\n }", "func_hash": 176093923983750820345810657124802459627, "file_name": "sparse_split_op.cc", "file_hash": 245131080943991113175868642752743372007, "cwe": ["CWE-369"], "cve": "CVE-2021-29584", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a denial of service via a `CHECK`-fail in caused by an integer overflow in constructing a new tensor shape. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/0908c2f2397c099338b901b067f6495a5b96760b/tensorflow/core/kernels/sparse_split_op.cc#L66-L70) builds a dense shape without checking that the dimensions would not result in overflow. The `TensorShape` constructor(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L183-L188) uses a `CHECK` operation which triggers when `InitDims`(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L212-L296) returns a non-OK status. This is a legacy implementation of the constructor and operations should use `BuildTensorShapeBase` or `AddDimWithStatus` to prevent `CHECK`-failures in the presence of overflows. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29584"} {"idx": 268106, "project": "tensorflow", "commit_id": "4c0ee937c0f61c4fc5f5d32d9bb4c67428012a60", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4c0ee937c0f61c4fc5f5d32d9bb4c67428012a60", "commit_message": "Prevent overflow in sparse op\n\nPiperOrigin-RevId: 372442006\nChange-Id: I60fe31cd7e56fb3501e97c63500caf902ddeee96", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const int64 axis_input = context->input(0).scalar()();\n const Tensor& input_indices = context->input(1);\n const Tensor& input_values = context->input(2);\n const Tensor& input_shape = context->input(3);\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices.shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values.shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape.shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape.shape().DebugString()));\n\n const int64 input_rank = input_shape.vec().size();\n const int64 axis = (axis_input < 0) ? input_rank + axis_input : axis_input;\n\n OP_REQUIRES(\n context, axis >= 0 && axis < input_rank,\n errors::InvalidArgument(\"Input axis should be in range [\", -input_rank,\n \", \", input_rank, \"), got \", axis_input));\n\n OP_REQUIRES(context,\n num_split_ >= 1 && num_split_ <= input_shape.vec()(axis),\n errors::InvalidArgument(\"Input num_split should be between 1 \"\n \"and the splitting dimension size (\",\n input_shape.vec()(axis),\n \"), got \", num_split_));\n\n // Prevent overflow by constructing the dense shape separately\n TensorShape dense_shape;\n const auto input_shape_flat = input_shape.flat();\n for (int i = 0; i < input_shape.NumElements(); i++) {\n OP_REQUIRES_OK(context,\n dense_shape.AddDimWithStatus(input_shape_flat(i)));\n }\n\n sparse::SparseTensor sparse_tensor;\n OP_REQUIRES_OK(context,\n sparse::SparseTensor::Create(input_indices, input_values,\n dense_shape, &sparse_tensor));\n\n std::vector outputs;\n OP_REQUIRES_OK(context, sparse::SparseTensor::Split(\n sparse_tensor, axis, num_split_, &outputs));\n\n for (int slice_index = 0; slice_index < num_split_; ++slice_index) {\n context->set_output(slice_index, outputs[slice_index].indices());\n context->set_output(slice_index + num_split_,\n outputs[slice_index].values());\n Tensor* shape = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n slice_index + 2 * num_split_,\n {outputs[slice_index].dims()}, &shape));\n auto output_shape = outputs[slice_index].shape();\n for (int dim = 0; dim < outputs[slice_index].dims(); ++dim) {\n shape->vec()(dim) = output_shape[dim];\n }\n }\n }", "func_hash": 268018619933603119234020397325326688192, "file_name": "sparse_split_op.cc", "file_hash": 97160717886219155831475643653777918713, "cwe": ["CWE-369"], "cve": "CVE-2021-29584", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a denial of service via a `CHECK`-fail in caused by an integer overflow in constructing a new tensor shape. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/0908c2f2397c099338b901b067f6495a5b96760b/tensorflow/core/kernels/sparse_split_op.cc#L66-L70) builds a dense shape without checking that the dimensions would not result in overflow. The `TensorShape` constructor(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L183-L188) uses a `CHECK` operation which triggers when `InitDims`(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L212-L296) returns a non-OK status. This is a legacy implementation of the constructor and operations should use `BuildTensorShapeBase` or `AddDimWithStatus` to prevent `CHECK`-failures in the presence of overflows. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29584"} {"idx": 198018, "project": "gpac", "commit_id": "1653f31cf874eb6df964bea88d58d8e9b98b485e", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/1653f31cf874eb6df964bea88d58d8e9b98b485e", "commit_message": "fixed #1770 (fuzz)", "target": 1, "func": "GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];\n\n\n\tgf_isom_sdp_clean(file);\n\n\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n //xtended attribute for copyright\n if (gf_sys_is_test_mode()) {\n sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n } else {\n sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n }\n\tgf_isom_sdp_add_line(file, buf64);\n\n\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;\n\n\todT = sceneT = 0;\n\tfor (i=0; iESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}\n\n\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);\n\n\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);\n\n\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}\n\n\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n\n\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);\n\n\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\tgf_list_add(iod->ESDescriptors, esd);\n\n\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; idecoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\telse has_v++;\n\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\telse has_a++;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}\n\n\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);\n\n\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);\n\n\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);\n\n\treturn GF_OK;\n}", "func_hash": 13577129875158486714896563629055972198, "file_name": "isom_hinter.c", "file_hash": 283626413965484459800194267771797894432, "cwe": ["CWE-476"], "cve": "CVE-2021-32437", "cve_desc": "The gf_hinter_finalize function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32437"} {"idx": 268147, "project": "gpac", "commit_id": "1653f31cf874eb6df964bea88d58d8e9b98b485e", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/1653f31cf874eb6df964bea88d58d8e9b98b485e", "commit_message": "fixed #1770 (fuzz)", "target": 0, "func": "GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];\n\n\n\tgf_isom_sdp_clean(file);\n\n\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n //xtended attribute for copyright\n if (gf_sys_is_test_mode()) {\n sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n } else {\n sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n }\n\tgf_isom_sdp_add_line(file, buf64);\n\n\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;\n\n\todT = sceneT = 0;\n\tfor (i=0; iESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}\n\n\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);\n\n\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);\n\n\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}\n\n\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n\n\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);\n\n\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\tgf_list_add(iod->ESDescriptors, esd);\n\n\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; idecoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\telse has_v++;\n\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\telse has_a++;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}\n\n\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);\n\n\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);\n\n\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);\n\n\treturn GF_OK;\n}", "func_hash": 132566293570175734893509846203547662106, "file_name": "isom_hinter.c", "file_hash": 88644659120941057073249055672963550124, "cwe": ["CWE-476"], "cve": "CVE-2021-32437", "cve_desc": "The gf_hinter_finalize function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32437"} {"idx": 198049, "project": "tensorflow", "commit_id": "0cc38aaa4064fd9e79101994ce9872c6d91f816b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0cc38aaa4064fd9e79101994ce9872c6d91f816b", "commit_message": "Prevent unitialized memory access in `GraphConstructor::MakeEdge`\n\nThe `MakeEdge` implementation assumes that there exists an output at `output_index` of `src` node and an input at `input_index` of `dst` node. However, if this is not the case this results in accessing data out of bounds. Because we are accessing an array that is a private member of a class and only in read only mode, this usually results only in unitialized memory access. However, it is reasonable to think that malicious users could manipulate these indexes to actually read data outside the class, thus resulting in information leakage and further exploits.\n\nPiperOrigin-RevId: 346343288\nChange-Id: I2127da27c2023d27f26efd39afa6c853385cab6f", "target": 1, "func": "Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,\n int input_index) {\n DataType src_out = src->output_type(output_index);\n DataType dst_in = dst->input_type(input_index);\n if (!TypesCompatible(dst_in, src_out)) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(), \" was passed \",\n DataTypeString(src_out), \" from \", src->name(), \":\", output_index,\n \" incompatible with expected \", DataTypeString(dst_in), \".\");\n }\n g_->AddEdge(src, output_index, dst, input_index);\n return Status::OK();\n}", "func_hash": 298801886219716653719805718444627908989, "file_name": "graph_constructor.cc", "file_hash": 273407926687809650006156410048018206028, "cwe": ["CWE-369"], "cve": "CVE-2020-26271", "cve_desc": "In affected versions of TensorFlow under certain cases, loading a saved model can result in accessing uninitialized memory while building the computation graph. The MakeEdge function creates an edge between one output tensor of the src node (given by output_index) and the input slot of the dst node (given by input_index). This is only possible if the types of the tensors on both sides coincide, so the function begins by obtaining the corresponding DataType values and comparing these for equality. However, there is no check that the indices point to inside of the arrays they index into. Thus, this can result in accessing data out of bounds of the corresponding heap allocated arrays. In most scenarios, this can manifest as unitialized data access, but if the index points far away from the boundaries of the arrays this can be used to leak addresses from the library. This is fixed in versions 1.15.5, 2.0.4, 2.1.3, 2.2.2, 2.3.2, and 2.4.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-26271"} {"idx": 268323, "project": "tensorflow", "commit_id": "0cc38aaa4064fd9e79101994ce9872c6d91f816b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0cc38aaa4064fd9e79101994ce9872c6d91f816b", "commit_message": "Prevent unitialized memory access in `GraphConstructor::MakeEdge`\n\nThe `MakeEdge` implementation assumes that there exists an output at `output_index` of `src` node and an input at `input_index` of `dst` node. However, if this is not the case this results in accessing data out of bounds. Because we are accessing an array that is a private member of a class and only in read only mode, this usually results only in unitialized memory access. However, it is reasonable to think that malicious users could manipulate these indexes to actually read data outside the class, thus resulting in information leakage and further exploits.\n\nPiperOrigin-RevId: 346343288\nChange-Id: I2127da27c2023d27f26efd39afa6c853385cab6f", "target": 0, "func": "Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,\n int input_index) {\n if (output_index >= src->num_outputs()) {\n return errors::InvalidArgument(\n \"Output \", output_index, \" of node \", src->name(),\n \" does not exist. Node only has \", src->num_outputs(), \" outputs.\");\n }\n if (input_index >= dst->num_inputs()) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(),\n \" does not exist. Node only has \", dst->num_inputs(), \" inputs.\");\n }\n\n DataType src_out = src->output_type(output_index);\n DataType dst_in = dst->input_type(input_index);\n if (!TypesCompatible(dst_in, src_out)) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(), \" was passed \",\n DataTypeString(src_out), \" from \", src->name(), \":\", output_index,\n \" incompatible with expected \", DataTypeString(dst_in), \".\");\n }\n g_->AddEdge(src, output_index, dst, input_index);\n return Status::OK();\n}", "func_hash": 93022868512752248377327160485097274207, "file_name": "graph_constructor.cc", "file_hash": 295650611001094859766794112883773179254, "cwe": ["CWE-369"], "cve": "CVE-2020-26271", "cve_desc": "In affected versions of TensorFlow under certain cases, loading a saved model can result in accessing uninitialized memory while building the computation graph. The MakeEdge function creates an edge between one output tensor of the src node (given by output_index) and the input slot of the dst node (given by input_index). This is only possible if the types of the tensors on both sides coincide, so the function begins by obtaining the corresponding DataType values and comparing these for equality. However, there is no check that the indices point to inside of the arrays they index into. Thus, this can result in accessing data out of bounds of the corresponding heap allocated arrays. In most scenarios, this can manifest as unitialized data access, but if the index points far away from the boundaries of the arrays this can be used to leak addresses from the library. This is fixed in versions 1.15.5, 2.0.4, 2.1.3, 2.2.2, 2.3.2, and 2.4.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-26271"} {"idx": 198095, "project": "radare2", "commit_id": "04edfa82c1f3fa2bc3621ccdad2f93bdbf00e4f9", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/04edfa82c1f3fa2bc3621ccdad2f93bdbf00e4f9", "commit_message": "Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\n* Fix build with --with-openssl\n* Use RBuffer in r_socket_http_answer()\n* r_socket_http_answer: Fix read for big responses\n* Implement r_str_escape_sh()\n* Cleanup r_socket_connect() on Windows\n* Fix socket being created without a protocol\n* Fix socket connect with SSL ##socket\n* Use select() in r_socket_ready()\n* Fix read failing if received only protocol answer\n* Fix double-free\n* r_socket_http_get: Fail if req. SSL with no support\n* Follow redirects in r_socket_http_answer()\n* Fix r_socket_http_get result length with R2_CURL=1\n* Also follow redirects\n* Avoid using curl for downloading PDBs\n* Use r_socket_http_get() on UNIXs\n* Use WinINet API on Windows for r_socket_http_get()\n* Fix command injection\n* Fix r_sys_cmd_str_full output for binary data\n* Validate GUID on PDB download\n* Pass depth to socket_http_get_recursive()\n* Remove 'r_' and '__' from static function names\n* Fix is_valid_guid\n* Fix for comments", "target": 1, "func": "static int download(struct SPDBDownloader *pd) {\n\tSPDBDownloaderOpt *opt = pd->opt;\n\tchar *curl_cmd = NULL;\n\tchar *extractor_cmd = NULL;\n\tchar *abspath_to_archive = NULL;\n\tchar *abspath_to_file = NULL;\n\tchar *archive_name = NULL;\n\tsize_t archive_name_len = 0;\n\tchar *symbol_store_path = NULL;\n\tchar *dbg_file = NULL;\n\tchar *guid = NULL;\n\tchar *archive_name_escaped = NULL;\n\tchar *user_agent = NULL;\n\tchar *symbol_server = NULL;\n\n\tint res = 0;\n\tint cmd_ret;\n\tif (!opt->dbg_file || !*opt->dbg_file) {\n\t\t// no pdb debug file\n\t\treturn 0;\n\t}\n\tif (!checkCurl ()) {\n\t\treturn 0;\n\t}\n\t// dbg_file len is > 0\n\tarchive_name_len = strlen (opt->dbg_file);\n\tarchive_name = malloc (archive_name_len + 1);\n\tif (!archive_name) {\n\t\treturn 0;\n\t}\n\tmemcpy (archive_name, opt->dbg_file, archive_name_len + 1);\n\tarchive_name[archive_name_len - 1] = '_';\n\tsymbol_store_path = r_str_escape (opt->symbol_store_path);\n\tdbg_file = r_str_escape (opt->dbg_file);\n\tguid = r_str_escape (opt->guid);\n\tarchive_name_escaped = r_str_escape (archive_name);\n\tuser_agent = r_str_escape (opt->user_agent);\n\tsymbol_server = r_str_escape (opt->symbol_server);\n\n\tabspath_to_archive = r_str_newf (\"%s%s%s%s%s%s%s\",\n\t\t\t symbol_store_path, R_SYS_DIR,\n\t\t\t dbg_file, R_SYS_DIR,\n\t\t\t guid, R_SYS_DIR,\n\t\t\t archive_name_escaped);\n\n\tabspath_to_file = strdup (abspath_to_archive);\n\tabspath_to_file[strlen (abspath_to_file) - 1] = 'b';\n\tif (r_file_exists (abspath_to_file)) {\n\t\teprintf (\"File already downloaded.\\n\");\n\t\tR_FREE (user_agent);\n\t\tR_FREE (abspath_to_archive);\n\t\tR_FREE (archive_name_escaped);\n\t\tR_FREE (symbol_store_path);\n\t\tR_FREE (dbg_file);\n\t\tR_FREE (guid);\n\t\tR_FREE (archive_name);\n\t\tR_FREE (abspath_to_file);\n\t\tR_FREE (symbol_server);\n\t\treturn 1;\n\t}\n\n\tif (checkExtract () || opt->extract == 0) {\n\t\tres = 1;\n\n\t\tcurl_cmd = r_str_newf (\"curl -sfLA \\\"%s\\\" \\\"%s/%s/%s/%s\\\" --create-dirs -o \\\"%s\\\"\",\n\t\t user_agent,\n\t\t symbol_server,\n\t\t\t\t\t\t\t dbg_file,\n\t\t\t\t\t\t\t guid,\n\t\t archive_name_escaped,\n\t\t abspath_to_archive);\n#if __WINDOWS__\n\t\tconst char *cabextractor = \"expand\";\n\t\tconst char *format = \"%s %s %s\";\n\n\t\t// extractor_cmd -> %1 %2 %3\n\t\t// %1 - 'expand'\n\t\t// %2 - absolute path to archive\n\t\t// %3 - absolute path to file that will be dearchive\n\t\textractor_cmd = r_str_newf (format, cabextractor,\n\t\t\tabspath_to_archive, abspath_to_file);\n#else\n\t\tconst char *cabextractor = \"cabextract\";\n\t\tconst char *format = \"%s -d \\\"%s\\\" \\\"%s\\\"\";\n\t\tchar *abspath_to_dir = r_file_dirname (abspath_to_archive);\n\t\t// cabextract -d %1 %2\n\t\t// %1 - path to directory where to extract all files from cab archive\n\t\t// %2 - absolute path to cab archive\n\t\textractor_cmd = r_str_newf (format, cabextractor, abspath_to_dir, abspath_to_archive);\n\t\tR_FREE (abspath_to_dir);\n#endif\n\t\teprintf (\"Attempting to download compressed pdb in %s\\n\", abspath_to_archive);\n\t\tif ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {\n\t\t\teprintf(\"curl exited with error %d\\n\", cmd_ret);\n\t\t\tres = 0;\n\t\t}\n\t\teprintf (\"Attempting to decompress pdb\\n\");\n\t\tif (opt->extract > 0) {\n\t\t\tif (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {\n\t\t\t\teprintf (\"cab extractor exited with error %d\\n\", cmd_ret);\n\t\t\t\tres = 0;\n\t\t\t}\n\t\t\tr_file_rm (abspath_to_archive);\n\t\t}\n\t\tR_FREE (curl_cmd);\n\t}\n\tif (res == 0) {\n\t\teprintf (\"Falling back to uncompressed pdb\\n\");\n\t\tres = 1;\n\n\t\tarchive_name_escaped[strlen (archive_name_escaped) - 1] = 'b';\n\n\t\tcurl_cmd = r_str_newf (\"curl -sfLA \\\"%s\\\" \\\"%s/%s/%s/%s\\\" --create-dirs -o \\\"%s\\\"\",\n\t\t opt->user_agent,\n\t\t opt->symbol_server,\n\t\t opt->dbg_file,\n\t\t opt->guid,\n\t\t archive_name_escaped,\n\t\t abspath_to_file);\n\t\teprintf (\"Attempting to download uncompressed pdb in %s\\n\", abspath_to_file);\n\t\tif ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {\n\t\t\teprintf(\"curl exited with error %d\\n\", cmd_ret);\n\t\t\tres = 0;\n\t\t}\n\t\tR_FREE (curl_cmd);\n\t}\n\tR_FREE (abspath_to_archive);\n\tR_FREE (abspath_to_file);\n\tR_FREE (archive_name);\n\tR_FREE (extractor_cmd);\n\tR_FREE (symbol_store_path);\n\tR_FREE (dbg_file);\n\tR_FREE (guid);\n\tR_FREE (archive_name_escaped);\n\tR_FREE (user_agent);\n\tR_FREE (symbol_server);\n\treturn res;\n}", "func_hash": 233872767125894504373188476371232459647, "file_name": "pdb_downloader.c", "file_hash": 10365937579447547207260761218396552714, "cwe": ["CWE-78"], "cve": "CVE-2020-15121", "cve_desc": "In radare2 before version 4.5.0, malformed PDB file names in the PDB server path cause shell injection. To trigger the problem it's required to open the executable in radare2 and run idpd to trigger the download. The shell code will execute, and will create a file called pwned in the current directory.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15121"} {"idx": 268829, "project": "radare2", "commit_id": "04edfa82c1f3fa2bc3621ccdad2f93bdbf00e4f9", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/04edfa82c1f3fa2bc3621ccdad2f93bdbf00e4f9", "commit_message": "Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\n* Fix build with --with-openssl\n* Use RBuffer in r_socket_http_answer()\n* r_socket_http_answer: Fix read for big responses\n* Implement r_str_escape_sh()\n* Cleanup r_socket_connect() on Windows\n* Fix socket being created without a protocol\n* Fix socket connect with SSL ##socket\n* Use select() in r_socket_ready()\n* Fix read failing if received only protocol answer\n* Fix double-free\n* r_socket_http_get: Fail if req. SSL with no support\n* Follow redirects in r_socket_http_answer()\n* Fix r_socket_http_get result length with R2_CURL=1\n* Also follow redirects\n* Avoid using curl for downloading PDBs\n* Use r_socket_http_get() on UNIXs\n* Use WinINet API on Windows for r_socket_http_get()\n* Fix command injection\n* Fix r_sys_cmd_str_full output for binary data\n* Validate GUID on PDB download\n* Pass depth to socket_http_get_recursive()\n* Remove 'r_' and '__' from static function names\n* Fix is_valid_guid\n* Fix for comments", "target": 0, "func": "static int download(struct SPDBDownloader *pd) {\n\tSPDBDownloaderOpt *opt = pd->opt;\n\tint res = 0;\n\tint cmd_ret;\n\n\tif (!opt->dbg_file || !*opt->dbg_file) {\n\t\t// no pdb debug file\n\t\treturn 0;\n\t}\n\n\tchar *abspath_to_file = r_str_newf (\"%s%s%s%s%s%s%s\",\n\t\topt->symbol_store_path, R_SYS_DIR,\n\t\topt->dbg_file, R_SYS_DIR,\n\t\topt->guid, R_SYS_DIR,\n\t\topt->dbg_file);\n\n\tif (r_file_exists (abspath_to_file)) {\n\t\teprintf (\"File already downloaded.\\n\");\n\t\tfree (abspath_to_file);\n\t\treturn 1;\n\t}\n\n\tif (checkExtract () || opt->extract == 0) {\n\t\tchar *extractor_cmd = NULL;\n\t\tchar *archive_name = strdup (opt->dbg_file);\n\t\tarchive_name[strlen (archive_name) - 1] = '_';\n\t\tchar *abspath_to_archive = r_str_newf (\"%s%s%s%s%s%s%s\",\n\t\t\topt->symbol_store_path, R_SYS_DIR,\n\t\t\topt->dbg_file, R_SYS_DIR,\n\t\t\topt->guid, R_SYS_DIR,\n\t\t\tarchive_name);\n\n\t\teprintf (\"Attempting to download compressed pdb in %s\\n\", abspath_to_archive);\n\t\tchar *abs_arch_esc = r_str_escape_sh (abspath_to_archive);\n#if __WINDOWS__\n\t\tchar *abs_file_esc = r_str_escape_sh (abspath_to_file);\n\t\t// expand %1 %2\n\t\t// %1 - absolute path to archive\n\t\t// %2 - absolute path to file that will be dearchive\n\t\textractor_cmd = r_str_newf (\"expand \\\"%s\\\" \\\"%s\\\"\", abs_arch_esc, abs_file_esc);\n\t\tfree (abs_file_esc);\n#else\n\t\tchar *abspath_to_dir = r_file_dirname (abspath_to_archive);\n\t\tchar *abs_dir_esc = r_str_escape_sh (abspath_to_dir);\n\t\t// cabextract -d %1 %2\n\t\t// %1 - path to directory where to extract all files from cab archive\n\t\t// %2 - absolute path to cab archive\n\t\textractor_cmd = r_str_newf (\"cabextract -d \\\"%s\\\" \\\"%s\\\"\", abs_arch_esc, abs_dir_esc);\n\t\tfree (abs_dir_esc);\n\t\tfree (abspath_to_dir);\n#endif\n\t\tfree (abs_arch_esc);\n\t\tres = download_and_write (opt, archive_name);\n\n\t\tif (opt->extract > 0 && res) {\n\t\t\teprintf (\"Attempting to decompress pdb\\n\");\n\t\t\tif (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {\n\t\t\t\teprintf (\"cab extractor exited with error %d\\n\", cmd_ret);\n\t\t\t\tres = 0;\n\t\t\t}\n\t\t\tr_file_rm (abspath_to_archive);\n\t\t}\n\t\tfree (archive_name);\n\t\tfree (abspath_to_archive);\n\t}\n\tif (res == 0) {\n\t\teprintf (\"Falling back to uncompressed pdb\\n\");\n\t\teprintf (\"Attempting to download uncompressed pdb in %s\\n\", abspath_to_file);\n\t\tres = download_and_write (opt, opt->dbg_file);\n\t}\n\tfree (abspath_to_file);\n\treturn res;\n}", "func_hash": 148990285505074397292892947677571215827, "file_name": "pdb_downloader.c", "file_hash": 268180720849448661688924530386931352557, "cwe": ["CWE-78"], "cve": "CVE-2020-15121", "cve_desc": "In radare2 before version 4.5.0, malformed PDB file names in the PDB server path cause shell injection. To trigger the problem it's required to open the executable in radare2 and run idpd to trigger the download. The shell code will execute, and will create a file called pwned in the current directory.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15121"} {"idx": 198108, "project": "pupnp", "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "project_url": "https://github.com/pupnp/pupnp", "commit_url": "https://github.com/pupnp/pupnp/commit/c805c1de1141cb22f74c0d94dd5664bda37398e0", "commit_message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 1, "func": "service_info *FindServiceEventURLPath(\n\tservice_table *table, const char *eventURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (table &&\n\t\tparse_uri(eventURLPath, strlen(eventURLPath), &parsed_url_in) ==\n\t\t\tHTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->eventURL) {\n\t\t\t\tif (parse_uri(finger->eventURL,\n\t\t\t\t\t strlen(finger->eventURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "func_hash": 21413574486144157353381990464249888143, "file_name": "service_table.c", "file_hash": 308798001913620914907669356806640049957, "cwe": ["CWE-476"], "cve": "CVE-2020-13848", "cve_desc": "Portable UPnP SDK (aka libupnp) 1.12.1 and earlier allows remote attackers to cause a denial of service (crash) via a crafted SSDP message due to a NULL pointer dereference in the functions FindServiceControlURLPath and FindServiceEventURLPath in genlib/service_table/service_table.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13848"} {"idx": 269104, "project": "pupnp", "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "project_url": "https://github.com/pupnp/pupnp", "commit_url": "https://github.com/pupnp/pupnp/commit/c805c1de1141cb22f74c0d94dd5664bda37398e0", "commit_message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 0, "func": "service_info *FindServiceEventURLPath(\n\tservice_table *table, const char *eventURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (!table || !eventURLPath) {\n\t\treturn NULL;\n\t}\n\tif (parse_uri(eventURLPath, strlen(eventURLPath), &parsed_url_in) ==\n\t\tHTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->eventURL) {\n\t\t\t\tif (parse_uri(finger->eventURL,\n\t\t\t\t\t strlen(finger->eventURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "func_hash": 33798834866331214798104925471613078776, "file_name": "service_table.c", "file_hash": 152453853608803441546081505452070179068, "cwe": ["CWE-476"], "cve": "CVE-2020-13848", "cve_desc": "Portable UPnP SDK (aka libupnp) 1.12.1 and earlier allows remote attackers to cause a denial of service (crash) via a crafted SSDP message due to a NULL pointer dereference in the functions FindServiceControlURLPath and FindServiceEventURLPath in genlib/service_table/service_table.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13848"} {"idx": 198109, "project": "pupnp", "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "project_url": "https://github.com/pupnp/pupnp", "commit_url": "https://github.com/pupnp/pupnp/commit/c805c1de1141cb22f74c0d94dd5664bda37398e0", "commit_message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 1, "func": "service_info *FindServiceControlURLPath(\n\tservice_table *table, const char *controlURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (table && parse_uri(controlURLPath,\n\t\t\t strlen(controlURLPath),\n\t\t\t &parsed_url_in) == HTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->controlURL) {\n\t\t\t\tif (parse_uri(finger->controlURL,\n\t\t\t\t\t strlen(finger->controlURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "func_hash": 233346433032395129694831299540469382534, "file_name": "service_table.c", "file_hash": 308798001913620914907669356806640049957, "cwe": ["CWE-476"], "cve": "CVE-2020-13848", "cve_desc": "Portable UPnP SDK (aka libupnp) 1.12.1 and earlier allows remote attackers to cause a denial of service (crash) via a crafted SSDP message due to a NULL pointer dereference in the functions FindServiceControlURLPath and FindServiceEventURLPath in genlib/service_table/service_table.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13848"} {"idx": 269101, "project": "pupnp", "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "project_url": "https://github.com/pupnp/pupnp", "commit_url": "https://github.com/pupnp/pupnp/commit/c805c1de1141cb22f74c0d94dd5664bda37398e0", "commit_message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 0, "func": "service_info *FindServiceControlURLPath(\n\tservice_table *table, const char *controlURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (!table || !controlURLPath) {\n\t\treturn NULL;\n\t}\n\tif (parse_uri(controlURLPath, strlen(controlURLPath), &parsed_url_in) ==\n\t\tHTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->controlURL) {\n\t\t\t\tif (parse_uri(finger->controlURL,\n\t\t\t\t\t strlen(finger->controlURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "func_hash": 323463643849856402040808251275406143570, "file_name": "service_table.c", "file_hash": 152453853608803441546081505452070179068, "cwe": ["CWE-476"], "cve": "CVE-2020-13848", "cve_desc": "Portable UPnP SDK (aka libupnp) 1.12.1 and earlier allows remote attackers to cause a denial of service (crash) via a crafted SSDP message due to a NULL pointer dereference in the functions FindServiceControlURLPath and FindServiceEventURLPath in genlib/service_table/service_table.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13848"} {"idx": 198110, "project": "tensorflow", "commit_id": "efea03b38fb8d3b81762237dc85e579cc5fc6e87", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/efea03b38fb8d3b81762237dc85e579cc5fc6e87", "commit_message": "Validate inputs to `QuantizedMul`\n\nPiperOrigin-RevId: 369756982\nChange-Id: I00d960cc3b9316fd7a86bd37a44e341c96e17624", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n const float min_x = context->input(2).flat()(0);\n const float max_x = context->input(3).flat()(0);\n const float min_y = context->input(4).flat()(0);\n const float max_y = context->input(5).flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_a.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_x must be larger than min_b.\"));\n const int32 offset_x = FloatToQuantizedUnclamped(0.0f, min_x, max_x);\n const int32 offset_y = FloatToQuantizedUnclamped(0.0f, min_y, max_y);\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarMultiply(context, y_data, offset_y, y.NumElements(),\n x_data[0], offset_x, z_data);\n } else if (y.NumElements() == 1) {\n ScalarMultiply(context, x_data, offset_x, x.NumElements(),\n y_data[0], offset_y, z_data);\n } else {\n VectorMultiply(context, x_data, offset_x, y_data, offset_y,\n x.NumElements(), z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n int32 vector_offset;\n const T* tensor_data;\n int64 tensor_num_elements;\n int32 tensor_offset;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_offset = offset_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_offset = offset_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_offset = offset_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_offset = offset_x;\n }\n if (vector_num_elements == 0) {\n context->SetStatus(\n errors::InvalidArgument(\"vector must have at least 1 element\"));\n return;\n }\n VectorTensorMultiply(\n vector_data, vector_offset, vector_num_elements, tensor_data,\n tensor_offset, tensor_num_elements, z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n float min_z_value;\n float max_z_value;\n QuantizationRangeForMultiplication(\n min_x, max_x, min_y, max_y, &min_z_value, &max_z_value);\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "func_hash": 29080887326272878831929193731061028016, "file_name": "quantized_mul_op.cc", "file_hash": 171022554046865618292288459118891907496, "cwe": ["CWE-787"], "cve": "CVE-2021-29535", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `QuantizedMul` by passing in invalid thresholds for the quantization. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/87cf4d3ea9949051e50ca3f071fc909538a51cd0/tensorflow/core/kernels/quantized_mul_op.cc#L287-L290) assumes that the 4 arguments are always valid scalars and tries to access the numeric value directly. However, if any of these tensors is empty, then `.flat()` is an empty buffer and accessing the element at position 0 results in overflow. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29535"} {"idx": 269121, "project": "tensorflow", "commit_id": "efea03b38fb8d3b81762237dc85e579cc5fc6e87", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/efea03b38fb8d3b81762237dc85e579cc5fc6e87", "commit_message": "Validate inputs to `QuantizedMul`\n\nPiperOrigin-RevId: 369756982\nChange-Id: I00d960cc3b9316fd7a86bd37a44e341c96e17624", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n auto& min_x_tensor = context->input(2);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(min_x_tensor.shape()),\n errors::InvalidArgument(\"min_x must be a scalar\"));\n const float min_x = min_x_tensor.flat()(0);\n auto& max_x_tensor = context->input(3);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(max_x_tensor.shape()),\n errors::InvalidArgument(\"max_x must be a scalar\"));\n const float max_x = max_x_tensor.flat()(0);\n auto& min_y_tensor = context->input(4);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(min_y_tensor.shape()),\n errors::InvalidArgument(\"min_y must be a scalar\"));\n const float min_y = min_y_tensor.flat()(0);\n auto& max_y_tensor = context->input(5);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(max_y_tensor.shape()),\n errors::InvalidArgument(\"max_y must be a scalar\"));\n const float max_y = max_y_tensor.flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_a.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_x must be larger than min_b.\"));\n const int32 offset_x = FloatToQuantizedUnclamped(0.0f, min_x, max_x);\n const int32 offset_y = FloatToQuantizedUnclamped(0.0f, min_y, max_y);\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarMultiply(context, y_data, offset_y, y.NumElements(),\n x_data[0], offset_x, z_data);\n } else if (y.NumElements() == 1) {\n ScalarMultiply(context, x_data, offset_x, x.NumElements(),\n y_data[0], offset_y, z_data);\n } else {\n VectorMultiply(context, x_data, offset_x, y_data, offset_y,\n x.NumElements(), z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n int32 vector_offset;\n const T* tensor_data;\n int64 tensor_num_elements;\n int32 tensor_offset;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_offset = offset_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_offset = offset_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_offset = offset_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_offset = offset_x;\n }\n if (vector_num_elements == 0) {\n context->SetStatus(\n errors::InvalidArgument(\"vector must have at least 1 element\"));\n return;\n }\n VectorTensorMultiply(\n vector_data, vector_offset, vector_num_elements, tensor_data,\n tensor_offset, tensor_num_elements, z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n float min_z_value;\n float max_z_value;\n QuantizationRangeForMultiplication(\n min_x, max_x, min_y, max_y, &min_z_value, &max_z_value);\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "func_hash": 33793980932474497912313198020554893594, "file_name": "quantized_mul_op.cc", "file_hash": 110705109221499398368683939326102173043, "cwe": ["CWE-787"], "cve": "CVE-2021-29535", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `QuantizedMul` by passing in invalid thresholds for the quantization. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/87cf4d3ea9949051e50ca3f071fc909538a51cd0/tensorflow/core/kernels/quantized_mul_op.cc#L287-L290) assumes that the 4 arguments are always valid scalars and tries to access the numeric value directly. However, if any of these tensors is empty, then `.flat()` is an empty buffer and accessing the element at position 0 results in overflow. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29535"} {"idx": 198111, "project": "tensorflow", "commit_id": "8ee24e7949a203d234489f9da2c5bf45a7d5157d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8ee24e7949a203d234489f9da2c5bf45a7d5157d", "commit_message": "[tflite] Ensure `MatchingDim` does not allow buffer overflow.\n\nWe check in `MatchingDim` that both arguments have the same dimensionality, however that is a `DCHECK` only enabled if building in debug mode. Hence, it could be possible to cause buffer overflows by passing in a tensor with larger dimensions as the second argument. To fix, we now make `MatchingDim` return the minimum of the two sizes.\n\nA much better fix would be to return a status object but that requires refactoring a large part of the codebase for minor benefits.\n\nPiperOrigin-RevId: 332526127\nChange-Id: If627d0d2c80a685217b6e0d1e64b0872dbf1c5e4", "target": 1, "func": "inline int MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));\n return shape1.Dims(index1);\n}", "func_hash": 194320989531113656363273966402055705257, "file_name": "types.h", "file_hash": 68265180438018635909487709917657725178, "cwe": ["CWE-125"], "cve": "CVE-2020-15208", "cve_desc": "In tensorflow-lite before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, when determining the common dimension size of two tensors, TFLite uses a `DCHECK` which is no-op outside of debug compilation modes. Since the function always returns the dimension of the first tensor, malicious attackers can craft cases where this is larger than that of the second tensor. In turn, this would result in reads/writes outside of bounds since the interpreter will wrongly assume that there is enough data in both tensors. The issue is patched in commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15208"} {"idx": 269181, "project": "tensorflow", "commit_id": "8ee24e7949a203d234489f9da2c5bf45a7d5157d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8ee24e7949a203d234489f9da2c5bf45a7d5157d", "commit_message": "[tflite] Ensure `MatchingDim` does not allow buffer overflow.\n\nWe check in `MatchingDim` that both arguments have the same dimensionality, however that is a `DCHECK` only enabled if building in debug mode. Hence, it could be possible to cause buffer overflows by passing in a tensor with larger dimensions as the second argument. To fix, we now make `MatchingDim` return the minimum of the two sizes.\n\nA much better fix would be to return a status object but that requires refactoring a large part of the codebase for minor benefits.\n\nPiperOrigin-RevId: 332526127\nChange-Id: If627d0d2c80a685217b6e0d1e64b0872dbf1c5e4", "target": 0, "func": "inline int MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));\n return std::min(shape1.Dims(index1), shape2.Dims(index2));\n}", "func_hash": 184064808269708952772955421692702192693, "file_name": "types.h", "file_hash": 334656351380165418671070836117137771304, "cwe": ["CWE-125"], "cve": "CVE-2020-15208", "cve_desc": "In tensorflow-lite before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, when determining the common dimension size of two tensors, TFLite uses a `DCHECK` which is no-op outside of debug compilation modes. Since the function always returns the dimension of the first tensor, malicious attackers can craft cases where this is larger than that of the second tensor. In turn, this would result in reads/writes outside of bounds since the interpreter will wrongly assume that there is enough data in both tensors. The issue is patched in commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15208"} {"idx": 198140, "project": "tensorflow", "commit_id": "a324ac84e573fba362a5e53d4e74d5de6729933e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a324ac84e573fba362a5e53d4e74d5de6729933e", "commit_message": "Validate arguments to `QuantizedReshape`.\n\nEnsure that validations from `Reshape` also terminate `QuantizedReshape` on failure.\n\nPiperOrigin-RevId: 369775421\nChange-Id: If8c5342267aceea65b7cb83a4b183304886f1ce8", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n // This call processes inputs 1 and 2 to write output 0.\n ReshapeOp::Compute(ctx);\n\n const float input_min_float = ctx->input(2).flat()(0);\n const float input_max_float = ctx->input(3).flat()(0);\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min));\n output_min->flat()(0) = input_min_float;\n\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(2, TensorShape({}), &output_max));\n output_max->flat()(0) = input_max_float;\n }", "func_hash": 59011231186138155384668538291739498936, "file_name": "quantized_reshape_op.cc", "file_hash": 18511868915768084633183506596351870741, "cwe": ["CWE-787"], "cve": "CVE-2021-29536", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `QuantizedReshape` by passing in invalid thresholds for the quantization. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/a324ac84e573fba362a5e53d4e74d5de6729933e/tensorflow/core/kernels/quantized_reshape_op.cc#L38-L55) assumes that the 2 arguments are always valid scalars and tries to access the numeric value directly. However, if any of these tensors is empty, then `.flat()` is an empty buffer and accessing the element at position 0 results in overflow. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29536"} {"idx": 269702, "project": "tensorflow", "commit_id": "a324ac84e573fba362a5e53d4e74d5de6729933e", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a324ac84e573fba362a5e53d4e74d5de6729933e", "commit_message": "Validate arguments to `QuantizedReshape`.\n\nEnsure that validations from `Reshape` also terminate `QuantizedReshape` on failure.\n\nPiperOrigin-RevId: 369775421\nChange-Id: If8c5342267aceea65b7cb83a4b183304886f1ce8", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n // This call processes inputs 1 and 2 to write output 0.\n ReshapeOp::Compute(ctx);\n if (!ctx->status().ok()) {\n return;\n }\n\n const auto& input_min_float_tensor = ctx->input(2);\n const auto& input_min_float_shape = input_min_float_tensor.shape();\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsScalar(input_min_float_shape) ||\n (TensorShapeUtils::IsVector(input_min_float_shape) &&\n (input_min_float_shape.dim_size(0) == 1)),\n errors::InvalidArgument(\n \"input_min must be a scalar or a vector of 1 element\"));\n const float input_min_float = input_min_float_tensor.flat()(0);\n const auto& input_max_float_tensor = ctx->input(3);\n const auto& input_max_float_shape = input_max_float_tensor.shape();\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsScalar(input_max_float_shape) ||\n (TensorShapeUtils::IsVector(input_max_float_shape) &&\n (input_max_float_shape.dim_size(0) == 1)),\n errors::InvalidArgument(\n \"input_max must be a scalar or a vector of 1 element\"));\n const float input_max_float = input_max_float_tensor.flat()(0);\n\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min));\n output_min->flat()(0) = input_min_float;\n\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(2, TensorShape({}), &output_max));\n output_max->flat()(0) = input_max_float;\n }", "func_hash": 228000059895505209198506099265709354180, "file_name": "quantized_reshape_op.cc", "file_hash": 277618887848389341698114339480643311864, "cwe": ["CWE-787"], "cve": "CVE-2021-29536", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `QuantizedReshape` by passing in invalid thresholds for the quantization. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/a324ac84e573fba362a5e53d4e74d5de6729933e/tensorflow/core/kernels/quantized_reshape_op.cc#L38-L55) assumes that the 2 arguments are always valid scalars and tries to access the numeric value directly. However, if any of these tensors is empty, then `.flat()` is an empty buffer and accessing the element at position 0 results in overflow. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29536"} {"idx": 198143, "project": "electron", "commit_id": "18613925610ba319da7f497b6deed85ad712c59b", "project_url": "https://github.com/electron/electron", "commit_url": "https://github.com/electron/electron/commit/18613925610ba319da7f497b6deed85ad712c59b", "commit_message": "refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25108)\n\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25065)\n\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL\n\n* spec: add test for x-site _top navigation\n\n* chore: old code be old", "target": 1, "func": "content::WebContents* WebContents::OpenURLFromTab(\n content::WebContents* source,\n const content::OpenURLParams& params) {\n if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {\n Emit(\"-new-window\", params.url, \"\", params.disposition, \"\", params.referrer,\n params.post_data);\n return nullptr;\n }\n\n // Give user a chance to cancel navigation.\n if (Emit(\"will-navigate\", params.url))\n return nullptr;\n\n // Don't load the URL if the web contents was marked as destroyed from a\n // will-navigate event listener\n if (IsDestroyed())\n return nullptr;\n\n return CommonWebContentsDelegate::OpenURLFromTab(source, params);\n}", "func_hash": 188551196221489180364996963026507693017, "file_name": "None", "file_hash": null, "cwe": ["CWE-284"], "cve": "CVE-2020-15174", "cve_desc": "In Electron before versions 11.0.0-beta.1, 10.0.1, 9.3.0 or 8.5.1 the `will-navigate` event that apps use to prevent navigations to unexpected destinations as per our security recommendations can be bypassed when a sub-frame performs a top-frame navigation across sites. The issue is patched in versions 11.0.0-beta.1, 10.0.1, 9.3.0 or 8.5.1 As a workaround sandbox all your iframes using the sandbox attribute. This will prevent them creating top-frame navigations and is good practice anyway.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15174"} {"idx": 269738, "project": "electron", "commit_id": "18613925610ba319da7f497b6deed85ad712c59b", "project_url": "https://github.com/electron/electron", "commit_url": "https://github.com/electron/electron/commit/18613925610ba319da7f497b6deed85ad712c59b", "commit_message": "refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25108)\n\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25065)\n\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL\n\n* spec: add test for x-site _top navigation\n\n* chore: old code be old", "target": 0, "func": "content::WebContents* WebContents::OpenURLFromTab(\n content::WebContents* source,\n const content::OpenURLParams& params) {\n if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {\n Emit(\"-new-window\", params.url, \"\", params.disposition, \"\", params.referrer,\n params.post_data);\n return nullptr;\n }\n\n if (IsDestroyed())\n return nullptr;\n\n return CommonWebContentsDelegate::OpenURLFromTab(source, params);\n}", "func_hash": 106959985801736535023231413745402570861, "file_name": "None", "file_hash": null, "cwe": ["CWE-284"], "cve": "CVE-2020-15174", "cve_desc": "In Electron before versions 11.0.0-beta.1, 10.0.1, 9.3.0 or 8.5.1 the `will-navigate` event that apps use to prevent navigations to unexpected destinations as per our security recommendations can be bypassed when a sub-frame performs a top-frame navigation across sites. The issue is patched in versions 11.0.0-beta.1, 10.0.1, 9.3.0 or 8.5.1 As a workaround sandbox all your iframes using the sandbox attribute. This will prevent them creating top-frame navigations and is good practice anyway.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15174"} {"idx": 198147, "project": "openthread", "commit_id": "c3a3a0c424322009fec3ab735fb20ce8f6e19e70", "project_url": "https://github.com/openthread/openthread", "commit_url": "https://github.com/openthread/openthread/commit/c3a3a0c424322009fec3ab735fb20ce8f6e19e70", "commit_message": "[commissioner] use strnlen instead of strlen (#4404)", "target": 1, "func": "otError Commissioner::GeneratePskc(const char * aPassPhrase,\n const char * aNetworkName,\n const Mac::ExtendedPanId &aExtPanId,\n Pskc & aPskc)\n{\n otError error = OT_ERROR_NONE;\n const char *saltPrefix = \"Thread\";\n uint8_t salt[OT_PBKDF2_SALT_MAX_LEN];\n uint16_t saltLen = 0;\n\n VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) &&\n (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) &&\n (strlen(aNetworkName) <= OT_NETWORK_NAME_MAX_SIZE),\n error = OT_ERROR_INVALID_ARGS);\n\n memset(salt, 0, sizeof(salt));\n memcpy(salt, saltPrefix, strlen(saltPrefix));\n saltLen += static_cast(strlen(saltPrefix));\n\n memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId));\n saltLen += OT_EXT_PAN_ID_SIZE;\n\n memcpy(salt + saltLen, aNetworkName, strlen(aNetworkName));\n saltLen += static_cast(strlen(aNetworkName));\n\n otPbkdf2Cmac(reinterpret_cast(aPassPhrase), static_cast(strlen(aPassPhrase)),\n reinterpret_cast(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8);\n\nexit:\n return error;\n}", "func_hash": 280545964661162185516349760170520913527, "file_name": "commissioner.cpp", "file_hash": 86390431114996644315302566342980259461, "cwe": ["CWE-787"], "cve": "CVE-2019-20791", "cve_desc": "OpenThread before 2019-12-13 has a stack-based buffer overflow in MeshCoP::Commissioner::GeneratePskc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20791"} {"idx": 269900, "project": "openthread", "commit_id": "c3a3a0c424322009fec3ab735fb20ce8f6e19e70", "project_url": "https://github.com/openthread/openthread", "commit_url": "https://github.com/openthread/openthread/commit/c3a3a0c424322009fec3ab735fb20ce8f6e19e70", "commit_message": "[commissioner] use strnlen instead of strlen (#4404)", "target": 0, "func": "otError Commissioner::GeneratePskc(const char * aPassPhrase,\n const char * aNetworkName,\n const Mac::ExtendedPanId &aExtPanId,\n Pskc & aPskc)\n{\n otError error = OT_ERROR_NONE;\n const char saltPrefix[] = \"Thread\";\n uint8_t salt[OT_PBKDF2_SALT_MAX_LEN];\n uint16_t saltLen = 0;\n uint16_t passphraseLen;\n uint8_t networkNameLen;\n\n passphraseLen = static_cast(strnlen(aPassPhrase, OT_COMMISSIONING_PASSPHRASE_MAX_SIZE + 1));\n networkNameLen = static_cast(strnlen(aNetworkName, OT_NETWORK_NAME_MAX_SIZE + 1));\n\n VerifyOrExit((passphraseLen >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) &&\n (passphraseLen <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) &&\n (networkNameLen <= OT_NETWORK_NAME_MAX_SIZE),\n error = OT_ERROR_INVALID_ARGS);\n\n memset(salt, 0, sizeof(salt));\n memcpy(salt, saltPrefix, sizeof(saltPrefix) - 1);\n saltLen += static_cast(sizeof(saltPrefix) - 1);\n\n memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId));\n saltLen += OT_EXT_PAN_ID_SIZE;\n\n memcpy(salt + saltLen, aNetworkName, networkNameLen);\n saltLen += networkNameLen;\n\n otPbkdf2Cmac(reinterpret_cast(aPassPhrase), passphraseLen, reinterpret_cast(salt),\n saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8);\n\nexit:\n return error;\n}", "func_hash": 38318037127642801268031465094074323992, "file_name": "commissioner.cpp", "file_hash": 188411621124957637699306632127170682205, "cwe": ["CWE-787"], "cve": "CVE-2019-20791", "cve_desc": "OpenThread before 2019-12-13 has a stack-based buffer overflow in MeshCoP::Commissioner::GeneratePskc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20791"} {"idx": 198174, "project": "tensorflow", "commit_id": "da8558533d925694483d2c136a9220d6d49d843c", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/da8558533d925694483d2c136a9220d6d49d843c", "commit_message": "Fix undefined behavior in `tf.raw_ops.Switch` in eager mode.\n\nPiperOrigin-RevId: 332578058\nChange-Id: I9727571d2f21476b10d8aa27c1b7176564b76ac9", "target": 1, "func": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional& remote_func_params) {\n OpKernelContext::Params params;\n params.device = device_;\n params.frame_iter = FrameAndIter(0, 0);\n params.inputs = inputs.GetTensorValues();\n params.op_kernel = kernel_.get();\n params.resource_manager = device_->resource_manager();\n params.input_alloc_attrs = &input_alloc_attrs_;\n params.output_attr_array = output_alloc_attrs_.data();\n params.function_library = flr_;\n params.slice_reader_cache = &slice_reader_cache_;\n params.rendezvous = rendezvous_;\n OpExecutionState* op_execution_state = nullptr;\n\n CancellationManager default_cancellation_manager;\n if (cancellation_manager) {\n params.cancellation_manager = cancellation_manager;\n } else if (kernel_->is_deferred()) {\n op_execution_state = new OpExecutionState;\n params.cancellation_manager = &op_execution_state->cancellation_manager;\n params.inc_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Ref();\n };\n params.dec_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Unref();\n };\n } else {\n params.cancellation_manager = &default_cancellation_manager;\n }\n\n params.log_memory = log_memory_;\n\n params.runner = get_runner();\n\n params.step_container =\n step_container == nullptr ? &step_container_ : step_container;\n auto step_container_cleanup = gtl::MakeCleanup([step_container, this] {\n if (step_container == nullptr) {\n this->step_container_.CleanUp();\n }\n });\n\n params.collective_executor =\n collective_executor_ ? collective_executor_->get() : nullptr;\n\n OpKernelContext context(¶ms);\n\n {\n port::ScopedFlushDenormal flush;\n port::ScopedSetRound round(FE_TONEAREST);\n // 'AnnotatedTraceMe' will trace both scheduling time on host and execution\n // time on device of the OpKernel.\n profiler::AnnotatedTraceMe activity(\n [&] { return kernel_->TraceString(context, /*verbose=*/false); },\n profiler::TraceMeLevel::kInfo);\n device_->Compute(kernel_.get(), &context);\n }\n\n // Clean up execution op_execution_state if deferred ops aren't running.\n if (op_execution_state != nullptr) {\n op_execution_state->Unref();\n }\n\n if (!context.status().ok()) return context.status();\n\n if (outputs != nullptr) {\n outputs->clear();\n for (int i = 0; i < context.num_outputs(); ++i) {\n outputs->push_back(Tensor(*context.mutable_output(i)));\n }\n }\n return Status::OK();\n}", "func_hash": 233863544437748687385309926539934324225, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2020-15190", "cve_desc": "In Tensorflow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, the `tf.raw_ops.Switch` operation takes as input a tensor and a boolean and outputs two tensors. Depending on the boolean value, one of the tensors is exactly the input tensor whereas the other one should be an empty tensor. However, the eager runtime traverses all tensors in the output. Since only one of the tensors is defined, the other one is `nullptr`, hence we are binding a reference to `nullptr`. This is undefined behavior and reported as an error if compiling with `-fsanitize=null`. In this case, this results in a segmentation fault The issue is patched in commit da8558533d925694483d2c136a9220d6d49d843c, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15190"} {"idx": 270145, "project": "tensorflow", "commit_id": "da8558533d925694483d2c136a9220d6d49d843c", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/da8558533d925694483d2c136a9220d6d49d843c", "commit_message": "Fix undefined behavior in `tf.raw_ops.Switch` in eager mode.\n\nPiperOrigin-RevId: 332578058\nChange-Id: I9727571d2f21476b10d8aa27c1b7176564b76ac9", "target": 0, "func": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional& remote_func_params) {\n OpKernelContext::Params params;\n params.device = device_;\n params.frame_iter = FrameAndIter(0, 0);\n params.inputs = inputs.GetTensorValues();\n params.op_kernel = kernel_.get();\n params.resource_manager = device_->resource_manager();\n params.input_alloc_attrs = &input_alloc_attrs_;\n params.output_attr_array = output_alloc_attrs_.data();\n params.function_library = flr_;\n params.slice_reader_cache = &slice_reader_cache_;\n params.rendezvous = rendezvous_;\n OpExecutionState* op_execution_state = nullptr;\n\n CancellationManager default_cancellation_manager;\n if (cancellation_manager) {\n params.cancellation_manager = cancellation_manager;\n } else if (kernel_->is_deferred()) {\n op_execution_state = new OpExecutionState;\n params.cancellation_manager = &op_execution_state->cancellation_manager;\n params.inc_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Ref();\n };\n params.dec_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Unref();\n };\n } else {\n params.cancellation_manager = &default_cancellation_manager;\n }\n\n params.log_memory = log_memory_;\n\n params.runner = get_runner();\n\n params.step_container =\n step_container == nullptr ? &step_container_ : step_container;\n auto step_container_cleanup = gtl::MakeCleanup([step_container, this] {\n if (step_container == nullptr) {\n this->step_container_.CleanUp();\n }\n });\n\n params.collective_executor =\n collective_executor_ ? collective_executor_->get() : nullptr;\n\n OpKernelContext context(¶ms);\n\n {\n port::ScopedFlushDenormal flush;\n port::ScopedSetRound round(FE_TONEAREST);\n // 'AnnotatedTraceMe' will trace both scheduling time on host and execution\n // time on device of the OpKernel.\n profiler::AnnotatedTraceMe activity(\n [&] { return kernel_->TraceString(context, /*verbose=*/false); },\n profiler::TraceMeLevel::kInfo);\n device_->Compute(kernel_.get(), &context);\n }\n\n // Clean up execution op_execution_state if deferred ops aren't running.\n if (op_execution_state != nullptr) {\n op_execution_state->Unref();\n }\n\n if (!context.status().ok()) return context.status();\n\n if (outputs != nullptr) {\n outputs->clear();\n for (int i = 0; i < context.num_outputs(); ++i) {\n const auto* output_tensor = context.mutable_output(i);\n if (output_tensor != nullptr) {\n outputs->push_back(Tensor(*output_tensor));\n } else {\n outputs->push_back(Tensor());\n }\n }\n }\n return Status::OK();\n}", "func_hash": 175491620024710901505226058197666027202, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2020-15190", "cve_desc": "In Tensorflow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, the `tf.raw_ops.Switch` operation takes as input a tensor and a boolean and outputs two tensors. Depending on the boolean value, one of the tensors is exactly the input tensor whereas the other one should be an empty tensor. However, the eager runtime traverses all tensors in the output. Since only one of the tensors is defined, the other one is `nullptr`, hence we are binding a reference to `nullptr`. This is undefined behavior and reported as an error if compiling with `-fsanitize=null`. In this case, this results in a segmentation fault The issue is patched in commit da8558533d925694483d2c136a9220d6d49d843c, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15190"} {"idx": 198180, "project": "tensorflow", "commit_id": "eebb96c2830d48597d055d247c0e9aebaea94cd5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/eebb96c2830d48597d055d247c0e9aebaea94cd5", "commit_message": "Fix an invalid address vulnerability in `tf.raw_ops.RaggedBincount`.\n\nPiperOrigin-RevId: 368293153\nChange-Id: I4b4e493d3fd05e7dc55a55de3a041a80a4f275c3", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n const auto splits = ctx->input(0).flat();\n const auto values = ctx->input(1).flat();\n const Tensor& size_t = ctx->input(2);\n const auto weights = ctx->input(3).flat();\n const int64 weights_size = weights.size();\n\n Tidx size = size_t.scalar()();\n OP_REQUIRES(\n ctx, size >= 0,\n errors::InvalidArgument(\"size (\", size, \") must be non-negative\"));\n\n int num_rows = splits.size() - 1;\n int num_values = values.size();\n int batch_idx = 0;\n\n Tensor* out_t;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({num_rows, size}), &out_t));\n functor::SetZeroFunctor fill;\n fill(ctx->eigen_device(), out_t->flat());\n const auto out = out_t->matrix();\n\n for (int idx = 0; idx < num_values; ++idx) {\n while (idx >= splits(batch_idx)) {\n batch_idx++;\n }\n Tidx bin = values(idx);\n OP_REQUIRES(ctx, bin >= 0,\n errors::InvalidArgument(\"Input must be non-negative\"));\n if (bin < size) {\n if (binary_output_) {\n out(batch_idx - 1, bin) = T(1);\n } else {\n T value = (weights_size > 0) ? weights(idx) : T(1);\n out(batch_idx - 1, bin) += value;\n }\n }\n }\n }", "func_hash": 73343511372550174102378281594475311664, "file_name": "bincount_op.cc", "file_hash": 88513654485119458550128550578511862086, "cwe": ["CWE-703"], "cve": "CVE-2021-29512", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. If the `splits` argument of `RaggedBincount` does not specify a valid `SparseTensor`(https://www.tensorflow.org/api_docs/python/tf/sparse/SparseTensor), then an attacker can trigger a heap buffer overflow. This will cause a read from outside the bounds of the `splits` tensor buffer in the implementation of the `RaggedBincount` op(https://github.com/tensorflow/tensorflow/blob/8b677d79167799f71c42fd3fa074476e0295413a/tensorflow/core/kernels/bincount_op.cc#L430-L433). Before the `for` loop, `batch_idx` is set to 0. The user controls the `splits` array, making it contain only one element, 0. Thus, the code in the `while` loop would increment `batch_idx` and then try to read `splits(1)`, which is outside of bounds. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2 and TensorFlow 2.3.3, as these are also affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29512"} {"idx": 270171, "project": "tensorflow", "commit_id": "eebb96c2830d48597d055d247c0e9aebaea94cd5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/eebb96c2830d48597d055d247c0e9aebaea94cd5", "commit_message": "Fix an invalid address vulnerability in `tf.raw_ops.RaggedBincount`.\n\nPiperOrigin-RevId: 368293153\nChange-Id: I4b4e493d3fd05e7dc55a55de3a041a80a4f275c3", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n const auto splits = ctx->input(0).flat();\n const auto values = ctx->input(1).flat();\n const Tensor& size_t = ctx->input(2);\n const auto weights = ctx->input(3).flat();\n const int64 weights_size = weights.size();\n\n Tidx size = size_t.scalar()();\n OP_REQUIRES(\n ctx, size >= 0,\n errors::InvalidArgument(\"size (\", size, \") must be non-negative\"));\n\n int num_rows = splits.size() - 1;\n int num_values = values.size();\n int batch_idx = 0;\n\n OP_REQUIRES(ctx, splits(0) == 0,\n errors::InvalidArgument(\"Splits must start with 0, not with \",\n splits(0)));\n\n OP_REQUIRES(ctx, splits(num_rows) == num_values,\n errors::InvalidArgument(\n \"Splits must end with the number of values, got \",\n splits(num_rows), \" instead of \", num_values));\n\n Tensor* out_t;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({num_rows, size}), &out_t));\n functor::SetZeroFunctor fill;\n fill(ctx->eigen_device(), out_t->flat());\n const auto out = out_t->matrix();\n\n for (int idx = 0; idx < num_values; ++idx) {\n while (idx >= splits(batch_idx)) {\n batch_idx++;\n }\n Tidx bin = values(idx);\n OP_REQUIRES(ctx, bin >= 0,\n errors::InvalidArgument(\"Input must be non-negative\"));\n if (bin < size) {\n if (binary_output_) {\n out(batch_idx - 1, bin) = T(1);\n } else {\n T value = (weights_size > 0) ? weights(idx) : T(1);\n out(batch_idx - 1, bin) += value;\n }\n }\n }\n }", "func_hash": 339146624540381045570853744170707888551, "file_name": "bincount_op.cc", "file_hash": 5777552375064963952554533147206947342, "cwe": ["CWE-703"], "cve": "CVE-2021-29512", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. If the `splits` argument of `RaggedBincount` does not specify a valid `SparseTensor`(https://www.tensorflow.org/api_docs/python/tf/sparse/SparseTensor), then an attacker can trigger a heap buffer overflow. This will cause a read from outside the bounds of the `splits` tensor buffer in the implementation of the `RaggedBincount` op(https://github.com/tensorflow/tensorflow/blob/8b677d79167799f71c42fd3fa074476e0295413a/tensorflow/core/kernels/bincount_op.cc#L430-L433). Before the `for` loop, `batch_idx` is set to 0. The user controls the `splits` array, making it contain only one element, 0. Thus, the code in the `while` loop would increment `batch_idx` and then try to read `splits(1)`, which is outside of bounds. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2 and TensorFlow 2.3.3, as these are also affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29512"} {"idx": 198191, "project": "tensorflow", "commit_id": "69c68ecbb24dff3fa0e46da0d16c821a2dd22d7c", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/69c68ecbb24dff3fa0e46da0d16c821a2dd22d7c", "commit_message": "Fix overflow CHECK issue with `tf.raw_ops.AddManySparseToTensorsMap`.\n\nPiperOrigin-RevId: 369492969\nChange-Id: I1d70d6c0c92e3d7a25bc3b3aa2a0c0ac9688bf81", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor* input_indices;\n const Tensor* input_values;\n const Tensor* input_shape;\n SparseTensorsMap* map;\n\n OP_REQUIRES_OK(context, context->input(\"sparse_indices\", &input_indices));\n OP_REQUIRES_OK(context, context->input(\"sparse_values\", &input_values));\n OP_REQUIRES_OK(context, context->input(\"sparse_shape\", &input_shape));\n OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_values->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape->shape().DebugString()));\n\n int rank = input_shape->NumElements();\n\n OP_REQUIRES(\n context, rank > 1,\n errors::InvalidArgument(\n \"Rank of input SparseTensor should be > 1, but saw rank: \", rank));\n\n TensorShape tensor_input_shape(input_shape->vec());\n gtl::InlinedVector std_order(rank);\n std::iota(std_order.begin(), std_order.end(), 0);\n SparseTensor input_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,\n tensor_input_shape, std_order,\n &input_st));\n\n auto input_shape_t = input_shape->vec();\n const int64 N = input_shape_t(0);\n\n Tensor sparse_handles(DT_INT64, TensorShape({N}));\n auto sparse_handles_t = sparse_handles.vec();\n\n OP_REQUIRES_OK(context, input_st.IndicesValid());\n\n // We can generate the output shape proto string now, for all\n // minibatch entries.\n TensorShape output_shape;\n OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(\n input_shape_t.data() + 1,\n input_shape->NumElements() - 1, &output_shape));\n\n // Get groups by minibatch dimension\n std::unordered_set visited;\n sparse::GroupIterable minibatch = input_st.group({0});\n for (const auto& subset : minibatch) {\n const int64 b = subset.group()[0];\n visited.insert(b);\n OP_REQUIRES(\n context, b > -1 && b < N,\n errors::InvalidArgument(\n \"Received unexpected column 0 value in input SparseTensor: \", b,\n \" < 0 or >= N (= \", N, \")\"));\n\n const auto indices = subset.indices();\n const auto values = subset.values();\n const int64 num_entries = values.size();\n\n Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});\n Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix();\n auto output_values_t = output_values.vec();\n\n for (int i = 0; i < num_entries; ++i) {\n for (int d = 1; d < rank; ++d) {\n output_indices_t(i, d - 1) = indices(i, d);\n }\n output_values_t(i) = values(i);\n }\n\n SparseTensor st_i;\n OP_REQUIRES_OK(context,\n SparseTensor::Create(output_indices, output_values,\n output_shape, &st_i));\n int64 handle;\n OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));\n sparse_handles_t(b) = handle;\n }\n\n // Fill in any gaps; we must provide an empty ST for batch entries\n // the grouper didn't find.\n if (visited.size() < N) {\n Tensor empty_indices(DT_INT64, {0, rank - 1});\n Tensor empty_values(DataTypeToEnum::value, {0});\n SparseTensor empty_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,\n output_shape, &empty_st));\n\n for (int64 b = 0; b < N; ++b) {\n // We skipped this batch entry.\n if (visited.find(b) == visited.end()) {\n int64 handle;\n OP_REQUIRES_OK(context,\n map->AddSparseTensor(context, empty_st, &handle));\n sparse_handles_t(b) = handle;\n }\n }\n }\n\n context->set_output(0, sparse_handles);\n }", "func_hash": 79930957610988051709276423004277209764, "file_name": "sparse_tensors_map_ops.cc", "file_hash": 320913889113013064888999703653074496450, "cwe": ["CWE-369"], "cve": "CVE-2021-29523", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a denial of service via a `CHECK`-fail in `tf.raw_ops.AddManySparseToTensorsMap`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/kernels/sparse_tensors_map_ops.cc#L257) takes the values specified in `sparse_shape` as dimensions for the output shape. The `TensorShape` constructor(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L183-L188) uses a `CHECK` operation which triggers when `InitDims`(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L212-L296) returns a non-OK status. This is a legacy implementation of the constructor and operations should use `BuildTensorShapeBase` or `AddDimWithStatus` to prevent `CHECK`-failures in the presence of overflows. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29523"} {"idx": 270289, "project": "tensorflow", "commit_id": "69c68ecbb24dff3fa0e46da0d16c821a2dd22d7c", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/69c68ecbb24dff3fa0e46da0d16c821a2dd22d7c", "commit_message": "Fix overflow CHECK issue with `tf.raw_ops.AddManySparseToTensorsMap`.\n\nPiperOrigin-RevId: 369492969\nChange-Id: I1d70d6c0c92e3d7a25bc3b3aa2a0c0ac9688bf81", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor* input_indices;\n const Tensor* input_values;\n const Tensor* input_shape;\n SparseTensorsMap* map;\n\n OP_REQUIRES_OK(context, context->input(\"sparse_indices\", &input_indices));\n OP_REQUIRES_OK(context, context->input(\"sparse_values\", &input_values));\n OP_REQUIRES_OK(context, context->input(\"sparse_shape\", &input_shape));\n OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_values->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape->shape().DebugString()));\n\n int rank = input_shape->NumElements();\n\n OP_REQUIRES(\n context, rank > 1,\n errors::InvalidArgument(\n \"Rank of input SparseTensor should be > 1, but saw rank: \", rank));\n\n auto input_shape_vec = input_shape->vec();\n int new_num_elements = 1;\n bool overflow_ocurred = false;\n for (int i = 0; i < input_shape_vec.size(); i++) {\n new_num_elements =\n MultiplyWithoutOverflow(new_num_elements, input_shape_vec(i));\n if (new_num_elements < 0) {\n overflow_ocurred = true;\n }\n }\n\n OP_REQUIRES(\n context, !overflow_ocurred,\n errors::Internal(\"Encountered overflow from large input shape.\"));\n\n TensorShape tensor_input_shape(input_shape_vec);\n gtl::InlinedVector std_order(rank);\n std::iota(std_order.begin(), std_order.end(), 0);\n SparseTensor input_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,\n tensor_input_shape, std_order,\n &input_st));\n\n const int64 N = input_shape_vec(0);\n\n Tensor sparse_handles(DT_INT64, TensorShape({N}));\n auto sparse_handles_t = sparse_handles.vec();\n\n OP_REQUIRES_OK(context, input_st.IndicesValid());\n\n // We can generate the output shape proto string now, for all\n // minibatch entries.\n TensorShape output_shape;\n OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(\n input_shape_vec.data() + 1,\n input_shape->NumElements() - 1, &output_shape));\n\n // Get groups by minibatch dimension\n std::unordered_set visited;\n sparse::GroupIterable minibatch = input_st.group({0});\n for (const auto& subset : minibatch) {\n const int64 b = subset.group()[0];\n visited.insert(b);\n OP_REQUIRES(\n context, b > -1 && b < N,\n errors::InvalidArgument(\n \"Received unexpected column 0 value in input SparseTensor: \", b,\n \" < 0 or >= N (= \", N, \")\"));\n\n const auto indices = subset.indices();\n const auto values = subset.values();\n const int64 num_entries = values.size();\n\n Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});\n Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix();\n auto output_values_t = output_values.vec();\n\n for (int i = 0; i < num_entries; ++i) {\n for (int d = 1; d < rank; ++d) {\n output_indices_t(i, d - 1) = indices(i, d);\n }\n output_values_t(i) = values(i);\n }\n\n SparseTensor st_i;\n OP_REQUIRES_OK(context,\n SparseTensor::Create(output_indices, output_values,\n output_shape, &st_i));\n int64 handle;\n OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));\n sparse_handles_t(b) = handle;\n }\n\n // Fill in any gaps; we must provide an empty ST for batch entries\n // the grouper didn't find.\n if (visited.size() < N) {\n Tensor empty_indices(DT_INT64, {0, rank - 1});\n Tensor empty_values(DataTypeToEnum::value, {0});\n SparseTensor empty_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,\n output_shape, &empty_st));\n\n for (int64 b = 0; b < N; ++b) {\n // We skipped this batch entry.\n if (visited.find(b) == visited.end()) {\n int64 handle;\n OP_REQUIRES_OK(context,\n map->AddSparseTensor(context, empty_st, &handle));\n sparse_handles_t(b) = handle;\n }\n }\n }\n\n context->set_output(0, sparse_handles);\n }", "func_hash": 60149579989989910582822324295303227680, "file_name": "sparse_tensors_map_ops.cc", "file_hash": 148675830793774510301857528466424930562, "cwe": ["CWE-369"], "cve": "CVE-2021-29523", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a denial of service via a `CHECK`-fail in `tf.raw_ops.AddManySparseToTensorsMap`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/kernels/sparse_tensors_map_ops.cc#L257) takes the values specified in `sparse_shape` as dimensions for the output shape. The `TensorShape` constructor(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L183-L188) uses a `CHECK` operation which triggers when `InitDims`(https://github.com/tensorflow/tensorflow/blob/6f9896890c4c703ae0a0845394086e2e1e523299/tensorflow/core/framework/tensor_shape.cc#L212-L296) returns a non-OK status. This is a legacy implementation of the constructor and operations should use `BuildTensorShapeBase` or `AddDimWithStatus` to prevent `CHECK`-failures in the presence of overflows. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29523"} {"idx": 198208, "project": "FFmpeg", "commit_id": "6959358683c7533f586c07a766acc5fe9544d8b2", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/6959358683c7533f586c07a766acc5fe9544d8b2", "commit_message": "avformat/hls: check segment duration value of EXTINF\n\nfix ticket: 8673\nset the default EXTINF duration to 1ms if duration is smaller than 1ms\n\nSigned-off-by: Steven Liu \n(cherry picked from commit 9dfb19baeb86a8bb02c53a441682c6e9a6e104cc)", "target": 1, "func": "static int parse_playlist(HLSContext *c, const char *url,\n struct playlist *pls, AVIOContext *in)\n{\n int ret = 0, is_segment = 0, is_variant = 0;\n int64_t duration = 0;\n enum KeyType key_type = KEY_NONE;\n uint8_t iv[16] = \"\";\n int has_iv = 0;\n char key[MAX_URL_SIZE] = \"\";\n char line[MAX_URL_SIZE];\n const char *ptr;\n int close_in = 0;\n int64_t seg_offset = 0;\n int64_t seg_size = -1;\n uint8_t *new_url = NULL;\n struct variant_info variant_info;\n char tmp_str[MAX_URL_SIZE];\n struct segment *cur_init_section = NULL;\n\n if (!in) {\n#if 1\n AVDictionary *opts = NULL;\n close_in = 1;\n /* Some HLS servers don't like being sent the range header */\n av_dict_set(&opts, \"seekable\", \"0\", 0);\n\n // broker prior HTTP options that should be consistent across requests\n av_dict_set(&opts, \"user-agent\", c->user_agent, 0);\n av_dict_set(&opts, \"cookies\", c->cookies, 0);\n av_dict_set(&opts, \"headers\", c->headers, 0);\n\n ret = avio_open2(&in, url, AVIO_FLAG_READ,\n c->interrupt_callback, &opts);\n av_dict_free(&opts);\n if (ret < 0)\n return ret;\n#else\n ret = open_in(c, &in, url);\n if (ret < 0)\n return ret;\n close_in = 1;\n#endif\n }\n\n if (av_opt_get(in, \"location\", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)\n url = new_url;\n\n read_chomp_line(in, line, sizeof(line));\n if (strcmp(line, \"#EXTM3U\")) {\n ret = AVERROR_INVALIDDATA;\n goto fail;\n }\n\n if (pls) {\n free_segment_list(pls);\n pls->finished = 0;\n pls->type = PLS_TYPE_UNSPECIFIED;\n }\n while (!avio_feof(in)) {\n read_chomp_line(in, line, sizeof(line));\n if (av_strstart(line, \"#EXT-X-STREAM-INF:\", &ptr)) {\n is_variant = 1;\n memset(&variant_info, 0, sizeof(variant_info));\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,\n &variant_info);\n } else if (av_strstart(line, \"#EXT-X-KEY:\", &ptr)) {\n struct key_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,\n &info);\n key_type = KEY_NONE;\n has_iv = 0;\n if (!strcmp(info.method, \"AES-128\"))\n key_type = KEY_AES_128;\n if (!strcmp(info.method, \"SAMPLE-AES\"))\n key_type = KEY_SAMPLE_AES;\n if (!strncmp(info.iv, \"0x\", 2) || !strncmp(info.iv, \"0X\", 2)) {\n ff_hex_to_data(iv, info.iv + 2);\n has_iv = 1;\n }\n av_strlcpy(key, info.uri, sizeof(key));\n } else if (av_strstart(line, \"#EXT-X-MEDIA:\", &ptr)) {\n struct rendition_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,\n &info);\n new_rendition(c, &info, url);\n } else if (av_strstart(line, \"#EXT-X-TARGETDURATION:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->target_duration = atoi(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-MEDIA-SEQUENCE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->start_seq_no = atoi(ptr);\n } else if (av_strstart(line, \"#EXT-X-PLAYLIST-TYPE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n if (!strcmp(ptr, \"EVENT\"))\n pls->type = PLS_TYPE_EVENT;\n else if (!strcmp(ptr, \"VOD\"))\n pls->type = PLS_TYPE_VOD;\n } else if (av_strstart(line, \"#EXT-X-MAP:\", &ptr)) {\n struct init_section_info info = {{0}};\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,\n &info);\n cur_init_section = new_init_section(pls, &info, url);\n } else if (av_strstart(line, \"#EXT-X-ENDLIST\", &ptr)) {\n if (pls)\n pls->finished = 1;\n } else if (av_strstart(line, \"#EXTINF:\", &ptr)) {\n is_segment = 1;\n duration = atof(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-BYTERANGE:\", &ptr)) {\n seg_size = atoi(ptr);\n ptr = strchr(ptr, '@');\n if (ptr)\n seg_offset = atoi(ptr+1);\n } else if (av_strstart(line, \"#\", NULL)) {\n continue;\n } else if (line[0]) {\n if (is_variant) {\n if (!new_variant(c, &variant_info, line, url)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n is_variant = 0;\n }\n if (is_segment) {\n struct segment *seg;\n if (!pls) {\n if (!new_variant(c, 0, url, NULL)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n pls = c->playlists[c->n_playlists - 1];\n }\n seg = av_malloc(sizeof(struct segment));\n if (!seg) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n seg->duration = duration;\n seg->key_type = key_type;\n if (has_iv) {\n memcpy(seg->iv, iv, sizeof(iv));\n } else {\n int seq = pls->start_seq_no + pls->n_segments;\n memset(seg->iv, 0, sizeof(seg->iv));\n AV_WB32(seg->iv + 12, seq);\n }\n\n if (key_type != KEY_NONE) {\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);\n seg->key = av_strdup(tmp_str);\n if (!seg->key) {\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n } else {\n seg->key = NULL;\n }\n\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);\n seg->url = av_strdup(tmp_str);\n if (!seg->url) {\n av_free(seg->key);\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n\n dynarray_add(&pls->segments, &pls->n_segments, seg);\n is_segment = 0;\n\n seg->size = seg_size;\n if (seg_size >= 0) {\n seg->url_offset = seg_offset;\n seg_offset += seg_size;\n seg_size = -1;\n } else {\n seg->url_offset = 0;\n seg_offset = 0;\n }\n\n seg->init_section = cur_init_section;\n }\n }\n }\n if (pls)\n pls->last_load_time = av_gettime_relative();\n\nfail:\n av_free(new_url);\n if (close_in)\n avio_close(in);\n return ret;\n}", "func_hash": 30174141859763237223954131091038269298, "file_name": "hls.c", "file_hash": 108861598852777573475661810969221848391, "cwe": ["CWE-416"], "cve": "CVE-2020-13904", "cve_desc": "FFmpeg 2.8 and 4.2.3 has a use-after-free via a crafted EXTINF duration in an m3u8 file because parse_playlist in libavformat/hls.c frees a pointer, and later that pointer is accessed in av_probe_input_format3 in libavformat/format.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13904"} {"idx": 270450, "project": "FFmpeg", "commit_id": "6959358683c7533f586c07a766acc5fe9544d8b2", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/6959358683c7533f586c07a766acc5fe9544d8b2", "commit_message": "avformat/hls: check segment duration value of EXTINF\n\nfix ticket: 8673\nset the default EXTINF duration to 1ms if duration is smaller than 1ms\n\nSigned-off-by: Steven Liu \n(cherry picked from commit 9dfb19baeb86a8bb02c53a441682c6e9a6e104cc)", "target": 0, "func": "static int parse_playlist(HLSContext *c, const char *url,\n struct playlist *pls, AVIOContext *in)\n{\n int ret = 0, is_segment = 0, is_variant = 0;\n int64_t duration = 0;\n enum KeyType key_type = KEY_NONE;\n uint8_t iv[16] = \"\";\n int has_iv = 0;\n char key[MAX_URL_SIZE] = \"\";\n char line[MAX_URL_SIZE];\n const char *ptr;\n int close_in = 0;\n int64_t seg_offset = 0;\n int64_t seg_size = -1;\n uint8_t *new_url = NULL;\n struct variant_info variant_info;\n char tmp_str[MAX_URL_SIZE];\n struct segment *cur_init_section = NULL;\n\n if (!in) {\n#if 1\n AVDictionary *opts = NULL;\n close_in = 1;\n /* Some HLS servers don't like being sent the range header */\n av_dict_set(&opts, \"seekable\", \"0\", 0);\n\n // broker prior HTTP options that should be consistent across requests\n av_dict_set(&opts, \"user-agent\", c->user_agent, 0);\n av_dict_set(&opts, \"cookies\", c->cookies, 0);\n av_dict_set(&opts, \"headers\", c->headers, 0);\n\n ret = avio_open2(&in, url, AVIO_FLAG_READ,\n c->interrupt_callback, &opts);\n av_dict_free(&opts);\n if (ret < 0)\n return ret;\n#else\n ret = open_in(c, &in, url);\n if (ret < 0)\n return ret;\n close_in = 1;\n#endif\n }\n\n if (av_opt_get(in, \"location\", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)\n url = new_url;\n\n read_chomp_line(in, line, sizeof(line));\n if (strcmp(line, \"#EXTM3U\")) {\n ret = AVERROR_INVALIDDATA;\n goto fail;\n }\n\n if (pls) {\n free_segment_list(pls);\n pls->finished = 0;\n pls->type = PLS_TYPE_UNSPECIFIED;\n }\n while (!avio_feof(in)) {\n read_chomp_line(in, line, sizeof(line));\n if (av_strstart(line, \"#EXT-X-STREAM-INF:\", &ptr)) {\n is_variant = 1;\n memset(&variant_info, 0, sizeof(variant_info));\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,\n &variant_info);\n } else if (av_strstart(line, \"#EXT-X-KEY:\", &ptr)) {\n struct key_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,\n &info);\n key_type = KEY_NONE;\n has_iv = 0;\n if (!strcmp(info.method, \"AES-128\"))\n key_type = KEY_AES_128;\n if (!strcmp(info.method, \"SAMPLE-AES\"))\n key_type = KEY_SAMPLE_AES;\n if (!strncmp(info.iv, \"0x\", 2) || !strncmp(info.iv, \"0X\", 2)) {\n ff_hex_to_data(iv, info.iv + 2);\n has_iv = 1;\n }\n av_strlcpy(key, info.uri, sizeof(key));\n } else if (av_strstart(line, \"#EXT-X-MEDIA:\", &ptr)) {\n struct rendition_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,\n &info);\n new_rendition(c, &info, url);\n } else if (av_strstart(line, \"#EXT-X-TARGETDURATION:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->target_duration = atoi(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-MEDIA-SEQUENCE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->start_seq_no = atoi(ptr);\n } else if (av_strstart(line, \"#EXT-X-PLAYLIST-TYPE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n if (!strcmp(ptr, \"EVENT\"))\n pls->type = PLS_TYPE_EVENT;\n else if (!strcmp(ptr, \"VOD\"))\n pls->type = PLS_TYPE_VOD;\n } else if (av_strstart(line, \"#EXT-X-MAP:\", &ptr)) {\n struct init_section_info info = {{0}};\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,\n &info);\n cur_init_section = new_init_section(pls, &info, url);\n } else if (av_strstart(line, \"#EXT-X-ENDLIST\", &ptr)) {\n if (pls)\n pls->finished = 1;\n } else if (av_strstart(line, \"#EXTINF:\", &ptr)) {\n is_segment = 1;\n duration = atof(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-BYTERANGE:\", &ptr)) {\n seg_size = atoi(ptr);\n ptr = strchr(ptr, '@');\n if (ptr)\n seg_offset = atoi(ptr+1);\n } else if (av_strstart(line, \"#\", NULL)) {\n continue;\n } else if (line[0]) {\n if (is_variant) {\n if (!new_variant(c, &variant_info, line, url)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n is_variant = 0;\n }\n if (is_segment) {\n struct segment *seg;\n if (!pls) {\n if (!new_variant(c, 0, url, NULL)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n pls = c->playlists[c->n_playlists - 1];\n }\n seg = av_malloc(sizeof(struct segment));\n if (!seg) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n if (has_iv) {\n memcpy(seg->iv, iv, sizeof(iv));\n } else {\n int seq = pls->start_seq_no + pls->n_segments;\n memset(seg->iv, 0, sizeof(seg->iv));\n AV_WB32(seg->iv + 12, seq);\n }\n\n if (key_type != KEY_NONE) {\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);\n seg->key = av_strdup(tmp_str);\n if (!seg->key) {\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n } else {\n seg->key = NULL;\n }\n\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);\n seg->url = av_strdup(tmp_str);\n if (!seg->url) {\n av_free(seg->key);\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n\n if (duration < 0.001 * AV_TIME_BASE) {\n duration = 0.001 * AV_TIME_BASE;\n }\n seg->duration = duration;\n seg->key_type = key_type;\n dynarray_add(&pls->segments, &pls->n_segments, seg);\n is_segment = 0;\n\n seg->size = seg_size;\n if (seg_size >= 0) {\n seg->url_offset = seg_offset;\n seg_offset += seg_size;\n seg_size = -1;\n } else {\n seg->url_offset = 0;\n seg_offset = 0;\n }\n\n seg->init_section = cur_init_section;\n }\n }\n }\n if (pls)\n pls->last_load_time = av_gettime_relative();\n\nfail:\n av_free(new_url);\n if (close_in)\n avio_close(in);\n return ret;\n}", "func_hash": 321489963422717456447724542601376438145, "file_name": "hls.c", "file_hash": 170061828104634510369959832195448428852, "cwe": ["CWE-416"], "cve": "CVE-2020-13904", "cve_desc": "FFmpeg 2.8 and 4.2.3 has a use-after-free via a crafted EXTINF duration in an m3u8 file because parse_playlist in libavformat/hls.c frees a pointer, and later that pointer is accessed in av_probe_input_format3 in libavformat/format.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13904"} {"idx": 198278, "project": "gpac", "commit_id": "b2db2f99b4c30f96e17b9a14537c776da6cb5dca", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/b2db2f99b4c30f96e17b9a14537c776da6cb5dca", "commit_message": "fixed #1728", "target": 1, "func": "GF_Err latm_dmx_process(GF_Filter *filter)\n{\n\tGF_LATMDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu32 pos;\n\tu8 *data, *output;\n\tu32 pck_size, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\n\tif (ctx->in_error)\n\t\treturn ctx->in_error;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tlatm_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->latm_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t}\n\n\tdata = (char *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tprev_pck_size = ctx->latm_buffer_size;\n\n\tif (pck && !ctx->resume_from) {\n\t\tif (ctx->latm_buffer_size + pck_size > ctx->latm_buffer_alloc) {\n\t\t\tctx->latm_buffer_alloc = ctx->latm_buffer_size + pck_size;\n\t\t\tctx->latm_buffer = gf_realloc(ctx->latm_buffer, ctx->latm_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->latm_buffer + ctx->latm_buffer_size, data, pck_size);\n\t\tctx->latm_buffer_size += pck_size;\n\t}\n\n\tif (!ctx->bs) ctx->bs = gf_bs_new(ctx->latm_buffer, ctx->latm_buffer_size, GF_BITSTREAM_READ);\n\telse gf_bs_reassign_buffer(ctx->bs, ctx->latm_buffer, ctx->latm_buffer_size);\n\n\tif (ctx->resume_from) {\n\t\tgf_bs_seek(ctx->bs, ctx->resume_from-1);\n\t\tctx->resume_from = 0;\n\t}\n\n\tif (cts == GF_FILTER_NO_TS)\n\t\tprev_pck_size = 0;\n\n\n\twhile (1) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tu8 latm_buffer[4096];\n\t\tu32 latm_frame_size = 4096;\n\t\tif (!latm_dmx_sync_frame_bs(ctx->bs,&ctx->acfg, &latm_frame_size, latm_buffer, NULL)) break;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * GF_M4ASampleRates[ctx->sr_idx]);\n\t\t\tif (ctx->cts + ctx->dts_inc >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tlatm_dmx_check_pid(filter, ctx);\n\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = pos+1;\n\t\t\treturn GF_OK;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tGF_FilterSAPType sap = GF_FILTER_SAP_1;\n\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, latm_frame_size, &output);\n\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\n\t\t\tmemcpy(output, latm_buffer, latm_frame_size);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tgf_filter_pck_set_duration(dst_pck, ctx->dts_inc);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\t/*xHE-AAC, check RAP*/\n\t\t\tif (ctx->acfg.base_object_type==GF_CODECID_USAC) {\n\t\t\t\tif (latm_frame_size && (output[0] & 0x80) && !ctx->prev_sap) {\n\t\t\t\t\tsap = GF_FILTER_SAP_1;\n\t\t\t\t\tctx->prev_sap = GF_TRUE;\n\t\t\t\t} else {\n\t\t\t\t\tsap = GF_FILTER_SAP_NONE;\n\t\t\t\t\tctx->prev_sap = GF_FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, sap);\n\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tlatm_dmx_update_cts(ctx);\n\n\t\tif (prev_pck_size) {\n\t\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\t\tif (prev_pck_size<=pos) {\n\t\t\t\tprev_pck_size=0;\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = pck;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pck) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tassert(ctx->latm_buffer_size >= pos);\n\t\tmemmove(ctx->latm_buffer, ctx->latm_buffer+pos, ctx->latm_buffer_size - pos);\n\t\tctx->latm_buffer_size -= pos;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\tassert(!ctx->resume_from);\n\t} else {\n\t\tctx->latm_buffer_size = 0;\n\t\treturn latm_dmx_process(filter);\n\t}\n\treturn GF_OK;\n}", "func_hash": 204180570731143680931226995412169270610, "file_name": "reframe_latm.c", "file_hash": 166242177824681291664839300187665664543, "cwe": ["CWE-476"], "cve": "CVE-2021-30199", "cve_desc": "In filters/reframe_latm.c in GPAC 1.0.1 there is a Null Pointer Dereference, when gf_filter_pck_get_data is called. The first arg pck may be null with a crafted mp4 file,which results in a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30199"} {"idx": 271474, "project": "gpac", "commit_id": "b2db2f99b4c30f96e17b9a14537c776da6cb5dca", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/b2db2f99b4c30f96e17b9a14537c776da6cb5dca", "commit_message": "fixed #1728", "target": 0, "func": "GF_Err latm_dmx_process(GF_Filter *filter)\n{\n\tGF_LATMDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu32 pos;\n\tu8 *data=NULL, *output;\n\tu32 pck_size=0, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\n\tif (ctx->in_error)\n\t\treturn ctx->in_error;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tlatm_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->latm_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t} else {\n\t\tdata = (char *) gf_filter_pck_get_data(pck, &pck_size);\n\t}\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tprev_pck_size = ctx->latm_buffer_size;\n\n\tif (pck && !ctx->resume_from) {\n\t\tif (ctx->latm_buffer_size + pck_size > ctx->latm_buffer_alloc) {\n\t\t\tctx->latm_buffer_alloc = ctx->latm_buffer_size + pck_size;\n\t\t\tctx->latm_buffer = gf_realloc(ctx->latm_buffer, ctx->latm_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->latm_buffer + ctx->latm_buffer_size, data, pck_size);\n\t\tctx->latm_buffer_size += pck_size;\n\t}\n\n\tif (!ctx->bs) ctx->bs = gf_bs_new(ctx->latm_buffer, ctx->latm_buffer_size, GF_BITSTREAM_READ);\n\telse gf_bs_reassign_buffer(ctx->bs, ctx->latm_buffer, ctx->latm_buffer_size);\n\n\tif (ctx->resume_from) {\n\t\tgf_bs_seek(ctx->bs, ctx->resume_from-1);\n\t\tctx->resume_from = 0;\n\t}\n\n\tif (cts == GF_FILTER_NO_TS)\n\t\tprev_pck_size = 0;\n\n\n\twhile (1) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tu8 latm_buffer[4096];\n\t\tu32 latm_frame_size = 4096;\n\t\tif (!latm_dmx_sync_frame_bs(ctx->bs,&ctx->acfg, &latm_frame_size, latm_buffer, NULL)) break;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * GF_M4ASampleRates[ctx->sr_idx]);\n\t\t\tif (ctx->cts + ctx->dts_inc >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tlatm_dmx_check_pid(filter, ctx);\n\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = pos+1;\n\t\t\treturn GF_OK;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tGF_FilterSAPType sap = GF_FILTER_SAP_1;\n\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, latm_frame_size, &output);\n\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\n\t\t\tmemcpy(output, latm_buffer, latm_frame_size);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tgf_filter_pck_set_duration(dst_pck, ctx->dts_inc);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\t/*xHE-AAC, check RAP*/\n\t\t\tif (ctx->acfg.base_object_type==GF_CODECID_USAC) {\n\t\t\t\tif (latm_frame_size && (output[0] & 0x80) && !ctx->prev_sap) {\n\t\t\t\t\tsap = GF_FILTER_SAP_1;\n\t\t\t\t\tctx->prev_sap = GF_TRUE;\n\t\t\t\t} else {\n\t\t\t\t\tsap = GF_FILTER_SAP_NONE;\n\t\t\t\t\tctx->prev_sap = GF_FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, sap);\n\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tlatm_dmx_update_cts(ctx);\n\n\t\tif (prev_pck_size) {\n\t\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\t\tif (prev_pck_size<=pos) {\n\t\t\t\tprev_pck_size=0;\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = pck;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pck) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tassert(ctx->latm_buffer_size >= pos);\n\t\tmemmove(ctx->latm_buffer, ctx->latm_buffer+pos, ctx->latm_buffer_size - pos);\n\t\tctx->latm_buffer_size -= pos;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\tassert(!ctx->resume_from);\n\t} else {\n\t\tctx->latm_buffer_size = 0;\n\t\treturn latm_dmx_process(filter);\n\t}\n\treturn GF_OK;\n}", "func_hash": 62197720089725097305480498761218323244, "file_name": "reframe_latm.c", "file_hash": 225594436372368455139694306232582621243, "cwe": ["CWE-476"], "cve": "CVE-2021-30199", "cve_desc": "In filters/reframe_latm.c in GPAC 1.0.1 there is a Null Pointer Dereference, when gf_filter_pck_get_data is called. The first arg pck may be null with a crafted mp4 file,which results in a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30199"} {"idx": 198286, "project": "gpac", "commit_id": "fe5155cf047252d1c4cb91602048bfa682af0ea7", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/fe5155cf047252d1c4cb91602048bfa682af0ea7", "commit_message": "fixed #1783 (fuzz)", "target": 1, "func": "static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)\n{\n\tGF_Box *a;\n\tu64 totSize, mdat_end=0;\n\tGF_Err e = GF_OK;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (mov->single_moof_mode && mov->single_moof_state == 2) {\n\t\treturn e;\n\t}\n\n\t/*restart from where we stopped last*/\n\ttotSize = mov->current_top_box_start;\n\tif (mov->bytes_removed) {\n\t\tassert(totSize >= mov->bytes_removed);\n\t\ttotSize -= mov->bytes_removed;\n\t}\n\tgf_bs_seek(mov->movieFileMap->bs, totSize);\n#endif\n\n\n\t/*while we have some data, parse our boxes*/\n\twhile (gf_bs_available(mov->movieFileMap->bs)) {\n\t\t*bytesMissing = 0;\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Parsing a top-level box at position %d\\n\", mov->current_top_box_start));\n#endif\n\n\t\te = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);\n\n\t\tif (e >= 0) {\n\n\t\t} else if (e == GF_ISOM_INCOMPLETE_FILE) {\n\t\t\t/*our mdat is uncomplete, only valid for READ ONLY files...*/\n\t\t\tif (mov->openMode != GF_ISOM_OPEN_READ) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete MDAT while file is not read-only\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tif ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete file while reading for dump - aborting parsing\\n\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t} else {\n\t\t\treturn e;\n\t\t}\n\n\t\tswitch (a->type) {\n\t\t/*MOOV box*/\n\t\tcase GF_ISOM_BOX_TYPE_MOOV:\n\t\t\tif (mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate MOOV detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->moov = (GF_MovieBox *)a;\n\t\t\tmov->original_moov_offset = mov->current_top_box_start;\n\t\t\t/*set our pointer to the movie*/\n\t\t\tmov->moov->mov = mov;\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->moov->mvex) mov->moov->mvex->mov = mov;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tgf_isom_setup_traf_inheritance(mov);\n\t\t\t}\n#endif\n\n#endif\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\n\t\t\ttotSize += a->size;\n\n if (!mov->moov->mvhd) {\n GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MovieHeaderBox\\n\"));\n return GF_ISOM_INVALID_FILE;\n }\n\n if (mov->meta) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\n\t\t\t//dump senc info in dump mode\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\n\t\t\t\t\tif (trak->sample_encryption) {\n\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\t\t\t\t\tif (trak->Media->information->sampleTable->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\tbreak;\n\n\t\t/*META box*/\n\t\tcase GF_ISOM_BOX_TYPE_META:\n\t\t\tif (mov->meta) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate META detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->meta = (GF_MetaBox *)a;\n\t\t\tmov->original_meta_offset = mov->current_top_box_start;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\ttotSize += a->size;\n if (mov->moov) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*we only keep the MDAT in READ for dump purposes*/\n\t\tcase GF_ISOM_BOX_TYPE_MDAT:\n\t\t\tif (!mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->openMode == GF_ISOM_OPEN_READ) {\n\t\t\t\tif (!mov->mdat) {\n\t\t\t\t\tmov->mdat = (GF_MediaDataBox *) a;\n\t\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\t\telse if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);\n#endif\n\t\t\t\telse gf_isom_box_del(a); //in other modes we don't care\n\n\n\t\t\t\tif (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n mdat_end = gf_bs_get_position(mov->movieFileMap->bs);\n if (mov->moov) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*if we don't have any MDAT yet, create one (edit-write mode)\n\t\t\tWe only work with one mdat, but we're puting it at the place\n\t\t\tof the first mdat found when opening a file for editing*/\n\t\t\telse if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\t\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\tif (e) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_BOX_TYPE_FTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->brand) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'ftyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->brand = (GF_FileTypeBox *)a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_OTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->otyp) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'otyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tmov->otyp = (GF_Box *)a;\n\t\t\t\ttotSize += a->size;\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else {\n\t\t\t\tGF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);\n\t\t\t\tif (brand) {\n\t\t\t\t\ts32 pos;\n\t\t\t\t\tgf_list_del_item(a->child_boxes, brand);\n\t\t\t\t\tpos = gf_list_del_item(mov->TopBoxes, mov->brand);\n\t\t\t\t\tgf_isom_box_del((GF_Box *) mov->brand);\n\t\t\t\t\tmov->brand = brand;\n\t\t\t\t\tif (pos<0) pos=0;\n\t\t\t\t\tgf_list_insert(mov->TopBoxes, brand, pos);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PDIN:\n\t\t\t/*ONE AND ONLY ONE PDIN*/\n\t\t\tif (mov->pdin) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'pdin'' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->pdin = (GF_ProgressiveDownloadBox *) a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tcase GF_ISOM_BOX_TYPE_STYP:\n\t\t{\n\t\t\tu32 brand = ((GF_FileTypeBox *)a)->majorBrand;\n\t\t\tswitch (brand) {\n\t\t\tcase GF_ISOM_BRAND_SISX:\n\t\t\tcase GF_ISOM_BRAND_RISX:\n\t\t\tcase GF_ISOM_BRAND_SSSS:\n\t\t\t\tmov->is_index_segment = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/*fall-through*/\n\n\t\tcase GF_ISOM_BOX_TYPE_SIDX:\n\t\tcase GF_ISOM_BOX_TYPE_SSIX:\n\t\t\tif (mov->moov && !mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)\n\t\t\t) {\n\t\t\t\tif (a->type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t\t\tif (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);\n\t\t\t\t\tmov->root_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\t\tmov->sidx_start_offset = mov->current_top_box_start;\n\t\t\t\t\tmov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);\n\n\t\t\t\t}\n\t\t\t\telse if (a->type==GF_ISOM_BOX_TYPE_STYP) {\n\t\t\t\t\tmov->styp_start_offset = mov->current_top_box_start;\n\n\t\t\t\t\tif (mov->seg_styp) gf_isom_box_del(mov->seg_styp);\n\t\t\t\t\tmov->seg_styp = a;\n\t\t\t\t} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t\t\tif (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);\n\t\t\t\t\tmov->seg_ssix = a;\n\t\t\t\t} else {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t}\n\t\t\t\tgf_isom_push_mdat_end(mov, mov->current_top_box_start);\n\t\t\t} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {\n\t\t\t\tif (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);\n\t\t\t\tmov->main_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\tmov->main_sidx_end_pos = mov->current_top_box_start + a->size;\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_MOOF:\n\t\t\t//no support for inplace rewrite for fragmented files\n\t\t\tgf_isom_disable_inplace_rewrite(mov);\n\t\t\tif (!mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\\n\"));\n\t\t\t}\n\t\t\tif (mov->single_moof_mode) {\n\t\t\t\tmov->single_moof_state++;\n\t\t\t\tif (mov->single_moof_state > 1) {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((GF_MovieFragmentBox *)a)->mov = mov;\n\n\t\t\ttotSize += a->size;\n\t\t\tmov->moof = (GF_MovieFragmentBox *) a;\n\n\t\t\t/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/\n\t\t\tFixTrackID(mov);\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tFixSDTPInTRAF(mov->moof);\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\tif (traf->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*read & debug: store at root level*/\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tgf_list_add(mov->TopBoxes, a);\n\t\t\t\t/*also update pointers to trex for debug*/\n\t\t\t\tif (mov->moov) {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tu32 j=0;\n\t\t\t\t\t\t\twhile ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {\n\t\t\t\t\t\t\t\tif (traf->trex->trackID == traf->tfhd->trackID) {\n\t\t\t\t\t\t\t\t\tif (!traf->trex->track) traf->trex->track = trak;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttraf->trex = NULL;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly\n\t\t\t\t\t\tif (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->sample_encryption) {\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {\n\t\t\t\tmov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;\n\t\t\t\tmov->moof = NULL;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\t/*merge all info*/\n\t\t\t\te = MergeFragment((GF_MovieFragmentBox *)a, mov);\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\n\t\t\t//done with moov\n\t\t\tif (mov->root_sidx) {\n\t\t\t\tgf_isom_box_del((GF_Box *) mov->root_sidx);\n\t\t\t\tmov->root_sidx = NULL;\n\t\t\t}\n\t\t\tif (mov->root_ssix) {\n\t\t\t\tgf_isom_box_del(mov->seg_ssix);\n\t\t\t\tmov->root_ssix = NULL;\n\t\t\t}\n\t\t\tif (mov->seg_styp) {\n\t\t\t\tgf_isom_box_del(mov->seg_styp);\n\t\t\t\tmov->seg_styp = NULL;\n\t\t\t}\n\t\t\tmov->sidx_start_offset = 0;\n\t\t\tmov->sidx_end_offset = 0;\n\t\t\tmov->styp_start_offset = 0;\n\t\t\tbreak;\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\t{\n\t\t\tGF_UnknownBox *box = (GF_UnknownBox*)a;\n\t\t\tif (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {\n\t\t\t\tu8 *c = (u8 *) box->data;\n\t\t\t\tif ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))\n\t\t\t\t\tmov->is_jp2 = 1;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PRFT:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\t//keep the last one read\n\t\t\t\tif (mov->last_producer_ref_time)\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\telse\n\t\t\t\t\tmov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t//fallthrough\n\n\t\tdefault:\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\t\t}\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*remember where we left, in case we append an entire number of movie fragments*/\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n#endif\n\t}\n\n\t/*we need at least moov or meta*/\n\tif (!mov->moov && !mov->meta\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t && !mov->moof && !mov->is_index_segment\n#endif\n\t ) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\t/*we MUST have movie header*/\n\tif (!gf_opts_get_bool(\"core\", \"no-check\")) {\n\t\tif (mov->moov && !mov->moov->mvhd) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MVHD in MOOV!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\t/*we MUST have meta handler*/\n\t\tif (mov->meta && !mov->meta->handler) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing handler in META!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\n\tif (mov->moov) {\n\t\t/*set the default interleaving time*/\n\t\tmov->interleavingTime = mov->moov->mvhd->timeScale;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*in edit mode with successfully loaded fragments, delete all fragment signaling since\n\t\tfile is no longer fragmented*/\n\t\tif ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {\n\t\t\tgf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);\n\t\t\tmov->moov->mvex = NULL;\n\t\t}\n#endif\n\n\t}\n\n\t//create a default mdat if none was found\n\tif (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\tif (e) return e;\n\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\n\treturn GF_OK;\n}", "func_hash": 291656080500746263577983285206220334271, "file_name": "isom_intern.c", "file_hash": 92347110276646265829493457699687403678, "cwe": ["CWE-401"], "cve": "CVE-2021-33364", "cve_desc": "Memory leak in the def_parent_box_new function in MP4Box in GPAC 1.0.1 allows attackers to read memory via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33364"} {"idx": 271715, "project": "gpac", "commit_id": "fe5155cf047252d1c4cb91602048bfa682af0ea7", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/fe5155cf047252d1c4cb91602048bfa682af0ea7", "commit_message": "fixed #1783 (fuzz)", "target": 0, "func": "static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)\n{\n\tGF_Box *a;\n\tu64 totSize, mdat_end=0;\n\tGF_Err e = GF_OK;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (mov->single_moof_mode && mov->single_moof_state == 2) {\n\t\treturn e;\n\t}\n\n\t/*restart from where we stopped last*/\n\ttotSize = mov->current_top_box_start;\n\tif (mov->bytes_removed) {\n\t\tassert(totSize >= mov->bytes_removed);\n\t\ttotSize -= mov->bytes_removed;\n\t}\n\tgf_bs_seek(mov->movieFileMap->bs, totSize);\n#endif\n\n\n\t/*while we have some data, parse our boxes*/\n\twhile (gf_bs_available(mov->movieFileMap->bs)) {\n\t\t*bytesMissing = 0;\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Parsing a top-level box at position %d\\n\", mov->current_top_box_start));\n#endif\n\n\t\te = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);\n\n\t\tif (e >= 0) {\n\n\t\t} else if (e == GF_ISOM_INCOMPLETE_FILE) {\n\t\t\t/*our mdat is uncomplete, only valid for READ ONLY files...*/\n\t\t\tif (mov->openMode != GF_ISOM_OPEN_READ) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete MDAT while file is not read-only\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tif ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete file while reading for dump - aborting parsing\\n\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t} else {\n\t\t\treturn e;\n\t\t}\n\n\t\tswitch (a->type) {\n\t\t/*MOOV box*/\n\t\tcase GF_ISOM_BOX_TYPE_MOOV:\n\t\t\tif (mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate MOOV detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->moov = (GF_MovieBox *)a;\n\t\t\tmov->original_moov_offset = mov->current_top_box_start;\n\t\t\t/*set our pointer to the movie*/\n\t\t\tmov->moov->mov = mov;\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->moov->mvex) mov->moov->mvex->mov = mov;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tgf_isom_setup_traf_inheritance(mov);\n\t\t\t}\n#endif\n\n#endif\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\n\t\t\ttotSize += a->size;\n\n if (!mov->moov->mvhd) {\n GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MovieHeaderBox\\n\"));\n return GF_ISOM_INVALID_FILE;\n }\n\n if (mov->meta) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\n\t\t\t//dump senc info in dump mode\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\n\t\t\t\t\tif (trak->sample_encryption) {\n\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\t\t\t\t\tif (trak->Media->information->sampleTable->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\tbreak;\n\n\t\t/*META box*/\n\t\tcase GF_ISOM_BOX_TYPE_META:\n\t\t\tif (mov->meta) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate META detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->meta = (GF_MetaBox *)a;\n\t\t\tmov->original_meta_offset = mov->current_top_box_start;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\ttotSize += a->size;\n if (mov->moov) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*we only keep the MDAT in READ for dump purposes*/\n\t\tcase GF_ISOM_BOX_TYPE_MDAT:\n\t\t\tif (!mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->openMode == GF_ISOM_OPEN_READ) {\n\t\t\t\tif (!mov->mdat) {\n\t\t\t\t\tmov->mdat = (GF_MediaDataBox *) a;\n\t\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\t\telse if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);\n#endif\n\t\t\t\telse gf_isom_box_del(a); //in other modes we don't care\n\n\n\t\t\t\tif (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n mdat_end = gf_bs_get_position(mov->movieFileMap->bs);\n if (mov->moov) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*if we don't have any MDAT yet, create one (edit-write mode)\n\t\t\tWe only work with one mdat, but we're puting it at the place\n\t\t\tof the first mdat found when opening a file for editing*/\n\t\t\telse if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\t\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\tif (e) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_BOX_TYPE_FTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->brand) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'ftyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->brand = (GF_FileTypeBox *)a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_OTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->otyp) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'otyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tmov->otyp = (GF_Box *)a;\n\t\t\t\ttotSize += a->size;\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else {\n\t\t\t\tGF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);\n\t\t\t\tif (brand) {\n\t\t\t\t\ts32 pos;\n\t\t\t\t\tgf_list_del_item(a->child_boxes, brand);\n\t\t\t\t\tpos = gf_list_del_item(mov->TopBoxes, mov->brand);\n\t\t\t\t\tgf_isom_box_del((GF_Box *) mov->brand);\n\t\t\t\t\tmov->brand = brand;\n\t\t\t\t\tif (pos<0) pos=0;\n\t\t\t\t\tgf_list_insert(mov->TopBoxes, brand, pos);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PDIN:\n\t\t\t/*ONE AND ONLY ONE PDIN*/\n\t\t\tif (mov->pdin) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'pdin'' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->pdin = (GF_ProgressiveDownloadBox *) a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tcase GF_ISOM_BOX_TYPE_STYP:\n\t\t{\n\t\t\tu32 brand = ((GF_FileTypeBox *)a)->majorBrand;\n\t\t\tswitch (brand) {\n\t\t\tcase GF_ISOM_BRAND_SISX:\n\t\t\tcase GF_ISOM_BRAND_RISX:\n\t\t\tcase GF_ISOM_BRAND_SSSS:\n\t\t\t\tmov->is_index_segment = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/*fall-through*/\n\n\t\tcase GF_ISOM_BOX_TYPE_SIDX:\n\t\tcase GF_ISOM_BOX_TYPE_SSIX:\n\t\t\tif (mov->moov && !mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)\n\t\t\t) {\n\t\t\t\tif (a->type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t\t\tif (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);\n\t\t\t\t\tmov->root_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\t\tmov->sidx_start_offset = mov->current_top_box_start;\n\t\t\t\t\tmov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);\n\n\t\t\t\t}\n\t\t\t\telse if (a->type==GF_ISOM_BOX_TYPE_STYP) {\n\t\t\t\t\tmov->styp_start_offset = mov->current_top_box_start;\n\n\t\t\t\t\tif (mov->seg_styp) gf_isom_box_del(mov->seg_styp);\n\t\t\t\t\tmov->seg_styp = a;\n\t\t\t\t} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t\t\tif (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);\n\t\t\t\t\tmov->seg_ssix = a;\n\t\t\t\t} else {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t}\n\t\t\t\tgf_isom_push_mdat_end(mov, mov->current_top_box_start);\n\t\t\t} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {\n\t\t\t\tif (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);\n\t\t\t\tmov->main_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\tmov->main_sidx_end_pos = mov->current_top_box_start + a->size;\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_MOOF:\n\t\t\t//no support for inplace rewrite for fragmented files\n\t\t\tgf_isom_disable_inplace_rewrite(mov);\n\t\t\tif (!mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\\n\"));\n\t\t\t}\n\t\t\tif (mov->single_moof_mode) {\n\t\t\t\tmov->single_moof_state++;\n\t\t\t\tif (mov->single_moof_state > 1) {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((GF_MovieFragmentBox *)a)->mov = mov;\n\n\t\t\ttotSize += a->size;\n\t\t\tmov->moof = (GF_MovieFragmentBox *) a;\n\n\t\t\t/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/\n\t\t\tFixTrackID(mov);\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tFixSDTPInTRAF(mov->moof);\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\tif (traf->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*read & debug: store at root level*/\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tgf_list_add(mov->TopBoxes, a);\n\t\t\t\t/*also update pointers to trex for debug*/\n\t\t\t\tif (mov->moov) {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tu32 j=0;\n\t\t\t\t\t\t\twhile ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {\n\t\t\t\t\t\t\t\tif (traf->trex->trackID == traf->tfhd->trackID) {\n\t\t\t\t\t\t\t\t\tif (!traf->trex->track) traf->trex->track = trak;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttraf->trex = NULL;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly\n\t\t\t\t\t\tif (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->sample_encryption) {\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {\n\t\t\t\tmov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;\n\t\t\t\tmov->moof = NULL;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\t/*merge all info*/\n\t\t\t\te = MergeFragment((GF_MovieFragmentBox *)a, mov);\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\n\t\t\t//done with moov\n\t\t\tif (mov->root_sidx) {\n\t\t\t\tgf_isom_box_del((GF_Box *) mov->root_sidx);\n\t\t\t\tmov->root_sidx = NULL;\n\t\t\t}\n\t\t\tif (mov->root_ssix) {\n\t\t\t\tgf_isom_box_del(mov->seg_ssix);\n\t\t\t\tmov->root_ssix = NULL;\n\t\t\t}\n\t\t\tif (mov->seg_styp) {\n\t\t\t\tgf_isom_box_del(mov->seg_styp);\n\t\t\t\tmov->seg_styp = NULL;\n\t\t\t}\n\t\t\tmov->sidx_start_offset = 0;\n\t\t\tmov->sidx_end_offset = 0;\n\t\t\tmov->styp_start_offset = 0;\n\t\t\tbreak;\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\t{\n\t\t\tGF_UnknownBox *box = (GF_UnknownBox*)a;\n\t\t\tif (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {\n\t\t\t\tu8 *c = (u8 *) box->data;\n\t\t\t\tif ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))\n\t\t\t\t\tmov->is_jp2 = 1;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PRFT:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\t//keep the last one read\n\t\t\t\tif (mov->last_producer_ref_time)\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\telse\n\t\t\t\t\tmov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t//fallthrough\n\n\t\tdefault:\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\t\t}\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*remember where we left, in case we append an entire number of movie fragments*/\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n#endif\n\t}\n\n\t/*we need at least moov or meta*/\n\tif (!mov->moov && !mov->meta\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t && !mov->moof && !mov->is_index_segment\n#endif\n\t ) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\t/*we MUST have movie header*/\n\tif (!gf_opts_get_bool(\"core\", \"no-check\")) {\n\t\tif (mov->moov && !mov->moov->mvhd) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MVHD in MOOV!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\t/*we MUST have meta handler*/\n\t\tif (mov->meta && !mov->meta->handler) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing handler in META!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\n\tif (mov->moov) {\n\t\t/*set the default interleaving time*/\n\t\tmov->interleavingTime = mov->moov->mvhd->timeScale;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*in edit mode with successfully loaded fragments, delete all fragment signaling since\n\t\tfile is no longer fragmented*/\n\t\tif ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {\n\t\t\tgf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);\n\t\t\tmov->moov->mvex = NULL;\n\t\t}\n#endif\n\n\t}\n\n\t//create a default mdat if none was found\n\tif (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\tif (e) return e;\n\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\n\treturn GF_OK;\n}", "func_hash": 308778039006783747558037861317409138617, "file_name": "isom_intern.c", "file_hash": 222253413406937686232969416940772997244, "cwe": ["CWE-401"], "cve": "CVE-2021-33364", "cve_desc": "Memory leak in the def_parent_box_new function in MP4Box in GPAC 1.0.1 allows attackers to read memory via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33364"} {"idx": 198315, "project": "openvpn", "commit_id": "37bc691e7d26ea4eb61a8a434ebd7a9ae76225ab", "project_url": "https://github.com/OpenVPN/openvpn", "commit_url": "https://github.com/OpenVPN/openvpn/commit/37bc691e7d26ea4eb61a8a434ebd7a9ae76225ab", "commit_message": "Fix illegal client float (CVE-2020-11810)\n\nThere is a time frame between allocating peer-id and initializing data\nchannel key (which is performed on receiving push request or on async\npush-reply) in which the existing peer-id float checks do not work right.\n\nIf a \"rogue\" data channel packet arrives during that time frame from\nanother address and with same peer-id, this would cause client to float\nto that new address. This is because:\n\n - tls_pre_decrypt() sets packet length to zero if\n data channel key has not been initialized, which leads to\n\n - openvpn_decrypt() returns true if packet length is zero,\n which leads to\n\n - process_incoming_link_part1() returns true, which\n calls multi_process_float(), which commits float\n\nNote that problem doesn't happen when data channel key is initialized,\nsince in this case openvpn_decrypt() returns false.\n\nThe net effect of this behaviour is that the VPN session for the\n\"victim client\" is broken. Since the \"attacker client\" does not have\nsuitable keys, it can not inject or steal VPN traffic from the other\nsession. The time window is small and it can not be used to attack\na specific client's session, unless some other way is found to make it\ndisconnect and reconnect first.\n\nCVE-2020-11810 has been assigned to acknowledge this risk.\n\nFix illegal float by adding buffer length check (\"is this packet still\nconsidered valid\") before calling multi_process_float().\n\nTrac: #1272\nCVE: 2020-11810\n\nSigned-off-by: Lev Stipakov \nAcked-by: Arne Schwabe \nAcked-by: Antonio Quartulli \nAcked-by: Gert Doering \nMessage-Id: <20200415073017.22839-1-lstipakov@gmail.com>\nURL: https://www.mail-archive.com/openvpn-devel@lists.sourceforge.net/msg19720.html\nSigned-off-by: Gert Doering ", "target": 1, "func": "multi_process_incoming_link(struct multi_context *m, struct multi_instance *instance, const unsigned int mpp_flags)\n{\n struct gc_arena gc = gc_new();\n\n struct context *c;\n struct mroute_addr src, dest;\n unsigned int mroute_flags;\n struct multi_instance *mi;\n bool ret = true;\n bool floated = false;\n\n if (m->pending)\n {\n return true;\n }\n\n if (!instance)\n {\n#ifdef MULTI_DEBUG_EVENT_LOOP\n printf(\"TCP/UDP -> TUN [%d]\\n\", BLEN(&m->top.c2.buf));\n#endif\n multi_set_pending(m, multi_get_create_instance_udp(m, &floated));\n }\n else\n {\n multi_set_pending(m, instance);\n }\n\n if (m->pending)\n {\n set_prefix(m->pending);\n\n /* get instance context */\n c = &m->pending->context;\n\n if (!instance)\n {\n /* transfer packet pointer from top-level context buffer to instance */\n c->c2.buf = m->top.c2.buf;\n\n /* transfer from-addr from top-level context buffer to instance */\n if (!floated)\n {\n c->c2.from = m->top.c2.from;\n }\n }\n\n if (BLEN(&c->c2.buf) > 0)\n {\n struct link_socket_info *lsi;\n const uint8_t *orig_buf;\n\n /* decrypt in instance context */\n\n perf_push(PERF_PROC_IN_LINK);\n lsi = get_link_socket_info(c);\n orig_buf = c->c2.buf.data;\n if (process_incoming_link_part1(c, lsi, floated))\n {\n if (floated)\n {\n multi_process_float(m, m->pending);\n }\n\n process_incoming_link_part2(c, lsi, orig_buf);\n }\n perf_pop();\n\n if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TUN)\n {\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n NULL,\n 0,\n &c->c2.to_tun,\n DEV_TYPE_TUN);\n\n /* drop packet if extract failed */\n if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED))\n {\n c->c2.to_tun.len = 0;\n }\n /* make sure that source address is associated with this client */\n else if (multi_get_instance_by_virtual_addr(m, &src, true) != m->pending)\n {\n /* IPv6 link-local address (fe80::xxx)? */\n if ( (src.type & MR_ADDR_MASK) == MR_ADDR_IPV6\n && IN6_IS_ADDR_LINKLOCAL(&src.v6.addr) )\n {\n /* do nothing, for now. TODO: add address learning */\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n }\n c->c2.to_tun.len = 0;\n }\n /* client-to-client communication enabled? */\n else if (m->enable_c2c)\n {\n /* multicast? */\n if (mroute_flags & MROUTE_EXTRACT_MCAST)\n {\n /* for now, treat multicast as broadcast */\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL, 0);\n }\n else /* possible client to client routing */\n {\n ASSERT(!(mroute_flags & MROUTE_EXTRACT_BCAST));\n mi = multi_get_instance_by_virtual_addr(m, &dest, true);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tun_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TUN packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, &dest,\n \"tun_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TUN packet filter\",\n mroute_addr_print_ex(&dest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TAP)\n {\n uint16_t vid = 0;\n#ifdef ENABLE_PF\n struct mroute_addr edest;\n mroute_addr_reset(&edest);\n#endif\n\n if (m->top.options.vlan_tagging)\n {\n if (vlan_is_tagged(&c->c2.to_tun))\n {\n /* Drop VLAN-tagged frame. */\n msg(D_VLAN_DEBUG, \"dropping incoming VLAN-tagged frame\");\n c->c2.to_tun.len = 0;\n }\n else\n {\n vid = c->options.vlan_pvid;\n }\n }\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n#ifdef ENABLE_PF\n &edest,\n#else\n NULL,\n#endif\n vid,\n &c->c2.to_tun,\n DEV_TYPE_TAP);\n\n if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)\n {\n if (multi_learn_addr(m, m->pending, &src, 0) == m->pending)\n {\n /* check for broadcast */\n if (m->enable_c2c)\n {\n if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))\n {\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL,\n vid);\n }\n else /* try client-to-client routing */\n {\n mi = multi_get_instance_by_virtual_addr(m, &dest, false);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tap_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TAP packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c,\n &edest,\n \"tap_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TAP packet filter\",\n mroute_addr_print_ex(&edest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n c->c2.to_tun.len = 0;\n }\n }\n else\n {\n c->c2.to_tun.len = 0;\n }\n }\n }\n\n /* postprocess and set wakeup */\n ret = multi_process_post(m, m->pending, mpp_flags);\n\n clear_prefix();\n }\n\n gc_free(&gc);\n return ret;\n}", "func_hash": 282367254381229209024101595984836191625, "file_name": "multi.c", "file_hash": 272123969276480440045373534795880000588, "cwe": ["CWE-476"], "cve": "CVE-2020-11810", "cve_desc": "An issue was discovered in OpenVPN 2.4.x before 2.4.9. An attacker can inject a data channel v2 (P_DATA_V2) packet using a victim's peer-id. Normally such packets are dropped, but if this packet arrives before the data channel crypto parameters have been initialized, the victim's connection will be dropped. This requires careful timing due to the small time window (usually within a few seconds) between the victim client connection starting and the server PUSH_REPLY response back to the client. This attack will only work if Negotiable Cipher Parameters (NCP) is in use.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11810"} {"idx": 272280, "project": "openvpn", "commit_id": "37bc691e7d26ea4eb61a8a434ebd7a9ae76225ab", "project_url": "https://github.com/OpenVPN/openvpn", "commit_url": "https://github.com/OpenVPN/openvpn/commit/37bc691e7d26ea4eb61a8a434ebd7a9ae76225ab", "commit_message": "Fix illegal client float (CVE-2020-11810)\n\nThere is a time frame between allocating peer-id and initializing data\nchannel key (which is performed on receiving push request or on async\npush-reply) in which the existing peer-id float checks do not work right.\n\nIf a \"rogue\" data channel packet arrives during that time frame from\nanother address and with same peer-id, this would cause client to float\nto that new address. This is because:\n\n - tls_pre_decrypt() sets packet length to zero if\n data channel key has not been initialized, which leads to\n\n - openvpn_decrypt() returns true if packet length is zero,\n which leads to\n\n - process_incoming_link_part1() returns true, which\n calls multi_process_float(), which commits float\n\nNote that problem doesn't happen when data channel key is initialized,\nsince in this case openvpn_decrypt() returns false.\n\nThe net effect of this behaviour is that the VPN session for the\n\"victim client\" is broken. Since the \"attacker client\" does not have\nsuitable keys, it can not inject or steal VPN traffic from the other\nsession. The time window is small and it can not be used to attack\na specific client's session, unless some other way is found to make it\ndisconnect and reconnect first.\n\nCVE-2020-11810 has been assigned to acknowledge this risk.\n\nFix illegal float by adding buffer length check (\"is this packet still\nconsidered valid\") before calling multi_process_float().\n\nTrac: #1272\nCVE: 2020-11810\n\nSigned-off-by: Lev Stipakov \nAcked-by: Arne Schwabe \nAcked-by: Antonio Quartulli \nAcked-by: Gert Doering \nMessage-Id: <20200415073017.22839-1-lstipakov@gmail.com>\nURL: https://www.mail-archive.com/openvpn-devel@lists.sourceforge.net/msg19720.html\nSigned-off-by: Gert Doering ", "target": 0, "func": "multi_process_incoming_link(struct multi_context *m, struct multi_instance *instance, const unsigned int mpp_flags)\n{\n struct gc_arena gc = gc_new();\n\n struct context *c;\n struct mroute_addr src, dest;\n unsigned int mroute_flags;\n struct multi_instance *mi;\n bool ret = true;\n bool floated = false;\n\n if (m->pending)\n {\n return true;\n }\n\n if (!instance)\n {\n#ifdef MULTI_DEBUG_EVENT_LOOP\n printf(\"TCP/UDP -> TUN [%d]\\n\", BLEN(&m->top.c2.buf));\n#endif\n multi_set_pending(m, multi_get_create_instance_udp(m, &floated));\n }\n else\n {\n multi_set_pending(m, instance);\n }\n\n if (m->pending)\n {\n set_prefix(m->pending);\n\n /* get instance context */\n c = &m->pending->context;\n\n if (!instance)\n {\n /* transfer packet pointer from top-level context buffer to instance */\n c->c2.buf = m->top.c2.buf;\n\n /* transfer from-addr from top-level context buffer to instance */\n if (!floated)\n {\n c->c2.from = m->top.c2.from;\n }\n }\n\n if (BLEN(&c->c2.buf) > 0)\n {\n struct link_socket_info *lsi;\n const uint8_t *orig_buf;\n\n /* decrypt in instance context */\n\n perf_push(PERF_PROC_IN_LINK);\n lsi = get_link_socket_info(c);\n orig_buf = c->c2.buf.data;\n if (process_incoming_link_part1(c, lsi, floated))\n {\n /* nonzero length means that we have a valid, decrypted packed */\n if (floated && c->c2.buf.len > 0)\n {\n multi_process_float(m, m->pending);\n }\n\n process_incoming_link_part2(c, lsi, orig_buf);\n }\n perf_pop();\n\n if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TUN)\n {\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n NULL,\n 0,\n &c->c2.to_tun,\n DEV_TYPE_TUN);\n\n /* drop packet if extract failed */\n if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED))\n {\n c->c2.to_tun.len = 0;\n }\n /* make sure that source address is associated with this client */\n else if (multi_get_instance_by_virtual_addr(m, &src, true) != m->pending)\n {\n /* IPv6 link-local address (fe80::xxx)? */\n if ( (src.type & MR_ADDR_MASK) == MR_ADDR_IPV6\n && IN6_IS_ADDR_LINKLOCAL(&src.v6.addr) )\n {\n /* do nothing, for now. TODO: add address learning */\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n }\n c->c2.to_tun.len = 0;\n }\n /* client-to-client communication enabled? */\n else if (m->enable_c2c)\n {\n /* multicast? */\n if (mroute_flags & MROUTE_EXTRACT_MCAST)\n {\n /* for now, treat multicast as broadcast */\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL, 0);\n }\n else /* possible client to client routing */\n {\n ASSERT(!(mroute_flags & MROUTE_EXTRACT_BCAST));\n mi = multi_get_instance_by_virtual_addr(m, &dest, true);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tun_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TUN packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, &dest,\n \"tun_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TUN packet filter\",\n mroute_addr_print_ex(&dest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TAP)\n {\n uint16_t vid = 0;\n#ifdef ENABLE_PF\n struct mroute_addr edest;\n mroute_addr_reset(&edest);\n#endif\n\n if (m->top.options.vlan_tagging)\n {\n if (vlan_is_tagged(&c->c2.to_tun))\n {\n /* Drop VLAN-tagged frame. */\n msg(D_VLAN_DEBUG, \"dropping incoming VLAN-tagged frame\");\n c->c2.to_tun.len = 0;\n }\n else\n {\n vid = c->options.vlan_pvid;\n }\n }\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n#ifdef ENABLE_PF\n &edest,\n#else\n NULL,\n#endif\n vid,\n &c->c2.to_tun,\n DEV_TYPE_TAP);\n\n if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)\n {\n if (multi_learn_addr(m, m->pending, &src, 0) == m->pending)\n {\n /* check for broadcast */\n if (m->enable_c2c)\n {\n if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))\n {\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL,\n vid);\n }\n else /* try client-to-client routing */\n {\n mi = multi_get_instance_by_virtual_addr(m, &dest, false);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tap_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TAP packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c,\n &edest,\n \"tap_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TAP packet filter\",\n mroute_addr_print_ex(&edest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n c->c2.to_tun.len = 0;\n }\n }\n else\n {\n c->c2.to_tun.len = 0;\n }\n }\n }\n\n /* postprocess and set wakeup */\n ret = multi_process_post(m, m->pending, mpp_flags);\n\n clear_prefix();\n }\n\n gc_free(&gc);\n return ret;\n}", "func_hash": 67508135795402145366288089044741319203, "file_name": "multi.c", "file_hash": 146855803057174359309194312432251865163, "cwe": ["CWE-476"], "cve": "CVE-2020-11810", "cve_desc": "An issue was discovered in OpenVPN 2.4.x before 2.4.9. An attacker can inject a data channel v2 (P_DATA_V2) packet using a victim's peer-id. Normally such packets are dropped, but if this packet arrives before the data channel crypto parameters have been initialized, the victim's connection will be dropped. This requires careful timing due to the small time window (usually within a few seconds) between the victim client connection starting and the server PUSH_REPLY response back to the client. This attack will only work if Negotiable Cipher Parameters (NCP) is in use.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11810"} {"idx": 198316, "project": "gpac", "commit_id": "df8fffd839fe5ae9acd82d26fd48280a397411d9", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/df8fffd839fe5ae9acd82d26fd48280a397411d9", "commit_message": "fixed #1736", "target": 1, "func": "GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragmentBox *moof_box, u64 moof_offset, s32 compressed_diff, u64 *cumulated_offset, Bool is_first_merge)\n{\n\tu32 i, j, chunk_size, track_num;\n\tu64 base_offset, data_offset, traf_duration;\n\tu32 def_duration, DescIndex, def_size, def_flags;\n\tu32 duration, size, flags, prev_trun_data_offset, sample_index;\n\tu8 pad, sync;\n\tu16 degr;\n\tBool first_samp_in_traf=GF_TRUE;\n\tBool store_traf_map=GF_FALSE;\n\tu8 *moof_template=NULL;\n\tu32 moof_template_size=0;\n\tBool is_seg_start = GF_FALSE;\n\tu64 seg_start=0, sidx_start=0, sidx_end=0, frag_start=0, last_dts=0;\n\tGF_TrackFragmentRunBox *trun;\n\tGF_TrunEntry *ent;\n#ifdef GF_ENABLE_CTRN\n\tGF_TrackFragmentBox *traf_ref = NULL;\n#endif\n\n\tGF_Err stbl_AppendTime(GF_SampleTableBox *stbl, u32 duration, u32 nb_pack);\n\tGF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack);\n\tGF_Err stbl_AppendChunk(GF_SampleTableBox *stbl, u64 offset);\n\tGF_Err stbl_AppendSampleToChunk(GF_SampleTableBox *stbl, u32 DescIndex, u32 samplesInChunk);\n\tGF_Err stbl_AppendCTSOffset(GF_SampleTableBox *stbl, s32 CTSOffset);\n\tGF_Err stbl_AppendRAP(GF_SampleTableBox *stbl, u8 isRap);\n\tGF_Err stbl_AppendPadding(GF_SampleTableBox *stbl, u8 padding);\n\tGF_Err stbl_AppendDegradation(GF_SampleTableBox *stbl, u16 DegradationPriority);\n\n\tif (trak->Header->trackID != traf->tfhd->trackID) return GF_OK;\n\tif (!trak->Media->information->sampleTable\n\t\t|| !trak->Media->information->sampleTable->SampleSize\n\t\t|| !trak->Media->information->sampleTable->TimeToSample\n\t\t|| !trak->Media->information->sampleTable->SampleToChunk\n\t\t|| !trak->Media->information->sampleTable->ChunkOffset\n\t) {\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\tif (!traf->trex->track)\n\t\ttraf->trex->track = trak;\n\n\t//setup all our defaults\n\tDescIndex = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DESC) ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\tif (!DescIndex) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to 0, likely broken ! Fixing to 1\\n\" ));\n\t\tDescIndex = 1;\n\t} else if (DescIndex > gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to %d but only %d sample description(s), likely broken ! Fixing to 1\\n\", DescIndex, gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)));\n\t\tDescIndex = 1;\n\t}\n#ifdef GF_ENABLE_CTRN\n\tif (traf->trex->inherit_from_traf_id) {\n\t\tu32 traf_count = gf_list_count(moof_box->TrackList);\n\t\tfor (i=0; iTrackList, i);\n\t\t\tif (atraf->tfhd && atraf->tfhd->trackID==traf->trex->inherit_from_traf_id) {\n\t\t\t\ttraf_ref = atraf;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\tdef_duration = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DUR) ? traf->tfhd->def_sample_duration : traf->trex->def_sample_duration;\n\tdef_size = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_SIZE) ? traf->tfhd->def_sample_size : traf->trex->def_sample_size;\n\tdef_flags = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) ? traf->tfhd->def_sample_flags : traf->trex->def_sample_flags;\n\n\t//locate base offset, by default use moof (dash-like)\n\tbase_offset = moof_offset;\n\t//explicit base offset, use it\n\tif (traf->tfhd->flags & GF_ISOM_TRAF_BASE_OFFSET)\n\t\tbase_offset = traf->tfhd->base_data_offset;\n\t//no moof offset and no explicit offset, the offset is the end of the last written chunk of\n\t//the previous traf. For the first traf, *cumulated_offset is actually moof offset\n\telse if (!(traf->tfhd->flags & GF_ISOM_MOOF_BASE_OFFSET))\n\t\tbase_offset = *cumulated_offset;\n\n\tchunk_size = 0;\n\tprev_trun_data_offset = 0;\n\tdata_offset = 0;\n\ttraf_duration = 0;\n\n\t/*in playback mode*/\n\tif (traf->tfdt && is_first_merge) {\n#ifndef GPAC_DISABLE_LOG\n\t\tif (trak->moov->mov->NextMoofNumber && trak->present_in_scalable_segment && trak->sample_count_at_seg_start && (trak->dts_at_seg_start != traf->tfdt->baseMediaDecodeTime)) {\n\t\t\ts32 drift = (s32) ((s64) traf->tfdt->baseMediaDecodeTime - (s64)trak->dts_at_seg_start);\n\t\t\tif (drift<0) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Warning: TFDT timing \"LLD\" less than cumulated timing \"LLD\" - using tfdt\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"[iso file] TFDT timing \"LLD\" higher than cumulated timing \"LLD\" (last sample got extended in duration)\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t}\n\t\t}\n#endif\n\t\ttrak->dts_at_seg_start = traf->tfdt->baseMediaDecodeTime;\n\t}\n\telse if (traf->tfxd) {\n\t\ttrak->dts_at_seg_start = traf->tfxd->absolute_time_in_track_timescale;\n\t}\n\n\tif (traf->tfxd) {\n\t\ttrak->last_tfxd_value = traf->tfxd->absolute_time_in_track_timescale;\n\t\ttrak->last_tfxd_value += traf->tfxd->fragment_duration_in_track_timescale;\n\t}\n\tif (traf->tfrf) {\n\t\tif (trak->tfrf) gf_isom_box_del_parent(&trak->child_boxes, (GF_Box *)trak->tfrf);\n\t\ttrak->tfrf = traf->tfrf;\n\t\tgf_list_del_item(traf->child_boxes, traf->tfrf);\n\t\tgf_list_add(trak->child_boxes, trak->tfrf);\n\t}\n\n\tif (trak->moov->mov->signal_frag_bounds) {\n\t\tstore_traf_map = GF_TRUE;\n\t\tif (is_first_merge) {\n\t\t\tGF_MovieFragmentBox *moof_clone = NULL;\n\t\t\tgf_isom_box_freeze_order((GF_Box *)moof_box);\n\t\t\tgf_isom_clone_box((GF_Box *)moof_box, (GF_Box **)&moof_clone);\n\n\t\t\tif (moof_clone) {\n\t\t\t\tGF_BitStream *bs;\n\t\t\t\tfor (i=0; iTrackList); i++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf_clone = gf_list_get(moof_clone->TrackList, i);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->TrackRuns);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroups);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroupsDescription);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sub_samples);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_offsets);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_sizes);\n\t\t\t\t\tif (traf_clone->sample_encryption) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sample_encryption);\n\t\t\t\t\t\ttraf_clone->sample_encryption = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tif (traf_clone->sdtp) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sdtp);\n\t\t\t\t\t\ttraf_clone->sdtp = NULL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_isom_box_size((GF_Box *)moof_clone);\n\t\t\t\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\n\t\t\t\tif (trak->moov->mov->seg_styp) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_styp);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_styp, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->root_sidx) {\n\t\t\t\t\tgf_isom_box_size((GF_Box *)trak->moov->mov->root_sidx);\n\t\t\t\t\tgf_isom_box_write((GF_Box *)trak->moov->mov->root_sidx, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->seg_ssix) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_ssix);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_ssix, bs);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_write((GF_Box *)moof_clone, bs);\n\t\t\t\tgf_isom_box_del((GF_Box*)moof_clone);\n\n\t\t\t\tgf_bs_get_content(bs, &moof_template, &moof_template_size);\n\t\t\t\tgf_bs_del(bs);\n\t\t\t}\n\t\t}\n\t\tif (trak->moov->mov->seg_styp) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tseg_start = trak->moov->mov->styp_start_offset;\n\t\t}\n\t\tif (trak->moov->mov->root_sidx) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tsidx_start = trak->moov->mov->sidx_start_offset;\n\t\t\tsidx_end = trak->moov->mov->sidx_end_offset;\n\t\t\tif (! seg_start || (sidx_startmoov->mov->current_top_box_start;\n\t}\n\telse if (trak->moov->mov->store_traf_map) {\n\t\tstore_traf_map = GF_TRUE;\n\t}\n\n\n\tsample_index = 0;\n\ti=0;\n\twhile ((trun = (GF_TrackFragmentRunBox *)gf_list_enum(traf->TrackRuns, &i))) {\n\t\t//merge the run\n\t\tfor (j=0; jsample_count; j++) {\n\t\t\tGF_Err e;\n\t\t\ts32 cts_offset=0;\n\t\t\tif (jnb_samples) {\n\t\t\t\tent = &trun->samples[j];\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d doesn't have enough trun entries (%d) compared to sample count (%d) in run\\n\", traf->trex->trackID, trun->nb_samples, trun->sample_count ));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsize = def_size;\n\t\t\tduration = def_duration;\n\t\t\tflags = def_flags;\n\n\t\t\t//CTS - if flag not set (trun or ctrn) defaults to 0 which is the base value after alloc\n\t\t\t//we just need to overrite its value if inherited\n\t\t\tcts_offset = ent->CTS_Offset;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (trun->use_ctrn) {\n\t\t\t\tif (!j && (trun->ctrn_flags & GF_ISOM_CTRN_FIRST_SAMPLE) ) {\n\t\t\t\t\tif (trun->ctrn_first_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_first_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_first_ctts) flags = ent->flags;\n\t\t\t\t} else {\n\t\t\t\t\tif (trun->ctrn_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_sample_flags) flags = ent->flags;\n\t\t\t\t}\n\t\t\t\t/*re-override*/\n\t\t\t\tif (trun->ctrn_flags & 0xF0) {\n\t\t\t\t\tGF_TrunEntry *ref_entry;\n\t\t\t\t\tif (!traf_ref) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance to track ID %d but reference traf not found\\n\", traf->trex->trackID, traf->trex->inherit_from_traf_id ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tref_entry = traf_get_sample_entry(traf_ref, sample_index);\n\t\t\t\t\tif (!ref_entry) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance but sample %d not found in reference traf\\n\", traf->trex->trackID, sample_index+1 ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_DUR)\n\t\t\t\t\t\tduration = ref_entry->Duration;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_SIZE)\n\t\t\t\t\t\tsize = ref_entry->size;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_FLAGS)\n\t\t\t\t\t\tflags = ref_entry->flags;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_CTSO)\n\t\t\t\t\t\tcts_offset = ref_entry->CTS_Offset;\n\t\t\t\t}\n\n\t\t\t} else\n#endif\n\t\t\t{\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DURATION) duration = ent->Duration;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_SIZE) size = ent->size;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_FLAGS) {\n\t\t\t\t\tflags = ent->flags;\n\t\t\t\t} else if (!j && (trun->flags & GF_ISOM_TRUN_FIRST_FLAG)) {\n\t\t\t\t\tflags = trun->first_sample_flags;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsample_index++;\n\t\t\t/*store the resolved value in case we have inheritance*/\n\t\t\tent->size = size;\n\t\t\tent->Duration = duration;\n\t\t\tent->flags = flags;\n\t\t\tent->CTS_Offset = cts_offset;\n\n\t\t\tlast_dts += duration;\n\n\t\t\t//add size first\n\t\t\tif (!trak->Media->information->sampleTable->SampleSize) {\n\t\t\t\ttrak->Media->information->sampleTable->SampleSize = (GF_SampleSizeBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSZ);\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleSize)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendSize(trak->Media->information->sampleTable, size, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//then TS\n\t\t\tif (!trak->Media->information->sampleTable->TimeToSample) {\n\t\t\t\ttrak->Media->information->sampleTable->TimeToSample = (GF_TimeToSampleBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STTS);\n\t\t\t\tif (!trak->Media->information->sampleTable->TimeToSample)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendTime(trak->Media->information->sampleTable, duration, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//add chunk on first sample\n\t\t\tif (!j) {\n\t\t\t\tu64 final_offset;\n\t\t\t\tdata_offset = base_offset;\n\t\t\t\t//we have an explicit data offset for this trun\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DATA_OFFSET) {\n\t\t\t\t\tdata_offset += trun->data_offset;\n\t\t\t\t\t/*reset chunk size since data is now relative to this trun*/\n\t\t\t\t\tchunk_size = 0;\n\t\t\t\t\t/*remember this data offset for following trun*/\n\t\t\t\t\tprev_trun_data_offset = trun->data_offset;\n\t\t\t\t\t/*if mdat is located after the moof, and the moof was compressed, adjust offset\n\t\t\t\t\totherwise the offset does not need adjustment*/\n\t\t\t\t\tif (trun->data_offset>=0) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t\tprev_trun_data_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//we had an explicit data offset for the previous trun, use it + chunk size\n\t\t\t\telse if (prev_trun_data_offset) {\n\t\t\t\t\t/*data offset is previous chunk size plus previous offset of the trun*/\n\t\t\t\t\tdata_offset += prev_trun_data_offset + chunk_size;\n\t\t\t\t}\n\t\t\t\t//no explicit data offset, continuous data after last data in previous chunk\n\t\t\t\telse {\n\t\t\t\t\tdata_offset += chunk_size;\n\t\t\t\t\t//data offset of first trun in first traf, adjust if compressed moof\n\t\t\t\t\tif ((i==1) && (trun->data_offset>=0)) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinal_offset = data_offset;\n\t\t\t\t//adjust offset if moov was also compressed and we are still in the same file\n\t\t\t\t//so that later call to gf_isom_get_sample properly adjust back the offset\n\t\t\t\tif (trak->moov->compressed_diff) {\n\t\t\t\t\tfinal_offset += trak->moov->compressed_diff;\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset) {\n\t\t\t\t\ttrak->Media->information->sampleTable->ChunkOffset = gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STCO);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendChunk(trak->Media->information->sampleTable, final_offset);\n\t\t\t\tif (e) return e;\n\t\t\t\t//then sampleToChunk\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk) {\n\t\t\t\t\ttrak->Media->information->sampleTable->SampleToChunk = (GF_SampleToChunkBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSC);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendSampleToChunk(trak->Media->information->sampleTable,\n\t\t\t\t DescIndex, trun->sample_count);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tchunk_size += size;\n\n\t\t\tif (store_traf_map && first_samp_in_traf) {\n\t\t\t\tfirst_samp_in_traf = GF_FALSE;\n\t\t\t\te = stbl_AppendTrafMap(trak->Media->information->sampleTable, is_seg_start, seg_start, frag_start, moof_template, moof_template_size, sidx_start, sidx_end);\n\t\t\t\tif (e) return e;\n\t\t\t\t//do not deallocate, the memory is now owned by traf map\n\t\t\t\tmoof_template = NULL;\n\t\t\t\tmoof_template_size = 0;\n\t\t\t}\n\t\t\tif (ent->nb_pack>1) {\n\t\t\t\tj+= ent->nb_pack-1;\n\t\t\t\ttraf_duration += ent->nb_pack*duration;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttraf_duration += duration;\n\n\t\t\te = stbl_AppendCTSOffset(trak->Media->information->sampleTable, cts_offset);\n\t\t\tif (e) return e;\n\t\t\t//flags\n\t\t\tsync = GF_ISOM_GET_FRAG_SYNC(flags);\n\t\t\tif (trak->Media->information->sampleTable->no_sync_found && sync) {\n\t\t\t\ttrak->Media->information->sampleTable->no_sync_found = 0;\n\t\t\t}\n\t\t\te = stbl_AppendRAP(trak->Media->information->sampleTable, sync);\n\t\t\tif (e) return e;\n\t\t\tpad = GF_ISOM_GET_FRAG_PAD(flags);\n\t\t\tif (pad) {\n\t\t\t\te = stbl_AppendPadding(trak->Media->information->sampleTable, pad);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tdegr = GF_ISOM_GET_FRAG_DEG(flags);\n\t\t\tif (degr) {\n\t\t\t\te = stbl_AppendDegradation(trak->Media->information->sampleTable, degr);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\te = stbl_AppendDependencyType(trak->Media->information->sampleTable, GF_ISOM_GET_FRAG_LEAD(flags), GF_ISOM_GET_FRAG_DEPENDS(flags), GF_ISOM_GET_FRAG_DEPENDED(flags), GF_ISOM_GET_FRAG_REDUNDANT(flags));\n\t\t\tif (e) return e;\n\t\t}\n\t}\n\n\tif (trak->moov->mov->is_smooth && !traf->tfdt && !traf->tfxd) {\n\t\tif (is_first_merge)\n\t\t\ttrak->dts_at_seg_start = trak->dts_at_next_seg_start;\n\t\ttrak->dts_at_next_seg_start += last_dts;\n\t}\n\tif (traf_duration && trak->editBox && trak->editBox->editList) {\n\t\tfor (i=0; ieditBox->editList->entryList); i++) {\n\t\t\tGF_EdtsEntry *edts_e = gf_list_get(trak->editBox->editList->entryList, i);\n\t\t\tif (edts_e->was_empty_dur) {\n\t\t\t\tu64 extend_dur = traf_duration;\n\t\t\t\textend_dur *= trak->moov->mvhd->timeScale;\n\t\t\t\textend_dur /= trak->Media->mediaHeader->timeScale;\n\t\t\t\tedts_e->segmentDuration += extend_dur;\n\t\t\t}\n\t\t\telse if (!edts_e->segmentDuration) {\n\t\t\t\tedts_e->was_empty_dur = GF_TRUE;\n\t\t\t\tif ((s64) traf_duration > edts_e->mediaTime)\n\t\t\t\t\ttraf_duration -= edts_e->mediaTime;\n\t\t\t\telse\n\t\t\t\t\ttraf_duration = 0;\n\n\t\t\t\tedts_e->segmentDuration = traf_duration;\n\t\t\t\tedts_e->segmentDuration *= trak->moov->mvhd->timeScale;\n\t\t\t\tedts_e->segmentDuration /= trak->Media->mediaHeader->timeScale;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//in any case, update the cumulated offset\n\t//this will handle hypothetical files mixing MOOF offset and implicit non-moof offset\n\t*cumulated_offset = data_offset + chunk_size;\n\n\t/*merge sample groups*/\n\tif (traf->sampleGroups) {\n\t\tGF_List *groups;\n\t\tGF_List *groupDescs;\n\t\tBool is_identical_sgpd = GF_TRUE;\n\t\tu32 *new_idx = NULL, new_idx_count=0;\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroups)\n\t\t\ttrak->Media->information->sampleTable->sampleGroups = gf_list_new();\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroupsDescription)\n\t\t\ttrak->Media->information->sampleTable->sampleGroupsDescription = gf_list_new();\n\n\t\tgroupDescs = trak->Media->information->sampleTable->sampleGroupsDescription;\n\t\tfor (i=0; isampleGroupsDescription); i++) {\n\t\t\tGF_SampleGroupDescriptionBox *new_sgdesc = NULL;\n\t\t\tGF_SampleGroupDescriptionBox *sgdesc = gf_list_get(traf->sampleGroupsDescription, i);\n\t\t\tfor (j=0; jgrouping_type==sgdesc->grouping_type) break;\n\t\t\t\tnew_sgdesc = NULL;\n\t\t\t}\n\t\t\t/*new description, move it to our sample table*/\n\t\t\tif (!new_sgdesc) {\n\t\t\t\tgf_list_add(groupDescs, sgdesc);\n\t\t\t\tgf_list_add(trak->Media->information->sampleTable->child_boxes, sgdesc);\n\t\t\t\tgf_list_rem(traf->sampleGroupsDescription, i);\n\t\t\t\tgf_list_del_item(traf->child_boxes, sgdesc);\n\t\t\t\ti--;\n\t\t\t}\n\t\t\t/*merge descriptions*/\n\t\t\telse {\n\t\t\t\tu32 count;\n\n\t\t\t\tis_identical_sgpd = gf_isom_is_identical_sgpd(new_sgdesc, sgdesc, 0);\n\t\t\t\tif (is_identical_sgpd)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tnew_idx_count = gf_list_count(sgdesc->group_descriptions);\n\t\t\t\tnew_idx = (u32 *)gf_malloc(new_idx_count * sizeof(u32));\n\t\t\t\tif (!new_idx) return GF_OUT_OF_MEM;\n\n\t\t\t\tcount = 0;\n\t\t\t\twhile (gf_list_count(sgdesc->group_descriptions)) {\n\t\t\t\t\tvoid *sgpd_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\t\t\tBool new_entry = GF_TRUE;\n\n\t\t\t\t\tfor (j = 0; j < gf_list_count(new_sgdesc->group_descriptions); j++) {\n\t\t\t\t\t\tvoid *ptr = gf_list_get(new_sgdesc->group_descriptions, j);\n\t\t\t\t\t\tif (gf_isom_is_identical_sgpd(sgpd_entry, ptr, new_sgdesc->grouping_type)) {\n\t\t\t\t\t\t\tnew_idx[count] = j + 1;\n\t\t\t\t\t\t\tcount ++;\n\t\t\t\t\t\t\tnew_entry = GF_FALSE;\n\t\t\t\t\t\t\tgf_free(sgpd_entry);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (new_entry) {\n\t\t\t\t\t\tgf_list_add(new_sgdesc->group_descriptions, sgpd_entry);\n\t\t\t\t\t\tnew_idx[count] = gf_list_count(new_sgdesc->group_descriptions);\n\t\t\t\t\t\tcount ++;\n\t\t\t\t\t}\n\n\t\t\t\t\tgf_list_rem(sgdesc->group_descriptions, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tgroups = trak->Media->information->sampleTable->sampleGroups;\n\t\tfor (i=0; isampleGroups); i++) {\n\t\t\tGF_SampleGroupBox *stbl_group = NULL;\n\t\t\tGF_SampleGroupBox *frag_group = gf_list_get(traf->sampleGroups, i);\n\n\n\t\t\tfor (j=0; jgrouping_type==stbl_group->grouping_type) && (frag_group->grouping_type_parameter==stbl_group->grouping_type_parameter))\n\t\t\t\t\tbreak;\n\t\t\t\tstbl_group = NULL;\n\t\t\t}\n\t\t\tif (!stbl_group) {\n\t\t\t\tstbl_group = (GF_SampleGroupBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_SBGP);\n\t\t\t\tif (!stbl_group) return GF_OUT_OF_MEM;\n\t\t\t\tstbl_group->grouping_type = frag_group->grouping_type;\n\t\t\t\tstbl_group->grouping_type_parameter = frag_group->grouping_type_parameter;\n\t\t\t\tstbl_group->version = frag_group->version;\n\t\t\t\tgf_list_add(groups, stbl_group);\n\t\t\t}\n\n\t\t\tif (is_identical_sgpd) {\n\t\t\t\t//adjust sgpd index: in traf index start at 0x1001\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++)\n\t\t\t\t\tfrag_group->sample_entries[j].group_description_index &= 0x0FFFF;\n\t\t\t\tif (frag_group->entry_count && stbl_group->entry_count &&\n\t\t\t\t (frag_group->sample_entries[0].group_description_index==stbl_group->sample_entries[stbl_group->entry_count-1].group_description_index)\n\t\t\t\t ) {\n\t\t\t\t\tstbl_group->sample_entries[stbl_group->entry_count - 1].sample_count += frag_group->sample_entries[0].sample_count;\n\t\t\t\t\tif (frag_group->entry_count>1) {\n\t\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count - 1));\n\t\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[1], sizeof(GF_SampleGroupEntry) * (frag_group->entry_count - 1));\n\t\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count - 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t//adjust sgpd index\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++) {\n\t\t\t\t\tu32 sgidx = frag_group->sample_entries[j].group_description_index;\n\t\t\t\t\tif (sgidx > 0x10000) {\n\t\t\t\t\t\tsgidx -= 0x10001;\n\t\t\t\t\t\tif (sgidx>=new_idx_count) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[isobmf] corrupted sample group index in fragment %d but only %d group descriptions in fragment\\n\", sgidx, new_idx_count));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfrag_group->sample_entries[j].group_description_index = new_idx[sgidx];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t}\n\t\t}\n\n\t\tif (new_idx) gf_free(new_idx);\n\t}\n\n\t/*content is encrypted*/\n\ttrack_num = gf_isom_get_tracknum_from_id(trak->moov, trak->Header->trackID);\n\tif (gf_isom_is_cenc_media(trak->moov->mov, track_num, DescIndex)\n\t\t|| traf->sample_encryption) {\n\t\t/*Merge sample auxiliary encryption information*/\n\t\tGF_SampleEncryptionBox *senc = NULL;\n\t\tu32 scheme_type;\n\t\tgf_isom_get_cenc_info(trak->moov->mov, track_num, DescIndex, NULL, &scheme_type, NULL);\n\n\t\tif (traf->sample_encryption) {\n\t\t\tfor (i = 0; i < gf_list_count(trak->Media->information->sampleTable->child_boxes); i++) {\n\t\t\t\tGF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->child_boxes, i);\n\t\t\t\tif (a->type != traf->sample_encryption->type) continue;\n\n\t\t\t\tif ((a->type ==GF_ISOM_BOX_TYPE_UUID) && (((GF_UUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC)) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (a->type ==GF_ISOM_BOX_TYPE_SENC) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!senc && trak->sample_encryption)\n\t\t\t\tsenc = trak->sample_encryption;\n\n\t\t\tif (!senc) {\n\t\t\t\tif (traf->sample_encryption->piff_type==1) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)gf_isom_create_piff_psec_box(1, 0x2, 0, 0, NULL);\n\t\t\t\t} else {\n\t\t\t\t\tsenc = gf_isom_create_samp_enc_box(1, 0x2);\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->child_boxes) trak->Media->information->sampleTable->child_boxes = gf_list_new();\n\n\t\t\t\ttrak->sample_encryption = senc;\n\t\t\t\tif (!trak->child_boxes) trak->child_boxes = gf_list_new();\n\t\t\t\tgf_list_add(trak->child_boxes, senc);\n\t\t\t}\n\t\t}\n\n\t\t/*get sample auxiliary information by saiz/saio rather than by parsing senc box*/\n\t\tif (gf_isom_cenc_has_saiz_saio_traf(traf, scheme_type)) {\n\t\t\tu32 nb_saio;\n\t\t\tu32 aux_info_type;\n\t\t\tu64 offset;\n\t\t\tGF_Err e;\n\t\t\tBool is_encrypted;\n\t\t\tGF_SampleAuxiliaryInfoOffsetBox *saio = NULL;\n\t\t\tGF_SampleAuxiliaryInfoSizeBox *saiz = NULL;\n\n\t\t\toffset = nb_saio = 0;\n\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_offsets); i++) {\n\t\t\t\tsaio = (GF_SampleAuxiliaryInfoOffsetBox *)gf_list_get(traf->sai_offsets, i);\n\t\t\t\taux_info_type = saio->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\n\t\t\t\t/*if we have only 1 sai_offsets, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_offsets) == 1)) {\n\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n\t\t\t\t\tnb_saio = saio->entry_count;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_sizes); i++) {\n\t\t\t\tsaiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(traf->sai_sizes, i);\n\t\t\t\taux_info_type = saiz->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\t\t\t\t/*if we have only 1 sai_sizes, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_sizes) == 1)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (saiz && saio && senc) {\n\t\t\t\tfor (i = 0; i < saiz->sample_count; i++) {\n\t\t\t\t\tGF_CENCSampleAuxInfo *sai;\n\t\t\t\t\tconst u8 *key_info=NULL;\n\t\t\t\t\tu32 key_info_size;\n\t\t\t\t\tu64 cur_position;\n\t\t\t\t\tif (nb_saio != 1)\n\t\t\t\t\t\toffset = saio->offsets[i] + moof_offset;\n\t\t\t\t\tsize = saiz->default_sample_info_size ? saiz->default_sample_info_size : saiz->sample_info_size[i];\n\n\t\t\t\t\tcur_position = gf_bs_get_position(trak->moov->mov->movieFileMap->bs);\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, offset);\n\n\t\t\t\t\tGF_SAFEALLOC(sai, GF_CENCSampleAuxInfo);\n\t\t\t\t\tif (!sai) return GF_OUT_OF_MEM;\n\n\t\t\t\t\te = gf_isom_get_sample_cenc_info_internal(trak, traf, senc, i+1, &is_encrypted, NULL, NULL, &key_info, &key_info_size);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[isobmf] could not get cenc info for sample %d: %s\\n\", i+1, gf_error_to_string(e) ));\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (is_encrypted) {\n\t\t\t\t\t\tsai->cenc_data_size = size;\n\t\t\t\t\t\tsai->cenc_data = gf_malloc(sizeof(u8)*size);\n\t\t\t\t\t\tif (!sai->cenc_data) return GF_OUT_OF_MEM;\n\t\t\t\t\t\tgf_bs_read_data(trak->moov->mov->movieFileMap->bs, sai->cenc_data, sai->cenc_data_size);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsai->isNotProtected=1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (key_info) {\n\t\t\t\t\t\t//not multikey\n\t\t\t\t\t\tif (!key_info[0]) {\n\t\t\t\t\t\t\t//size greater than IV\n\t\t\t\t\t\t\tif (size > key_info[3])\n\t\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//multikey, always use subsamples\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, cur_position);\n\n\t\t\t\t\tgf_list_add(senc->samp_aux_info, sai);\n\n\t\t\t\t\te = gf_isom_cenc_merge_saiz_saio(senc, trak->Media->information->sampleTable, offset, size);\n\t\t\t\t\tif (e) return e;\n\t\t\t\t\tif (nb_saio == 1)\n\t\t\t\t\t\toffset += size;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (traf->sample_encryption) {\n\t\t\tsenc_Parse(trak->moov->mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\ttrak->sample_encryption->AlgorithmID = traf->sample_encryption->AlgorithmID;\n\t\t\tif (!trak->sample_encryption->IV_size)\n\t\t\t\ttrak->sample_encryption->IV_size = traf->sample_encryption->IV_size;\n\t\t\tif (!trak->sample_encryption->samp_aux_info) trak->sample_encryption->samp_aux_info = gf_list_new();\n\t\t\tgf_list_transfer(trak->sample_encryption->samp_aux_info, traf->sample_encryption->samp_aux_info);\n\t\t\tif (traf->sample_encryption->flags & 0x00000002)\n\t\t\t\ttrak->sample_encryption->flags |= 0x00000002;\n\t\t}\n\t}\n\treturn GF_OK;\n}", "func_hash": 137510724807707827211206951724769332151, "file_name": "track.c", "file_hash": 64556780743227222169140370119197040324, "cwe": ["CWE-476"], "cve": "CVE-2021-31260", "cve_desc": "The MergeTrack function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31260"} {"idx": 272325, "project": "gpac", "commit_id": "df8fffd839fe5ae9acd82d26fd48280a397411d9", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/df8fffd839fe5ae9acd82d26fd48280a397411d9", "commit_message": "fixed #1736", "target": 0, "func": "GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragmentBox *moof_box, u64 moof_offset, s32 compressed_diff, u64 *cumulated_offset, Bool is_first_merge)\n{\n\tu32 i, j, chunk_size, track_num;\n\tu64 base_offset, data_offset, traf_duration;\n\tu32 def_duration, DescIndex, def_size, def_flags;\n\tu32 duration, size, flags, prev_trun_data_offset, sample_index;\n\tu8 pad, sync;\n\tu16 degr;\n\tBool first_samp_in_traf=GF_TRUE;\n\tBool store_traf_map=GF_FALSE;\n\tu8 *moof_template=NULL;\n\tu32 moof_template_size=0;\n\tBool is_seg_start = GF_FALSE;\n\tu64 seg_start=0, sidx_start=0, sidx_end=0, frag_start=0, last_dts=0;\n\tGF_TrackFragmentRunBox *trun;\n\tGF_TrunEntry *ent;\n#ifdef GF_ENABLE_CTRN\n\tGF_TrackFragmentBox *traf_ref = NULL;\n#endif\n\n\tGF_Err stbl_AppendTime(GF_SampleTableBox *stbl, u32 duration, u32 nb_pack);\n\tGF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack);\n\tGF_Err stbl_AppendChunk(GF_SampleTableBox *stbl, u64 offset);\n\tGF_Err stbl_AppendSampleToChunk(GF_SampleTableBox *stbl, u32 DescIndex, u32 samplesInChunk);\n\tGF_Err stbl_AppendCTSOffset(GF_SampleTableBox *stbl, s32 CTSOffset);\n\tGF_Err stbl_AppendRAP(GF_SampleTableBox *stbl, u8 isRap);\n\tGF_Err stbl_AppendPadding(GF_SampleTableBox *stbl, u8 padding);\n\tGF_Err stbl_AppendDegradation(GF_SampleTableBox *stbl, u16 DegradationPriority);\n\n\tif (trak->Header->trackID != traf->tfhd->trackID) return GF_OK;\n\tif (!trak->Media->information->sampleTable\n\t\t|| !trak->Media->information->sampleTable->SampleSize\n\t\t|| !trak->Media->information->sampleTable->TimeToSample\n\t\t|| !trak->Media->information->sampleTable->SampleToChunk\n\t\t|| !trak->Media->information->sampleTable->ChunkOffset\n\t) {\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\tif (!traf->trex->track)\n\t\ttraf->trex->track = trak;\n\n\t//setup all our defaults\n\tDescIndex = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DESC) ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\tif (!DescIndex) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to 0, likely broken ! Fixing to 1\\n\" ));\n\t\tDescIndex = 1;\n\t} else if (DescIndex > gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to %d but only %d sample description(s), likely broken ! Fixing to 1\\n\", DescIndex, gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)));\n\t\tDescIndex = 1;\n\t}\n#ifdef GF_ENABLE_CTRN\n\tif (traf->trex->inherit_from_traf_id) {\n\t\tu32 traf_count = gf_list_count(moof_box->TrackList);\n\t\tfor (i=0; iTrackList, i);\n\t\t\tif (atraf->tfhd && atraf->tfhd->trackID==traf->trex->inherit_from_traf_id) {\n\t\t\t\ttraf_ref = atraf;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\tdef_duration = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DUR) ? traf->tfhd->def_sample_duration : traf->trex->def_sample_duration;\n\tdef_size = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_SIZE) ? traf->tfhd->def_sample_size : traf->trex->def_sample_size;\n\tdef_flags = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) ? traf->tfhd->def_sample_flags : traf->trex->def_sample_flags;\n\n\t//locate base offset, by default use moof (dash-like)\n\tbase_offset = moof_offset;\n\t//explicit base offset, use it\n\tif (traf->tfhd->flags & GF_ISOM_TRAF_BASE_OFFSET)\n\t\tbase_offset = traf->tfhd->base_data_offset;\n\t//no moof offset and no explicit offset, the offset is the end of the last written chunk of\n\t//the previous traf. For the first traf, *cumulated_offset is actually moof offset\n\telse if (!(traf->tfhd->flags & GF_ISOM_MOOF_BASE_OFFSET))\n\t\tbase_offset = *cumulated_offset;\n\n\tchunk_size = 0;\n\tprev_trun_data_offset = 0;\n\tdata_offset = 0;\n\ttraf_duration = 0;\n\n\t/*in playback mode*/\n\tif (traf->tfdt && is_first_merge) {\n#ifndef GPAC_DISABLE_LOG\n\t\tif (trak->moov->mov->NextMoofNumber && trak->present_in_scalable_segment && trak->sample_count_at_seg_start && (trak->dts_at_seg_start != traf->tfdt->baseMediaDecodeTime)) {\n\t\t\ts32 drift = (s32) ((s64) traf->tfdt->baseMediaDecodeTime - (s64)trak->dts_at_seg_start);\n\t\t\tif (drift<0) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Warning: TFDT timing \"LLD\" less than cumulated timing \"LLD\" - using tfdt\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"[iso file] TFDT timing \"LLD\" higher than cumulated timing \"LLD\" (last sample got extended in duration)\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t}\n\t\t}\n#endif\n\t\ttrak->dts_at_seg_start = traf->tfdt->baseMediaDecodeTime;\n\t}\n\telse if (traf->tfxd) {\n\t\ttrak->dts_at_seg_start = traf->tfxd->absolute_time_in_track_timescale;\n\t}\n\n\tif (traf->tfxd) {\n\t\ttrak->last_tfxd_value = traf->tfxd->absolute_time_in_track_timescale;\n\t\ttrak->last_tfxd_value += traf->tfxd->fragment_duration_in_track_timescale;\n\t}\n\tif (traf->tfrf) {\n\t\tif (trak->tfrf) gf_isom_box_del_parent(&trak->child_boxes, (GF_Box *)trak->tfrf);\n\t\ttrak->tfrf = traf->tfrf;\n\t\tgf_list_del_item(traf->child_boxes, traf->tfrf);\n\t\tgf_list_add(trak->child_boxes, trak->tfrf);\n\t}\n\n\tif (trak->moov->mov->signal_frag_bounds) {\n\t\tstore_traf_map = GF_TRUE;\n\t\tif (is_first_merge) {\n\t\t\tGF_MovieFragmentBox *moof_clone = NULL;\n\t\t\tgf_isom_box_freeze_order((GF_Box *)moof_box);\n\t\t\tgf_isom_clone_box((GF_Box *)moof_box, (GF_Box **)&moof_clone);\n\n\t\t\tif (moof_clone) {\n\t\t\t\tGF_BitStream *bs;\n\t\t\t\tfor (i=0; iTrackList); i++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf_clone = gf_list_get(moof_clone->TrackList, i);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->TrackRuns);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroups);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroupsDescription);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sub_samples);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_offsets);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_sizes);\n\t\t\t\t\tif (traf_clone->sample_encryption) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sample_encryption);\n\t\t\t\t\t\ttraf_clone->sample_encryption = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tif (traf_clone->sdtp) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sdtp);\n\t\t\t\t\t\ttraf_clone->sdtp = NULL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_isom_box_size((GF_Box *)moof_clone);\n\t\t\t\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\n\t\t\t\tif (trak->moov->mov->seg_styp) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_styp);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_styp, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->root_sidx) {\n\t\t\t\t\tgf_isom_box_size((GF_Box *)trak->moov->mov->root_sidx);\n\t\t\t\t\tgf_isom_box_write((GF_Box *)trak->moov->mov->root_sidx, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->seg_ssix) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_ssix);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_ssix, bs);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_write((GF_Box *)moof_clone, bs);\n\t\t\t\tgf_isom_box_del((GF_Box*)moof_clone);\n\n\t\t\t\tgf_bs_get_content(bs, &moof_template, &moof_template_size);\n\t\t\t\tgf_bs_del(bs);\n\t\t\t}\n\t\t}\n\t\tif (trak->moov->mov->seg_styp) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tseg_start = trak->moov->mov->styp_start_offset;\n\t\t}\n\t\tif (trak->moov->mov->root_sidx) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tsidx_start = trak->moov->mov->sidx_start_offset;\n\t\t\tsidx_end = trak->moov->mov->sidx_end_offset;\n\t\t\tif (! seg_start || (sidx_startmoov->mov->current_top_box_start;\n\t}\n\telse if (trak->moov->mov->store_traf_map) {\n\t\tstore_traf_map = GF_TRUE;\n\t}\n\n\n\tsample_index = 0;\n\ti=0;\n\twhile ((trun = (GF_TrackFragmentRunBox *)gf_list_enum(traf->TrackRuns, &i))) {\n\t\t//merge the run\n\t\tfor (j=0; jsample_count; j++) {\n\t\t\tGF_Err e;\n\t\t\ts32 cts_offset=0;\n\t\t\tif (jnb_samples) {\n\t\t\t\tent = &trun->samples[j];\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d doesn't have enough trun entries (%d) compared to sample count (%d) in run\\n\", traf->trex->trackID, trun->nb_samples, trun->sample_count ));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsize = def_size;\n\t\t\tduration = def_duration;\n\t\t\tflags = def_flags;\n\n\t\t\t//CTS - if flag not set (trun or ctrn) defaults to 0 which is the base value after alloc\n\t\t\t//we just need to overrite its value if inherited\n\t\t\tcts_offset = ent->CTS_Offset;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (trun->use_ctrn) {\n\t\t\t\tif (!j && (trun->ctrn_flags & GF_ISOM_CTRN_FIRST_SAMPLE) ) {\n\t\t\t\t\tif (trun->ctrn_first_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_first_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_first_ctts) flags = ent->flags;\n\t\t\t\t} else {\n\t\t\t\t\tif (trun->ctrn_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_sample_flags) flags = ent->flags;\n\t\t\t\t}\n\t\t\t\t/*re-override*/\n\t\t\t\tif (trun->ctrn_flags & 0xF0) {\n\t\t\t\t\tGF_TrunEntry *ref_entry;\n\t\t\t\t\tif (!traf_ref) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance to track ID %d but reference traf not found\\n\", traf->trex->trackID, traf->trex->inherit_from_traf_id ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tref_entry = traf_get_sample_entry(traf_ref, sample_index);\n\t\t\t\t\tif (!ref_entry) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance but sample %d not found in reference traf\\n\", traf->trex->trackID, sample_index+1 ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_DUR)\n\t\t\t\t\t\tduration = ref_entry->Duration;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_SIZE)\n\t\t\t\t\t\tsize = ref_entry->size;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_FLAGS)\n\t\t\t\t\t\tflags = ref_entry->flags;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_CTSO)\n\t\t\t\t\t\tcts_offset = ref_entry->CTS_Offset;\n\t\t\t\t}\n\n\t\t\t} else\n#endif\n\t\t\t{\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DURATION) duration = ent->Duration;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_SIZE) size = ent->size;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_FLAGS) {\n\t\t\t\t\tflags = ent->flags;\n\t\t\t\t} else if (!j && (trun->flags & GF_ISOM_TRUN_FIRST_FLAG)) {\n\t\t\t\t\tflags = trun->first_sample_flags;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsample_index++;\n\t\t\t/*store the resolved value in case we have inheritance*/\n\t\t\tent->size = size;\n\t\t\tent->Duration = duration;\n\t\t\tent->flags = flags;\n\t\t\tent->CTS_Offset = cts_offset;\n\n\t\t\tlast_dts += duration;\n\n\t\t\t//add size first\n\t\t\tif (!trak->Media->information->sampleTable->SampleSize) {\n\t\t\t\ttrak->Media->information->sampleTable->SampleSize = (GF_SampleSizeBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSZ);\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleSize)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendSize(trak->Media->information->sampleTable, size, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//then TS\n\t\t\tif (!trak->Media->information->sampleTable->TimeToSample) {\n\t\t\t\ttrak->Media->information->sampleTable->TimeToSample = (GF_TimeToSampleBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STTS);\n\t\t\t\tif (!trak->Media->information->sampleTable->TimeToSample)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendTime(trak->Media->information->sampleTable, duration, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//add chunk on first sample\n\t\t\tif (!j) {\n\t\t\t\tu64 final_offset;\n\t\t\t\tdata_offset = base_offset;\n\t\t\t\t//we have an explicit data offset for this trun\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DATA_OFFSET) {\n\t\t\t\t\tdata_offset += trun->data_offset;\n\t\t\t\t\t/*reset chunk size since data is now relative to this trun*/\n\t\t\t\t\tchunk_size = 0;\n\t\t\t\t\t/*remember this data offset for following trun*/\n\t\t\t\t\tprev_trun_data_offset = trun->data_offset;\n\t\t\t\t\t/*if mdat is located after the moof, and the moof was compressed, adjust offset\n\t\t\t\t\totherwise the offset does not need adjustment*/\n\t\t\t\t\tif (trun->data_offset>=0) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t\tprev_trun_data_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//we had an explicit data offset for the previous trun, use it + chunk size\n\t\t\t\telse if (prev_trun_data_offset) {\n\t\t\t\t\t/*data offset is previous chunk size plus previous offset of the trun*/\n\t\t\t\t\tdata_offset += prev_trun_data_offset + chunk_size;\n\t\t\t\t}\n\t\t\t\t//no explicit data offset, continuous data after last data in previous chunk\n\t\t\t\telse {\n\t\t\t\t\tdata_offset += chunk_size;\n\t\t\t\t\t//data offset of first trun in first traf, adjust if compressed moof\n\t\t\t\t\tif ((i==1) && (trun->data_offset>=0)) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinal_offset = data_offset;\n\t\t\t\t//adjust offset if moov was also compressed and we are still in the same file\n\t\t\t\t//so that later call to gf_isom_get_sample properly adjust back the offset\n\t\t\t\tif (trak->moov->compressed_diff) {\n\t\t\t\t\tfinal_offset += trak->moov->compressed_diff;\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset) {\n\t\t\t\t\ttrak->Media->information->sampleTable->ChunkOffset = gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STCO);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendChunk(trak->Media->information->sampleTable, final_offset);\n\t\t\t\tif (e) return e;\n\t\t\t\t//then sampleToChunk\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk) {\n\t\t\t\t\ttrak->Media->information->sampleTable->SampleToChunk = (GF_SampleToChunkBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSC);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendSampleToChunk(trak->Media->information->sampleTable,\n\t\t\t\t DescIndex, trun->sample_count);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tchunk_size += size;\n\n\t\t\tif (store_traf_map && first_samp_in_traf) {\n\t\t\t\tfirst_samp_in_traf = GF_FALSE;\n\t\t\t\te = stbl_AppendTrafMap(trak->Media->information->sampleTable, is_seg_start, seg_start, frag_start, moof_template, moof_template_size, sidx_start, sidx_end);\n\t\t\t\tif (e) return e;\n\t\t\t\t//do not deallocate, the memory is now owned by traf map\n\t\t\t\tmoof_template = NULL;\n\t\t\t\tmoof_template_size = 0;\n\t\t\t}\n\t\t\tif (ent->nb_pack>1) {\n\t\t\t\tj+= ent->nb_pack-1;\n\t\t\t\ttraf_duration += ent->nb_pack*duration;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttraf_duration += duration;\n\n\t\t\te = stbl_AppendCTSOffset(trak->Media->information->sampleTable, cts_offset);\n\t\t\tif (e) return e;\n\t\t\t//flags\n\t\t\tsync = GF_ISOM_GET_FRAG_SYNC(flags);\n\t\t\tif (trak->Media->information->sampleTable->no_sync_found && sync) {\n\t\t\t\ttrak->Media->information->sampleTable->no_sync_found = 0;\n\t\t\t}\n\t\t\te = stbl_AppendRAP(trak->Media->information->sampleTable, sync);\n\t\t\tif (e) return e;\n\t\t\tpad = GF_ISOM_GET_FRAG_PAD(flags);\n\t\t\tif (pad) {\n\t\t\t\te = stbl_AppendPadding(trak->Media->information->sampleTable, pad);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tdegr = GF_ISOM_GET_FRAG_DEG(flags);\n\t\t\tif (degr) {\n\t\t\t\te = stbl_AppendDegradation(trak->Media->information->sampleTable, degr);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\te = stbl_AppendDependencyType(trak->Media->information->sampleTable, GF_ISOM_GET_FRAG_LEAD(flags), GF_ISOM_GET_FRAG_DEPENDS(flags), GF_ISOM_GET_FRAG_DEPENDED(flags), GF_ISOM_GET_FRAG_REDUNDANT(flags));\n\t\t\tif (e) return e;\n\t\t}\n\t}\n\n\tif (trak->moov->mov->is_smooth && !traf->tfdt && !traf->tfxd) {\n\t\tif (is_first_merge)\n\t\t\ttrak->dts_at_seg_start = trak->dts_at_next_seg_start;\n\t\ttrak->dts_at_next_seg_start += last_dts;\n\t}\n\tif (traf_duration && trak->editBox && trak->editBox->editList) {\n\t\tfor (i=0; ieditBox->editList->entryList); i++) {\n\t\t\tGF_EdtsEntry *edts_e = gf_list_get(trak->editBox->editList->entryList, i);\n\t\t\tif (edts_e->was_empty_dur) {\n\t\t\t\tu64 extend_dur = traf_duration;\n\t\t\t\textend_dur *= trak->moov->mvhd->timeScale;\n\t\t\t\textend_dur /= trak->Media->mediaHeader->timeScale;\n\t\t\t\tedts_e->segmentDuration += extend_dur;\n\t\t\t}\n\t\t\telse if (!edts_e->segmentDuration) {\n\t\t\t\tedts_e->was_empty_dur = GF_TRUE;\n\t\t\t\tif ((s64) traf_duration > edts_e->mediaTime)\n\t\t\t\t\ttraf_duration -= edts_e->mediaTime;\n\t\t\t\telse\n\t\t\t\t\ttraf_duration = 0;\n\n\t\t\t\tedts_e->segmentDuration = traf_duration;\n\t\t\t\tedts_e->segmentDuration *= trak->moov->mvhd->timeScale;\n\t\t\t\tedts_e->segmentDuration /= trak->Media->mediaHeader->timeScale;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//in any case, update the cumulated offset\n\t//this will handle hypothetical files mixing MOOF offset and implicit non-moof offset\n\t*cumulated_offset = data_offset + chunk_size;\n\n\t/*merge sample groups*/\n\tif (traf->sampleGroups) {\n\t\tGF_List *groups;\n\t\tGF_List *groupDescs;\n\t\tBool is_identical_sgpd = GF_TRUE;\n\t\tu32 *new_idx = NULL, new_idx_count=0;\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroups)\n\t\t\ttrak->Media->information->sampleTable->sampleGroups = gf_list_new();\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroupsDescription)\n\t\t\ttrak->Media->information->sampleTable->sampleGroupsDescription = gf_list_new();\n\n\t\tgroupDescs = trak->Media->information->sampleTable->sampleGroupsDescription;\n\t\tfor (i=0; isampleGroupsDescription); i++) {\n\t\t\tGF_SampleGroupDescriptionBox *new_sgdesc = NULL;\n\t\t\tGF_SampleGroupDescriptionBox *sgdesc = gf_list_get(traf->sampleGroupsDescription, i);\n\t\t\tfor (j=0; jgrouping_type==sgdesc->grouping_type) break;\n\t\t\t\tnew_sgdesc = NULL;\n\t\t\t}\n\t\t\t/*new description, move it to our sample table*/\n\t\t\tif (!new_sgdesc) {\n\t\t\t\tgf_list_add(groupDescs, sgdesc);\n\t\t\t\tgf_list_add(trak->Media->information->sampleTable->child_boxes, sgdesc);\n\t\t\t\tgf_list_rem(traf->sampleGroupsDescription, i);\n\t\t\t\tgf_list_del_item(traf->child_boxes, sgdesc);\n\t\t\t\ti--;\n\t\t\t}\n\t\t\t/*merge descriptions*/\n\t\t\telse {\n\t\t\t\tu32 count;\n\n\t\t\t\tis_identical_sgpd = gf_isom_is_identical_sgpd(new_sgdesc, sgdesc, 0);\n\t\t\t\tif (is_identical_sgpd)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tnew_idx_count = gf_list_count(sgdesc->group_descriptions);\n\t\t\t\tnew_idx = (u32 *)gf_malloc(new_idx_count * sizeof(u32));\n\t\t\t\tif (!new_idx) return GF_OUT_OF_MEM;\n\n\t\t\t\tcount = 0;\n\t\t\t\twhile (gf_list_count(sgdesc->group_descriptions)) {\n\t\t\t\t\tvoid *sgpd_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\t\t\tBool new_entry = GF_TRUE;\n\n\t\t\t\t\tfor (j = 0; j < gf_list_count(new_sgdesc->group_descriptions); j++) {\n\t\t\t\t\t\tvoid *ptr = gf_list_get(new_sgdesc->group_descriptions, j);\n\t\t\t\t\t\tif (gf_isom_is_identical_sgpd(sgpd_entry, ptr, new_sgdesc->grouping_type)) {\n\t\t\t\t\t\t\tnew_idx[count] = j + 1;\n\t\t\t\t\t\t\tcount ++;\n\t\t\t\t\t\t\tnew_entry = GF_FALSE;\n\t\t\t\t\t\t\tgf_free(sgpd_entry);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (new_entry) {\n\t\t\t\t\t\tgf_list_add(new_sgdesc->group_descriptions, sgpd_entry);\n\t\t\t\t\t\tnew_idx[count] = gf_list_count(new_sgdesc->group_descriptions);\n\t\t\t\t\t\tcount ++;\n\t\t\t\t\t}\n\n\t\t\t\t\tgf_list_rem(sgdesc->group_descriptions, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tgroups = trak->Media->information->sampleTable->sampleGroups;\n\t\tfor (i=0; isampleGroups); i++) {\n\t\t\tGF_SampleGroupBox *stbl_group = NULL;\n\t\t\tGF_SampleGroupBox *frag_group = gf_list_get(traf->sampleGroups, i);\n\n\n\t\t\tfor (j=0; jgrouping_type==stbl_group->grouping_type) && (frag_group->grouping_type_parameter==stbl_group->grouping_type_parameter))\n\t\t\t\t\tbreak;\n\t\t\t\tstbl_group = NULL;\n\t\t\t}\n\t\t\tif (!stbl_group) {\n\t\t\t\tstbl_group = (GF_SampleGroupBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_SBGP);\n\t\t\t\tif (!stbl_group) return GF_OUT_OF_MEM;\n\t\t\t\tstbl_group->grouping_type = frag_group->grouping_type;\n\t\t\t\tstbl_group->grouping_type_parameter = frag_group->grouping_type_parameter;\n\t\t\t\tstbl_group->version = frag_group->version;\n\t\t\t\tgf_list_add(groups, stbl_group);\n\t\t\t}\n\n\t\t\tif (is_identical_sgpd) {\n\t\t\t\t//adjust sgpd index: in traf index start at 0x1001\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++)\n\t\t\t\t\tfrag_group->sample_entries[j].group_description_index &= 0x0FFFF;\n\t\t\t\tif (frag_group->entry_count && stbl_group->entry_count &&\n\t\t\t\t (frag_group->sample_entries[0].group_description_index==stbl_group->sample_entries[stbl_group->entry_count-1].group_description_index)\n\t\t\t\t ) {\n\t\t\t\t\tstbl_group->sample_entries[stbl_group->entry_count - 1].sample_count += frag_group->sample_entries[0].sample_count;\n\t\t\t\t\tif (frag_group->entry_count>1) {\n\t\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count - 1));\n\t\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[1], sizeof(GF_SampleGroupEntry) * (frag_group->entry_count - 1));\n\t\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count - 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t//adjust sgpd index\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++) {\n\t\t\t\t\tu32 sgidx = frag_group->sample_entries[j].group_description_index;\n\t\t\t\t\tif (sgidx > 0x10000) {\n\t\t\t\t\t\tsgidx -= 0x10001;\n\t\t\t\t\t\tif (sgidx>=new_idx_count) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[isobmf] corrupted sample group index in fragment %d but only %d group descriptions in fragment\\n\", sgidx, new_idx_count));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfrag_group->sample_entries[j].group_description_index = new_idx[sgidx];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t}\n\t\t}\n\n\t\tif (new_idx) gf_free(new_idx);\n\t}\n\n\t/*content is encrypted*/\n\ttrack_num = gf_isom_get_tracknum_from_id(trak->moov, trak->Header->trackID);\n\tif (gf_isom_is_cenc_media(trak->moov->mov, track_num, DescIndex)\n\t\t|| traf->sample_encryption) {\n\t\t/*Merge sample auxiliary encryption information*/\n\t\tGF_SampleEncryptionBox *senc = NULL;\n\t\tu32 scheme_type;\n\t\tgf_isom_get_cenc_info(trak->moov->mov, track_num, DescIndex, NULL, &scheme_type, NULL);\n\n\t\tif (traf->sample_encryption) {\n\t\t\tfor (i = 0; i < gf_list_count(trak->Media->information->sampleTable->child_boxes); i++) {\n\t\t\t\tGF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->child_boxes, i);\n\t\t\t\tif (a->type != traf->sample_encryption->type) continue;\n\n\t\t\t\tif ((a->type ==GF_ISOM_BOX_TYPE_UUID) && (((GF_UUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC)) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (a->type ==GF_ISOM_BOX_TYPE_SENC) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!senc && trak->sample_encryption)\n\t\t\t\tsenc = trak->sample_encryption;\n\n\t\t\tif (!senc) {\n\t\t\t\tif (traf->sample_encryption->piff_type==1) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)gf_isom_create_piff_psec_box(1, 0x2, 0, 0, NULL);\n\t\t\t\t} else {\n\t\t\t\t\tsenc = gf_isom_create_samp_enc_box(1, 0x2);\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->child_boxes) trak->Media->information->sampleTable->child_boxes = gf_list_new();\n\n\t\t\t\ttrak->sample_encryption = senc;\n\t\t\t\tif (!trak->child_boxes) trak->child_boxes = gf_list_new();\n\t\t\t\tgf_list_add(trak->child_boxes, senc);\n\t\t\t}\n\t\t}\n\n\t\t/*get sample auxiliary information by saiz/saio rather than by parsing senc box*/\n\t\tif (gf_isom_cenc_has_saiz_saio_traf(traf, scheme_type)) {\n\t\t\tu32 nb_saio;\n\t\t\tu32 aux_info_type;\n\t\t\tu64 offset;\n\t\t\tGF_Err e;\n\t\t\tBool is_encrypted;\n\t\t\tGF_SampleAuxiliaryInfoOffsetBox *saio = NULL;\n\t\t\tGF_SampleAuxiliaryInfoSizeBox *saiz = NULL;\n\n\t\t\toffset = nb_saio = 0;\n\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_offsets); i++) {\n\t\t\t\tsaio = (GF_SampleAuxiliaryInfoOffsetBox *)gf_list_get(traf->sai_offsets, i);\n\t\t\t\taux_info_type = saio->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\n\t\t\t\t/*if we have only 1 sai_offsets, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_offsets) == 1)) {\n\t\t\t\t\tif (saio->offsets && saio->entry_count) {\n\t\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n\t\t\t\t\t\tnb_saio = saio->entry_count;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsaio = NULL;\n\t\t\t}\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_sizes); i++) {\n\t\t\t\tsaiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(traf->sai_sizes, i);\n\t\t\t\taux_info_type = saiz->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\t\t\t\t/*if we have only 1 sai_sizes, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_sizes) == 1)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsaiz = NULL;\n\t\t\t}\n\t\t\tif (saiz && saio && senc) {\n\t\t\t\tfor (i = 0; i < saiz->sample_count; i++) {\n\t\t\t\t\tGF_CENCSampleAuxInfo *sai;\n\t\t\t\t\tconst u8 *key_info=NULL;\n\t\t\t\t\tu32 key_info_size;\n\t\t\t\t\tu64 cur_position;\n\t\t\t\t\tif (nb_saio != 1)\n\t\t\t\t\t\toffset = saio->offsets[i] + moof_offset;\n\t\t\t\t\tsize = saiz->default_sample_info_size ? saiz->default_sample_info_size : saiz->sample_info_size[i];\n\n\t\t\t\t\tcur_position = gf_bs_get_position(trak->moov->mov->movieFileMap->bs);\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, offset);\n\n\t\t\t\t\tGF_SAFEALLOC(sai, GF_CENCSampleAuxInfo);\n\t\t\t\t\tif (!sai) return GF_OUT_OF_MEM;\n\n\t\t\t\t\te = gf_isom_get_sample_cenc_info_internal(trak, traf, senc, i+1, &is_encrypted, NULL, NULL, &key_info, &key_info_size);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[isobmf] could not get cenc info for sample %d: %s\\n\", i+1, gf_error_to_string(e) ));\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (is_encrypted) {\n\t\t\t\t\t\tsai->cenc_data_size = size;\n\t\t\t\t\t\tsai->cenc_data = gf_malloc(sizeof(u8)*size);\n\t\t\t\t\t\tif (!sai->cenc_data) return GF_OUT_OF_MEM;\n\t\t\t\t\t\tgf_bs_read_data(trak->moov->mov->movieFileMap->bs, sai->cenc_data, sai->cenc_data_size);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsai->isNotProtected=1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (key_info) {\n\t\t\t\t\t\t//not multikey\n\t\t\t\t\t\tif (!key_info[0]) {\n\t\t\t\t\t\t\t//size greater than IV\n\t\t\t\t\t\t\tif (size > key_info[3])\n\t\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//multikey, always use subsamples\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, cur_position);\n\n\t\t\t\t\tgf_list_add(senc->samp_aux_info, sai);\n\n\t\t\t\t\te = gf_isom_cenc_merge_saiz_saio(senc, trak->Media->information->sampleTable, offset, size);\n\t\t\t\t\tif (e) return e;\n\t\t\t\t\tif (nb_saio == 1)\n\t\t\t\t\t\toffset += size;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (traf->sample_encryption) {\n\t\t\tsenc_Parse(trak->moov->mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\ttrak->sample_encryption->AlgorithmID = traf->sample_encryption->AlgorithmID;\n\t\t\tif (!trak->sample_encryption->IV_size)\n\t\t\t\ttrak->sample_encryption->IV_size = traf->sample_encryption->IV_size;\n\t\t\tif (!trak->sample_encryption->samp_aux_info) trak->sample_encryption->samp_aux_info = gf_list_new();\n\t\t\tgf_list_transfer(trak->sample_encryption->samp_aux_info, traf->sample_encryption->samp_aux_info);\n\t\t\tif (traf->sample_encryption->flags & 0x00000002)\n\t\t\t\ttrak->sample_encryption->flags |= 0x00000002;\n\t\t}\n\t}\n\treturn GF_OK;\n}", "func_hash": 27964125637319559355016864333099885959, "file_name": "track.c", "file_hash": 282279983561684757889571324858568848947, "cwe": ["CWE-476"], "cve": "CVE-2021-31260", "cve_desc": "The MergeTrack function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31260"} {"idx": 198349, "project": "tensorflow", "commit_id": "4253f96a58486ffe84b61c0415bb234a4632ee73", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4253f96a58486ffe84b61c0415bb234a4632ee73", "commit_message": "Fix integer overflow in TFLite concat\n\nPiperOrigin-RevId: 371013841\nChange-Id: I6a4782ce7ca753e23ff31e7fb6aeb7f9d412cd29", "target": 1, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n int axis = params->axis;\n int num_inputs = node->inputs->size;\n\n // The number of dimensions of the input tensors must match, and all\n // dimensions except 'axis' must be equal.\n const TfLiteTensor* t0;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0));\n TfLiteType input_type = t0->type;\n if (axis < 0) axis += t0->dims->size;\n TF_LITE_ENSURE(context, axis >= 0);\n TF_LITE_ENSURE(context, axis < t0->dims->size);\n\n TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone);\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||\n input_type == kTfLiteInt32 || input_type == kTfLiteInt64 ||\n input_type == kTfLiteBool);\n\n // Output dimensions will match input dimensions, except 'axis', which\n // will be the sum of inputs\n int sum_axis = t0->dims->data[axis];\n for (int i = 1; i < num_inputs; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size);\n TF_LITE_ENSURE_EQ(context, t->type, input_type);\n for (int d = 0; d < t0->dims->size; ++d) {\n if (d == axis) {\n sum_axis += t->dims->data[axis];\n } else {\n TF_LITE_ENSURE_EQ(context, t->dims->data[d], t0->dims->data[d]);\n }\n }\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(t0->dims->size);\n for (int d = 0; d < t0->dims->size; ++d) {\n output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d];\n }\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type);\n\n if (input_type == kTfLiteInt8) {\n // Make sure there is no re-scaling needed for Int8 quantized kernel. This\n // is a restriction we introduced to Int8 kernels.\n VectorOfTensors all_inputs(*context, *node->inputs);\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point,\n output->params.zero_point);\n }\n }\n\n if (input_type == kTfLiteInt16) {\n // Make sure that all Int16 inputs have a null zero-point.\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t = GetInput(context, node, i);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point, 0);\n }\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "func_hash": 224701039406132273250932089664065250335, "file_name": "concatenation.cc", "file_hash": 18994167719758144984877147039224389652, "cwe": ["CWE-476"], "cve": "CVE-2021-29601", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The TFLite implementation of concatenation is vulnerable to an integer overflow issue(https://github.com/tensorflow/tensorflow/blob/7b7352a724b690b11bfaae2cd54bc3907daf6285/tensorflow/lite/kernels/concatenation.cc#L70-L76). An attacker can craft a model such that the dimensions of one of the concatenation input overflow the values of `int`. TFLite uses `int` to represent tensor dimensions, whereas TF uses `int64`. Hence, valid TF models can trigger an integer overflow when converted to TFLite format. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29601"} {"idx": 273050, "project": "tensorflow", "commit_id": "4253f96a58486ffe84b61c0415bb234a4632ee73", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4253f96a58486ffe84b61c0415bb234a4632ee73", "commit_message": "Fix integer overflow in TFLite concat\n\nPiperOrigin-RevId: 371013841\nChange-Id: I6a4782ce7ca753e23ff31e7fb6aeb7f9d412cd29", "target": 0, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n int axis = params->axis;\n int num_inputs = node->inputs->size;\n\n // The number of dimensions of the input tensors must match, and all\n // dimensions except 'axis' must be equal.\n const TfLiteTensor* t0;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0));\n TfLiteType input_type = t0->type;\n if (axis < 0) axis += t0->dims->size;\n TF_LITE_ENSURE(context, axis >= 0);\n TF_LITE_ENSURE(context, axis < t0->dims->size);\n\n TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone);\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||\n input_type == kTfLiteInt32 || input_type == kTfLiteInt64 ||\n input_type == kTfLiteBool);\n\n // Output dimensions will match input dimensions, except 'axis', which\n // will be the sum of inputs\n int sum_axis = t0->dims->data[axis];\n for (int i = 1; i < num_inputs; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size);\n TF_LITE_ENSURE_EQ(context, t->type, input_type);\n for (int d = 0; d < t0->dims->size; ++d) {\n if (d == axis) {\n // Avoid integer overflow in sum_axis below\n TF_LITE_ENSURE(context, t->dims->data[axis] >= 0);\n TF_LITE_ENSURE(context, t->dims->data[axis] <=\n std::numeric_limits::max() - sum_axis);\n sum_axis += t->dims->data[axis];\n } else {\n TF_LITE_ENSURE_EQ(context, t->dims->data[d], t0->dims->data[d]);\n }\n }\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(t0->dims->size);\n for (int d = 0; d < t0->dims->size; ++d) {\n output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d];\n }\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type);\n\n if (input_type == kTfLiteInt8) {\n // Make sure there is no re-scaling needed for Int8 quantized kernel. This\n // is a restriction we introduced to Int8 kernels.\n VectorOfTensors all_inputs(*context, *node->inputs);\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point,\n output->params.zero_point);\n }\n }\n\n if (input_type == kTfLiteInt16) {\n // Make sure that all Int16 inputs have a null zero-point.\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t = GetInput(context, node, i);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point, 0);\n }\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "func_hash": 79891174955770203143331492144301757897, "file_name": "concatenation.cc", "file_hash": 25040922309420915234539500051914926902, "cwe": ["CWE-476"], "cve": "CVE-2021-29601", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The TFLite implementation of concatenation is vulnerable to an integer overflow issue(https://github.com/tensorflow/tensorflow/blob/7b7352a724b690b11bfaae2cd54bc3907daf6285/tensorflow/lite/kernels/concatenation.cc#L70-L76). An attacker can craft a model such that the dimensions of one of the concatenation input overflow the values of `int`. TFLite uses `int` to represent tensor dimensions, whereas TF uses `int64`. Hence, valid TF models can trigger an integer overflow when converted to TFLite format. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29601"} {"idx": 198370, "project": "inspircd", "commit_id": "4350a11c663b0d75f8119743bffb7736d87abd4d", "project_url": "https://github.com/inspircd/inspircd", "commit_url": "https://github.com/inspircd/inspircd/commit/4350a11c663b0d75f8119743bffb7736d87abd4d", "commit_message": "Fix sending malformed pong messages in some cases.", "target": 1, "func": "\tPong(const std::string& cookie, const std::string& server = \"\")\n\t\t: ClientProtocol::Message(\"PONG\", ServerInstance->Config->GetServerName())\n\t{\n\t\tPushParamRef(ServerInstance->Config->GetServerName());\n\t\tif (!server.empty())\n\t\t\tPushParamRef(server);\n\t\tPushParamRef(cookie);\n\t}", "func_hash": 296394883430475052611691801068783768824, "file_name": "clientprotocolmsg.h", "file_hash": 230213903956800443490285907454868592213, "cwe": ["CWE-200"], "cve": "CVE-2021-33586", "cve_desc": "InspIRCd 3.8.0 through 3.9.x before 3.10.0 allows any user (able to connect to the server) to access recently deallocated memory, aka the \"malformed PONG\" issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33586"} {"idx": 273215, "project": "inspircd", "commit_id": "4350a11c663b0d75f8119743bffb7736d87abd4d", "project_url": "https://github.com/inspircd/inspircd", "commit_url": "https://github.com/inspircd/inspircd/commit/4350a11c663b0d75f8119743bffb7736d87abd4d", "commit_message": "Fix sending malformed pong messages in some cases.", "target": 0, "func": "\tPong(const std::string& cookie, const std::string& server = \"\")\n\t\t: ClientProtocol::Message(\"PONG\", ServerInstance->Config->GetServerName())\n\t{\n\t\tif (server.empty())\n\t\t\tPushParamRef(ServerInstance->Config->GetServerName());\n\t\telse\n\t\t\tPushParam(server);\n\t\tPushParamRef(cookie);\n\t}", "func_hash": 113509034929303689157143918941820510261, "file_name": "clientprotocolmsg.h", "file_hash": 191742783054767097839440710244305356067, "cwe": ["CWE-200"], "cve": "CVE-2021-33586", "cve_desc": "InspIRCd 3.8.0 through 3.9.x before 3.10.0 allows any user (able to connect to the server) to access recently deallocated memory, aka the \"malformed PONG\" issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33586"} {"idx": 198372, "project": "FFmpeg", "commit_id": "a3a3730b5456ca00587455004d40c047f7b20a99", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/a3a3730b5456ca00587455004d40c047f7b20a99", "commit_message": "avcodec/cbs_jpeg: Check length for SOS\n\nFixes: out of array access\nFixes: 19734/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5673507031875584\nFixes: 19353/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5703944462663680\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 1812352d767ccf5431aa440123e2e260a4db2726)\nSigned-off-by: Michael Niedermayer ", "target": 1, "func": "static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,\n CodedBitstreamFragment *frag,\n int header)\n{\n AVBufferRef *data_ref;\n uint8_t *data;\n size_t data_size;\n int unit, start, end, marker, next_start, next_marker;\n int err, i, j, length;\n\n if (frag->data_size < 4) {\n // Definitely too short to be meaningful.\n return AVERROR_INVALIDDATA;\n }\n\n for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);\n if (i > 0) {\n av_log(ctx->log_ctx, AV_LOG_WARNING, \"Discarding %d bytes at \"\n \"beginning of image.\\n\", i);\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size && frag->data[i]) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no SOI marker found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n if (marker != JPEG_MARKER_SOI) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: first \"\n \"marker is %02x, should be SOI.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no image content found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n start = i + 1;\n\n for (unit = 0;; unit++) {\n if (marker == JPEG_MARKER_EOI) {\n break;\n } else if (marker == JPEG_MARKER_SOS) {\n for (i = start; i + 1 < frag->data_size; i++) {\n if (frag->data[i] != 0xff)\n continue;\n end = i;\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n if (frag->data[i] == 0x00)\n continue;\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n break;\n }\n } else {\n i = start;\n if (i + 2 > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n length = AV_RB16(frag->data + i);\n if (i + length > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker segment.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n end = start + length;\n\n i = end;\n if (frag->data[i] != 0xff) {\n next_marker = -1;\n } else {\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n }\n }\n\n if (marker == JPEG_MARKER_SOS) {\n length = AV_RB16(frag->data + start);\n\n data_ref = NULL;\n data = av_malloc(end - start +\n AV_INPUT_BUFFER_PADDING_SIZE);\n if (!data)\n return AVERROR(ENOMEM);\n\n memcpy(data, frag->data + start, length);\n for (i = start + length, j = length; i < end; i++, j++) {\n if (frag->data[i] == 0xff) {\n while (frag->data[i] == 0xff)\n ++i;\n data[j] = 0xff;\n } else {\n data[j] = frag->data[i];\n }\n }\n data_size = j;\n\n memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);\n\n } else {\n data = frag->data + start;\n data_size = end - start;\n data_ref = frag->data_ref;\n }\n\n err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,\n data, data_size, data_ref);\n if (err < 0) {\n if (!data_ref)\n av_freep(&data);\n return err;\n }\n\n if (next_marker == -1)\n break;\n marker = next_marker;\n start = next_start;\n }\n\n return 0;\n}", "func_hash": 38526679396248915103866893953052068409, "file_name": "cbs_jpeg.c", "file_hash": 159851152747428277041660596531252806358, "cwe": ["CWE-787"], "cve": "CVE-2020-12284", "cve_desc": "cbs_jpeg_split_fragment in libavcodec/cbs_jpeg.c in FFmpeg 4.1 and 4.2.2 has a heap-based buffer overflow during JPEG_MARKER_SOS handling because of a missing length check.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12284"} {"idx": 273279, "project": "FFmpeg", "commit_id": "a3a3730b5456ca00587455004d40c047f7b20a99", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/a3a3730b5456ca00587455004d40c047f7b20a99", "commit_message": "avcodec/cbs_jpeg: Check length for SOS\n\nFixes: out of array access\nFixes: 19734/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5673507031875584\nFixes: 19353/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5703944462663680\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 1812352d767ccf5431aa440123e2e260a4db2726)\nSigned-off-by: Michael Niedermayer ", "target": 0, "func": "static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,\n CodedBitstreamFragment *frag,\n int header)\n{\n AVBufferRef *data_ref;\n uint8_t *data;\n size_t data_size;\n int unit, start, end, marker, next_start, next_marker;\n int err, i, j, length;\n\n if (frag->data_size < 4) {\n // Definitely too short to be meaningful.\n return AVERROR_INVALIDDATA;\n }\n\n for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);\n if (i > 0) {\n av_log(ctx->log_ctx, AV_LOG_WARNING, \"Discarding %d bytes at \"\n \"beginning of image.\\n\", i);\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size && frag->data[i]) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no SOI marker found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n if (marker != JPEG_MARKER_SOI) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: first \"\n \"marker is %02x, should be SOI.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no image content found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n start = i + 1;\n\n for (unit = 0;; unit++) {\n if (marker == JPEG_MARKER_EOI) {\n break;\n } else if (marker == JPEG_MARKER_SOS) {\n for (i = start; i + 1 < frag->data_size; i++) {\n if (frag->data[i] != 0xff)\n continue;\n end = i;\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n if (frag->data[i] == 0x00)\n continue;\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n break;\n }\n } else {\n i = start;\n if (i + 2 > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n length = AV_RB16(frag->data + i);\n if (i + length > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker segment.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n end = start + length;\n\n i = end;\n if (frag->data[i] != 0xff) {\n next_marker = -1;\n } else {\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n }\n }\n\n if (marker == JPEG_MARKER_SOS) {\n length = AV_RB16(frag->data + start);\n\n if (length > end - start)\n return AVERROR_INVALIDDATA;\n\n data_ref = NULL;\n data = av_malloc(end - start +\n AV_INPUT_BUFFER_PADDING_SIZE);\n if (!data)\n return AVERROR(ENOMEM);\n\n memcpy(data, frag->data + start, length);\n for (i = start + length, j = length; i < end; i++, j++) {\n if (frag->data[i] == 0xff) {\n while (frag->data[i] == 0xff)\n ++i;\n data[j] = 0xff;\n } else {\n data[j] = frag->data[i];\n }\n }\n data_size = j;\n\n memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);\n\n } else {\n data = frag->data + start;\n data_size = end - start;\n data_ref = frag->data_ref;\n }\n\n err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,\n data, data_size, data_ref);\n if (err < 0) {\n if (!data_ref)\n av_freep(&data);\n return err;\n }\n\n if (next_marker == -1)\n break;\n marker = next_marker;\n start = next_start;\n }\n\n return 0;\n}", "func_hash": 8493976558356122155686039338167824272, "file_name": "cbs_jpeg.c", "file_hash": 305569968213733216731229352840925863129, "cwe": ["CWE-787"], "cve": "CVE-2020-12284", "cve_desc": "cbs_jpeg_split_fragment in libavcodec/cbs_jpeg.c in FFmpeg 4.1 and 4.2.2 has a heap-based buffer overflow during JPEG_MARKER_SOS handling because of a missing length check.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12284"} {"idx": 198396, "project": "tensorflow", "commit_id": "c59c37e7b2d563967da813fa50fe20b21f4da683", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c59c37e7b2d563967da813fa50fe20b21f4da683", "commit_message": "Prevent array write out-of-bounds.\n\nIf user passes an invalid axis, then we copy one too many dimensions to the output in the loop below these checks. Even if we didn't do that, there will be further issues with an invalid axis, so we check for that right now.\n\nPiperOrigin-RevId: 371023299\nChange-Id: I9eca37ffc2b29e8e48710f500701270ef0790224", "target": 1, "func": "TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input,\n const TfLiteTensor* axis, TfLiteTensor* output) {\n int axis_value;\n // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss.\n if (axis->type == kTfLiteInt64) {\n axis_value = static_cast(*GetTensorData(axis));\n } else {\n axis_value = *GetTensorData(axis);\n }\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n // Copy the input dimensions to output except the axis dimension.\n TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1);\n int j = 0;\n for (int i = 0; i < NumDimensions(input); ++i) {\n if (i != axis_value) {\n output_dims->data[j] = SizeOfDimension(input, i);\n ++j;\n }\n }\n return context->ResizeTensor(context, output, output_dims);\n}", "func_hash": 280719387801064389726140715021658711115, "file_name": "arg_min_max.cc", "file_hash": 93871290388699095836914171659562135730, "cwe": ["CWE-787"], "cve": "CVE-2021-29603", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. A specially crafted TFLite model could trigger an OOB write on heap in the TFLite implementation of `ArgMin`/`ArgMax`(https://github.com/tensorflow/tensorflow/blob/102b211d892f3abc14f845a72047809b39cc65ab/tensorflow/lite/kernels/arg_min_max.cc#L52-L59). If `axis_value` is not a value between 0 and `NumDimensions(input)`, then the condition in the `if` is never true, so code writes past the last valid element of `output_dims->data`. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29603"} {"idx": 273769, "project": "tensorflow", "commit_id": "c59c37e7b2d563967da813fa50fe20b21f4da683", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c59c37e7b2d563967da813fa50fe20b21f4da683", "commit_message": "Prevent array write out-of-bounds.\n\nIf user passes an invalid axis, then we copy one too many dimensions to the output in the loop below these checks. Even if we didn't do that, there will be further issues with an invalid axis, so we check for that right now.\n\nPiperOrigin-RevId: 371023299\nChange-Id: I9eca37ffc2b29e8e48710f500701270ef0790224", "target": 0, "func": "TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input,\n const TfLiteTensor* axis, TfLiteTensor* output) {\n int axis_value;\n // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss.\n if (axis->type == kTfLiteInt64) {\n axis_value = static_cast(*GetTensorData(axis));\n } else {\n axis_value = *GetTensorData(axis);\n }\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n TF_LITE_ENSURE(context, axis_value >= 0);\n TF_LITE_ENSURE(context, axis_value < NumDimensions(input));\n\n // Copy the input dimensions to output except the axis dimension.\n TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1);\n int j = 0;\n for (int i = 0; i < NumDimensions(input); ++i) {\n if (i != axis_value) {\n output_dims->data[j] = SizeOfDimension(input, i);\n ++j;\n }\n }\n return context->ResizeTensor(context, output, output_dims);\n}", "func_hash": 264548325728563106665385284085080948668, "file_name": "arg_min_max.cc", "file_hash": 85405975132654385141461165810884927943, "cwe": ["CWE-787"], "cve": "CVE-2021-29603", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. A specially crafted TFLite model could trigger an OOB write on heap in the TFLite implementation of `ArgMin`/`ArgMax`(https://github.com/tensorflow/tensorflow/blob/102b211d892f3abc14f845a72047809b39cc65ab/tensorflow/lite/kernels/arg_min_max.cc#L52-L59). If `axis_value` is not a value between 0 and `NumDimensions(input)`, then the condition in the `if` is never true, so code writes past the last valid element of `output_dims->data`. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29603"} {"idx": 198402, "project": "mruby", "commit_id": "97319697c8f9f6ff27b32589947e1918e3015503", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/97319697c8f9f6ff27b32589947e1918e3015503", "commit_message": "Cancel 9cdf439\n\nShould not free the pointer in `realloc` since it can cause\nuse-after-free problem.", "target": 1, "func": "mrb_realloc(mrb_state *mrb, void *p, size_t len)\n{\n void *p2;\n\n p2 = mrb_realloc_simple(mrb, p, len);\n if (len == 0) return p2;\n if (p2 == NULL) {\n mrb_free(mrb, p);\n mrb->gc.out_of_memory = TRUE;\n mrb_raise_nomemory(mrb);\n }\n else {\n mrb->gc.out_of_memory = FALSE;\n }\n\n return p2;\n}", "func_hash": 337272044153746238223778171758271349080, "file_name": "gc.c", "file_hash": 143401837984494307402475670481116159994, "cwe": ["CWE-415"], "cve": "CVE-2020-36401", "cve_desc": "mruby 2.1.2 has a double free in mrb_default_allocf (called from mrb_free and obj_free).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36401"} {"idx": 274032, "project": "mruby", "commit_id": "97319697c8f9f6ff27b32589947e1918e3015503", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/97319697c8f9f6ff27b32589947e1918e3015503", "commit_message": "Cancel 9cdf439\n\nShould not free the pointer in `realloc` since it can cause\nuse-after-free problem.", "target": 0, "func": "mrb_realloc(mrb_state *mrb, void *p, size_t len)\n{\n void *p2;\n\n p2 = mrb_realloc_simple(mrb, p, len);\n if (len == 0) return p2;\n if (p2 == NULL) {\n mrb->gc.out_of_memory = TRUE;\n mrb_raise_nomemory(mrb);\n }\n else {\n mrb->gc.out_of_memory = FALSE;\n }\n\n return p2;\n}", "func_hash": 280636652556282822596442671804806594243, "file_name": "gc.c", "file_hash": 140313279910593616412441734212494220813, "cwe": ["CWE-415"], "cve": "CVE-2020-36401", "cve_desc": "mruby 2.1.2 has a double free in mrb_default_allocf (called from mrb_free and obj_free).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36401"} {"idx": 198407, "project": "tensorflow", "commit_id": "301ae88b331d37a2a16159b65b255f4f9eb39314", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/301ae88b331d37a2a16159b65b255f4f9eb39314", "commit_message": "Fix null ptr deref in tf.raw_ops.RaggedTensorToTensor\n\nPiperOrigin-RevId: 384257511\nChange-Id: I0484ad285039d132d6c41b284a7fcdd2b774a38e", "target": 1, "func": " Status GetFirstDimensionSize(OpKernelContext* context, INDEX_TYPE* result) {\n const Tensor first_partition_tensor =\n context->input(kFirstPartitionInputIndex);\n const RowPartitionType first_partition_type = row_partition_types_[0];\n switch (first_partition_type) {\n case RowPartitionType::FIRST_DIM_SIZE:\n *result = first_partition_tensor.scalar()();\n return Status::OK();\n case RowPartitionType::VALUE_ROWIDS:\n return errors::InvalidArgument(\n \"Cannot handle VALUE_ROWIDS in first dimension.\");\n case RowPartitionType::ROW_SPLITS:\n *result = first_partition_tensor.shape().dim_size(0) - 1;\n return Status::OK();\n default:\n return errors::InvalidArgument(\n \"Cannot handle type \",\n RowPartitionTypeToString(first_partition_type));\n }\n }", "func_hash": 234857882236085176411641225787192059376, "file_name": "ragged_tensor_to_tensor_op.cc", "file_hash": 214841802031497455475309338328330138393, "cwe": ["CWE-125"], "cve": "CVE-2021-37638", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Sending invalid argument for `row_partition_types` of `tf.raw_ops.RaggedTensorToTensor` API results in a null pointer dereference and undefined behavior. The [implementation](https://github.com/tensorflow/tensorflow/blob/47a06f40411a69c99f381495f490536972152ac0/tensorflow/core/kernels/ragged_tensor_to_tensor_op.cc#L328) accesses the first element of a user supplied list of values without validating that the provided list is not empty. We have patched the issue in GitHub commit 301ae88b331d37a2a16159b65b255f4f9eb39314. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37638"} {"idx": 274041, "project": "tensorflow", "commit_id": "301ae88b331d37a2a16159b65b255f4f9eb39314", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/301ae88b331d37a2a16159b65b255f4f9eb39314", "commit_message": "Fix null ptr deref in tf.raw_ops.RaggedTensorToTensor\n\nPiperOrigin-RevId: 384257511\nChange-Id: I0484ad285039d132d6c41b284a7fcdd2b774a38e", "target": 0, "func": " Status GetFirstDimensionSize(OpKernelContext* context, INDEX_TYPE* result) {\n const Tensor first_partition_tensor =\n context->input(kFirstPartitionInputIndex);\n if (row_partition_types_.empty()) {\n return errors::InvalidArgument(\"No row_partition_types given.\");\n }\n const RowPartitionType first_partition_type = row_partition_types_[0];\n switch (first_partition_type) {\n case RowPartitionType::FIRST_DIM_SIZE:\n *result = first_partition_tensor.scalar()();\n return Status::OK();\n case RowPartitionType::VALUE_ROWIDS:\n return errors::InvalidArgument(\n \"Cannot handle VALUE_ROWIDS in first dimension.\");\n case RowPartitionType::ROW_SPLITS:\n *result = first_partition_tensor.shape().dim_size(0) - 1;\n return Status::OK();\n default:\n return errors::InvalidArgument(\n \"Cannot handle type \",\n RowPartitionTypeToString(first_partition_type));\n }\n }", "func_hash": 84397887333828206012157874638813454561, "file_name": "ragged_tensor_to_tensor_op.cc", "file_hash": 112933183202525364489598328495111084737, "cwe": ["CWE-125"], "cve": "CVE-2021-37638", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Sending invalid argument for `row_partition_types` of `tf.raw_ops.RaggedTensorToTensor` API results in a null pointer dereference and undefined behavior. The [implementation](https://github.com/tensorflow/tensorflow/blob/47a06f40411a69c99f381495f490536972152ac0/tensorflow/core/kernels/ragged_tensor_to_tensor_op.cc#L328) accesses the first element of a user supplied list of values without validating that the provided list is not empty. We have patched the issue in GitHub commit 301ae88b331d37a2a16159b65b255f4f9eb39314. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37638"} {"idx": 198409, "project": "tensorflow", "commit_id": "41727ff06111117bdf86b37db198217fd7a143cc", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/41727ff06111117bdf86b37db198217fd7a143cc", "commit_message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373248068\nChange-Id: I0a2041a0747901b3f00387a6a3bce9bca6b0b3b1", "target": 1, "func": " void Compute(OpKernelContext *ctx) override {\n // (0) validations\n const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,\n *b_shape, *thresh_t;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsMatrix(a_indices->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be matrices but received shapes: \",\n a_indices->shape().DebugString(), \" and \",\n b_indices->shape().DebugString()));\n const int64 a_nnz = a_indices->dim_size(0);\n const int64 b_nnz = b_indices->dim_size(0);\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Input values should be vectors but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n auto a_values = ctx->input(1).vec();\n auto b_values = ctx->input(4).vec();\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape->shape()) &&\n TensorShapeUtils::IsVector(b_shape->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape->shape().DebugString(), \" and \",\n b_shape->shape().DebugString()));\n OP_REQUIRES(\n ctx, a_shape->IsSameSize(*b_shape),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape->SummarizeValue(10), \" and \", b_shape->SummarizeValue(10)));\n const auto a_shape_flat = a_shape->flat();\n const auto b_shape_flat = b_shape->flat();\n for (int i = 0; i < a_shape->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),\n errors::InvalidArgument(\n \"Operands' shapes do not match: got \", a_shape_flat(i),\n \" and \", b_shape_flat(i), \" for dimension \", i));\n }\n\n OP_REQUIRES_OK(ctx, ctx->input(\"thresh\", &thresh_t));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),\n errors::InvalidArgument(\n \"The magnitude threshold must be a scalar: got shape \",\n thresh_t->shape().DebugString()));\n // std::abs() so that it works for complex{64,128} values as well\n const Treal thresh = thresh_t->scalar()();\n\n // (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix();\n auto b_indices_mat = b_indices->matrix();\n std::vector> entries_to_copy; // from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector out_values;\n const int num_dims = a_shape->dim_size(0);\n\n OP_REQUIRES(ctx, num_dims > 0,\n errors::InvalidArgument(\"Invalid input_a shape. Received: \",\n a_shape->DebugString()));\n\n // The input and output sparse tensors are assumed to be ordered along\n // increasing dimension number.\n int64 i = 0, j = 0;\n T s;\n while (i < a_nnz && j < b_nnz) {\n switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,\n num_dims)) {\n case -1:\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(a_values(i));\n ++i;\n break;\n case 0:\n s = a_values(i) + b_values(j);\n if (thresh <= std::abs(s)) {\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(s);\n }\n ++i;\n ++j;\n break;\n case 1:\n entries_to_copy.emplace_back(false, j);\n out_values.push_back(b_values(j));\n ++j;\n break;\n }\n }\n\n#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \\\n while (IDX < A_OR_B##_nnz) { \\\n entries_to_copy.emplace_back(IS_A, IDX); \\\n out_values.push_back(A_OR_B##_values(IDX)); \\\n ++IDX; \\\n }\n\n // at most one of these calls appends new values\n HANDLE_LEFTOVERS(a, i, true);\n HANDLE_LEFTOVERS(b, j, false);\n#undef HANDLE_LEFTOVERS\n\n // (2) allocate and fill output tensors\n const int64 sum_nnz = out_values.size();\n Tensor *out_indices_t, *out_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &out_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));\n auto out_indices_mat = out_indices_t->matrix();\n auto out_values_flat = out_values_t->vec();\n\n for (i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n out_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n if (sum_nnz > 0) {\n std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));\n }\n ctx->set_output(2, *a_shape);\n }", "func_hash": 95671267291504004763395667040061673019, "file_name": "sparse_add_op.cc", "file_hash": 89770237416688219588870986078802270371, "cwe": ["CWE-787"], "cve": "CVE-2021-29609", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Incomplete validation in `SparseAdd` results in allowing attackers to exploit undefined behavior (dereferencing null pointers) as well as write outside of bounds of heap allocated data. The implementation(https://github.com/tensorflow/tensorflow/blob/656e7673b14acd7835dc778867f84916c6d1cac2/tensorflow/core/kernels/sparse_add_op.cc) has a large set of validation for the two sparse tensor inputs (6 tensors in total), but does not validate that the tensors are not empty or that the second dimension of `*_indices` matches the size of corresponding `*_shape`. This allows attackers to send tensor triples that represent invalid sparse tensors to abuse code assumptions that are not protected by validation. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29609"} {"idx": 274064, "project": "tensorflow", "commit_id": "41727ff06111117bdf86b37db198217fd7a143cc", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/41727ff06111117bdf86b37db198217fd7a143cc", "commit_message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373248068\nChange-Id: I0a2041a0747901b3f00387a6a3bce9bca6b0b3b1", "target": 0, "func": " void Compute(OpKernelContext *ctx) override {\n // (0) validations\n const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,\n *b_shape, *thresh_t;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsMatrix(a_indices->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be matrices but received shapes: \",\n a_indices->shape().DebugString(), \" and \",\n b_indices->shape().DebugString()));\n const int64 a_nnz = a_indices->dim_size(0);\n const int64 b_nnz = b_indices->dim_size(0);\n const int num_dims = a_indices->dim_size(1);\n OP_REQUIRES(ctx, b_indices->dim_size(1) == num_dims,\n errors::InvalidArgument(\n \"Input indices must have the same dimension, got \",\n num_dims, \" and \", b_indices->dim_size(1)));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Input values should be vectors but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n auto a_values = ctx->input(1).vec();\n auto b_values = ctx->input(4).vec();\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape->shape()) &&\n TensorShapeUtils::IsVector(b_shape->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape->shape().DebugString(), \" and \",\n b_shape->shape().DebugString()));\n OP_REQUIRES(\n ctx, a_shape->NumElements() == num_dims,\n errors::InvalidArgument(\"Second dimension of a_indices and length of \"\n \"a_shape must match, got \",\n num_dims, \" and \", a_shape->NumElements()));\n OP_REQUIRES(ctx, num_dims > 0,\n errors::InvalidArgument(\"Tesors must not be empty\"));\n OP_REQUIRES(\n ctx, a_shape->IsSameSize(*b_shape),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape->SummarizeValue(10), \" and \", b_shape->SummarizeValue(10)));\n const auto a_shape_flat = a_shape->flat();\n const auto b_shape_flat = b_shape->flat();\n for (int i = 0; i < a_shape->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),\n errors::InvalidArgument(\n \"Operands' shapes do not match: got \", a_shape_flat(i),\n \" and \", b_shape_flat(i), \" for dimension \", i));\n }\n\n OP_REQUIRES_OK(ctx, ctx->input(\"thresh\", &thresh_t));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),\n errors::InvalidArgument(\n \"The magnitude threshold must be a scalar: got shape \",\n thresh_t->shape().DebugString()));\n // std::abs() so that it works for complex{64,128} values as well\n const Treal thresh = thresh_t->scalar()();\n\n // (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix();\n auto b_indices_mat = b_indices->matrix();\n std::vector> entries_to_copy; // from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector out_values;\n\n // The input and output sparse tensors are assumed to be ordered along\n // increasing dimension number.\n int64 i = 0, j = 0;\n T s;\n while (i < a_nnz && j < b_nnz) {\n switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,\n num_dims)) {\n case -1:\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(a_values(i));\n ++i;\n break;\n case 0:\n s = a_values(i) + b_values(j);\n if (thresh <= std::abs(s)) {\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(s);\n }\n ++i;\n ++j;\n break;\n case 1:\n entries_to_copy.emplace_back(false, j);\n out_values.push_back(b_values(j));\n ++j;\n break;\n }\n }\n\n#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \\\n while (IDX < A_OR_B##_nnz) { \\\n entries_to_copy.emplace_back(IS_A, IDX); \\\n out_values.push_back(A_OR_B##_values(IDX)); \\\n ++IDX; \\\n }\n\n // at most one of these calls appends new values\n HANDLE_LEFTOVERS(a, i, true);\n HANDLE_LEFTOVERS(b, j, false);\n#undef HANDLE_LEFTOVERS\n\n // (2) allocate and fill output tensors\n const int64 sum_nnz = out_values.size();\n Tensor *out_indices_t, *out_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &out_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));\n auto out_indices_mat = out_indices_t->matrix();\n auto out_values_flat = out_values_t->vec();\n\n for (i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n out_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n if (sum_nnz > 0) {\n std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));\n }\n ctx->set_output(2, *a_shape);\n }", "func_hash": 239832425532166637863910958506032123974, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-29609", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. Incomplete validation in `SparseAdd` results in allowing attackers to exploit undefined behavior (dereferencing null pointers) as well as write outside of bounds of heap allocated data. The implementation(https://github.com/tensorflow/tensorflow/blob/656e7673b14acd7835dc778867f84916c6d1cac2/tensorflow/core/kernels/sparse_add_op.cc) has a large set of validation for the two sparse tensor inputs (6 tensors in total), but does not validate that the tensors are not empty or that the second dimension of `*_indices` matches the size of corresponding `*_shape`. This allows attackers to send tensor triples that represent invalid sparse tensors to abuse code assumptions that are not protected by validation. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29609"} {"idx": 198430, "project": "tensorflow", "commit_id": "26eb323554ffccd173e8a79a8c05c15b685ae4d1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/26eb323554ffccd173e8a79a8c05c15b685ae4d1", "commit_message": "Fix null CHECK issue with `tf.raw_ops.EncodePng`.\n\nPiperOrigin-RevId: 369717714\nChange-Id: I24136cd99c20b8466671f4f93b670ef6f6dd1250", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& image = context->input(0);\n OP_REQUIRES(context, image.dims() == 3,\n errors::InvalidArgument(\"image must be 3-dimensional\",\n image.shape().DebugString()));\n OP_REQUIRES(\n context,\n FastBoundsCheck(image.NumElements(), std::numeric_limits::max()),\n errors::InvalidArgument(\"image cannot have >= int32 max elements\"));\n const int32 height = static_cast(image.dim_size(0));\n const int32 width = static_cast(image.dim_size(1));\n const int32 channels = static_cast(image.dim_size(2));\n\n // In some cases, we pass width*channels*2 to png.\n const int32 max_row_width = std::numeric_limits::max() / 2;\n\n OP_REQUIRES(context, FastBoundsCheck(width * channels, max_row_width),\n errors::InvalidArgument(\"image too wide to encode\"));\n\n OP_REQUIRES(context, channels >= 1 && channels <= 4,\n errors::InvalidArgument(\n \"image must have 1, 2, 3, or 4 channels, got \", channels));\n\n // Encode image to png string\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, TensorShape({}), &output));\n if (desired_channel_bits_ == 8) {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n } else {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels * 2, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n }\n }", "func_hash": 107479218930678167966720430970938796987, "file_name": "encode_png_op.cc", "file_hash": 332104679634985322308416986495448740235, "cwe": ["CWE-787"], "cve": "CVE-2021-29531", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a `CHECK` fail in PNG encoding by providing an empty input tensor as the pixel data. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/e312e0791ce486a80c9d23110841525c6f7c3289/tensorflow/core/kernels/image/encode_png_op.cc#L57-L60) only validates that the total number of pixels in the image does not overflow. Thus, an attacker can send an empty matrix for encoding. However, if the tensor is empty, then the associated buffer is `nullptr`. Hence, when calling `png::WriteImageToBuffer`(https://github.com/tensorflow/tensorflow/blob/e312e0791ce486a80c9d23110841525c6f7c3289/tensorflow/core/kernels/image/encode_png_op.cc#L79-L93), the first argument (i.e., `image.flat().data()`) is `NULL`. This then triggers the `CHECK_NOTNULL` in the first line of `png::WriteImageToBuffer`(https://github.com/tensorflow/tensorflow/blob/e312e0791ce486a80c9d23110841525c6f7c3289/tensorflow/core/lib/png/png_io.cc#L345-L349). Since `image` is null, this results in `abort` being called after printing the stacktrace. Effectively, this allows an attacker to mount a denial of service attack. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29531"} {"idx": 274583, "project": "tensorflow", "commit_id": "26eb323554ffccd173e8a79a8c05c15b685ae4d1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/26eb323554ffccd173e8a79a8c05c15b685ae4d1", "commit_message": "Fix null CHECK issue with `tf.raw_ops.EncodePng`.\n\nPiperOrigin-RevId: 369717714\nChange-Id: I24136cd99c20b8466671f4f93b670ef6f6dd1250", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& image = context->input(0);\n OP_REQUIRES(context, image.dims() == 3,\n errors::InvalidArgument(\"image must be 3-dimensional\",\n image.shape().DebugString()));\n OP_REQUIRES(context, image.NumElements() > 0,\n errors::Internal(\"Invalid image provided.\"));\n OP_REQUIRES(\n context,\n FastBoundsCheck(image.NumElements(), std::numeric_limits::max()),\n errors::InvalidArgument(\"image cannot have >= int32 max elements\"));\n const int32 height = static_cast(image.dim_size(0));\n const int32 width = static_cast(image.dim_size(1));\n const int32 channels = static_cast(image.dim_size(2));\n\n // In some cases, we pass width*channels*2 to png.\n const int32 max_row_width = std::numeric_limits::max() / 2;\n\n OP_REQUIRES(context, FastBoundsCheck(width * channels, max_row_width),\n errors::InvalidArgument(\"image too wide to encode\"));\n\n OP_REQUIRES(context, channels >= 1 && channels <= 4,\n errors::InvalidArgument(\n \"image must have 1, 2, 3, or 4 channels, got \", channels));\n\n // Encode image to png string\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, TensorShape({}), &output));\n if (desired_channel_bits_ == 8) {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n } else {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels * 2, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n }\n }", "func_hash": 103338557647385620601336427069353494961, "file_name": "encode_png_op.cc", "file_hash": 134721190935651592740635954183715766606, "cwe": ["CWE-787"], "cve": "CVE-2021-29531", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can trigger a `CHECK` fail in PNG encoding by providing an empty input tensor as the pixel data. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/e312e0791ce486a80c9d23110841525c6f7c3289/tensorflow/core/kernels/image/encode_png_op.cc#L57-L60) only validates that the total number of pixels in the image does not overflow. Thus, an attacker can send an empty matrix for encoding. However, if the tensor is empty, then the associated buffer is `nullptr`. Hence, when calling `png::WriteImageToBuffer`(https://github.com/tensorflow/tensorflow/blob/e312e0791ce486a80c9d23110841525c6f7c3289/tensorflow/core/kernels/image/encode_png_op.cc#L79-L93), the first argument (i.e., `image.flat().data()`) is `NULL`. This then triggers the `CHECK_NOTNULL` in the first line of `png::WriteImageToBuffer`(https://github.com/tensorflow/tensorflow/blob/e312e0791ce486a80c9d23110841525c6f7c3289/tensorflow/core/lib/png/png_io.cc#L345-L349). Since `image` is null, this results in `abort` being called after printing the stacktrace. Effectively, this allows an attacker to mount a denial of service attack. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29531"} {"idx": 198440, "project": "jerryscript", "commit_id": "69f8e78c2f8d562bd6d8002b5488f1662ac30d24", "project_url": "https://github.com/zherczeg/jerryscript", "commit_url": "https://github.com/jerryscript-project/jerryscript/commit/69f8e78c2f8d562bd6d8002b5488f1662ac30d24", "commit_message": "Fix error handling in scanner when in case of OOM (#3793)\n\nThis patch fixes #3786 and fixes #3788.\n\nJerryScript-DCO-1.0-Signed-off-by: Robert Fancsik frobert@inf.u-szeged.hu", "target": 1, "func": "scanner_scan_all (parser_context_t *context_p, /**< context */\n const uint8_t *arg_list_p, /**< function argument list */\n const uint8_t *arg_list_end_p, /**< end of argument list */\n const uint8_t *source_p, /**< valid UTF-8 source code */\n const uint8_t *source_end_p) /**< end of source code */\n{\n scanner_context_t scanner_context;\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n JERRY_DEBUG_MSG (\"\\n--- Scanning start ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n scanner_context.context_status_flags = context_p->status_flags;\n scanner_context.status_flags = SCANNER_CONTEXT_NO_FLAGS;\n#if ENABLED (JERRY_DEBUGGER)\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED)\n {\n scanner_context.status_flags |= SCANNER_CONTEXT_DEBUGGER_ENABLED;\n }\n#endif /* ENABLED (JERRY_DEBUGGER) */\n#if ENABLED (JERRY_ES2015)\n scanner_context.binding_type = SCANNER_BINDING_NONE;\n scanner_context.active_binding_list_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n scanner_context.active_literal_pool_p = NULL;\n scanner_context.active_switch_statement.last_case_p = NULL;\n scanner_context.end_arguments_p = NULL;\n#if ENABLED (JERRY_ES2015)\n scanner_context.async_source_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n\n /* This assignment must be here because of Apple compilers. */\n context_p->u.scanner_context_p = &scanner_context;\n\n parser_stack_init (context_p);\n\n PARSER_TRY (context_p->try_buffer)\n {\n context_p->line = 1;\n context_p->column = 1;\n\n if (arg_list_p == NULL)\n {\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION_WITHOUT_ARGUMENTS | SCANNER_LITERAL_POOL_CAN_EVAL;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n scanner_literal_pool_t *literal_pool_p = scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n literal_pool_p->source_p = source_p;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT);\n\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n }\n else\n {\n context_p->source_p = arg_list_p;\n context_p->source_end_p = arg_list_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->status_flags & PARSER_IS_GENERATOR_FUNCTION)\n {\n status_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT_FUNCTION);\n\n /* Faking the first token. */\n context_p->token.type = LEXER_LEFT_PAREN;\n }\n\n while (true)\n {\n lexer_token_type_t type = (lexer_token_type_t) context_p->token.type;\n scan_stack_modes_t stack_top = (scan_stack_modes_t) context_p->stack_top_uint8;\n\n switch (scanner_context.mode)\n {\n case SCAN_MODE_PRIMARY_EXPRESSION:\n {\n if (type == LEXER_ADD\n || type == LEXER_SUBTRACT\n || LEXER_IS_UNARY_OP_TOKEN (type))\n {\n break;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_AFTER_NEW:\n {\n if (scanner_scan_primary_expression (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_CLASS_DECLARATION:\n {\n if (context_p->token.type == LEXER_KEYW_EXTENDS)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_CLASS_EXTENDS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n else if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_CLASS_METHOD;\n /* FALLTHRU */\n }\n case SCAN_MODE_CLASS_METHOD:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR\n || stack_top == SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n\n lexer_skip_empty_statements (context_p);\n\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_source_start_t source_start;\n\n parser_stack_pop_uint8 (context_p);\n\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n }\n\n stack_top = context_p->stack_top_uint8;\n\n JERRY_ASSERT (stack_top == SCAN_STACK_CLASS_STATEMENT || stack_top == SCAN_STACK_CLASS_EXPRESSION);\n\n if (stack_top == SCAN_STACK_CLASS_STATEMENT)\n {\n /* The token is kept to disallow consuming a semicolon after it. */\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n parser_stack_pop_uint8 (context_p);\n break;\n }\n\n if (context_p->token.type == LEXER_LITERAL\n && LEXER_IS_IDENT_OR_STRING (context_p->token.lit_location.type)\n && lexer_compare_literal_to_string (context_p, \"constructor\", 11))\n {\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n scanner_source_start_t source_start;\n parser_stack_pop_uint8 (context_p);\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n\n scanner_info_t *info_p = scanner_insert_info (context_p, source_start.source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_CLASS_CONSTRUCTOR;\n parser_stack_push_uint8 (context_p, SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n }\n }\n\n if (lexer_token_is_identifier (context_p, \"static\", 6))\n {\n lexer_scan_identifier (context_p);\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (lexer_token_is_identifier (context_p, \"get\", 3)\n || lexer_token_is_identifier (context_p, \"set\", 3))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n }\n else if (lexer_token_is_identifier (context_p, \"async\", 5))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n else if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (literal_pool_flags & SCANNER_LITERAL_POOL_GENERATOR)\n {\n context_p->status_flags |= PARSER_IS_GENERATOR_FUNCTION;\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n lexer_next_token (context_p);\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCAN_MODE_POST_PRIMARY_EXPRESSION:\n {\n if (scanner_scan_post_primary_expression (context_p, &scanner_context, type, stack_top))\n {\n break;\n }\n type = (lexer_token_type_t) context_p->token.type;\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_END:\n {\n if (scanner_scan_primary_expression_end (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_OR_TERMINATOR:\n {\n if (type == LEXER_RIGHT_BRACE || type == LEXER_EOS)\n {\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_STATEMENT:\n {\n if (scanner_scan_statement (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_END:\n {\n if (scanner_scan_statement_end (context_p, &scanner_context, type) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n\n if (context_p->token.type == LEXER_EOS)\n {\n goto scan_completed;\n }\n\n break;\n }\n case SCAN_MODE_VAR_STATEMENT:\n {\n#if ENABLED (JERRY_ES2015)\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n uint8_t binding_type = SCANNER_BINDING_VAR;\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n binding_type = SCANNER_BINDING_LET;\n }\n else if (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START)\n {\n binding_type = SCANNER_BINDING_CONST;\n }\n\n scanner_push_destructuring_pattern (context_p, &scanner_context, binding_type, false);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n if (stack_top != SCAN_STACK_VAR && stack_top != SCAN_STACK_FOR_VAR_START)\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START);\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n }\n\n lexer_next_token (context_p);\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n }\n else if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n }\n }\n else\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n\n lexer_next_token (context_p);\n }\n#else /* !ENABLED (JERRY_ES2015) */\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n\n lexer_next_token (context_p);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n switch (context_p->token.type)\n {\n case LEXER_ASSIGN:\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n /* FALLTHRU */\n }\n case LEXER_COMMA:\n {\n lexer_next_token (context_p);\n continue;\n }\n }\n\n if (SCANNER_IS_FOR_START (stack_top))\n {\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n JERRY_ASSERT (!(scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT));\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n if (context_p->token.type != LEXER_SEMICOLON\n && context_p->token.type != LEXER_KEYW_IN\n && !SCANNER_IDENTIFIER_IS_OF ())\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR || stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_CONST);\n#else /* !ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n scanner_context.active_literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_EXPORT;\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n parser_stack_pop_uint8 (context_p);\n continue;\n }\n case SCAN_MODE_FUNCTION_ARGUMENTS:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_SCRIPT_FUNCTION\n || stack_top == SCAN_STACK_FUNCTION_STATEMENT\n || stack_top == SCAN_STACK_FUNCTION_EXPRESSION\n || stack_top == SCAN_STACK_FUNCTION_PROPERTY);\n\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n JERRY_ASSERT (literal_pool_p != NULL && (literal_pool_p->status_flags & SCANNER_LITERAL_POOL_FUNCTION));\n\n literal_pool_p->source_p = context_p->source_p;\n\n#if ENABLED (JERRY_ES2015)\n if (JERRY_UNLIKELY (scanner_context.async_source_p != NULL))\n {\n literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ASYNC;\n literal_pool_p->source_p = scanner_context.async_source_p;\n scanner_context.async_source_p = NULL;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LEFT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n /* FALLTHRU */\n }\n case SCAN_MODE_CONTINUE_FUNCTION_ARGUMENTS:\n {\n#endif /* ENABLED (JERRY_ES2015) */\n if (context_p->token.type != LEXER_RIGHT_PAREN && context_p->token.type != LEXER_EOS)\n {\n#if ENABLED (JERRY_ES2015)\n lexer_lit_location_t *argument_literal_p;\n#endif /* ENABLED (JERRY_ES2015) */\n\n while (true)\n {\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_THREE_DOTS)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n lexer_next_token (context_p);\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE || context_p->token.type == LEXER_LEFT_BRACE)\n {\n argument_literal_p = NULL;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n argument_literal_p = scanner_append_argument (context_p, &scanner_context);\n#else /* !ENABLED (JERRY_ES2015) */\n scanner_append_argument (context_p, &scanner_context);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_COMMA)\n {\n break;\n }\n lexer_next_token (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (argument_literal_p == NULL)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_append_hole (context_p, &scanner_context);\n scanner_push_destructuring_pattern (context_p, &scanner_context, SCANNER_BINDING_ARG, false);\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n if (argument_literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n JERRY_ASSERT (argument_literal_p->type & SCANNER_LITERAL_EARLY_CREATE);\n break;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = argument_literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (context_p->token.type == LEXER_EOS && stack_top == SCAN_STACK_SCRIPT_FUNCTION)\n {\n /* End of argument parsing. */\n scanner_info_t *scanner_info_p = (scanner_info_t *) scanner_malloc (context_p, sizeof (scanner_info_t));\n scanner_info_p->next_p = context_p->next_scanner_info_p;\n scanner_info_p->source_p = NULL;\n scanner_info_p->type = SCANNER_TYPE_END_ARGUMENTS;\n scanner_context.end_arguments_p = scanner_info_p;\n\n context_p->next_scanner_info_p = scanner_info_p;\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n context_p->line = 1;\n context_p->column = 1;\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n\n if (context_p->token.type != LEXER_RIGHT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n case SCAN_MODE_PROPERTY_NAME:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_OBJECT_LITERAL);\n\n if (lexer_scan_identifier (context_p))\n {\n lexer_check_property_modifier (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_COMPUTED_PROPERTY);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n if (context_p->token.type == LEXER_PROPERTY_GETTER\n#if ENABLED (JERRY_ES2015)\n || context_p->token.type == LEXER_KEYW_ASYNC\n || context_p->token.type == LEXER_MULTIPLY\n#endif /* ENABLED (JERRY_ES2015) */\n || context_p->token.type == LEXER_PROPERTY_SETTER)\n {\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n else if (context_p->token.type == LEXER_KEYW_ASYNC)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (lexer_consume_generator (context_p))\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n lexer_scan_identifier (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n parser_line_counter_t start_line = context_p->token.line;\n parser_line_counter_t start_column = context_p->token.column;\n bool is_ident = (context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n continue;\n }\n\n if (is_ident\n && (context_p->token.type == LEXER_COMMA\n || context_p->token.type == LEXER_RIGHT_BRACE\n || context_p->token.type == LEXER_ASSIGN))\n {\n context_p->source_p = context_p->token.lit_location.char_p;\n context_p->line = start_line;\n context_p->column = start_column;\n\n lexer_next_token (context_p);\n\n JERRY_ASSERT (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n continue;\n }\n\n scanner_add_reference (context_p, &scanner_context);\n\n lexer_next_token (context_p);\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_COLON)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n#if ENABLED (JERRY_ES2015)\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_BINDING:\n {\n JERRY_ASSERT (scanner_context.binding_type == SCANNER_BINDING_VAR\n || scanner_context.binding_type == SCANNER_BINDING_LET\n || scanner_context.binding_type == SCANNER_BINDING_CATCH\n || scanner_context.binding_type == SCANNER_BINDING_CONST\n || scanner_context.binding_type == SCANNER_BINDING_ARG\n || scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG);\n\n if (type == LEXER_THREE_DOTS)\n {\n lexer_next_token (context_p);\n type = (lexer_token_type_t) context_p->token.type;\n }\n\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n scanner_push_destructuring_pattern (context_p, &scanner_context, scanner_context.binding_type, true);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n continue;\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n\n if (scanner_context.binding_type == SCANNER_BINDING_VAR)\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n break;\n }\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_IS_ARROW_DESTRUCTURED_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n else\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (scanner_context.binding_type <= SCANNER_BINDING_CATCH)\n {\n JERRY_ASSERT ((scanner_context.binding_type == SCANNER_BINDING_LET)\n || (scanner_context.binding_type == SCANNER_BINDING_CATCH));\n\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n }\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n\n scanner_binding_item_t *binding_item_p;\n binding_item_p = (scanner_binding_item_t *) scanner_malloc (context_p, sizeof (scanner_binding_item_t));\n\n binding_item_p->next_p = scanner_context.active_binding_list_p->items_p;\n binding_item_p->literal_p = literal_p;\n\n scanner_context.active_binding_list_p->items_p = binding_item_p;\n\n lexer_next_token (context_p);\n if (context_p->token.type != LEXER_ASSIGN)\n {\n continue;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n lexer_next_token (context_p);\n }\n\nscan_completed:\n if (context_p->stack_top_uint8 != SCAN_STACK_SCRIPT\n && context_p->stack_top_uint8 != SCAN_STACK_SCRIPT_FUNCTION)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_pop_literal_pool (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (scanner_context.active_binding_list_p == NULL);\n#endif /* ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (scanner_context.active_literal_pool_p == NULL);\n\n#ifndef JERRY_NDEBUG\n scanner_context.context_status_flags |= PARSER_SCANNING_SUCCESSFUL;\n#endif /* !JERRY_NDEBUG */\n }\n PARSER_CATCH\n {\n /* Ignore the errors thrown by the lexer. */\n if (context_p->error != PARSER_ERR_OUT_OF_MEMORY)\n {\n context_p->error = PARSER_ERR_NO_ERROR;\n }\n\n#if ENABLED (JERRY_ES2015)\n while (scanner_context.active_binding_list_p != NULL)\n {\n scanner_pop_binding_list (&scanner_context);\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n /* The following code may allocate memory, so it is enclosed in a try/catch. */\n PARSER_TRY (context_p->try_buffer)\n {\n#if ENABLED (JERRY_ES2015)\n if (scanner_context.status_flags & SCANNER_CONTEXT_THROW_ERR_ASYNC_FUNCTION)\n {\n JERRY_ASSERT (scanner_context.async_source_p != NULL);\n\n scanner_info_t *info_p;\n info_p = scanner_insert_info (context_p, scanner_context.async_source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_ERR_ASYNC_FUNCTION;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_pop_literal_pool (context_p, &scanner_context);\n }\n }\n PARSER_CATCH\n {\n JERRY_ASSERT (context_p->error == PARSER_ERR_NO_ERROR);\n\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n scanner_context.active_literal_pool_p = literal_pool_p->prev_p;\n\n parser_list_free (&literal_pool_p->literal_pool);\n scanner_free (literal_pool_p, sizeof (scanner_literal_pool_t));\n }\n }\n PARSER_TRY_END\n\n#if ENABLED (JERRY_ES2015)\n context_p->status_flags &= (uint32_t) ~PARSER_IS_GENERATOR_FUNCTION;\n#endif /* ENABLED (JERRY_ES2015) */\n }\n PARSER_TRY_END\n\n context_p->status_flags = scanner_context.context_status_flags;\n scanner_reverse_info_list (context_p);\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n scanner_info_t *info_p = context_p->next_scanner_info_p;\n const uint8_t *source_start_p = (arg_list_p == NULL) ? source_p : arg_list_p;\n\n while (info_p->type != SCANNER_TYPE_END)\n {\n const char *name_p = NULL;\n bool print_location = false;\n\n switch (info_p->type)\n {\n case SCANNER_TYPE_END_ARGUMENTS:\n {\n JERRY_DEBUG_MSG (\" END_ARGUMENTS\\n\");\n source_start_p = source_p;\n break;\n }\n case SCANNER_TYPE_FUNCTION:\n case SCANNER_TYPE_BLOCK:\n {\n const uint8_t *prev_source_p = info_p->source_p - 1;\n const uint8_t *data_p;\n\n if (info_p->type == SCANNER_TYPE_FUNCTION)\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" FUNCTION: flags: 0x%x declarations: %d\",\n (int) info_p->u8_arg,\n (int) info_p->u16_arg);\n }\n else\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" BLOCK:\");\n }\n\n JERRY_DEBUG_MSG (\" source:%d\\n\", (int) (info_p->source_p - source_start_p));\n\n while (data_p[0] != SCANNER_STREAM_TYPE_END)\n {\n switch (data_p[0] & SCANNER_STREAM_TYPE_MASK)\n {\n case SCANNER_STREAM_TYPE_VAR:\n {\n JERRY_DEBUG_MSG (\" VAR \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_LET:\n {\n JERRY_DEBUG_MSG (\" LET \");\n break;\n }\n case SCANNER_STREAM_TYPE_CONST:\n {\n JERRY_DEBUG_MSG (\" CONST \");\n break;\n }\n case SCANNER_STREAM_TYPE_LOCAL:\n {\n JERRY_DEBUG_MSG (\" LOCAL \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n case SCANNER_STREAM_TYPE_IMPORT:\n {\n JERRY_DEBUG_MSG (\" IMPORT \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n case SCANNER_STREAM_TYPE_ARG:\n {\n JERRY_DEBUG_MSG (\" ARG \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" ARG_FUNC \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG_FUNC \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_FUNC:\n {\n JERRY_DEBUG_MSG (\" FUNC \");\n break;\n }\n default:\n {\n JERRY_ASSERT ((data_p[0] & SCANNER_STREAM_TYPE_MASK) == SCANNER_STREAM_TYPE_HOLE);\n JERRY_DEBUG_MSG (\" HOLE\\n\");\n data_p++;\n continue;\n }\n }\n\n size_t length;\n\n if (!(data_p[0] & SCANNER_STREAM_UINT16_DIFF))\n {\n if (data_p[2] != 0)\n {\n prev_source_p += data_p[2];\n length = 2 + 1;\n }\n else\n {\n memcpy (&prev_source_p, data_p + 2 + 1, sizeof (const uint8_t *));\n length = 2 + 1 + sizeof (const uint8_t *);\n }\n }\n else\n {\n int32_t diff = ((int32_t) data_p[2]) | ((int32_t) data_p[3]) << 8;\n\n if (diff <= UINT8_MAX)\n {\n diff = -diff;\n }\n\n prev_source_p += diff;\n length = 2 + 2;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (data_p[0] & SCANNER_STREAM_EARLY_CREATE)\n {\n JERRY_ASSERT (data_p[0] & SCANNER_STREAM_NO_REG);\n JERRY_DEBUG_MSG (\"*\");\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (data_p[0] & SCANNER_STREAM_NO_REG)\n {\n JERRY_DEBUG_MSG (\"* \");\n }\n\n JERRY_DEBUG_MSG (\"'%.*s'\\n\", data_p[1], (char *) prev_source_p);\n prev_source_p += data_p[1];\n data_p += length;\n }\n break;\n }\n case SCANNER_TYPE_WHILE:\n {\n name_p = \"WHILE\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_FOR:\n {\n scanner_for_info_t *for_info_p = (scanner_for_info_t *) info_p;\n JERRY_DEBUG_MSG (\" FOR: source:%d expression:%d[%d:%d] end:%d[%d:%d]\\n\",\n (int) (for_info_p->info.source_p - source_start_p),\n (int) (for_info_p->expression_location.source_p - source_start_p),\n (int) for_info_p->expression_location.line,\n (int) for_info_p->expression_location.column,\n (int) (for_info_p->end_location.source_p - source_start_p),\n (int) for_info_p->end_location.line,\n (int) for_info_p->end_location.column);\n break;\n }\n case SCANNER_TYPE_FOR_IN:\n {\n name_p = \"FOR-IN\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_FOR_OF:\n {\n name_p = \"FOR-OF\";\n print_location = true;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_TYPE_SWITCH:\n {\n JERRY_DEBUG_MSG (\" SWITCH: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n\n scanner_case_info_t *current_case_p = ((scanner_switch_info_t *) info_p)->case_p;\n\n while (current_case_p != NULL)\n {\n JERRY_DEBUG_MSG (\" CASE: location:%d[%d:%d]\\n\",\n (int) (current_case_p->location.source_p - source_start_p),\n (int) current_case_p->location.line,\n (int) current_case_p->location.column);\n\n current_case_p = current_case_p->next_p;\n }\n break;\n }\n case SCANNER_TYPE_CASE:\n {\n name_p = \"CASE\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_INITIALIZER:\n {\n name_p = \"INITIALIZER\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_CLASS_CONSTRUCTOR:\n {\n JERRY_DEBUG_MSG (\" CLASS-CONSTRUCTOR: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n print_location = false;\n break;\n }\n case SCANNER_TYPE_LET_EXPRESSION:\n {\n JERRY_DEBUG_MSG (\" LET_EXPRESSION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_REDECLARED:\n {\n JERRY_DEBUG_MSG (\" ERR_REDECLARED: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_ASYNC_FUNCTION:\n {\n JERRY_DEBUG_MSG (\" ERR_ASYNC_FUNCTION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (print_location)\n {\n scanner_location_info_t *location_info_p = (scanner_location_info_t *) info_p;\n JERRY_DEBUG_MSG (\" %s: source:%d location:%d[%d:%d]\\n\",\n name_p,\n (int) (location_info_p->info.source_p - source_start_p),\n (int) (location_info_p->location.source_p - source_start_p),\n (int) location_info_p->location.line,\n (int) location_info_p->location.column);\n }\n\n info_p = info_p->next_p;\n }\n\n JERRY_DEBUG_MSG (\"\\n--- Scanning end ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n parser_stack_free (context_p);\n} /* scanner_scan_all */", "func_hash": 311309890310447140309860356868697518245, "file_name": "js-scanner.c", "file_hash": 166512408458471137546569233907332416350, "cwe": ["CWE-703"], "cve": "CVE-2020-13649", "cve_desc": "parser/js/js-scanner.c in JerryScript 2.2.0 mishandles errors during certain out-of-memory conditions, as demonstrated by a scanner_reverse_info_list NULL pointer dereference and a scanner_scan_all assertion failure.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13649"} {"idx": 274775, "project": "jerryscript", "commit_id": "69f8e78c2f8d562bd6d8002b5488f1662ac30d24", "project_url": "https://github.com/zherczeg/jerryscript", "commit_url": "https://github.com/jerryscript-project/jerryscript/commit/69f8e78c2f8d562bd6d8002b5488f1662ac30d24", "commit_message": "Fix error handling in scanner when in case of OOM (#3793)\n\nThis patch fixes #3786 and fixes #3788.\n\nJerryScript-DCO-1.0-Signed-off-by: Robert Fancsik frobert@inf.u-szeged.hu", "target": 0, "func": "scanner_scan_all (parser_context_t *context_p, /**< context */\n const uint8_t *arg_list_p, /**< function argument list */\n const uint8_t *arg_list_end_p, /**< end of argument list */\n const uint8_t *source_p, /**< valid UTF-8 source code */\n const uint8_t *source_end_p) /**< end of source code */\n{\n scanner_context_t scanner_context;\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n JERRY_DEBUG_MSG (\"\\n--- Scanning start ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n scanner_context.context_status_flags = context_p->status_flags;\n scanner_context.status_flags = SCANNER_CONTEXT_NO_FLAGS;\n#if ENABLED (JERRY_DEBUGGER)\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED)\n {\n scanner_context.status_flags |= SCANNER_CONTEXT_DEBUGGER_ENABLED;\n }\n#endif /* ENABLED (JERRY_DEBUGGER) */\n#if ENABLED (JERRY_ES2015)\n scanner_context.binding_type = SCANNER_BINDING_NONE;\n scanner_context.active_binding_list_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n scanner_context.active_literal_pool_p = NULL;\n scanner_context.active_switch_statement.last_case_p = NULL;\n scanner_context.end_arguments_p = NULL;\n#if ENABLED (JERRY_ES2015)\n scanner_context.async_source_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n\n /* This assignment must be here because of Apple compilers. */\n context_p->u.scanner_context_p = &scanner_context;\n\n parser_stack_init (context_p);\n\n PARSER_TRY (context_p->try_buffer)\n {\n context_p->line = 1;\n context_p->column = 1;\n\n if (arg_list_p == NULL)\n {\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION_WITHOUT_ARGUMENTS | SCANNER_LITERAL_POOL_CAN_EVAL;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n scanner_literal_pool_t *literal_pool_p = scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n literal_pool_p->source_p = source_p;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT);\n\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n }\n else\n {\n context_p->source_p = arg_list_p;\n context_p->source_end_p = arg_list_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->status_flags & PARSER_IS_GENERATOR_FUNCTION)\n {\n status_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT_FUNCTION);\n\n /* Faking the first token. */\n context_p->token.type = LEXER_LEFT_PAREN;\n }\n\n while (true)\n {\n lexer_token_type_t type = (lexer_token_type_t) context_p->token.type;\n scan_stack_modes_t stack_top = (scan_stack_modes_t) context_p->stack_top_uint8;\n\n switch (scanner_context.mode)\n {\n case SCAN_MODE_PRIMARY_EXPRESSION:\n {\n if (type == LEXER_ADD\n || type == LEXER_SUBTRACT\n || LEXER_IS_UNARY_OP_TOKEN (type))\n {\n break;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_AFTER_NEW:\n {\n if (scanner_scan_primary_expression (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_CLASS_DECLARATION:\n {\n if (context_p->token.type == LEXER_KEYW_EXTENDS)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_CLASS_EXTENDS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n else if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_CLASS_METHOD;\n /* FALLTHRU */\n }\n case SCAN_MODE_CLASS_METHOD:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR\n || stack_top == SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n\n lexer_skip_empty_statements (context_p);\n\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_source_start_t source_start;\n\n parser_stack_pop_uint8 (context_p);\n\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n }\n\n stack_top = context_p->stack_top_uint8;\n\n JERRY_ASSERT (stack_top == SCAN_STACK_CLASS_STATEMENT || stack_top == SCAN_STACK_CLASS_EXPRESSION);\n\n if (stack_top == SCAN_STACK_CLASS_STATEMENT)\n {\n /* The token is kept to disallow consuming a semicolon after it. */\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n parser_stack_pop_uint8 (context_p);\n break;\n }\n\n if (context_p->token.type == LEXER_LITERAL\n && LEXER_IS_IDENT_OR_STRING (context_p->token.lit_location.type)\n && lexer_compare_literal_to_string (context_p, \"constructor\", 11))\n {\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n scanner_source_start_t source_start;\n parser_stack_pop_uint8 (context_p);\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n\n scanner_info_t *info_p = scanner_insert_info (context_p, source_start.source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_CLASS_CONSTRUCTOR;\n parser_stack_push_uint8 (context_p, SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n }\n }\n\n if (lexer_token_is_identifier (context_p, \"static\", 6))\n {\n lexer_scan_identifier (context_p);\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (lexer_token_is_identifier (context_p, \"get\", 3)\n || lexer_token_is_identifier (context_p, \"set\", 3))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n }\n else if (lexer_token_is_identifier (context_p, \"async\", 5))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n else if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (literal_pool_flags & SCANNER_LITERAL_POOL_GENERATOR)\n {\n context_p->status_flags |= PARSER_IS_GENERATOR_FUNCTION;\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n lexer_next_token (context_p);\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCAN_MODE_POST_PRIMARY_EXPRESSION:\n {\n if (scanner_scan_post_primary_expression (context_p, &scanner_context, type, stack_top))\n {\n break;\n }\n type = (lexer_token_type_t) context_p->token.type;\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_END:\n {\n if (scanner_scan_primary_expression_end (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_OR_TERMINATOR:\n {\n if (type == LEXER_RIGHT_BRACE || type == LEXER_EOS)\n {\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_STATEMENT:\n {\n if (scanner_scan_statement (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_END:\n {\n if (scanner_scan_statement_end (context_p, &scanner_context, type) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n\n if (context_p->token.type == LEXER_EOS)\n {\n goto scan_completed;\n }\n\n break;\n }\n case SCAN_MODE_VAR_STATEMENT:\n {\n#if ENABLED (JERRY_ES2015)\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n uint8_t binding_type = SCANNER_BINDING_VAR;\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n binding_type = SCANNER_BINDING_LET;\n }\n else if (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START)\n {\n binding_type = SCANNER_BINDING_CONST;\n }\n\n scanner_push_destructuring_pattern (context_p, &scanner_context, binding_type, false);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n if (stack_top != SCAN_STACK_VAR && stack_top != SCAN_STACK_FOR_VAR_START)\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START);\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n }\n\n lexer_next_token (context_p);\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n }\n else if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n }\n }\n else\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n\n lexer_next_token (context_p);\n }\n#else /* !ENABLED (JERRY_ES2015) */\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n\n lexer_next_token (context_p);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n switch (context_p->token.type)\n {\n case LEXER_ASSIGN:\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n /* FALLTHRU */\n }\n case LEXER_COMMA:\n {\n lexer_next_token (context_p);\n continue;\n }\n }\n\n if (SCANNER_IS_FOR_START (stack_top))\n {\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n JERRY_ASSERT (!(scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT));\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n if (context_p->token.type != LEXER_SEMICOLON\n && context_p->token.type != LEXER_KEYW_IN\n && !SCANNER_IDENTIFIER_IS_OF ())\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR || stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_CONST);\n#else /* !ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n scanner_context.active_literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_EXPORT;\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n parser_stack_pop_uint8 (context_p);\n continue;\n }\n case SCAN_MODE_FUNCTION_ARGUMENTS:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_SCRIPT_FUNCTION\n || stack_top == SCAN_STACK_FUNCTION_STATEMENT\n || stack_top == SCAN_STACK_FUNCTION_EXPRESSION\n || stack_top == SCAN_STACK_FUNCTION_PROPERTY);\n\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n JERRY_ASSERT (literal_pool_p != NULL && (literal_pool_p->status_flags & SCANNER_LITERAL_POOL_FUNCTION));\n\n literal_pool_p->source_p = context_p->source_p;\n\n#if ENABLED (JERRY_ES2015)\n if (JERRY_UNLIKELY (scanner_context.async_source_p != NULL))\n {\n literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ASYNC;\n literal_pool_p->source_p = scanner_context.async_source_p;\n scanner_context.async_source_p = NULL;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LEFT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n /* FALLTHRU */\n }\n case SCAN_MODE_CONTINUE_FUNCTION_ARGUMENTS:\n {\n#endif /* ENABLED (JERRY_ES2015) */\n if (context_p->token.type != LEXER_RIGHT_PAREN && context_p->token.type != LEXER_EOS)\n {\n#if ENABLED (JERRY_ES2015)\n lexer_lit_location_t *argument_literal_p;\n#endif /* ENABLED (JERRY_ES2015) */\n\n while (true)\n {\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_THREE_DOTS)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n lexer_next_token (context_p);\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE || context_p->token.type == LEXER_LEFT_BRACE)\n {\n argument_literal_p = NULL;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n argument_literal_p = scanner_append_argument (context_p, &scanner_context);\n#else /* !ENABLED (JERRY_ES2015) */\n scanner_append_argument (context_p, &scanner_context);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_COMMA)\n {\n break;\n }\n lexer_next_token (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (argument_literal_p == NULL)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_append_hole (context_p, &scanner_context);\n scanner_push_destructuring_pattern (context_p, &scanner_context, SCANNER_BINDING_ARG, false);\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n if (argument_literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n JERRY_ASSERT (argument_literal_p->type & SCANNER_LITERAL_EARLY_CREATE);\n break;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = argument_literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (context_p->token.type == LEXER_EOS && stack_top == SCAN_STACK_SCRIPT_FUNCTION)\n {\n /* End of argument parsing. */\n scanner_info_t *scanner_info_p = (scanner_info_t *) scanner_malloc (context_p, sizeof (scanner_info_t));\n scanner_info_p->next_p = context_p->next_scanner_info_p;\n scanner_info_p->source_p = NULL;\n scanner_info_p->type = SCANNER_TYPE_END_ARGUMENTS;\n scanner_context.end_arguments_p = scanner_info_p;\n\n context_p->next_scanner_info_p = scanner_info_p;\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n context_p->line = 1;\n context_p->column = 1;\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n\n if (context_p->token.type != LEXER_RIGHT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n case SCAN_MODE_PROPERTY_NAME:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_OBJECT_LITERAL);\n\n if (lexer_scan_identifier (context_p))\n {\n lexer_check_property_modifier (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_COMPUTED_PROPERTY);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n if (context_p->token.type == LEXER_PROPERTY_GETTER\n#if ENABLED (JERRY_ES2015)\n || context_p->token.type == LEXER_KEYW_ASYNC\n || context_p->token.type == LEXER_MULTIPLY\n#endif /* ENABLED (JERRY_ES2015) */\n || context_p->token.type == LEXER_PROPERTY_SETTER)\n {\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n else if (context_p->token.type == LEXER_KEYW_ASYNC)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (lexer_consume_generator (context_p))\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n lexer_scan_identifier (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n parser_line_counter_t start_line = context_p->token.line;\n parser_line_counter_t start_column = context_p->token.column;\n bool is_ident = (context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n continue;\n }\n\n if (is_ident\n && (context_p->token.type == LEXER_COMMA\n || context_p->token.type == LEXER_RIGHT_BRACE\n || context_p->token.type == LEXER_ASSIGN))\n {\n context_p->source_p = context_p->token.lit_location.char_p;\n context_p->line = start_line;\n context_p->column = start_column;\n\n lexer_next_token (context_p);\n\n JERRY_ASSERT (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n continue;\n }\n\n scanner_add_reference (context_p, &scanner_context);\n\n lexer_next_token (context_p);\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_COLON)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n#if ENABLED (JERRY_ES2015)\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_BINDING:\n {\n JERRY_ASSERT (scanner_context.binding_type == SCANNER_BINDING_VAR\n || scanner_context.binding_type == SCANNER_BINDING_LET\n || scanner_context.binding_type == SCANNER_BINDING_CATCH\n || scanner_context.binding_type == SCANNER_BINDING_CONST\n || scanner_context.binding_type == SCANNER_BINDING_ARG\n || scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG);\n\n if (type == LEXER_THREE_DOTS)\n {\n lexer_next_token (context_p);\n type = (lexer_token_type_t) context_p->token.type;\n }\n\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n scanner_push_destructuring_pattern (context_p, &scanner_context, scanner_context.binding_type, true);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n continue;\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n\n if (scanner_context.binding_type == SCANNER_BINDING_VAR)\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n break;\n }\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_IS_ARROW_DESTRUCTURED_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n else\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (scanner_context.binding_type <= SCANNER_BINDING_CATCH)\n {\n JERRY_ASSERT ((scanner_context.binding_type == SCANNER_BINDING_LET)\n || (scanner_context.binding_type == SCANNER_BINDING_CATCH));\n\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n }\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n\n scanner_binding_item_t *binding_item_p;\n binding_item_p = (scanner_binding_item_t *) scanner_malloc (context_p, sizeof (scanner_binding_item_t));\n\n binding_item_p->next_p = scanner_context.active_binding_list_p->items_p;\n binding_item_p->literal_p = literal_p;\n\n scanner_context.active_binding_list_p->items_p = binding_item_p;\n\n lexer_next_token (context_p);\n if (context_p->token.type != LEXER_ASSIGN)\n {\n continue;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n lexer_next_token (context_p);\n }\n\nscan_completed:\n if (context_p->stack_top_uint8 != SCAN_STACK_SCRIPT\n && context_p->stack_top_uint8 != SCAN_STACK_SCRIPT_FUNCTION)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_pop_literal_pool (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (scanner_context.active_binding_list_p == NULL);\n#endif /* ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (scanner_context.active_literal_pool_p == NULL);\n\n#ifndef JERRY_NDEBUG\n scanner_context.context_status_flags |= PARSER_SCANNING_SUCCESSFUL;\n#endif /* !JERRY_NDEBUG */\n }\n PARSER_CATCH\n {\n#if ENABLED (JERRY_ES2015)\n while (scanner_context.active_binding_list_p != NULL)\n {\n scanner_pop_binding_list (&scanner_context);\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (JERRY_UNLIKELY (context_p->error != PARSER_ERR_OUT_OF_MEMORY))\n {\n /* Ignore the errors thrown by the lexer. */\n context_p->error = PARSER_ERR_NO_ERROR;\n\n /* The following code may allocate memory, so it is enclosed in a try/catch. */\n PARSER_TRY (context_p->try_buffer)\n {\n #if ENABLED (JERRY_ES2015)\n if (scanner_context.status_flags & SCANNER_CONTEXT_THROW_ERR_ASYNC_FUNCTION)\n {\n JERRY_ASSERT (scanner_context.async_source_p != NULL);\n\n scanner_info_t *info_p;\n info_p = scanner_insert_info (context_p, scanner_context.async_source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_ERR_ASYNC_FUNCTION;\n }\n #endif /* ENABLED (JERRY_ES2015) */\n\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_pop_literal_pool (context_p, &scanner_context);\n }\n }\n PARSER_CATCH\n {\n JERRY_ASSERT (context_p->error == PARSER_ERR_OUT_OF_MEMORY);\n }\n PARSER_TRY_END\n }\n\n JERRY_ASSERT (context_p->error == PARSER_ERR_NO_ERROR || context_p->error == PARSER_ERR_OUT_OF_MEMORY);\n\n if (context_p->error == PARSER_ERR_OUT_OF_MEMORY)\n {\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n scanner_context.active_literal_pool_p = literal_pool_p->prev_p;\n\n parser_list_free (&literal_pool_p->literal_pool);\n scanner_free (literal_pool_p, sizeof (scanner_literal_pool_t));\n }\n\n parser_stack_free (context_p);\n return;\n }\n }\n PARSER_TRY_END\n\n context_p->status_flags = scanner_context.context_status_flags;\n scanner_reverse_info_list (context_p);\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n scanner_info_t *info_p = context_p->next_scanner_info_p;\n const uint8_t *source_start_p = (arg_list_p == NULL) ? source_p : arg_list_p;\n\n while (info_p->type != SCANNER_TYPE_END)\n {\n const char *name_p = NULL;\n bool print_location = false;\n\n switch (info_p->type)\n {\n case SCANNER_TYPE_END_ARGUMENTS:\n {\n JERRY_DEBUG_MSG (\" END_ARGUMENTS\\n\");\n source_start_p = source_p;\n break;\n }\n case SCANNER_TYPE_FUNCTION:\n case SCANNER_TYPE_BLOCK:\n {\n const uint8_t *prev_source_p = info_p->source_p - 1;\n const uint8_t *data_p;\n\n if (info_p->type == SCANNER_TYPE_FUNCTION)\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" FUNCTION: flags: 0x%x declarations: %d\",\n (int) info_p->u8_arg,\n (int) info_p->u16_arg);\n }\n else\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" BLOCK:\");\n }\n\n JERRY_DEBUG_MSG (\" source:%d\\n\", (int) (info_p->source_p - source_start_p));\n\n while (data_p[0] != SCANNER_STREAM_TYPE_END)\n {\n switch (data_p[0] & SCANNER_STREAM_TYPE_MASK)\n {\n case SCANNER_STREAM_TYPE_VAR:\n {\n JERRY_DEBUG_MSG (\" VAR \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_LET:\n {\n JERRY_DEBUG_MSG (\" LET \");\n break;\n }\n case SCANNER_STREAM_TYPE_CONST:\n {\n JERRY_DEBUG_MSG (\" CONST \");\n break;\n }\n case SCANNER_STREAM_TYPE_LOCAL:\n {\n JERRY_DEBUG_MSG (\" LOCAL \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n case SCANNER_STREAM_TYPE_IMPORT:\n {\n JERRY_DEBUG_MSG (\" IMPORT \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n case SCANNER_STREAM_TYPE_ARG:\n {\n JERRY_DEBUG_MSG (\" ARG \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" ARG_FUNC \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG_FUNC \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_FUNC:\n {\n JERRY_DEBUG_MSG (\" FUNC \");\n break;\n }\n default:\n {\n JERRY_ASSERT ((data_p[0] & SCANNER_STREAM_TYPE_MASK) == SCANNER_STREAM_TYPE_HOLE);\n JERRY_DEBUG_MSG (\" HOLE\\n\");\n data_p++;\n continue;\n }\n }\n\n size_t length;\n\n if (!(data_p[0] & SCANNER_STREAM_UINT16_DIFF))\n {\n if (data_p[2] != 0)\n {\n prev_source_p += data_p[2];\n length = 2 + 1;\n }\n else\n {\n memcpy (&prev_source_p, data_p + 2 + 1, sizeof (const uint8_t *));\n length = 2 + 1 + sizeof (const uint8_t *);\n }\n }\n else\n {\n int32_t diff = ((int32_t) data_p[2]) | ((int32_t) data_p[3]) << 8;\n\n if (diff <= UINT8_MAX)\n {\n diff = -diff;\n }\n\n prev_source_p += diff;\n length = 2 + 2;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (data_p[0] & SCANNER_STREAM_EARLY_CREATE)\n {\n JERRY_ASSERT (data_p[0] & SCANNER_STREAM_NO_REG);\n JERRY_DEBUG_MSG (\"*\");\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (data_p[0] & SCANNER_STREAM_NO_REG)\n {\n JERRY_DEBUG_MSG (\"* \");\n }\n\n JERRY_DEBUG_MSG (\"'%.*s'\\n\", data_p[1], (char *) prev_source_p);\n prev_source_p += data_p[1];\n data_p += length;\n }\n break;\n }\n case SCANNER_TYPE_WHILE:\n {\n name_p = \"WHILE\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_FOR:\n {\n scanner_for_info_t *for_info_p = (scanner_for_info_t *) info_p;\n JERRY_DEBUG_MSG (\" FOR: source:%d expression:%d[%d:%d] end:%d[%d:%d]\\n\",\n (int) (for_info_p->info.source_p - source_start_p),\n (int) (for_info_p->expression_location.source_p - source_start_p),\n (int) for_info_p->expression_location.line,\n (int) for_info_p->expression_location.column,\n (int) (for_info_p->end_location.source_p - source_start_p),\n (int) for_info_p->end_location.line,\n (int) for_info_p->end_location.column);\n break;\n }\n case SCANNER_TYPE_FOR_IN:\n {\n name_p = \"FOR-IN\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_FOR_OF:\n {\n name_p = \"FOR-OF\";\n print_location = true;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_TYPE_SWITCH:\n {\n JERRY_DEBUG_MSG (\" SWITCH: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n\n scanner_case_info_t *current_case_p = ((scanner_switch_info_t *) info_p)->case_p;\n\n while (current_case_p != NULL)\n {\n JERRY_DEBUG_MSG (\" CASE: location:%d[%d:%d]\\n\",\n (int) (current_case_p->location.source_p - source_start_p),\n (int) current_case_p->location.line,\n (int) current_case_p->location.column);\n\n current_case_p = current_case_p->next_p;\n }\n break;\n }\n case SCANNER_TYPE_CASE:\n {\n name_p = \"CASE\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_INITIALIZER:\n {\n name_p = \"INITIALIZER\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_CLASS_CONSTRUCTOR:\n {\n JERRY_DEBUG_MSG (\" CLASS-CONSTRUCTOR: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n print_location = false;\n break;\n }\n case SCANNER_TYPE_LET_EXPRESSION:\n {\n JERRY_DEBUG_MSG (\" LET_EXPRESSION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_REDECLARED:\n {\n JERRY_DEBUG_MSG (\" ERR_REDECLARED: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_ASYNC_FUNCTION:\n {\n JERRY_DEBUG_MSG (\" ERR_ASYNC_FUNCTION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (print_location)\n {\n scanner_location_info_t *location_info_p = (scanner_location_info_t *) info_p;\n JERRY_DEBUG_MSG (\" %s: source:%d location:%d[%d:%d]\\n\",\n name_p,\n (int) (location_info_p->info.source_p - source_start_p),\n (int) (location_info_p->location.source_p - source_start_p),\n (int) location_info_p->location.line,\n (int) location_info_p->location.column);\n }\n\n info_p = info_p->next_p;\n }\n\n JERRY_DEBUG_MSG (\"\\n--- Scanning end ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n parser_stack_free (context_p);\n} /* scanner_scan_all */", "func_hash": 105454422257663761598357792653580219932, "file_name": "js-scanner.c", "file_hash": 55354157720381743794606423583623078160, "cwe": ["CWE-703"], "cve": "CVE-2020-13649", "cve_desc": "parser/js/js-scanner.c in JerryScript 2.2.0 mishandles errors during certain out-of-memory conditions, as demonstrated by a scanner_reverse_info_list NULL pointer dereference and a scanner_scan_all assertion failure.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13649"} {"idx": 198448, "project": "tensorflow", "commit_id": "0d45ea1ca641b21b73bcf9c00e0179cda284e7e7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0d45ea1ca641b21b73bcf9c00e0179cda284e7e7", "commit_message": "Prevent one more div by 0 in TFLite\n\nPiperOrigin-RevId: 370800114\nChange-Id: I6b956aeb8c458cc6f514408d2e89ffacfe249e57", "target": 1, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n auto data_type = output->type;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||\n data_type == kTfLiteInt64);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n const int block_size = params->block_size;\n const int input_height = input->dims->data[1];\n const int input_width = input->dims->data[2];\n int output_height = input_height / block_size;\n int output_width = input_width / block_size;\n\n TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size);\n TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = output_height;\n output_size->data[2] = output_width;\n output_size->data[3] = input->dims->data[3] * block_size * block_size;\n\n return context->ResizeTensor(context, output, output_size);\n}", "func_hash": 83942713041391726667764124263161304520, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29587", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The `Prepare` step of the `SpaceToDepth` TFLite operator does not check for 0 before division(https://github.com/tensorflow/tensorflow/blob/5f7975d09eac0f10ed8a17dbb6f5964977725adc/tensorflow/lite/kernels/space_to_depth.cc#L63-L67). An attacker can craft a model such that `params->block_size` would be zero. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29587"} {"idx": 274812, "project": "tensorflow", "commit_id": "0d45ea1ca641b21b73bcf9c00e0179cda284e7e7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0d45ea1ca641b21b73bcf9c00e0179cda284e7e7", "commit_message": "Prevent one more div by 0 in TFLite\n\nPiperOrigin-RevId: 370800114\nChange-Id: I6b956aeb8c458cc6f514408d2e89ffacfe249e57", "target": 0, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n auto data_type = output->type;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||\n data_type == kTfLiteInt64);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n const int block_size = params->block_size;\n TF_LITE_ENSURE(context, block_size > 0);\n const int input_height = input->dims->data[1];\n const int input_width = input->dims->data[2];\n int output_height = input_height / block_size;\n int output_width = input_width / block_size;\n\n TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size);\n TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = output_height;\n output_size->data[2] = output_width;\n output_size->data[3] = input->dims->data[3] * block_size * block_size;\n\n return context->ResizeTensor(context, output, output_size);\n}", "func_hash": 183826125159213279773062350451228767286, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-29587", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. The `Prepare` step of the `SpaceToDepth` TFLite operator does not check for 0 before division(https://github.com/tensorflow/tensorflow/blob/5f7975d09eac0f10ed8a17dbb6f5964977725adc/tensorflow/lite/kernels/space_to_depth.cc#L63-L67). An attacker can craft a model such that `params->block_size` would be zero. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29587"} {"idx": 198469, "project": "gpac", "commit_id": "3b84ffcbacf144ce35650df958432f472b6483f8", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/3b84ffcbacf144ce35650df958432f472b6483f8", "commit_message": "fixed #1735", "target": 1, "func": "void gf_isom_cenc_get_default_info_internal(GF_TrackBox *trak, u32 sampleDescriptionIndex, u32 *container_type, Bool *default_IsEncrypted, u8 *crypt_byte_block, u8 *skip_byte_block, const u8 **key_info, u32 *key_info_size)\n{\n\tGF_ProtectionSchemeInfoBox *sinf;\n\n\n\t//setup all default as not encrypted\n\tif (default_IsEncrypted) *default_IsEncrypted = GF_FALSE;\n\tif (crypt_byte_block) *crypt_byte_block = 0;\n\tif (skip_byte_block) *skip_byte_block = 0;\n\tif (container_type) *container_type = 0;\n\tif (key_info) *key_info = NULL;\n\tif (key_info_size) *key_info_size = 0;\n\n\tsinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBCS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_PIFF_SCHEME, NULL);\n\n\tif (!sinf) {\n\t\tu32 i, nb_stsd = gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes);\n\t\tfor (i=0; iMedia->information->sampleTable->SampleDescription->child_boxes, i);\n\t\t\ta_sinf = (GF_ProtectionSchemeInfoBox *) gf_isom_box_find_child(sentry->child_boxes, GF_ISOM_BOX_TYPE_SINF);\n\t\t\tif (!a_sinf) continue;\n\t\t\t//signal default (not encrypted)\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (sinf && sinf->info && sinf->info->tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = sinf->info->tenc->isProtected;\n\t\tif (crypt_byte_block) *crypt_byte_block = sinf->info->tenc->crypt_byte_block;\n\t\tif (skip_byte_block) *skip_byte_block = sinf->info->tenc->skip_byte_block;\n\t\tif (key_info) *key_info = sinf->info->tenc->key_info;\n\t\tif (key_info_size) {\n\t\t\t*key_info_size = 20;\n\t\t\tif (!sinf->info->tenc->key_info[3])\n\t\t\t\t*key_info_size += 1 + sinf->info->tenc->key_info[20];\n\t\t}\n\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t} else if (sinf && sinf->info && sinf->info->piff_tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\tif (key_info) *key_info = sinf->info->piff_tenc->key_info;\n\t\tif (key_info_size) *key_info_size = 19;\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t} else {\n\t\tu32 i, count = 0;\n\t\tGF_CENCSampleEncryptionGroupEntry *seig_entry = NULL;\n\n\t\tif (!trak->moov->mov->is_smooth)\n\t\t\tcount = gf_list_count(trak->Media->information->sampleTable->sampleGroupsDescription);\n\n\t\tfor (i=0; iMedia->information->sampleTable->sampleGroupsDescription, i);\n\t\t\tif (sgdesc->grouping_type!=GF_ISOM_SAMPLE_GROUP_SEIG) continue;\n\t\t\tif (sgdesc->default_description_index)\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, sgdesc->default_description_index-1);\n\t\t\telse\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\tif (!seig_entry->key_info[0])\n\t\t\t\tseig_entry = NULL;\n\t\t\tbreak;\n\t\t}\n\t\tif (seig_entry) {\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = seig_entry->IsProtected;\n\t\t\tif (crypt_byte_block) *crypt_byte_block = seig_entry->crypt_byte_block;\n\t\t\tif (skip_byte_block) *skip_byte_block = seig_entry->skip_byte_block;\n\t\t\tif (key_info) *key_info = seig_entry->key_info;\n\t\t\tif (key_info_size) *key_info_size = seig_entry->key_info_size;\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\t} else {\n\t\t\tif (! trak->moov->mov->is_smooth ) {\n\t\t\t\ttrak->moov->mov->is_smooth = GF_TRUE;\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] senc box without tenc, assuming MS smooth+piff\\n\"));\n\t\t\t}\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\t\t//set default value, overwritten below\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t\t}\n\t}\n\n\tif (container_type && trak->sample_encryption) {\n\t\tif (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_SENC) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\telse if (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_UUID) *container_type = ((GF_UUIDBox*)trak->sample_encryption)->internal_4cc;\n\t}\n}", "func_hash": 99327200489611178525631890685348730887, "file_name": "drm_sample.c", "file_hash": 23993698983666150791443597067245479767, "cwe": ["CWE-476"], "cve": "CVE-2021-31259", "cve_desc": "The gf_isom_cenc_get_default_info_internal function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31259"} {"idx": 275434, "project": "gpac", "commit_id": "3b84ffcbacf144ce35650df958432f472b6483f8", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/3b84ffcbacf144ce35650df958432f472b6483f8", "commit_message": "fixed #1735", "target": 0, "func": "void gf_isom_cenc_get_default_info_internal(GF_TrackBox *trak, u32 sampleDescriptionIndex, u32 *container_type, Bool *default_IsEncrypted, u8 *crypt_byte_block, u8 *skip_byte_block, const u8 **key_info, u32 *key_info_size)\n{\n\tGF_ProtectionSchemeInfoBox *sinf;\n\n\n\t//setup all default as not encrypted\n\tif (default_IsEncrypted) *default_IsEncrypted = GF_FALSE;\n\tif (crypt_byte_block) *crypt_byte_block = 0;\n\tif (skip_byte_block) *skip_byte_block = 0;\n\tif (container_type) *container_type = 0;\n\tif (key_info) *key_info = NULL;\n\tif (key_info_size) *key_info_size = 0;\n\n\tsinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBCS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_PIFF_SCHEME, NULL);\n\n\tif (!sinf) {\n\t\tu32 i, nb_stsd = gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes);\n\t\tfor (i=0; iMedia->information->sampleTable->SampleDescription->child_boxes, i);\n\t\t\ta_sinf = (GF_ProtectionSchemeInfoBox *) gf_isom_box_find_child(sentry->child_boxes, GF_ISOM_BOX_TYPE_SINF);\n\t\t\tif (!a_sinf) continue;\n\t\t\t//signal default (not encrypted)\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (sinf && sinf->info && sinf->info->tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = sinf->info->tenc->isProtected;\n\t\tif (crypt_byte_block) *crypt_byte_block = sinf->info->tenc->crypt_byte_block;\n\t\tif (skip_byte_block) *skip_byte_block = sinf->info->tenc->skip_byte_block;\n\t\tif (key_info) *key_info = sinf->info->tenc->key_info;\n\t\tif (key_info_size) {\n\t\t\t*key_info_size = 20;\n\t\t\tif (!sinf->info->tenc->key_info[3])\n\t\t\t\t*key_info_size += 1 + sinf->info->tenc->key_info[20];\n\t\t}\n\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t} else if (sinf && sinf->info && sinf->info->piff_tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\tif (key_info) *key_info = sinf->info->piff_tenc->key_info;\n\t\tif (key_info_size) *key_info_size = 19;\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t} else {\n\t\tu32 i, count = 0;\n\t\tGF_CENCSampleEncryptionGroupEntry *seig_entry = NULL;\n\n\t\tif (!trak->moov->mov->is_smooth)\n\t\t\tcount = gf_list_count(trak->Media->information->sampleTable->sampleGroupsDescription);\n\n\t\tfor (i=0; iMedia->information->sampleTable->sampleGroupsDescription, i);\n\t\t\tif (sgdesc->grouping_type!=GF_ISOM_SAMPLE_GROUP_SEIG) continue;\n\t\t\tif (sgdesc->default_description_index)\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, sgdesc->default_description_index-1);\n\t\t\telse\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\tif (seig_entry && !seig_entry->key_info[0])\n\t\t\t\tseig_entry = NULL;\n\t\t\tbreak;\n\t\t}\n\t\tif (seig_entry) {\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = seig_entry->IsProtected;\n\t\t\tif (crypt_byte_block) *crypt_byte_block = seig_entry->crypt_byte_block;\n\t\t\tif (skip_byte_block) *skip_byte_block = seig_entry->skip_byte_block;\n\t\t\tif (key_info) *key_info = seig_entry->key_info;\n\t\t\tif (key_info_size) *key_info_size = seig_entry->key_info_size;\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\t} else {\n\t\t\tif (! trak->moov->mov->is_smooth ) {\n\t\t\t\ttrak->moov->mov->is_smooth = GF_TRUE;\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] senc box without tenc, assuming MS smooth+piff\\n\"));\n\t\t\t}\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\t\t//set default value, overwritten below\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t\t}\n\t}\n\n\tif (container_type && trak->sample_encryption) {\n\t\tif (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_SENC) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\telse if (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_UUID) *container_type = ((GF_UUIDBox*)trak->sample_encryption)->internal_4cc;\n\t}\n}", "func_hash": 129256017458997016432638086188678116807, "file_name": "drm_sample.c", "file_hash": 124612895538832440769832293391565862577, "cwe": ["CWE-476"], "cve": "CVE-2021-31259", "cve_desc": "The gf_isom_cenc_get_default_info_internal function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31259"} {"idx": 198557, "project": "tensorflow", "commit_id": "8ba6fa29cd8bf9cef9b718dc31c78c73081f5b31", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8ba6fa29cd8bf9cef9b718dc31c78c73081f5b31", "commit_message": "Fix heap-buffer-overflow issue with `tf.raw_ops.SparseSplit`.\n\nPiperOrigin-RevId: 371242872\nChange-Id: I482bb3d12602c7c3cc9446f97fb9f584bb98e9a4", "target": 1, "func": "inline Status SparseTensor::Split(const SparseTensor& input_tensor,\n const int split_dim, const int num_split,\n std::vector* result) {\n std::vector output_indices;\n std::vector output_values;\n std::vector output_shapes;\n output_indices.reserve(num_split);\n output_values.reserve(num_split);\n output_shapes.reserve(num_split);\n\n std::vector::Matrix> output_indices_t;\n std::vector::Vec> output_values_t;\n output_indices_t.reserve(num_split);\n output_values_t.reserve(num_split);\n auto input_values_t = input_tensor.values().vec();\n auto input_indices_t = input_tensor.indices().matrix();\n\n std::vector num_values(num_split, 0);\n const int num_dim = input_tensor.shape().size();\n const int split_dim_size = input_tensor.shape()[split_dim];\n const int split_size = split_dim_size / num_split;\n\n if (!(num_split > 0 && num_split <= split_dim_size)) {\n return errors::InvalidArgument(\"num_split must be in the interval (0, \",\n split_dim_size, \"]\");\n }\n if (!(split_dim >= 0 && split_dim < num_dim)) {\n return errors::InvalidArgument(\"num_dim must be in the interval [0, \",\n num_dim, \")\");\n }\n\n const int residual = split_dim_size % num_split;\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_tensor.indices().matrix()(i, split_dim);\n int slice_index = GetSliceIndex(dim, split_size, residual);\n num_values[slice_index]++;\n }\n\n for (int i = 0; i < num_split; ++i) {\n // TODO(ataei): Pass an allocator to avoid allocating large memory buffer.\n output_indices.emplace_back(DT_INT64,\n TensorShape({num_values[i], num_dim}));\n output_values.emplace_back(DataTypeToEnum::v(),\n TensorShape({num_values[i]}));\n output_shapes.emplace_back(input_tensor.shape());\n output_indices_t.emplace_back(output_indices[i].matrix());\n output_values_t.emplace_back(output_values[i].vec());\n const int size = GetSliceShape(i, split_size, residual);\n output_shapes[i].set_dim(split_dim, size);\n }\n\n std::vector values_inserted_in_slice(num_split, 0);\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_indices_t(i, split_dim);\n const int slice_index = GetSliceIndex(dim, split_size, residual);\n const int slice_dim = values_inserted_in_slice[slice_index]++;\n output_values_t[slice_index](slice_dim) = input_values_t(i);\n for (int j = 0; j < num_dim; ++j) {\n const int64 original_dim = input_indices_t(i, j);\n output_indices_t[slice_index](slice_dim, j) =\n (j == split_dim)\n ? GetDimensionInSlice(original_dim, split_size, residual)\n : original_dim;\n }\n }\n\n result->clear();\n result->reserve(num_split);\n for (int i = 0; i < num_split; ++i) {\n SparseTensor tensor;\n Status create_status =\n Create(output_indices[i], output_values[i], output_shapes[i], &tensor);\n if (!create_status.ok()) {\n return create_status;\n }\n result->push_back(std::move(tensor));\n }\n return Status::OK();\n}", "func_hash": 225464515410200786942331363302206128963, "file_name": "sparse_tensor.h", "file_hash": 298289814909722074518594061431660340252, "cwe": ["CWE-703"], "cve": "CVE-2021-29558", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `tf.raw_ops.SparseSplit`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/699bff5d961f0abfde8fa3f876e6d241681fbef8/tensorflow/core/util/sparse/sparse_tensor.h#L528-L530) accesses an array element based on a user controlled offset. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29558"} {"idx": 277030, "project": "tensorflow", "commit_id": "8ba6fa29cd8bf9cef9b718dc31c78c73081f5b31", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8ba6fa29cd8bf9cef9b718dc31c78c73081f5b31", "commit_message": "Fix heap-buffer-overflow issue with `tf.raw_ops.SparseSplit`.\n\nPiperOrigin-RevId: 371242872\nChange-Id: I482bb3d12602c7c3cc9446f97fb9f584bb98e9a4", "target": 0, "func": "inline Status SparseTensor::Split(const SparseTensor& input_tensor,\n const int split_dim, const int num_split,\n std::vector* result) {\n std::vector output_indices;\n std::vector output_values;\n std::vector output_shapes;\n output_indices.reserve(num_split);\n output_values.reserve(num_split);\n output_shapes.reserve(num_split);\n\n std::vector::Matrix> output_indices_t;\n std::vector::Vec> output_values_t;\n output_indices_t.reserve(num_split);\n output_values_t.reserve(num_split);\n auto input_values_t = input_tensor.values().vec();\n auto input_indices_t = input_tensor.indices().matrix();\n\n std::vector num_values(num_split, 0);\n const int num_dim = input_tensor.shape().size();\n const int split_dim_size = input_tensor.shape()[split_dim];\n const int split_size = split_dim_size / num_split;\n\n if (!(num_split > 0 && num_split <= split_dim_size)) {\n return errors::InvalidArgument(\"num_split must be in the interval (0, \",\n split_dim_size, \"]\");\n }\n if (!(split_dim >= 0 && split_dim < num_dim)) {\n return errors::InvalidArgument(\"num_dim must be in the interval [0, \",\n num_dim, \")\");\n }\n\n const int residual = split_dim_size % num_split;\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_tensor.indices().matrix()(i, split_dim);\n int slice_index = GetSliceIndex(dim, split_size, residual);\n if (slice_index >= num_values.size()) {\n return errors::InvalidArgument(\"Slice index \", slice_index,\n \" is larger than num_split.\");\n }\n num_values[slice_index]++;\n }\n\n for (int i = 0; i < num_split; ++i) {\n // TODO(ataei): Pass an allocator to avoid allocating large memory buffer.\n output_indices.emplace_back(DT_INT64,\n TensorShape({num_values[i], num_dim}));\n output_values.emplace_back(DataTypeToEnum::v(),\n TensorShape({num_values[i]}));\n output_shapes.emplace_back(input_tensor.shape());\n output_indices_t.emplace_back(output_indices[i].matrix());\n output_values_t.emplace_back(output_values[i].vec());\n const int size = GetSliceShape(i, split_size, residual);\n output_shapes[i].set_dim(split_dim, size);\n }\n\n std::vector values_inserted_in_slice(num_split, 0);\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_indices_t(i, split_dim);\n const int slice_index = GetSliceIndex(dim, split_size, residual);\n const int slice_dim = values_inserted_in_slice[slice_index]++;\n output_values_t[slice_index](slice_dim) = input_values_t(i);\n for (int j = 0; j < num_dim; ++j) {\n const int64 original_dim = input_indices_t(i, j);\n output_indices_t[slice_index](slice_dim, j) =\n (j == split_dim)\n ? GetDimensionInSlice(original_dim, split_size, residual)\n : original_dim;\n }\n }\n\n result->clear();\n result->reserve(num_split);\n for (int i = 0; i < num_split; ++i) {\n SparseTensor tensor;\n Status create_status =\n Create(output_indices[i], output_values[i], output_shapes[i], &tensor);\n if (!create_status.ok()) {\n return create_status;\n }\n result->push_back(std::move(tensor));\n }\n return Status::OK();\n}", "func_hash": 223964998829728917751371054545417203078, "file_name": "sparse_tensor.h", "file_hash": 154749475892699056540412392589289020037, "cwe": ["CWE-703"], "cve": "CVE-2021-29558", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a heap buffer overflow in `tf.raw_ops.SparseSplit`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/699bff5d961f0abfde8fa3f876e6d241681fbef8/tensorflow/core/util/sparse/sparse_tensor.h#L528-L530) accesses an array element based on a user controlled offset. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29558"} {"idx": 198559, "project": "ghostpdl", "commit_id": "ab109aaeb3ddba59518b036fb288402a65cf7ce8", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=ab109aaeb3ddba59518b036fb288402a65cf7ce8", "commit_message": "Bug 694724: Have filenameforall and getenv honor SAFER", "target": 1, "func": "file_continue(i_ctx_t *i_ctx_p)\n{\n os_ptr op = osp;\n es_ptr pscratch = esp - 2;\n file_enum *pfen = r_ptr(esp - 1, file_enum);\n int devlen = esp[-3].value.intval;\n gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);\n uint len = r_size(pscratch);\n uint code;\n\n if (len < devlen)\n return_error(gs_error_rangecheck); /* not even room for device len */\n memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);\n code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,\n len - devlen);\n if (code == ~(uint) 0) { /* all done */\n esp -= 5; /* pop proc, pfen, devlen, iodev , mark */\n return o_pop_estack;\n } else if (code > len) /* overran string */\n return_error(gs_error_rangecheck);\n else {\n push(1);\n ref_assign(op, pscratch);\n r_set_size(op, code + devlen);\n push_op_estack(file_continue); /* come again */\n *++esp = pscratch[2]; /* proc */\n return o_push_estack;\n }\n}", "func_hash": 120325101549427873969709546076988842608, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2013-5653", "cve_desc": "The getenv and filenameforall functions in Ghostscript 9.10 ignore the \"-dSAFER\" argument, which allows remote attackers to read data via a crafted postscript file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-5653"} {"idx": 277036, "project": "ghostpdl", "commit_id": "ab109aaeb3ddba59518b036fb288402a65cf7ce8", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=ab109aaeb3ddba59518b036fb288402a65cf7ce8", "commit_message": "Bug 694724: Have filenameforall and getenv honor SAFER", "target": 0, "func": "file_continue(i_ctx_t *i_ctx_p)\n{\n os_ptr op = osp;\n es_ptr pscratch = esp - 2;\n file_enum *pfen = r_ptr(esp - 1, file_enum);\n int devlen = esp[-3].value.intval;\n gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);\n uint len = r_size(pscratch);\n uint code;\n\n if (len < devlen)\n return_error(gs_error_rangecheck); /* not even room for device len */\n\n do {\n memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);\n code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,\n len - devlen);\n if (code == ~(uint) 0) { /* all done */\n esp -= 5; /* pop proc, pfen, devlen, iodev , mark */\n return o_pop_estack;\n } else if (code > len) /* overran string */\n return_error(gs_error_rangecheck);\n else if (iodev != iodev_default(imemory)\n || (check_file_permissions_reduced(i_ctx_p, (char *)pscratch->value.bytes, code + devlen, \"PermitFileReading\")) == 0) {\n push(1);\n ref_assign(op, pscratch);\n r_set_size(op, code + devlen);\n push_op_estack(file_continue); /* come again */\n *++esp = pscratch[2]; /* proc */\n return o_push_estack;\n }\n } while(1);\n}", "func_hash": 255355658033032146221394353821789288123, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2013-5653", "cve_desc": "The getenv and filenameforall functions in Ghostscript 9.10 ignore the \"-dSAFER\" argument, which allows remote attackers to read data via a crafted postscript file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-5653"} {"idx": 198573, "project": "openexr", "commit_id": "2a18ed424a854598c2a20b5dd7e782b436a1e753", "project_url": "https://github.com/AcademySoftwareFoundation/openexr", "commit_url": "https://github.com/AcademySoftwareFoundation/openexr/commit/2a18ed424a854598c2a20b5dd7e782b436a1e753", "commit_message": "Avoid overflow in calculateNumTiles when size=MAX_INT (#825)\n\n* Avoid overflow in calculateNumTiles when size=MAX_INT\n\nSigned-off-by: Cary Phillips \n\n* Compute level size with 64 bits to avoid overflow\n\nSigned-off-by: Cary Phillips ", "target": 1, "func": "calculateNumTiles (int *numTiles,\n\t\t int numLevels,\n\t\t int min, int max,\n\t\t int size,\n\t\t LevelRoundingMode rmode)\n{\n for (int i = 0; i < numLevels; i++)\n {\n int l = levelSize (min, max, i, rmode);\n if (l > std::numeric_limits::max() - size + 1)\n throw IEX_NAMESPACE::ArgExc (\"Invalid size.\");\n\n numTiles[i] = (l + size - 1) / size;\n }\n}", "func_hash": 165044343827247220429334860758835087021, "file_name": "ImfTiledMisc.cpp", "file_hash": 260439999022624240152956062519351511030, "cwe": ["CWE-190"], "cve": "CVE-2021-3475", "cve_desc": "There is a flaw in OpenEXR in versions before 3.0.0-beta. An attacker who can submit a crafted file to be processed by OpenEXR could cause an integer overflow, potentially leading to problems with application availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3475"} {"idx": 277662, "project": "openexr", "commit_id": "2a18ed424a854598c2a20b5dd7e782b436a1e753", "project_url": "https://github.com/AcademySoftwareFoundation/openexr", "commit_url": "https://github.com/AcademySoftwareFoundation/openexr/commit/2a18ed424a854598c2a20b5dd7e782b436a1e753", "commit_message": "Avoid overflow in calculateNumTiles when size=MAX_INT (#825)\n\n* Avoid overflow in calculateNumTiles when size=MAX_INT\n\nSigned-off-by: Cary Phillips \n\n* Compute level size with 64 bits to avoid overflow\n\nSigned-off-by: Cary Phillips ", "target": 0, "func": "calculateNumTiles (int *numTiles,\n\t\t int numLevels,\n\t\t int min, int max,\n\t\t int size,\n\t\t LevelRoundingMode rmode)\n{\n for (int i = 0; i < numLevels; i++)\n {\n // use 64 bits to avoid int overflow if size is large.\n Int64 l = levelSize (min, max, i, rmode);\n numTiles[i] = (l + size - 1) / size;\n }\n}", "func_hash": 172809876146767485423584500669746906428, "file_name": "ImfTiledMisc.cpp", "file_hash": 332338748418967449154774475118654331971, "cwe": ["CWE-190"], "cve": "CVE-2021-3475", "cve_desc": "There is a flaw in OpenEXR in versions before 3.0.0-beta. An attacker who can submit a crafted file to be processed by OpenEXR could cause an integer overflow, potentially leading to problems with application availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3475"} {"idx": 198585, "project": "vim", "commit_id": "a6f9e300161f4cb54713da22f65b261595e8e614", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/a6f9e300161f4cb54713da22f65b261595e8e614", "commit_message": "patch 9.0.0102: reading past end of line with insert mode completion\n\nProblem: Reading past end of line with insert mode completion.\nSolution: Check text length.", "target": 1, "func": "ins_comp_get_next_word_or_line(\n\tbuf_T\t*ins_buf,\t\t// buffer being scanned\n\tpos_T\t*cur_match_pos,\t\t// current match position\n\tint\t*match_len,\n\tint\t*cont_s_ipos)\t\t// next ^X<> will set initial_pos\n{\n char_u\t*ptr;\n int\t\tlen;\n\n *match_len = 0;\n ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +\n\tcur_match_pos->col;\n if (ctrl_x_mode_line_or_eval())\n {\n\tif (compl_status_adding())\n\t{\n\t if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)\n\t\treturn NULL;\n\t ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t if (!p_paste)\n\t\tptr = skipwhite(ptr);\n\t}\n\tlen = (int)STRLEN(ptr);\n }\n else\n {\n\tchar_u\t*tmp_ptr = ptr;\n\n\tif (compl_status_adding())\n\t{\n\t tmp_ptr += compl_length;\n\t // Skip if already inside a word.\n\t if (vim_iswordp(tmp_ptr))\n\t\treturn NULL;\n\t // Find start of next word.\n\t tmp_ptr = find_word_start(tmp_ptr);\n\t}\n\t// Find end of this word.\n\ttmp_ptr = find_word_end(tmp_ptr);\n\tlen = (int)(tmp_ptr - ptr);\n\n\tif (compl_status_adding() && len == compl_length)\n\t{\n\t if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)\n\t {\n\t\t// Try next line, if any. the new word will be\n\t\t// \"join\" as if the normal command \"J\" was used.\n\t\t// IOSIZE is always greater than\n\t\t// compl_length, so the next STRNCPY always\n\t\t// works -- Acevedo\n\t\tSTRNCPY(IObuff, ptr, len);\n\t\tptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t\ttmp_ptr = ptr = skipwhite(ptr);\n\t\t// Find start of next word.\n\t\ttmp_ptr = find_word_start(tmp_ptr);\n\t\t// Find end of next word.\n\t\ttmp_ptr = find_word_end(tmp_ptr);\n\t\tif (tmp_ptr > ptr)\n\t\t{\n\t\t if (*ptr != ')' && IObuff[len - 1] != TAB)\n\t\t {\n\t\t\tif (IObuff[len - 1] != ' ')\n\t\t\t IObuff[len++] = ' ';\n\t\t\t// IObuf =~ \"\\k.* \", thus len >= 2\n\t\t\tif (p_js\n\t\t\t\t&& (IObuff[len - 2] == '.'\n\t\t\t\t || (vim_strchr(p_cpo, CPO_JOINSP)\n\t\t\t\t\t== NULL\n\t\t\t\t\t&& (IObuff[len - 2] == '?'\n\t\t\t\t\t || IObuff[len - 2] == '!'))))\n\t\t\t IObuff[len++] = ' ';\n\t\t }\n\t\t // copy as much as possible of the new word\n\t\t if (tmp_ptr - ptr >= IOSIZE - len)\n\t\t\ttmp_ptr = ptr + IOSIZE - len - 1;\n\t\t STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);\n\t\t len += (int)(tmp_ptr - ptr);\n\t\t *cont_s_ipos = TRUE;\n\t\t}\n\t\tIObuff[len] = NUL;\n\t\tptr = IObuff;\n\t }\n\t if (len == compl_length)\n\t\treturn NULL;\n\t}\n }\n\n *match_len = len;\n return ptr;\n}", "func_hash": 98585059976493999341147470153912300177, "file_name": "insexpand.c", "file_hash": 85601600050805296747970146345668146632, "cwe": ["CWE-787"], "cve": "CVE-2022-2571", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0101.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2571"} {"idx": 277954, "project": "vim", "commit_id": "a6f9e300161f4cb54713da22f65b261595e8e614", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/a6f9e300161f4cb54713da22f65b261595e8e614", "commit_message": "patch 9.0.0102: reading past end of line with insert mode completion\n\nProblem: Reading past end of line with insert mode completion.\nSolution: Check text length.", "target": 0, "func": "ins_comp_get_next_word_or_line(\n\tbuf_T\t*ins_buf,\t\t// buffer being scanned\n\tpos_T\t*cur_match_pos,\t\t// current match position\n\tint\t*match_len,\n\tint\t*cont_s_ipos)\t\t// next ^X<> will set initial_pos\n{\n char_u\t*ptr;\n int\t\tlen;\n\n *match_len = 0;\n ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +\n\tcur_match_pos->col;\n if (ctrl_x_mode_line_or_eval())\n {\n\tif (compl_status_adding())\n\t{\n\t if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)\n\t\treturn NULL;\n\t ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t if (!p_paste)\n\t\tptr = skipwhite(ptr);\n\t}\n\tlen = (int)STRLEN(ptr);\n }\n else\n {\n\tchar_u\t*tmp_ptr = ptr;\n\n\tif (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))\n\t{\n\t tmp_ptr += compl_length;\n\t // Skip if already inside a word.\n\t if (vim_iswordp(tmp_ptr))\n\t\treturn NULL;\n\t // Find start of next word.\n\t tmp_ptr = find_word_start(tmp_ptr);\n\t}\n\t// Find end of this word.\n\ttmp_ptr = find_word_end(tmp_ptr);\n\tlen = (int)(tmp_ptr - ptr);\n\n\tif (compl_status_adding() && len == compl_length)\n\t{\n\t if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)\n\t {\n\t\t// Try next line, if any. the new word will be\n\t\t// \"join\" as if the normal command \"J\" was used.\n\t\t// IOSIZE is always greater than\n\t\t// compl_length, so the next STRNCPY always\n\t\t// works -- Acevedo\n\t\tSTRNCPY(IObuff, ptr, len);\n\t\tptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t\ttmp_ptr = ptr = skipwhite(ptr);\n\t\t// Find start of next word.\n\t\ttmp_ptr = find_word_start(tmp_ptr);\n\t\t// Find end of next word.\n\t\ttmp_ptr = find_word_end(tmp_ptr);\n\t\tif (tmp_ptr > ptr)\n\t\t{\n\t\t if (*ptr != ')' && IObuff[len - 1] != TAB)\n\t\t {\n\t\t\tif (IObuff[len - 1] != ' ')\n\t\t\t IObuff[len++] = ' ';\n\t\t\t// IObuf =~ \"\\k.* \", thus len >= 2\n\t\t\tif (p_js\n\t\t\t\t&& (IObuff[len - 2] == '.'\n\t\t\t\t || (vim_strchr(p_cpo, CPO_JOINSP)\n\t\t\t\t\t== NULL\n\t\t\t\t\t&& (IObuff[len - 2] == '?'\n\t\t\t\t\t || IObuff[len - 2] == '!'))))\n\t\t\t IObuff[len++] = ' ';\n\t\t }\n\t\t // copy as much as possible of the new word\n\t\t if (tmp_ptr - ptr >= IOSIZE - len)\n\t\t\ttmp_ptr = ptr + IOSIZE - len - 1;\n\t\t STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);\n\t\t len += (int)(tmp_ptr - ptr);\n\t\t *cont_s_ipos = TRUE;\n\t\t}\n\t\tIObuff[len] = NUL;\n\t\tptr = IObuff;\n\t }\n\t if (len == compl_length)\n\t\treturn NULL;\n\t}\n }\n\n *match_len = len;\n return ptr;\n}", "func_hash": 37635914524667334210055186177223280800, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-2571", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0101.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2571"} {"idx": 198639, "project": "linux", "commit_id": "829933ef05a951c8ff140e814656d73e74915faf", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=829933ef05a951c8ff140e814656d73e74915faf", "commit_message": "firewire: nosy: Fix a use-after-free bug in nosy_ioctl()\n\nFor each device, the nosy driver allocates a pcilynx structure.\nA use-after-free might happen in the following scenario:\n\n 1. Open nosy device for the first time and call ioctl with command\n NOSY_IOC_START, then a new client A will be malloced and added to\n doubly linked list.\n 2. Open nosy device for the second time and call ioctl with command\n NOSY_IOC_START, then a new client B will be malloced and added to\n doubly linked list.\n 3. Call ioctl with command NOSY_IOC_START for client A, then client A\n will be readded to the doubly linked list. Now the doubly linked\n list is messed up.\n 4. Close the first nosy device and nosy_release will be called. In\n nosy_release, client A will be unlinked and freed.\n 5. Close the second nosy device, and client A will be referenced,\n resulting in UAF.\n\nThe root cause of this bug is that the element in the doubly linked list\nis reentered into the list.\n\nFix this bug by adding a check before inserting a client. If a client\nis already in the linked list, don't insert it.\n\nThe following KASAN report reveals it:\n\n BUG: KASAN: use-after-free in nosy_release+0x1ea/0x210\n Write of size 8 at addr ffff888102ad7360 by task poc\n CPU: 3 PID: 337 Comm: poc Not tainted 5.12.0-rc5+ #6\n Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS rel-1.12.0-59-gc9ba5276e321-prebuilt.qemu.org 04/01/2014\n Call Trace:\n nosy_release+0x1ea/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Allocated by task 337:\n nosy_open+0x154/0x4d0\n misc_open+0x2ec/0x410\n chrdev_open+0x20d/0x5a0\n do_dentry_open+0x40f/0xe80\n path_openat+0x1cf9/0x37b0\n do_filp_open+0x16d/0x390\n do_sys_openat2+0x11d/0x360\n __x64_sys_open+0xfd/0x1a0\n do_syscall_64+0x33/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Freed by task 337:\n kfree+0x8f/0x210\n nosy_release+0x158/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n The buggy address belongs to the object at ffff888102ad7300 which belongs to the cache kmalloc-128 of size 128\n The buggy address is located 96 bytes inside of 128-byte region [ffff888102ad7300, ffff888102ad7380)\n\n[ Modified to use 'list_empty()' inside proper lock - Linus ]\n\nLink: https://lore.kernel.org/lkml/1617433116-5930-1-git-send-email-zheyuma97@gmail.com/\nReported-and-tested-by: \u9a6c\u54f2\u5b87 (Zheyu Ma) \nSigned-off-by: Zheyu Ma \nCc: Greg Kroah-Hartman \nCc: Stefan Richter \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "nosy_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n{\n\tstruct client *client = file->private_data;\n\tspinlock_t *client_list_lock = &client->lynx->client_list_lock;\n\tstruct nosy_stats stats;\n\n\tswitch (cmd) {\n\tcase NOSY_IOC_GET_STATS:\n\t\tspin_lock_irq(client_list_lock);\n\t\tstats.total_packet_count = client->buffer.total_packet_count;\n\t\tstats.lost_packet_count = client->buffer.lost_packet_count;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\tif (copy_to_user((void __user *) arg, &stats, sizeof stats))\n\t\t\treturn -EFAULT;\n\t\telse\n\t\t\treturn 0;\n\n\tcase NOSY_IOC_START:\n\t\tspin_lock_irq(client_list_lock);\n\t\tlist_add_tail(&client->link, &client->lynx->client_list);\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tcase NOSY_IOC_STOP:\n\t\tspin_lock_irq(client_list_lock);\n\t\tlist_del_init(&client->link);\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tcase NOSY_IOC_FILTER:\n\t\tspin_lock_irq(client_list_lock);\n\t\tclient->tcode_mask = arg;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tdefault:\n\t\treturn -EINVAL;\n\t\t/* Flush buffer, configure filter. */\n\t}\n}", "func_hash": 274744398545491598605235675552477563171, "file_name": "nosy.c", "file_hash": 66561118036368551352623614107671831482, "cwe": ["CWE-416"], "cve": "CVE-2021-3483", "cve_desc": "A flaw was found in the Nosy driver in the Linux kernel. This issue allows a device to be inserted twice into a doubly-linked list, leading to a use-after-free when one of these devices is removed. The highest threat from this vulnerability is to confidentiality, integrity, as well as system availability. Versions before kernel 5.12-rc6 are affected", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3483"} {"idx": 279632, "project": "linux", "commit_id": "829933ef05a951c8ff140e814656d73e74915faf", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=829933ef05a951c8ff140e814656d73e74915faf", "commit_message": "firewire: nosy: Fix a use-after-free bug in nosy_ioctl()\n\nFor each device, the nosy driver allocates a pcilynx structure.\nA use-after-free might happen in the following scenario:\n\n 1. Open nosy device for the first time and call ioctl with command\n NOSY_IOC_START, then a new client A will be malloced and added to\n doubly linked list.\n 2. Open nosy device for the second time and call ioctl with command\n NOSY_IOC_START, then a new client B will be malloced and added to\n doubly linked list.\n 3. Call ioctl with command NOSY_IOC_START for client A, then client A\n will be readded to the doubly linked list. Now the doubly linked\n list is messed up.\n 4. Close the first nosy device and nosy_release will be called. In\n nosy_release, client A will be unlinked and freed.\n 5. Close the second nosy device, and client A will be referenced,\n resulting in UAF.\n\nThe root cause of this bug is that the element in the doubly linked list\nis reentered into the list.\n\nFix this bug by adding a check before inserting a client. If a client\nis already in the linked list, don't insert it.\n\nThe following KASAN report reveals it:\n\n BUG: KASAN: use-after-free in nosy_release+0x1ea/0x210\n Write of size 8 at addr ffff888102ad7360 by task poc\n CPU: 3 PID: 337 Comm: poc Not tainted 5.12.0-rc5+ #6\n Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS rel-1.12.0-59-gc9ba5276e321-prebuilt.qemu.org 04/01/2014\n Call Trace:\n nosy_release+0x1ea/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Allocated by task 337:\n nosy_open+0x154/0x4d0\n misc_open+0x2ec/0x410\n chrdev_open+0x20d/0x5a0\n do_dentry_open+0x40f/0xe80\n path_openat+0x1cf9/0x37b0\n do_filp_open+0x16d/0x390\n do_sys_openat2+0x11d/0x360\n __x64_sys_open+0xfd/0x1a0\n do_syscall_64+0x33/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Freed by task 337:\n kfree+0x8f/0x210\n nosy_release+0x158/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n The buggy address belongs to the object at ffff888102ad7300 which belongs to the cache kmalloc-128 of size 128\n The buggy address is located 96 bytes inside of 128-byte region [ffff888102ad7300, ffff888102ad7380)\n\n[ Modified to use 'list_empty()' inside proper lock - Linus ]\n\nLink: https://lore.kernel.org/lkml/1617433116-5930-1-git-send-email-zheyuma97@gmail.com/\nReported-and-tested-by: \u9a6c\u54f2\u5b87 (Zheyu Ma) \nSigned-off-by: Zheyu Ma \nCc: Greg Kroah-Hartman \nCc: Stefan Richter \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "nosy_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n{\n\tstruct client *client = file->private_data;\n\tspinlock_t *client_list_lock = &client->lynx->client_list_lock;\n\tstruct nosy_stats stats;\n\tint ret;\n\n\tswitch (cmd) {\n\tcase NOSY_IOC_GET_STATS:\n\t\tspin_lock_irq(client_list_lock);\n\t\tstats.total_packet_count = client->buffer.total_packet_count;\n\t\tstats.lost_packet_count = client->buffer.lost_packet_count;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\tif (copy_to_user((void __user *) arg, &stats, sizeof stats))\n\t\t\treturn -EFAULT;\n\t\telse\n\t\t\treturn 0;\n\n\tcase NOSY_IOC_START:\n\t\tret = -EBUSY;\n\t\tspin_lock_irq(client_list_lock);\n\t\tif (list_empty(&client->link)) {\n\t\t\tlist_add_tail(&client->link, &client->lynx->client_list);\n\t\t\tret = 0;\n\t\t}\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn ret;\n\n\tcase NOSY_IOC_STOP:\n\t\tspin_lock_irq(client_list_lock);\n\t\tlist_del_init(&client->link);\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tcase NOSY_IOC_FILTER:\n\t\tspin_lock_irq(client_list_lock);\n\t\tclient->tcode_mask = arg;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tdefault:\n\t\treturn -EINVAL;\n\t\t/* Flush buffer, configure filter. */\n\t}\n}", "func_hash": 152164187985745471129529023405180690598, "file_name": "nosy.c", "file_hash": 176073426086061114257448144784456374840, "cwe": ["CWE-416"], "cve": "CVE-2021-3483", "cve_desc": "A flaw was found in the Nosy driver in the Linux kernel. This issue allows a device to be inserted twice into a doubly-linked list, leading to a use-after-free when one of these devices is removed. The highest threat from this vulnerability is to confidentiality, integrity, as well as system availability. Versions before kernel 5.12-rc6 are affected", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3483"} {"idx": 198663, "project": "minetest", "commit_id": "b5956bde259faa240a81060ff4e598e25ad52dae", "project_url": "https://github.com/minetest/minetest", "commit_url": "https://github.com/minetest/minetest/commit/b5956bde259faa240a81060ff4e598e25ad52dae", "commit_message": "Sanitize ItemStack meta text", "target": 1, "func": "bool ItemStackMetadata::setString(const std::string &name, const std::string &var)\n{\n\tbool result = Metadata::setString(name, var);\n\tif (name == TOOLCAP_KEY)\n\t\tupdateToolCapabilities();\n\treturn result;\n}", "func_hash": 322987395178942569755562626424173524880, "file_name": "itemstackmetadata.cpp", "file_hash": 314527006867032696495161153674489266254, "cwe": ["CWE-74"], "cve": "CVE-2022-24300", "cve_desc": "Minetest before 5.4.0 allows attackers to add or modify arbitrary meta fields of the same item stack as saved user input, aka ItemStack meta injection.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24300"} {"idx": 279961, "project": "minetest", "commit_id": "b5956bde259faa240a81060ff4e598e25ad52dae", "project_url": "https://github.com/minetest/minetest", "commit_url": "https://github.com/minetest/minetest/commit/b5956bde259faa240a81060ff4e598e25ad52dae", "commit_message": "Sanitize ItemStack meta text", "target": 0, "func": "bool ItemStackMetadata::setString(const std::string &name, const std::string &var)\n{\n\tstd::string clean_name = name;\n\tstd::string clean_var = var;\n\tsanitize_string(clean_name);\n\tsanitize_string(clean_var);\n\n\tbool result = Metadata::setString(clean_name, clean_var);\n\tif (clean_name == TOOLCAP_KEY)\n\t\tupdateToolCapabilities();\n\treturn result;\n}", "func_hash": 199187775085494277155958434296687054376, "file_name": "itemstackmetadata.cpp", "file_hash": 105755028894363008393036780008701544701, "cwe": ["CWE-74"], "cve": "CVE-2022-24300", "cve_desc": "Minetest before 5.4.0 allows attackers to add or modify arbitrary meta fields of the same item stack as saved user input, aka ItemStack meta injection.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24300"} {"idx": 198733, "project": "zziplib", "commit_id": "ac9ae39ef419e9f0f83da1e583314d8c7cda34a6", "project_url": "https://github.com/gdraheim/zziplib", "commit_url": "https://github.com/gdraheim/zziplib/commit/ac9ae39ef419e9f0f83da1e583314d8c7cda34a6", "commit_message": "#68 ssize_t return value of zzip_file_read is a signed value being possibly -1", "target": 1, "func": "static void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out)\n{\n ZZIP_FILE* file = zzip_file_open (disk, name, 0);\n if (file) \n {\n\tchar buffer[1024]; int len;\n\twhile ((len = zzip_file_read (file, buffer, 1024))) \n\t{\n\t fwrite (buffer, 1, len, out);\n\t}\n\t\n\tzzip_file_close (file);\n }\n}", "func_hash": 186909391884982279590306740477623756364, "file_name": "unzzipcat-zip.c", "file_hash": 11747683761403774221318852395857055236, "cwe": ["CWE-835"], "cve": "CVE-2020-18442", "cve_desc": "Infinite Loop in zziplib v0.13.69 allows remote attackers to cause a denial of service via the return value \"zzip_file_read\" in the function \"unzzip_cat_file\".", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-18442"} {"idx": 282823, "project": "zziplib", "commit_id": "ac9ae39ef419e9f0f83da1e583314d8c7cda34a6", "project_url": "https://github.com/gdraheim/zziplib", "commit_url": "https://github.com/gdraheim/zziplib/commit/ac9ae39ef419e9f0f83da1e583314d8c7cda34a6", "commit_message": "#68 ssize_t return value of zzip_file_read is a signed value being possibly -1", "target": 0, "func": "static void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out)\n{\n ZZIP_FILE* file = zzip_file_open (disk, name, 0);\n if (file) \n {\n\tchar buffer[1024]; int len;\n\twhile (0 < (len = zzip_file_read (file, buffer, 1024))) \n\t{\n\t fwrite (buffer, 1, len, out);\n\t}\n\t\n\tzzip_file_close (file);\n }\n}", "func_hash": 169356348680733697006066408086107797420, "file_name": "unzzipcat-zip.c", "file_hash": 31438695045711768311618285397206635250, "cwe": ["CWE-835"], "cve": "CVE-2020-18442", "cve_desc": "Infinite Loop in zziplib v0.13.69 allows remote attackers to cause a denial of service via the return value \"zzip_file_read\" in the function \"unzzip_cat_file\".", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-18442"} {"idx": 198763, "project": "wireshark", "commit_id": "0137c24d60934f131b25506a88c9464e4dc827de", "project_url": "https://github.com/wireshark/wireshark", "commit_url": "https://github.com/wireshark/wireshark/commit/0137c24d60934f131b25506a88c9464e4dc827de", "commit_message": "DVB-S2-BB: Prevent infinite loop\n\nCommit 4bf4ee88f0544727e7f89f3f288c6afd2f650a4c removed an else\nstatement that broke out of the BBFrame processing loop. Without\nit, infinite loops might be possible if the GSE frames have bit errors\nin the length field.", "target": 1, "func": "static int dissect_dvb_s2_bb(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n{\n proto_item *ti;\n proto_tree *dvb_s2_bb_tree;\n\n guint8 input8, matype1;\n guint8 sync_flag = 0;\n guint16 input16, bb_data_len = 0, user_packet_length;\n\n int sub_dissected = 0, flag_is_ms = 0, new_off = 0;\n\n static int * const bb_header_bitfields[] = {\n &hf_dvb_s2_bb_matype1_gs,\n &hf_dvb_s2_bb_matype1_mis,\n &hf_dvb_s2_bb_matype1_acm,\n &hf_dvb_s2_bb_matype1_issyi,\n &hf_dvb_s2_bb_matype1_npd,\n &hf_dvb_s2_bb_matype1_low_ro,\n NULL\n };\n\n col_append_str(pinfo->cinfo, COL_PROTOCOL, \"BB \");\n col_append_str(pinfo->cinfo, COL_INFO, \"Baseband \");\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dvb_s2_bb, tvb, 0, DVB_S2_BB_HEADER_LEN, ENC_NA);\n dvb_s2_bb_tree = proto_item_add_subtree(ti, ett_dvb_s2_bb);\n\n matype1 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n new_off += 1;\n\n if (BIT_IS_CLEAR(matype1, DVB_S2_BB_MIS_POS))\n flag_is_ms = 1;\n\n proto_tree_add_bitmask_with_flags(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_MATYPE1, hf_dvb_s2_bb_matype1,\n ett_dvb_s2_bb_matype1, bb_header_bitfields, ENC_BIG_ENDIAN, BMT_NO_FLAGS);\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n\n if ((pinfo->fd->num == 1) && (_use_low_rolloff_value != 0)) {\n _use_low_rolloff_value = 0;\n }\n if (((input8 & 0x03) == 3) && !_use_low_rolloff_value) {\n _use_low_rolloff_value = 1;\n }\n if (_use_low_rolloff_value) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_low_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_high_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE2);\n new_off += 1;\n if (flag_is_ms) {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"Input Stream Identifier (ISI): %d\",\n input8);\n } else {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_UPL);\n new_off += 2;\n\n proto_tree_add_uint_format(dvb_s2_bb_tree, hf_dvb_s2_bb_upl, tvb,\n DVB_S2_BB_OFFS_UPL, 2, input16, \"User Packet Length: %d bits (%d bytes)\",\n (guint16) input16, (guint16) input16 / 8);\n\n bb_data_len = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_DFL);\n bb_data_len /= 8;\n new_off += 2;\n\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_dfl, tvb,\n DVB_S2_BB_OFFS_DFL, 2, input16, \"%d bits (%d bytes)\", input16, input16 / 8);\n\n new_off += 1;\n sync_flag = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, DVB_S2_BB_OFFS_SYNC, 1, ENC_BIG_ENDIAN);\n\n new_off += 2;\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_syncd, tvb, DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_CRC, hf_dvb_s2_bb_crc, hf_dvb_s2_bb_crc_status, &ei_dvb_s2_bb_crc, pinfo,\n compute_crc8(tvb, DVB_S2_BB_HEADER_LEN - 1, 0), ENC_NA, PROTO_CHECKSUM_VERIFY);\n\n switch (matype1 & DVB_S2_BB_TSGS_MASK) {\n case DVB_S2_BB_TSGS_GENERIC_CONTINUOUS:\n /* Check GSE constraints on the BB header per 9.2.1 of ETSI TS 102 771 */\n if (BIT_IS_SET(matype1, DVB_S2_BB_ISSYI_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_issy_invalid);\n }\n if (BIT_IS_SET(matype1, DVB_S2_BB_NPD_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_npd_invalid);\n }\n if (user_packet_length != 0x0000) {\n expert_add_info_format(pinfo, ti, &ei_dvb_s2_bb_upl_invalid,\n \"UPL is 0x%04x. It must be 0x0000 for GSE packets.\", user_packet_length);\n }\n\n\n if (dvb_s2_df_dissection) {\n while (bb_data_len) {\n if (sync_flag == DVB_S2_BB_SYNC_EIP_CRC32 && bb_data_len == DVB_S2_BB_EIP_CRC32_LEN) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_eip_crc32, tvb, new_off, bb_data_len, ENC_NA);\n bb_data_len = 0;\n new_off += DVB_S2_BB_EIP_CRC32_LEN;\n } else {\n /* start DVB-GSE dissector */\n sub_dissected = dissect_dvb_s2_gse(tvb_new_subset_length(tvb, new_off, bb_data_len), pinfo, tree, NULL);\n new_off += sub_dissected;\n\n if ((sub_dissected <= bb_data_len) && (sub_dissected >= DVB_S2_GSE_MINSIZE)) {\n bb_data_len -= sub_dissected;\n if (bb_data_len < DVB_S2_GSE_MINSIZE)\n bb_data_len = 0;\n }\n }\n }\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_df, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n }\n break;\n\n case DVB_S2_BB_TSGS_GENERIC_PACKETIZED:\n proto_tree_add_item(tree, hf_dvb_s2_bb_packetized, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n case DVB_S2_BB_TSGS_TRANSPORT_STREAM:\n proto_tree_add_item(tree, hf_dvb_s2_bb_transport, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n default:\n proto_tree_add_item(tree, hf_dvb_s2_bb_reserved, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_reserved);\n break;\n }\n\n return new_off;\n}", "func_hash": 301455780336148778049138753546805982512, "file_name": "packet-dvb-s2-bb.c", "file_hash": 12418946525456261942172260623780285586, "cwe": ["CWE-835"], "cve": "CVE-2021-22222", "cve_desc": "Infinite loop in DVB-S2-BB dissector in Wireshark 3.4.0 to 3.4.5 allows denial of service via packet injection or crafted capture file", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22222"} {"idx": 283344, "project": "wireshark", "commit_id": "0137c24d60934f131b25506a88c9464e4dc827de", "project_url": "https://github.com/wireshark/wireshark", "commit_url": "https://github.com/wireshark/wireshark/commit/0137c24d60934f131b25506a88c9464e4dc827de", "commit_message": "DVB-S2-BB: Prevent infinite loop\n\nCommit 4bf4ee88f0544727e7f89f3f288c6afd2f650a4c removed an else\nstatement that broke out of the BBFrame processing loop. Without\nit, infinite loops might be possible if the GSE frames have bit errors\nin the length field.", "target": 0, "func": "static int dissect_dvb_s2_bb(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n{\n proto_item *ti;\n proto_tree *dvb_s2_bb_tree;\n\n guint8 input8, matype1;\n guint8 sync_flag = 0;\n guint16 input16, bb_data_len = 0, user_packet_length;\n\n int sub_dissected = 0, flag_is_ms = 0, new_off = 0;\n\n static int * const bb_header_bitfields[] = {\n &hf_dvb_s2_bb_matype1_gs,\n &hf_dvb_s2_bb_matype1_mis,\n &hf_dvb_s2_bb_matype1_acm,\n &hf_dvb_s2_bb_matype1_issyi,\n &hf_dvb_s2_bb_matype1_npd,\n &hf_dvb_s2_bb_matype1_low_ro,\n NULL\n };\n\n col_append_str(pinfo->cinfo, COL_PROTOCOL, \"BB \");\n col_append_str(pinfo->cinfo, COL_INFO, \"Baseband \");\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dvb_s2_bb, tvb, 0, DVB_S2_BB_HEADER_LEN, ENC_NA);\n dvb_s2_bb_tree = proto_item_add_subtree(ti, ett_dvb_s2_bb);\n\n matype1 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n new_off += 1;\n\n if (BIT_IS_CLEAR(matype1, DVB_S2_BB_MIS_POS))\n flag_is_ms = 1;\n\n proto_tree_add_bitmask_with_flags(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_MATYPE1, hf_dvb_s2_bb_matype1,\n ett_dvb_s2_bb_matype1, bb_header_bitfields, ENC_BIG_ENDIAN, BMT_NO_FLAGS);\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n\n if ((pinfo->fd->num == 1) && (_use_low_rolloff_value != 0)) {\n _use_low_rolloff_value = 0;\n }\n if (((input8 & 0x03) == 3) && !_use_low_rolloff_value) {\n _use_low_rolloff_value = 1;\n }\n if (_use_low_rolloff_value) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_low_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_high_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE2);\n new_off += 1;\n if (flag_is_ms) {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"Input Stream Identifier (ISI): %d\",\n input8);\n } else {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_UPL);\n new_off += 2;\n\n proto_tree_add_uint_format(dvb_s2_bb_tree, hf_dvb_s2_bb_upl, tvb,\n DVB_S2_BB_OFFS_UPL, 2, input16, \"User Packet Length: %d bits (%d bytes)\",\n (guint16) input16, (guint16) input16 / 8);\n\n bb_data_len = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_DFL);\n bb_data_len /= 8;\n new_off += 2;\n\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_dfl, tvb,\n DVB_S2_BB_OFFS_DFL, 2, input16, \"%d bits (%d bytes)\", input16, input16 / 8);\n\n new_off += 1;\n sync_flag = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, DVB_S2_BB_OFFS_SYNC, 1, ENC_BIG_ENDIAN);\n\n new_off += 2;\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_syncd, tvb, DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_CRC, hf_dvb_s2_bb_crc, hf_dvb_s2_bb_crc_status, &ei_dvb_s2_bb_crc, pinfo,\n compute_crc8(tvb, DVB_S2_BB_HEADER_LEN - 1, 0), ENC_NA, PROTO_CHECKSUM_VERIFY);\n\n switch (matype1 & DVB_S2_BB_TSGS_MASK) {\n case DVB_S2_BB_TSGS_GENERIC_CONTINUOUS:\n /* Check GSE constraints on the BB header per 9.2.1 of ETSI TS 102 771 */\n if (BIT_IS_SET(matype1, DVB_S2_BB_ISSYI_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_issy_invalid);\n }\n if (BIT_IS_SET(matype1, DVB_S2_BB_NPD_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_npd_invalid);\n }\n if (user_packet_length != 0x0000) {\n expert_add_info_format(pinfo, ti, &ei_dvb_s2_bb_upl_invalid,\n \"UPL is 0x%04x. It must be 0x0000 for GSE packets.\", user_packet_length);\n }\n\n\n if (dvb_s2_df_dissection) {\n while (bb_data_len) {\n if (sync_flag == DVB_S2_BB_SYNC_EIP_CRC32 && bb_data_len == DVB_S2_BB_EIP_CRC32_LEN) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_eip_crc32, tvb, new_off, bb_data_len, ENC_NA);\n bb_data_len = 0;\n new_off += DVB_S2_BB_EIP_CRC32_LEN;\n } else {\n /* start DVB-GSE dissector */\n sub_dissected = dissect_dvb_s2_gse(tvb_new_subset_length(tvb, new_off, bb_data_len), pinfo, tree, NULL);\n new_off += sub_dissected;\n\n if ((sub_dissected <= bb_data_len) && (sub_dissected >= DVB_S2_GSE_MINSIZE)) {\n bb_data_len -= sub_dissected;\n if (bb_data_len < DVB_S2_GSE_MINSIZE)\n bb_data_len = 0;\n } else {\n bb_data_len = 0;\n }\n }\n }\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_df, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n }\n break;\n\n case DVB_S2_BB_TSGS_GENERIC_PACKETIZED:\n proto_tree_add_item(tree, hf_dvb_s2_bb_packetized, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n case DVB_S2_BB_TSGS_TRANSPORT_STREAM:\n proto_tree_add_item(tree, hf_dvb_s2_bb_transport, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n default:\n proto_tree_add_item(tree, hf_dvb_s2_bb_reserved, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_reserved);\n break;\n }\n\n return new_off;\n}", "func_hash": 199120095138878769101251512681197399097, "file_name": "packet-dvb-s2-bb.c", "file_hash": 235391186151618962472590158608859339897, "cwe": ["CWE-835"], "cve": "CVE-2021-22222", "cve_desc": "Infinite loop in DVB-S2-BB dissector in Wireshark 3.4.0 to 3.4.5 allows denial of service via packet injection or crafted capture file", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22222"} {"idx": 198837, "project": "httpd", "commit_id": "f990e5ecad40b100a8a5c7c1033c46044a9cb244", "project_url": "https://github.com/apache/httpd", "commit_url": "https://github.com/apache/httpd/commit/f990e5ecad40b100a8a5c7c1033c46044a9cb244", "commit_message": "mod_htt2: fix incomplete sync with latest changes in github, adjust version number.\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1889119 13f79535-47bb-0310-9956-ffa450edef68", "target": 1, "func": "static void set_error_response(h2_stream *stream, int http_status)\n{\n if (!h2_stream_is_ready(stream)) {\n stream->rtmp->http_status = http_status;\n }\n}", "func_hash": 259042477051232338910020136235535566445, "file_name": "h2_stream.c", "file_hash": 170627026068149724420261924656851550240, "cwe": ["CWE-476"], "cve": "CVE-2021-31618", "cve_desc": "Apache HTTP Server protocol handler for the HTTP/2 protocol checks received request headers against the size limitations as configured for the server and used for the HTTP/1 protocol as well. On violation of these restrictions and HTTP response is sent to the client with a status code indicating why the request was rejected. This rejection response was not fully initialised in the HTTP/2 protocol handler if the offending header was the very first one received or appeared in a a footer. This led to a NULL pointer dereference on initialised memory, crashing reliably the child process. Since such a triggering HTTP/2 request is easy to craft and submit, this can be exploited to DoS the server. This issue affected mod_http2 1.15.17 and Apache HTTP Server version 2.4.47 only. Apache HTTP Server 2.4.47 was never released.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31618"} {"idx": 284266, "project": "httpd", "commit_id": "f990e5ecad40b100a8a5c7c1033c46044a9cb244", "project_url": "https://github.com/apache/httpd", "commit_url": "https://github.com/apache/httpd/commit/f990e5ecad40b100a8a5c7c1033c46044a9cb244", "commit_message": "mod_htt2: fix incomplete sync with latest changes in github, adjust version number.\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1889119 13f79535-47bb-0310-9956-ffa450edef68", "target": 0, "func": "static void set_error_response(h2_stream *stream, int http_status)\n{\n if (!h2_stream_is_ready(stream) && stream->rtmp) {\n stream->rtmp->http_status = http_status;\n }\n}", "func_hash": 323306386870515934647211914396262133680, "file_name": "h2_stream.c", "file_hash": 184055430619956534950248229174120075872, "cwe": ["CWE-476"], "cve": "CVE-2021-31618", "cve_desc": "Apache HTTP Server protocol handler for the HTTP/2 protocol checks received request headers against the size limitations as configured for the server and used for the HTTP/1 protocol as well. On violation of these restrictions and HTTP response is sent to the client with a status code indicating why the request was rejected. This rejection response was not fully initialised in the HTTP/2 protocol handler if the offending header was the very first one received or appeared in a a footer. This led to a NULL pointer dereference on initialised memory, crashing reliably the child process. Since such a triggering HTTP/2 request is easy to craft and submit, this can be exploited to DoS the server. This issue affected mod_http2 1.15.17 and Apache HTTP Server version 2.4.47 only. Apache HTTP Server 2.4.47 was never released.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31618"} {"idx": 198942, "project": "gnulib", "commit_id": "5513b40999149090987a0341c018d05d3eea1272", "project_url": "https://github.com/coreutils/gnulib", "commit_url": "http://git.savannah.gnu.org/cgit/gnulib.git/commit/?id=5513b40999149090987a0341c018d05d3eea1272", "commit_message": "Diagnose ERE '()|\\1'\n\nProblem reported by Hanno B\u00f6ck in: http://bugs.gnu.org/21513\n* lib/regcomp.c (parse_reg_exp): While parsing alternatives, keep\ntrack of the set of previously-completed subexpressions available\nbefore the first alternative, and restore this set just before\nparsing each subsequent alternative. This lets us diagnose the\ninvalid back-reference in the ERE '()|\\1'.", "target": 1, "func": "parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,\n\t reg_syntax_t syntax, Idx nest, reg_errcode_t *err)\n{\n re_dfa_t *dfa = preg->buffer;\n bin_tree_t *tree, *branch = NULL;\n tree = parse_branch (regexp, preg, token, syntax, nest, err);\n if (BE (*err != REG_NOERROR && tree == NULL, 0))\n return NULL;\n\n while (token->type == OP_ALT)\n {\n fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);\n if (token->type != OP_ALT && token->type != END_OF_RE\n\t && (nest == 0 || token->type != OP_CLOSE_SUBEXP))\n\t{\n\t branch = parse_branch (regexp, preg, token, syntax, nest, err);\n\t if (BE (*err != REG_NOERROR && branch == NULL, 0))\n\t {\n\t if (tree != NULL)\n\t\tpostorder (tree, free_tree, NULL);\n\t return NULL;\n\t }\n\t}\n else\n\tbranch = NULL;\n tree = create_tree (dfa, tree, branch, OP_ALT);\n if (BE (tree == NULL, 0))\n\t{\n\t *err = REG_ESPACE;\n\t return NULL;\n\t}\n }\n return tree;\n}", "func_hash": 338247303888543653572283908497989727725, "file_name": "regcomp.c", "file_hash": 203301199216143889467587507104301992131, "cwe": ["CWE-19"], "cve": "CVE-2009-5155", "cve_desc": "In the GNU C Library (aka glibc or libc6) before 2.28, parse_reg_exp in posix/regcomp.c misparses alternatives, which allows attackers to cause a denial of service (assertion failure and application exit) or trigger an incorrect result by attempting a regular-expression match.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2009-5155"} {"idx": 285543, "project": "gnulib", "commit_id": "5513b40999149090987a0341c018d05d3eea1272", "project_url": "https://github.com/coreutils/gnulib", "commit_url": "http://git.savannah.gnu.org/cgit/gnulib.git/commit/?id=5513b40999149090987a0341c018d05d3eea1272", "commit_message": "Diagnose ERE '()|\\1'\n\nProblem reported by Hanno B\u00f6ck in: http://bugs.gnu.org/21513\n* lib/regcomp.c (parse_reg_exp): While parsing alternatives, keep\ntrack of the set of previously-completed subexpressions available\nbefore the first alternative, and restore this set just before\nparsing each subsequent alternative. This lets us diagnose the\ninvalid back-reference in the ERE '()|\\1'.", "target": 0, "func": "parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,\n\t reg_syntax_t syntax, Idx nest, reg_errcode_t *err)\n{\n re_dfa_t *dfa = preg->buffer;\n bin_tree_t *tree, *branch = NULL;\n bitset_word_t initial_bkref_map = dfa->completed_bkref_map;\n tree = parse_branch (regexp, preg, token, syntax, nest, err);\n if (BE (*err != REG_NOERROR && tree == NULL, 0))\n return NULL;\n\n while (token->type == OP_ALT)\n {\n fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);\n if (token->type != OP_ALT && token->type != END_OF_RE\n\t && (nest == 0 || token->type != OP_CLOSE_SUBEXP))\n\t{\n\t bitset_word_t accumulated_bkref_map = dfa->completed_bkref_map;\n\t dfa->completed_bkref_map = initial_bkref_map;\n\t branch = parse_branch (regexp, preg, token, syntax, nest, err);\n\t if (BE (*err != REG_NOERROR && branch == NULL, 0))\n\t {\n\t if (tree != NULL)\n\t\tpostorder (tree, free_tree, NULL);\n\t return NULL;\n\t }\n\t dfa->completed_bkref_map |= accumulated_bkref_map;\n\t}\n else\n\tbranch = NULL;\n tree = create_tree (dfa, tree, branch, OP_ALT);\n if (BE (tree == NULL, 0))\n\t{\n\t *err = REG_ESPACE;\n\t return NULL;\n\t}\n }\n return tree;\n}", "func_hash": 185466721886907734891619451021620129070, "file_name": "regcomp.c", "file_hash": 103833568612707461047428689237247948928, "cwe": ["CWE-19"], "cve": "CVE-2009-5155", "cve_desc": "In the GNU C Library (aka glibc or libc6) before 2.28, parse_reg_exp in posix/regcomp.c misparses alternatives, which allows attackers to cause a denial of service (assertion failure and application exit) or trigger an incorrect result by attempting a regular-expression match.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2009-5155"} {"idx": 198943, "project": "php-src", "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "commit_message": "Fix TSRM (after afc1debb)", "target": 1, "func": "xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\tzend_bool old_allow_url_fopen;\n\n/*\n\txmlInitParser();\n*/\n\n\told_allow_url_fopen = PG(allow_url_fopen);\n\tPG(allow_url_fopen) = 1;\n\tctxt = xmlCreateFileParserCtxt(filename);\n\tPG(allow_url_fopen) = old_allow_url_fopen;\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->keepBlanks = 0;\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n\t\told = php_libxml_disable_entity_loader(1);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n\treturn ret;\n}", "func_hash": 246438624913639420440184170319786781665, "file_name": "php_xml.c", "file_hash": 289993618850608383939256362841642877634, "cwe": ["CWE-200"], "cve": "CVE-2013-1643", "cve_desc": "The SOAP parser in PHP before 5.3.23 and 5.4.x before 5.4.13 allows remote attackers to read arbitrary files via a SOAP WSDL file containing an XML external entity declaration in conjunction with an entity reference, related to an XML External Entity (XXE) issue in the soap_xmlParseFile and soap_xmlParseMemory functions. NOTE: this vulnerability exists because of an incorrect fix for CVE-2013-1824.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-1643"} {"idx": 285598, "project": "php-src", "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "commit_message": "Fix TSRM (after afc1debb)", "target": 0, "func": "xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\tzend_bool old_allow_url_fopen;\n\n/*\n\txmlInitParser();\n*/\n\n\told_allow_url_fopen = PG(allow_url_fopen);\n\tPG(allow_url_fopen) = 1;\n\tctxt = xmlCreateFileParserCtxt(filename);\n\tPG(allow_url_fopen) = old_allow_url_fopen;\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->keepBlanks = 0;\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n\t\told = php_libxml_disable_entity_loader(1 TSRMLS_CC);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old TSRMLS_CC);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n\treturn ret;\n}", "func_hash": 250437720655066519752709478268406320838, "file_name": "php_xml.c", "file_hash": 16863940559788327962549538563004941785, "cwe": ["CWE-200"], "cve": "CVE-2013-1643", "cve_desc": "The SOAP parser in PHP before 5.3.23 and 5.4.x before 5.4.13 allows remote attackers to read arbitrary files via a SOAP WSDL file containing an XML external entity declaration in conjunction with an entity reference, related to an XML External Entity (XXE) issue in the soap_xmlParseFile and soap_xmlParseMemory functions. NOTE: this vulnerability exists because of an incorrect fix for CVE-2013-1824.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-1643"} {"idx": 198944, "project": "php-src", "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "commit_message": "Fix TSRM (after afc1debb)", "target": 1, "func": "xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\n/*\n\txmlInitParser();\n*/\n\tctxt = xmlCreateMemoryParserCtxt(buf, buf_size);\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n#if LIBXML_VERSION >= 20703\n\t\tctxt->options |= XML_PARSE_HUGE;\n#endif\n\t\told = php_libxml_disable_entity_loader(1);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n/*\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n*/\n\treturn ret;\n}", "func_hash": 44454461395216235013421541884941956510, "file_name": "php_xml.c", "file_hash": 289993618850608383939256362841642877634, "cwe": ["CWE-200"], "cve": "CVE-2013-1643", "cve_desc": "The SOAP parser in PHP before 5.3.23 and 5.4.x before 5.4.13 allows remote attackers to read arbitrary files via a SOAP WSDL file containing an XML external entity declaration in conjunction with an entity reference, related to an XML External Entity (XXE) issue in the soap_xmlParseFile and soap_xmlParseMemory functions. NOTE: this vulnerability exists because of an incorrect fix for CVE-2013-1824.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-1643"} {"idx": 285589, "project": "php-src", "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "commit_message": "Fix TSRM (after afc1debb)", "target": 0, "func": "xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\n\tTSRMLS_FETCH();\n\n/*\n\txmlInitParser();\n*/\n\tctxt = xmlCreateMemoryParserCtxt(buf, buf_size);\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n#if LIBXML_VERSION >= 20703\n\t\tctxt->options |= XML_PARSE_HUGE;\n#endif\n\t\told = php_libxml_disable_entity_loader(1 TSRMLS_CC);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old TSRMLS_CC);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n/*\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n*/\n\treturn ret;\n}", "func_hash": 120106858086948916868033808710881823100, "file_name": "php_xml.c", "file_hash": 16863940559788327962549538563004941785, "cwe": ["CWE-200"], "cve": "CVE-2013-1643", "cve_desc": "The SOAP parser in PHP before 5.3.23 and 5.4.x before 5.4.13 allows remote attackers to read arbitrary files via a SOAP WSDL file containing an XML external entity declaration in conjunction with an entity reference, related to an XML External Entity (XXE) issue in the soap_xmlParseFile and soap_xmlParseMemory functions. NOTE: this vulnerability exists because of an incorrect fix for CVE-2013-1824.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-1643"} {"idx": 199227, "project": "redis", "commit_id": "789f10156009b404950ad717642a9496ed887083", "project_url": "https://github.com/antirez/redis", "commit_url": "https://github.com/redis/redis/commit/789f10156009b404950ad717642a9496ed887083", "commit_message": "Fix integer overflow in intset (CVE-2021-29478)\n\nAn integer overflow bug in Redis 6.2 could be exploited to corrupt the heap and\npotentially result with remote code execution.\n\nThe vulnerability involves changing the default set-max-intset-entries\nconfiguration value, creating a large set key that consists of integer values\nand using the COPY command to duplicate it.\n\nThe integer overflow bug exists in all versions of Redis starting with 2.6,\nwhere it could result with a corrupted RDB or DUMP payload, but not exploited\nthrough COPY (which did not exist before 6.2).\n\n(cherry picked from commit 29900d4e6bccdf3691bedf0ea9a5d84863fa3592)", "target": 1, "func": "size_t intsetBlobLen(intset *is) {\n return sizeof(intset)+intrev32ifbe(is->length)*intrev32ifbe(is->encoding);\n}", "func_hash": 181417069959553414614257533315561603769, "file_name": "intset.c", "file_hash": 205252284515285875687367211797838046872, "cwe": ["CWE-190"], "cve": "CVE-2021-29478", "cve_desc": "Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. An integer overflow bug in Redis 6.2 before 6.2.3 could be exploited to corrupt the heap and potentially result with remote code execution. Redis 6.0 and earlier are not directly affected by this issue. The problem is fixed in version 6.2.3. An additional workaround to mitigate the problem without patching the `redis-server` executable is to prevent users from modifying the `set-max-intset-entries` configuration parameter. This can be done using ACL to restrict unprivileged users from using the `CONFIG SET` command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29478"} {"idx": 290629, "project": "redis", "commit_id": "789f10156009b404950ad717642a9496ed887083", "project_url": "https://github.com/antirez/redis", "commit_url": "https://github.com/redis/redis/commit/789f10156009b404950ad717642a9496ed887083", "commit_message": "Fix integer overflow in intset (CVE-2021-29478)\n\nAn integer overflow bug in Redis 6.2 could be exploited to corrupt the heap and\npotentially result with remote code execution.\n\nThe vulnerability involves changing the default set-max-intset-entries\nconfiguration value, creating a large set key that consists of integer values\nand using the COPY command to duplicate it.\n\nThe integer overflow bug exists in all versions of Redis starting with 2.6,\nwhere it could result with a corrupted RDB or DUMP payload, but not exploited\nthrough COPY (which did not exist before 6.2).\n\n(cherry picked from commit 29900d4e6bccdf3691bedf0ea9a5d84863fa3592)", "target": 0, "func": "size_t intsetBlobLen(intset *is) {\n return sizeof(intset)+(size_t)intrev32ifbe(is->length)*intrev32ifbe(is->encoding);\n}", "func_hash": 269060831104898951266302202478603766064, "file_name": "intset.c", "file_hash": 275517322796151602230710138936791885921, "cwe": ["CWE-190"], "cve": "CVE-2021-29478", "cve_desc": "Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. An integer overflow bug in Redis 6.2 before 6.2.3 could be exploited to corrupt the heap and potentially result with remote code execution. Redis 6.0 and earlier are not directly affected by this issue. The problem is fixed in version 6.2.3. An additional workaround to mitigate the problem without patching the `redis-server` executable is to prevent users from modifying the `set-max-intset-entries` configuration parameter. This can be done using ACL to restrict unprivileged users from using the `CONFIG SET` command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29478"} {"idx": 199700, "project": "php-src", "commit_id": "0216630ea2815a5789a24279a1211ac398d4de79", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=0216630ea2815a5789a24279a1211ac398d4de79", "commit_message": "Fix bug #79601 (Wrong ciphertext/tag in AES-CCM encryption for a 12 bytes IV)", "target": 1, "func": "static int php_openssl_validate_iv(char **piv, size_t *piv_len, size_t iv_required_len,\n\t\tzend_bool *free_iv, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode) /* {{{ */\n{\n\tchar *iv_new;\n\n\t/* Best case scenario, user behaved */\n\tif (*piv_len == iv_required_len) {\n\t\treturn SUCCESS;\n\t}\n\n\tif (mode->is_aead) {\n\t\tif (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_ivlen_flag, *piv_len, NULL) != 1) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Setting of IV length for AEAD mode failed\");\n\t\t\treturn FAILURE;\n\t\t}\n\t\treturn SUCCESS;\n\t}\n\n\tiv_new = ecalloc(1, iv_required_len + 1);\n\n\tif (*piv_len == 0) {\n\t\t/* BC behavior */\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\n\t}\n\n\tif (*piv_len < iv_required_len) {\n\t\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\t\"IV passed is only %zd bytes long, cipher expects an IV of precisely %zd bytes, padding with \\\\0\",\n\t\t\t\t*piv_len, iv_required_len);\n\t\tmemcpy(iv_new, *piv, *piv_len);\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\t}\n\n\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\"IV passed is %zd bytes long which is longer than the %zd expected by selected cipher, truncating\",\n\t\t\t*piv_len, iv_required_len);\n\tmemcpy(iv_new, *piv, iv_required_len);\n\t*piv_len = iv_required_len;\n\t*piv = iv_new;\n\t*free_iv = 1;\n\treturn SUCCESS;\n\n}", "func_hash": 174322635538872310176830587482260870247, "file_name": "openssl.c", "file_hash": 228449922038233493379569940784208153994, "cwe": ["CWE-326"], "cve": "CVE-2020-7069", "cve_desc": "In PHP versions 7.2.x below 7.2.34, 7.3.x below 7.3.23 and 7.4.x below 7.4.11, when AES-CCM mode is used with openssl_encrypt() function with 12 bytes IV, only first 7 bytes of the IV is actually used. This can lead to both decreased security and incorrect encryption data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7069"} {"idx": 291448, "project": "php-src", "commit_id": "0216630ea2815a5789a24279a1211ac398d4de79", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=0216630ea2815a5789a24279a1211ac398d4de79", "commit_message": "Fix bug #79601 (Wrong ciphertext/tag in AES-CCM encryption for a 12 bytes IV)", "target": 0, "func": "static int php_openssl_validate_iv(char **piv, size_t *piv_len, size_t iv_required_len,\n\t\tzend_bool *free_iv, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode) /* {{{ */\n{\n\tchar *iv_new;\n\n\tif (mode->is_aead) {\n\t\tif (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_ivlen_flag, *piv_len, NULL) != 1) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Setting of IV length for AEAD mode failed\");\n\t\t\treturn FAILURE;\n\t\t}\n\t\treturn SUCCESS;\n\t}\n\n\t/* Best case scenario, user behaved */\n\tif (*piv_len == iv_required_len) {\n\t\treturn SUCCESS;\n\t}\n\n\tiv_new = ecalloc(1, iv_required_len + 1);\n\n\tif (*piv_len == 0) {\n\t\t/* BC behavior */\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\n\t}\n\n\tif (*piv_len < iv_required_len) {\n\t\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\t\"IV passed is only %zd bytes long, cipher expects an IV of precisely %zd bytes, padding with \\\\0\",\n\t\t\t\t*piv_len, iv_required_len);\n\t\tmemcpy(iv_new, *piv, *piv_len);\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\t}\n\n\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\"IV passed is %zd bytes long which is longer than the %zd expected by selected cipher, truncating\",\n\t\t\t*piv_len, iv_required_len);\n\tmemcpy(iv_new, *piv, iv_required_len);\n\t*piv_len = iv_required_len;\n\t*piv = iv_new;\n\t*free_iv = 1;\n\treturn SUCCESS;\n\n}", "func_hash": 4670269784459687446323664545324362671, "file_name": "openssl.c", "file_hash": 68655368591181332306176526589709700825, "cwe": ["CWE-326"], "cve": "CVE-2020-7069", "cve_desc": "In PHP versions 7.2.x below 7.2.34, 7.3.x below 7.3.23 and 7.4.x below 7.4.11, when AES-CCM mode is used with openssl_encrypt() function with 12 bytes IV, only first 7 bytes of the IV is actually used. This can lead to both decreased security and incorrect encryption data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7069"} {"idx": 199840, "project": "linux", "commit_id": "b4e00444cab4c3f3fec876dc0cccc8cbb0d1a948", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/b4e00444cab4c3f3fec876dc0cccc8cbb0d1a948", "commit_message": "fork: fix copy_process(CLONE_PARENT) race with the exiting ->real_parent\n\ncurrent->group_leader->exit_signal may change during copy_process() if\ncurrent->real_parent exits.\n\nMove the assignment inside tasklist_lock to avoid the race.\n\nSigned-off-by: Eddy Wu \nAcked-by: Oleg Nesterov \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "static __latent_entropy struct task_struct *copy_process(\n\t\t\t\t\tstruct pid *pid,\n\t\t\t\t\tint trace,\n\t\t\t\t\tint node,\n\t\t\t\t\tstruct kernel_clone_args *args)\n{\n\tint pidfd = -1, retval;\n\tstruct task_struct *p;\n\tstruct multiprocess_signals delayed;\n\tstruct file *pidfile = NULL;\n\tu64 clone_flags = args->flags;\n\tstruct nsproxy *nsp = current->nsproxy;\n\n\t/*\n\t * Don't allow sharing the root directory with processes in a different\n\t * namespace\n\t */\n\tif ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\tif ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Thread groups must share signals as well, and detached threads\n\t * can only be started up within the thread group.\n\t */\n\tif ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Shared signal handlers imply shared VM. By way of the above,\n\t * thread groups also imply shared VM. Blocking this case allows\n\t * for various simplifications in other code.\n\t */\n\tif ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Siblings of global init remain as zombies on exit since they are\n\t * not reaped by their parent (swapper). To solve this and to avoid\n\t * multi-rooted process trees, prevent global and container-inits\n\t * from creating siblings.\n\t */\n\tif ((clone_flags & CLONE_PARENT) &&\n\t\t\t\tcurrent->signal->flags & SIGNAL_UNKILLABLE)\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * If the new process will be in a different pid or user namespace\n\t * do not allow it to share a thread group with the forking task.\n\t */\n\tif (clone_flags & CLONE_THREAD) {\n\t\tif ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||\n\t\t (task_active_pid_ns(current) != nsp->pid_ns_for_children))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * If the new process will be in a different time namespace\n\t * do not allow it to share VM or a thread group with the forking task.\n\t */\n\tif (clone_flags & (CLONE_THREAD | CLONE_VM)) {\n\t\tif (nsp->time_ns != nsp->time_ns_for_children)\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tif (clone_flags & CLONE_PIDFD) {\n\t\t/*\n\t\t * - CLONE_DETACHED is blocked so that we can potentially\n\t\t * reuse it later for CLONE_PIDFD.\n\t\t * - CLONE_THREAD is blocked until someone really needs it.\n\t\t */\n\t\tif (clone_flags & (CLONE_DETACHED | CLONE_THREAD))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * Force any signals received before this point to be delivered\n\t * before the fork happens. Collect up signals sent to multiple\n\t * processes that happen during the fork and delay them so that\n\t * they appear to happen after the fork.\n\t */\n\tsigemptyset(&delayed.signal);\n\tINIT_HLIST_NODE(&delayed.node);\n\n\tspin_lock_irq(¤t->sighand->siglock);\n\tif (!(clone_flags & CLONE_THREAD))\n\t\thlist_add_head(&delayed.node, ¤t->signal->multiprocess);\n\trecalc_sigpending();\n\tspin_unlock_irq(¤t->sighand->siglock);\n\tretval = -ERESTARTNOINTR;\n\tif (signal_pending(current))\n\t\tgoto fork_out;\n\n\tretval = -ENOMEM;\n\tp = dup_task_struct(current, node);\n\tif (!p)\n\t\tgoto fork_out;\n\n\t/*\n\t * This _must_ happen before we call free_task(), i.e. before we jump\n\t * to any of the bad_fork_* labels. This is to avoid freeing\n\t * p->set_child_tid which is (ab)used as a kthread's data pointer for\n\t * kernel threads (PF_KTHREAD).\n\t */\n\tp->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;\n\t/*\n\t * Clear TID on mm_release()?\n\t */\n\tp->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;\n\n\tftrace_graph_init_task(p);\n\n\trt_mutex_init_task(p);\n\n\tlockdep_assert_irqs_enabled();\n#ifdef CONFIG_PROVE_LOCKING\n\tDEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);\n#endif\n\tretval = -EAGAIN;\n\tif (atomic_read(&p->real_cred->user->processes) >=\n\t\t\ttask_rlimit(p, RLIMIT_NPROC)) {\n\t\tif (p->real_cred->user != INIT_USER &&\n\t\t !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))\n\t\t\tgoto bad_fork_free;\n\t}\n\tcurrent->flags &= ~PF_NPROC_EXCEEDED;\n\n\tretval = copy_creds(p, clone_flags);\n\tif (retval < 0)\n\t\tgoto bad_fork_free;\n\n\t/*\n\t * If multiple threads are within copy_process(), then this check\n\t * triggers too late. This doesn't hurt, the check is only there\n\t * to stop root fork bombs.\n\t */\n\tretval = -EAGAIN;\n\tif (data_race(nr_threads >= max_threads))\n\t\tgoto bad_fork_cleanup_count;\n\n\tdelayacct_tsk_init(p);\t/* Must remain after dup_task_struct() */\n\tp->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);\n\tp->flags |= PF_FORKNOEXEC;\n\tINIT_LIST_HEAD(&p->children);\n\tINIT_LIST_HEAD(&p->sibling);\n\trcu_copy_process(p);\n\tp->vfork_done = NULL;\n\tspin_lock_init(&p->alloc_lock);\n\n\tinit_sigpending(&p->pending);\n\n\tp->utime = p->stime = p->gtime = 0;\n#ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME\n\tp->utimescaled = p->stimescaled = 0;\n#endif\n\tprev_cputime_init(&p->prev_cputime);\n\n#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN\n\tseqcount_init(&p->vtime.seqcount);\n\tp->vtime.starttime = 0;\n\tp->vtime.state = VTIME_INACTIVE;\n#endif\n\n#ifdef CONFIG_IO_URING\n\tp->io_uring = NULL;\n#endif\n\n#if defined(SPLIT_RSS_COUNTING)\n\tmemset(&p->rss_stat, 0, sizeof(p->rss_stat));\n#endif\n\n\tp->default_timer_slack_ns = current->timer_slack_ns;\n\n#ifdef CONFIG_PSI\n\tp->psi_flags = 0;\n#endif\n\n\ttask_io_accounting_init(&p->ioac);\n\tacct_clear_integrals(p);\n\n\tposix_cputimers_init(&p->posix_cputimers);\n\n\tp->io_context = NULL;\n\taudit_set_context(p, NULL);\n\tcgroup_fork(p);\n#ifdef CONFIG_NUMA\n\tp->mempolicy = mpol_dup(p->mempolicy);\n\tif (IS_ERR(p->mempolicy)) {\n\t\tretval = PTR_ERR(p->mempolicy);\n\t\tp->mempolicy = NULL;\n\t\tgoto bad_fork_cleanup_threadgroup_lock;\n\t}\n#endif\n#ifdef CONFIG_CPUSETS\n\tp->cpuset_mem_spread_rotor = NUMA_NO_NODE;\n\tp->cpuset_slab_spread_rotor = NUMA_NO_NODE;\n\tseqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);\n#endif\n#ifdef CONFIG_TRACE_IRQFLAGS\n\tmemset(&p->irqtrace, 0, sizeof(p->irqtrace));\n\tp->irqtrace.hardirq_disable_ip\t= _THIS_IP_;\n\tp->irqtrace.softirq_enable_ip\t= _THIS_IP_;\n\tp->softirqs_enabled\t\t= 1;\n\tp->softirq_context\t\t= 0;\n#endif\n\n\tp->pagefault_disabled = 0;\n\n#ifdef CONFIG_LOCKDEP\n\tlockdep_init_task(p);\n#endif\n\n#ifdef CONFIG_DEBUG_MUTEXES\n\tp->blocked_on = NULL; /* not blocked yet */\n#endif\n#ifdef CONFIG_BCACHE\n\tp->sequential_io\t= 0;\n\tp->sequential_io_avg\t= 0;\n#endif\n\n\t/* Perform scheduler related setup. Assign this task to a CPU. */\n\tretval = sched_fork(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\n\tretval = perf_event_init_task(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\tretval = audit_alloc(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_perf;\n\t/* copy all the process information */\n\tshm_init_task(p);\n\tretval = security_task_alloc(p, clone_flags);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_audit;\n\tretval = copy_semundo(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_security;\n\tretval = copy_files(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_semundo;\n\tretval = copy_fs(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_files;\n\tretval = copy_sighand(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_fs;\n\tretval = copy_signal(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_sighand;\n\tretval = copy_mm(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_signal;\n\tretval = copy_namespaces(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_mm;\n\tretval = copy_io(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_namespaces;\n\tretval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_io;\n\n\tstackleak_task_init(p);\n\n\tif (pid != &init_struct_pid) {\n\t\tpid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,\n\t\t\t\targs->set_tid_size);\n\t\tif (IS_ERR(pid)) {\n\t\t\tretval = PTR_ERR(pid);\n\t\t\tgoto bad_fork_cleanup_thread;\n\t\t}\n\t}\n\n\t/*\n\t * This has to happen after we've potentially unshared the file\n\t * descriptor table (so that the pidfd doesn't leak into the child\n\t * if the fd table isn't shared).\n\t */\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tretval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);\n\t\tif (retval < 0)\n\t\t\tgoto bad_fork_free_pid;\n\n\t\tpidfd = retval;\n\n\t\tpidfile = anon_inode_getfile(\"[pidfd]\", &pidfd_fops, pid,\n\t\t\t\t\t O_RDWR | O_CLOEXEC);\n\t\tif (IS_ERR(pidfile)) {\n\t\t\tput_unused_fd(pidfd);\n\t\t\tretval = PTR_ERR(pidfile);\n\t\t\tgoto bad_fork_free_pid;\n\t\t}\n\t\tget_pid(pid);\t/* held by pidfile now */\n\n\t\tretval = put_user(pidfd, args->pidfd);\n\t\tif (retval)\n\t\t\tgoto bad_fork_put_pidfd;\n\t}\n\n#ifdef CONFIG_BLOCK\n\tp->plug = NULL;\n#endif\n\tfutex_init_task(p);\n\n\t/*\n\t * sigaltstack should be cleared when sharing the same VM\n\t */\n\tif ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)\n\t\tsas_ss_reset(p);\n\n\t/*\n\t * Syscall tracing and stepping should be turned off in the\n\t * child regardless of CLONE_PTRACE.\n\t */\n\tuser_disable_single_step(p);\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);\n#ifdef TIF_SYSCALL_EMU\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_EMU);\n#endif\n\tclear_tsk_latency_tracing(p);\n\n\t/* ok, now we should be set up.. */\n\tp->pid = pid_nr(pid);\n\tif (clone_flags & CLONE_THREAD) {\n\t\tp->exit_signal = -1;\n\t\tp->group_leader = current->group_leader;\n\t\tp->tgid = current->tgid;\n\t} else {\n\t\tif (clone_flags & CLONE_PARENT)\n\t\t\tp->exit_signal = current->group_leader->exit_signal;\n\t\telse\n\t\t\tp->exit_signal = args->exit_signal;\n\t\tp->group_leader = p;\n\t\tp->tgid = p->pid;\n\t}\n\n\tp->nr_dirtied = 0;\n\tp->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);\n\tp->dirty_paused_when = 0;\n\n\tp->pdeath_signal = 0;\n\tINIT_LIST_HEAD(&p->thread_group);\n\tp->task_works = NULL;\n\n\t/*\n\t * Ensure that the cgroup subsystem policies allow the new process to be\n\t * forked. It should be noted that the new process's css_set can be changed\n\t * between here and cgroup_post_fork() if an organisation operation is in\n\t * progress.\n\t */\n\tretval = cgroup_can_fork(p, args);\n\tif (retval)\n\t\tgoto bad_fork_put_pidfd;\n\n\t/*\n\t * From this point on we must avoid any synchronous user-space\n\t * communication until we take the tasklist-lock. In particular, we do\n\t * not want user-space to be able to predict the process start-time by\n\t * stalling fork(2) after we recorded the start_time but before it is\n\t * visible to the system.\n\t */\n\n\tp->start_time = ktime_get_ns();\n\tp->start_boottime = ktime_get_boottime_ns();\n\n\t/*\n\t * Make it visible to the rest of the system, but dont wake it up yet.\n\t * Need tasklist lock for parent etc handling!\n\t */\n\twrite_lock_irq(&tasklist_lock);\n\n\t/* CLONE_PARENT re-uses the old parent */\n\tif (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {\n\t\tp->real_parent = current->real_parent;\n\t\tp->parent_exec_id = current->parent_exec_id;\n\t} else {\n\t\tp->real_parent = current;\n\t\tp->parent_exec_id = current->self_exec_id;\n\t}\n\n\tklp_copy_process(p);\n\n\tspin_lock(¤t->sighand->siglock);\n\n\t/*\n\t * Copy seccomp details explicitly here, in case they were changed\n\t * before holding sighand lock.\n\t */\n\tcopy_seccomp(p);\n\n\trseq_fork(p, clone_flags);\n\n\t/* Don't start children in a dying pid namespace */\n\tif (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {\n\t\tretval = -ENOMEM;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* Let kill terminate clone/fork in the middle */\n\tif (fatal_signal_pending(current)) {\n\t\tretval = -EINTR;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* past the last point of failure */\n\tif (pidfile)\n\t\tfd_install(pidfd, pidfile);\n\n\tinit_task_pid_links(p);\n\tif (likely(p->pid)) {\n\t\tptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);\n\n\t\tinit_task_pid(p, PIDTYPE_PID, pid);\n\t\tif (thread_group_leader(p)) {\n\t\t\tinit_task_pid(p, PIDTYPE_TGID, pid);\n\t\t\tinit_task_pid(p, PIDTYPE_PGID, task_pgrp(current));\n\t\t\tinit_task_pid(p, PIDTYPE_SID, task_session(current));\n\n\t\t\tif (is_child_reaper(pid)) {\n\t\t\t\tns_of_pid(pid)->child_reaper = p;\n\t\t\t\tp->signal->flags |= SIGNAL_UNKILLABLE;\n\t\t\t}\n\t\t\tp->signal->shared_pending.signal = delayed.signal;\n\t\t\tp->signal->tty = tty_kref_get(current->signal->tty);\n\t\t\t/*\n\t\t\t * Inherit has_child_subreaper flag under the same\n\t\t\t * tasklist_lock with adding child to the process tree\n\t\t\t * for propagate_has_child_subreaper optimization.\n\t\t\t */\n\t\t\tp->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||\n\t\t\t\t\t\t\t p->real_parent->signal->is_child_subreaper;\n\t\t\tlist_add_tail(&p->sibling, &p->real_parent->children);\n\t\t\tlist_add_tail_rcu(&p->tasks, &init_task.tasks);\n\t\t\tattach_pid(p, PIDTYPE_TGID);\n\t\t\tattach_pid(p, PIDTYPE_PGID);\n\t\t\tattach_pid(p, PIDTYPE_SID);\n\t\t\t__this_cpu_inc(process_counts);\n\t\t} else {\n\t\t\tcurrent->signal->nr_threads++;\n\t\t\tatomic_inc(¤t->signal->live);\n\t\t\trefcount_inc(¤t->signal->sigcnt);\n\t\t\ttask_join_group_stop(p);\n\t\t\tlist_add_tail_rcu(&p->thread_group,\n\t\t\t\t\t &p->group_leader->thread_group);\n\t\t\tlist_add_tail_rcu(&p->thread_node,\n\t\t\t\t\t &p->signal->thread_head);\n\t\t}\n\t\tattach_pid(p, PIDTYPE_PID);\n\t\tnr_threads++;\n\t}\n\ttotal_forks++;\n\thlist_del_init(&delayed.node);\n\tspin_unlock(¤t->sighand->siglock);\n\tsyscall_tracepoint_update(p);\n\twrite_unlock_irq(&tasklist_lock);\n\n\tproc_fork_connector(p);\n\tsched_post_fork(p);\n\tcgroup_post_fork(p, args);\n\tperf_event_fork(p);\n\n\ttrace_task_newtask(p, clone_flags);\n\tuprobe_copy_process(p, clone_flags);\n\n\tcopy_oom_score_adj(clone_flags, p);\n\n\treturn p;\n\nbad_fork_cancel_cgroup:\n\tspin_unlock(¤t->sighand->siglock);\n\twrite_unlock_irq(&tasklist_lock);\n\tcgroup_cancel_fork(p, args);\nbad_fork_put_pidfd:\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tfput(pidfile);\n\t\tput_unused_fd(pidfd);\n\t}\nbad_fork_free_pid:\n\tif (pid != &init_struct_pid)\n\t\tfree_pid(pid);\nbad_fork_cleanup_thread:\n\texit_thread(p);\nbad_fork_cleanup_io:\n\tif (p->io_context)\n\t\texit_io_context(p);\nbad_fork_cleanup_namespaces:\n\texit_task_namespaces(p);\nbad_fork_cleanup_mm:\n\tif (p->mm) {\n\t\tmm_clear_owner(p->mm, p);\n\t\tmmput(p->mm);\n\t}\nbad_fork_cleanup_signal:\n\tif (!(clone_flags & CLONE_THREAD))\n\t\tfree_signal_struct(p->signal);\nbad_fork_cleanup_sighand:\n\t__cleanup_sighand(p->sighand);\nbad_fork_cleanup_fs:\n\texit_fs(p); /* blocking */\nbad_fork_cleanup_files:\n\texit_files(p); /* blocking */\nbad_fork_cleanup_semundo:\n\texit_sem(p);\nbad_fork_cleanup_security:\n\tsecurity_task_free(p);\nbad_fork_cleanup_audit:\n\taudit_free(p);\nbad_fork_cleanup_perf:\n\tperf_event_free_task(p);\nbad_fork_cleanup_policy:\n\tlockdep_free_task(p);\n#ifdef CONFIG_NUMA\n\tmpol_put(p->mempolicy);\nbad_fork_cleanup_threadgroup_lock:\n#endif\n\tdelayacct_tsk_free(p);\nbad_fork_cleanup_count:\n\tatomic_dec(&p->cred->user->processes);\n\texit_creds(p);\nbad_fork_free:\n\tp->state = TASK_DEAD;\n\tput_task_stack(p);\n\tdelayed_free_task(p);\nfork_out:\n\tspin_lock_irq(¤t->sighand->siglock);\n\thlist_del_init(&delayed.node);\n\tspin_unlock_irq(¤t->sighand->siglock);\n\treturn ERR_PTR(retval);\n}", "func_hash": 32186611525420761125196756499535835876, "file_name": "fork.c", "file_hash": 337139051241817667773946173830049023527, "cwe": ["CWE-665"], "cve": "CVE-2020-35508", "cve_desc": "A flaw possibility of race condition and incorrect initialization of the process id was found in the Linux kernel child/parent process identification handling while filtering signal handlers. A local attacker is able to abuse this flaw to bypass checks to send any signal to a privileged process.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35508"} {"idx": 293695, "project": "linux", "commit_id": "b4e00444cab4c3f3fec876dc0cccc8cbb0d1a948", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/b4e00444cab4c3f3fec876dc0cccc8cbb0d1a948", "commit_message": "fork: fix copy_process(CLONE_PARENT) race with the exiting ->real_parent\n\ncurrent->group_leader->exit_signal may change during copy_process() if\ncurrent->real_parent exits.\n\nMove the assignment inside tasklist_lock to avoid the race.\n\nSigned-off-by: Eddy Wu \nAcked-by: Oleg Nesterov \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "static __latent_entropy struct task_struct *copy_process(\n\t\t\t\t\tstruct pid *pid,\n\t\t\t\t\tint trace,\n\t\t\t\t\tint node,\n\t\t\t\t\tstruct kernel_clone_args *args)\n{\n\tint pidfd = -1, retval;\n\tstruct task_struct *p;\n\tstruct multiprocess_signals delayed;\n\tstruct file *pidfile = NULL;\n\tu64 clone_flags = args->flags;\n\tstruct nsproxy *nsp = current->nsproxy;\n\n\t/*\n\t * Don't allow sharing the root directory with processes in a different\n\t * namespace\n\t */\n\tif ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\tif ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Thread groups must share signals as well, and detached threads\n\t * can only be started up within the thread group.\n\t */\n\tif ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Shared signal handlers imply shared VM. By way of the above,\n\t * thread groups also imply shared VM. Blocking this case allows\n\t * for various simplifications in other code.\n\t */\n\tif ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Siblings of global init remain as zombies on exit since they are\n\t * not reaped by their parent (swapper). To solve this and to avoid\n\t * multi-rooted process trees, prevent global and container-inits\n\t * from creating siblings.\n\t */\n\tif ((clone_flags & CLONE_PARENT) &&\n\t\t\t\tcurrent->signal->flags & SIGNAL_UNKILLABLE)\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * If the new process will be in a different pid or user namespace\n\t * do not allow it to share a thread group with the forking task.\n\t */\n\tif (clone_flags & CLONE_THREAD) {\n\t\tif ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||\n\t\t (task_active_pid_ns(current) != nsp->pid_ns_for_children))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * If the new process will be in a different time namespace\n\t * do not allow it to share VM or a thread group with the forking task.\n\t */\n\tif (clone_flags & (CLONE_THREAD | CLONE_VM)) {\n\t\tif (nsp->time_ns != nsp->time_ns_for_children)\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tif (clone_flags & CLONE_PIDFD) {\n\t\t/*\n\t\t * - CLONE_DETACHED is blocked so that we can potentially\n\t\t * reuse it later for CLONE_PIDFD.\n\t\t * - CLONE_THREAD is blocked until someone really needs it.\n\t\t */\n\t\tif (clone_flags & (CLONE_DETACHED | CLONE_THREAD))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * Force any signals received before this point to be delivered\n\t * before the fork happens. Collect up signals sent to multiple\n\t * processes that happen during the fork and delay them so that\n\t * they appear to happen after the fork.\n\t */\n\tsigemptyset(&delayed.signal);\n\tINIT_HLIST_NODE(&delayed.node);\n\n\tspin_lock_irq(¤t->sighand->siglock);\n\tif (!(clone_flags & CLONE_THREAD))\n\t\thlist_add_head(&delayed.node, ¤t->signal->multiprocess);\n\trecalc_sigpending();\n\tspin_unlock_irq(¤t->sighand->siglock);\n\tretval = -ERESTARTNOINTR;\n\tif (signal_pending(current))\n\t\tgoto fork_out;\n\n\tretval = -ENOMEM;\n\tp = dup_task_struct(current, node);\n\tif (!p)\n\t\tgoto fork_out;\n\n\t/*\n\t * This _must_ happen before we call free_task(), i.e. before we jump\n\t * to any of the bad_fork_* labels. This is to avoid freeing\n\t * p->set_child_tid which is (ab)used as a kthread's data pointer for\n\t * kernel threads (PF_KTHREAD).\n\t */\n\tp->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;\n\t/*\n\t * Clear TID on mm_release()?\n\t */\n\tp->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;\n\n\tftrace_graph_init_task(p);\n\n\trt_mutex_init_task(p);\n\n\tlockdep_assert_irqs_enabled();\n#ifdef CONFIG_PROVE_LOCKING\n\tDEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);\n#endif\n\tretval = -EAGAIN;\n\tif (atomic_read(&p->real_cred->user->processes) >=\n\t\t\ttask_rlimit(p, RLIMIT_NPROC)) {\n\t\tif (p->real_cred->user != INIT_USER &&\n\t\t !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))\n\t\t\tgoto bad_fork_free;\n\t}\n\tcurrent->flags &= ~PF_NPROC_EXCEEDED;\n\n\tretval = copy_creds(p, clone_flags);\n\tif (retval < 0)\n\t\tgoto bad_fork_free;\n\n\t/*\n\t * If multiple threads are within copy_process(), then this check\n\t * triggers too late. This doesn't hurt, the check is only there\n\t * to stop root fork bombs.\n\t */\n\tretval = -EAGAIN;\n\tif (data_race(nr_threads >= max_threads))\n\t\tgoto bad_fork_cleanup_count;\n\n\tdelayacct_tsk_init(p);\t/* Must remain after dup_task_struct() */\n\tp->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);\n\tp->flags |= PF_FORKNOEXEC;\n\tINIT_LIST_HEAD(&p->children);\n\tINIT_LIST_HEAD(&p->sibling);\n\trcu_copy_process(p);\n\tp->vfork_done = NULL;\n\tspin_lock_init(&p->alloc_lock);\n\n\tinit_sigpending(&p->pending);\n\n\tp->utime = p->stime = p->gtime = 0;\n#ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME\n\tp->utimescaled = p->stimescaled = 0;\n#endif\n\tprev_cputime_init(&p->prev_cputime);\n\n#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN\n\tseqcount_init(&p->vtime.seqcount);\n\tp->vtime.starttime = 0;\n\tp->vtime.state = VTIME_INACTIVE;\n#endif\n\n#ifdef CONFIG_IO_URING\n\tp->io_uring = NULL;\n#endif\n\n#if defined(SPLIT_RSS_COUNTING)\n\tmemset(&p->rss_stat, 0, sizeof(p->rss_stat));\n#endif\n\n\tp->default_timer_slack_ns = current->timer_slack_ns;\n\n#ifdef CONFIG_PSI\n\tp->psi_flags = 0;\n#endif\n\n\ttask_io_accounting_init(&p->ioac);\n\tacct_clear_integrals(p);\n\n\tposix_cputimers_init(&p->posix_cputimers);\n\n\tp->io_context = NULL;\n\taudit_set_context(p, NULL);\n\tcgroup_fork(p);\n#ifdef CONFIG_NUMA\n\tp->mempolicy = mpol_dup(p->mempolicy);\n\tif (IS_ERR(p->mempolicy)) {\n\t\tretval = PTR_ERR(p->mempolicy);\n\t\tp->mempolicy = NULL;\n\t\tgoto bad_fork_cleanup_threadgroup_lock;\n\t}\n#endif\n#ifdef CONFIG_CPUSETS\n\tp->cpuset_mem_spread_rotor = NUMA_NO_NODE;\n\tp->cpuset_slab_spread_rotor = NUMA_NO_NODE;\n\tseqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);\n#endif\n#ifdef CONFIG_TRACE_IRQFLAGS\n\tmemset(&p->irqtrace, 0, sizeof(p->irqtrace));\n\tp->irqtrace.hardirq_disable_ip\t= _THIS_IP_;\n\tp->irqtrace.softirq_enable_ip\t= _THIS_IP_;\n\tp->softirqs_enabled\t\t= 1;\n\tp->softirq_context\t\t= 0;\n#endif\n\n\tp->pagefault_disabled = 0;\n\n#ifdef CONFIG_LOCKDEP\n\tlockdep_init_task(p);\n#endif\n\n#ifdef CONFIG_DEBUG_MUTEXES\n\tp->blocked_on = NULL; /* not blocked yet */\n#endif\n#ifdef CONFIG_BCACHE\n\tp->sequential_io\t= 0;\n\tp->sequential_io_avg\t= 0;\n#endif\n\n\t/* Perform scheduler related setup. Assign this task to a CPU. */\n\tretval = sched_fork(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\n\tretval = perf_event_init_task(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\tretval = audit_alloc(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_perf;\n\t/* copy all the process information */\n\tshm_init_task(p);\n\tretval = security_task_alloc(p, clone_flags);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_audit;\n\tretval = copy_semundo(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_security;\n\tretval = copy_files(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_semundo;\n\tretval = copy_fs(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_files;\n\tretval = copy_sighand(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_fs;\n\tretval = copy_signal(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_sighand;\n\tretval = copy_mm(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_signal;\n\tretval = copy_namespaces(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_mm;\n\tretval = copy_io(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_namespaces;\n\tretval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_io;\n\n\tstackleak_task_init(p);\n\n\tif (pid != &init_struct_pid) {\n\t\tpid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,\n\t\t\t\targs->set_tid_size);\n\t\tif (IS_ERR(pid)) {\n\t\t\tretval = PTR_ERR(pid);\n\t\t\tgoto bad_fork_cleanup_thread;\n\t\t}\n\t}\n\n\t/*\n\t * This has to happen after we've potentially unshared the file\n\t * descriptor table (so that the pidfd doesn't leak into the child\n\t * if the fd table isn't shared).\n\t */\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tretval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);\n\t\tif (retval < 0)\n\t\t\tgoto bad_fork_free_pid;\n\n\t\tpidfd = retval;\n\n\t\tpidfile = anon_inode_getfile(\"[pidfd]\", &pidfd_fops, pid,\n\t\t\t\t\t O_RDWR | O_CLOEXEC);\n\t\tif (IS_ERR(pidfile)) {\n\t\t\tput_unused_fd(pidfd);\n\t\t\tretval = PTR_ERR(pidfile);\n\t\t\tgoto bad_fork_free_pid;\n\t\t}\n\t\tget_pid(pid);\t/* held by pidfile now */\n\n\t\tretval = put_user(pidfd, args->pidfd);\n\t\tif (retval)\n\t\t\tgoto bad_fork_put_pidfd;\n\t}\n\n#ifdef CONFIG_BLOCK\n\tp->plug = NULL;\n#endif\n\tfutex_init_task(p);\n\n\t/*\n\t * sigaltstack should be cleared when sharing the same VM\n\t */\n\tif ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)\n\t\tsas_ss_reset(p);\n\n\t/*\n\t * Syscall tracing and stepping should be turned off in the\n\t * child regardless of CLONE_PTRACE.\n\t */\n\tuser_disable_single_step(p);\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);\n#ifdef TIF_SYSCALL_EMU\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_EMU);\n#endif\n\tclear_tsk_latency_tracing(p);\n\n\t/* ok, now we should be set up.. */\n\tp->pid = pid_nr(pid);\n\tif (clone_flags & CLONE_THREAD) {\n\t\tp->group_leader = current->group_leader;\n\t\tp->tgid = current->tgid;\n\t} else {\n\t\tp->group_leader = p;\n\t\tp->tgid = p->pid;\n\t}\n\n\tp->nr_dirtied = 0;\n\tp->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);\n\tp->dirty_paused_when = 0;\n\n\tp->pdeath_signal = 0;\n\tINIT_LIST_HEAD(&p->thread_group);\n\tp->task_works = NULL;\n\n\t/*\n\t * Ensure that the cgroup subsystem policies allow the new process to be\n\t * forked. It should be noted that the new process's css_set can be changed\n\t * between here and cgroup_post_fork() if an organisation operation is in\n\t * progress.\n\t */\n\tretval = cgroup_can_fork(p, args);\n\tif (retval)\n\t\tgoto bad_fork_put_pidfd;\n\n\t/*\n\t * From this point on we must avoid any synchronous user-space\n\t * communication until we take the tasklist-lock. In particular, we do\n\t * not want user-space to be able to predict the process start-time by\n\t * stalling fork(2) after we recorded the start_time but before it is\n\t * visible to the system.\n\t */\n\n\tp->start_time = ktime_get_ns();\n\tp->start_boottime = ktime_get_boottime_ns();\n\n\t/*\n\t * Make it visible to the rest of the system, but dont wake it up yet.\n\t * Need tasklist lock for parent etc handling!\n\t */\n\twrite_lock_irq(&tasklist_lock);\n\n\t/* CLONE_PARENT re-uses the old parent */\n\tif (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {\n\t\tp->real_parent = current->real_parent;\n\t\tp->parent_exec_id = current->parent_exec_id;\n\t\tif (clone_flags & CLONE_THREAD)\n\t\t\tp->exit_signal = -1;\n\t\telse\n\t\t\tp->exit_signal = current->group_leader->exit_signal;\n\t} else {\n\t\tp->real_parent = current;\n\t\tp->parent_exec_id = current->self_exec_id;\n\t\tp->exit_signal = args->exit_signal;\n\t}\n\n\tklp_copy_process(p);\n\n\tspin_lock(¤t->sighand->siglock);\n\n\t/*\n\t * Copy seccomp details explicitly here, in case they were changed\n\t * before holding sighand lock.\n\t */\n\tcopy_seccomp(p);\n\n\trseq_fork(p, clone_flags);\n\n\t/* Don't start children in a dying pid namespace */\n\tif (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {\n\t\tretval = -ENOMEM;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* Let kill terminate clone/fork in the middle */\n\tif (fatal_signal_pending(current)) {\n\t\tretval = -EINTR;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* past the last point of failure */\n\tif (pidfile)\n\t\tfd_install(pidfd, pidfile);\n\n\tinit_task_pid_links(p);\n\tif (likely(p->pid)) {\n\t\tptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);\n\n\t\tinit_task_pid(p, PIDTYPE_PID, pid);\n\t\tif (thread_group_leader(p)) {\n\t\t\tinit_task_pid(p, PIDTYPE_TGID, pid);\n\t\t\tinit_task_pid(p, PIDTYPE_PGID, task_pgrp(current));\n\t\t\tinit_task_pid(p, PIDTYPE_SID, task_session(current));\n\n\t\t\tif (is_child_reaper(pid)) {\n\t\t\t\tns_of_pid(pid)->child_reaper = p;\n\t\t\t\tp->signal->flags |= SIGNAL_UNKILLABLE;\n\t\t\t}\n\t\t\tp->signal->shared_pending.signal = delayed.signal;\n\t\t\tp->signal->tty = tty_kref_get(current->signal->tty);\n\t\t\t/*\n\t\t\t * Inherit has_child_subreaper flag under the same\n\t\t\t * tasklist_lock with adding child to the process tree\n\t\t\t * for propagate_has_child_subreaper optimization.\n\t\t\t */\n\t\t\tp->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||\n\t\t\t\t\t\t\t p->real_parent->signal->is_child_subreaper;\n\t\t\tlist_add_tail(&p->sibling, &p->real_parent->children);\n\t\t\tlist_add_tail_rcu(&p->tasks, &init_task.tasks);\n\t\t\tattach_pid(p, PIDTYPE_TGID);\n\t\t\tattach_pid(p, PIDTYPE_PGID);\n\t\t\tattach_pid(p, PIDTYPE_SID);\n\t\t\t__this_cpu_inc(process_counts);\n\t\t} else {\n\t\t\tcurrent->signal->nr_threads++;\n\t\t\tatomic_inc(¤t->signal->live);\n\t\t\trefcount_inc(¤t->signal->sigcnt);\n\t\t\ttask_join_group_stop(p);\n\t\t\tlist_add_tail_rcu(&p->thread_group,\n\t\t\t\t\t &p->group_leader->thread_group);\n\t\t\tlist_add_tail_rcu(&p->thread_node,\n\t\t\t\t\t &p->signal->thread_head);\n\t\t}\n\t\tattach_pid(p, PIDTYPE_PID);\n\t\tnr_threads++;\n\t}\n\ttotal_forks++;\n\thlist_del_init(&delayed.node);\n\tspin_unlock(¤t->sighand->siglock);\n\tsyscall_tracepoint_update(p);\n\twrite_unlock_irq(&tasklist_lock);\n\n\tproc_fork_connector(p);\n\tsched_post_fork(p);\n\tcgroup_post_fork(p, args);\n\tperf_event_fork(p);\n\n\ttrace_task_newtask(p, clone_flags);\n\tuprobe_copy_process(p, clone_flags);\n\n\tcopy_oom_score_adj(clone_flags, p);\n\n\treturn p;\n\nbad_fork_cancel_cgroup:\n\tspin_unlock(¤t->sighand->siglock);\n\twrite_unlock_irq(&tasklist_lock);\n\tcgroup_cancel_fork(p, args);\nbad_fork_put_pidfd:\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tfput(pidfile);\n\t\tput_unused_fd(pidfd);\n\t}\nbad_fork_free_pid:\n\tif (pid != &init_struct_pid)\n\t\tfree_pid(pid);\nbad_fork_cleanup_thread:\n\texit_thread(p);\nbad_fork_cleanup_io:\n\tif (p->io_context)\n\t\texit_io_context(p);\nbad_fork_cleanup_namespaces:\n\texit_task_namespaces(p);\nbad_fork_cleanup_mm:\n\tif (p->mm) {\n\t\tmm_clear_owner(p->mm, p);\n\t\tmmput(p->mm);\n\t}\nbad_fork_cleanup_signal:\n\tif (!(clone_flags & CLONE_THREAD))\n\t\tfree_signal_struct(p->signal);\nbad_fork_cleanup_sighand:\n\t__cleanup_sighand(p->sighand);\nbad_fork_cleanup_fs:\n\texit_fs(p); /* blocking */\nbad_fork_cleanup_files:\n\texit_files(p); /* blocking */\nbad_fork_cleanup_semundo:\n\texit_sem(p);\nbad_fork_cleanup_security:\n\tsecurity_task_free(p);\nbad_fork_cleanup_audit:\n\taudit_free(p);\nbad_fork_cleanup_perf:\n\tperf_event_free_task(p);\nbad_fork_cleanup_policy:\n\tlockdep_free_task(p);\n#ifdef CONFIG_NUMA\n\tmpol_put(p->mempolicy);\nbad_fork_cleanup_threadgroup_lock:\n#endif\n\tdelayacct_tsk_free(p);\nbad_fork_cleanup_count:\n\tatomic_dec(&p->cred->user->processes);\n\texit_creds(p);\nbad_fork_free:\n\tp->state = TASK_DEAD;\n\tput_task_stack(p);\n\tdelayed_free_task(p);\nfork_out:\n\tspin_lock_irq(¤t->sighand->siglock);\n\thlist_del_init(&delayed.node);\n\tspin_unlock_irq(¤t->sighand->siglock);\n\treturn ERR_PTR(retval);\n}", "func_hash": 326346272563108290661539307653854134885, "file_name": "fork.c", "file_hash": 63380205717297039909498355465180694389, "cwe": ["CWE-665"], "cve": "CVE-2020-35508", "cve_desc": "A flaw possibility of race condition and incorrect initialization of the process id was found in the Linux kernel child/parent process identification handling while filtering signal handlers. A local attacker is able to abuse this flaw to bypass checks to send any signal to a privileged process.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35508"} {"idx": 199860, "project": "FreeRDP", "commit_id": "40393700642ad38437982e8a3afc34ff33ccf28e", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/40393700642ad38437982e8a3afc34ff33ccf28e", "commit_message": "Fixed input sanitation in rdpgfx_recv_solid_fill_pdu\n\nThe input rectangle must be checked for plausibility.\n\nThanks to Sunglin and HuanGMz of the Knownsec 404 security team and pangzi of pwnzen", "target": 1, "func": "UINT rdpgfx_read_rect16(wStream* s, RECTANGLE_16* rect16)\n{\n\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"not enough data!\");\n\t\treturn ERROR_INVALID_DATA;\n\t}\n\n\tStream_Read_UINT16(s, rect16->left); /* left (2 bytes) */\n\tStream_Read_UINT16(s, rect16->top); /* top (2 bytes) */\n\tStream_Read_UINT16(s, rect16->right); /* right (2 bytes) */\n\tStream_Read_UINT16(s, rect16->bottom); /* bottom (2 bytes) */\n\treturn CHANNEL_RC_OK;\n}", "func_hash": 205619432801155878918798172599085525849, "file_name": "rdpgfx_common.c", "file_hash": 172968914733977070676000192786673542644, "cwe": ["CWE-190"], "cve": "CVE-2020-15103", "cve_desc": "In FreeRDP less than or equal to 2.1.2, an integer overflow exists due to missing input sanitation in rdpegfx channel. All FreeRDP clients are affected. The input rectangles from the server are not checked against local surface coordinates and blindly accepted. A malicious server can send data that will crash the client later on (invalid length arguments to a `memcpy`) This has been fixed in 2.2.0. As a workaround, stop using command line arguments /gfx, /gfx-h264 and /network:auto", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15103"} {"idx": 294212, "project": "FreeRDP", "commit_id": "40393700642ad38437982e8a3afc34ff33ccf28e", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/40393700642ad38437982e8a3afc34ff33ccf28e", "commit_message": "Fixed input sanitation in rdpgfx_recv_solid_fill_pdu\n\nThe input rectangle must be checked for plausibility.\n\nThanks to Sunglin and HuanGMz of the Knownsec 404 security team and pangzi of pwnzen", "target": 0, "func": "UINT rdpgfx_read_rect16(wStream* s, RECTANGLE_16* rect16)\n{\n\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"not enough data!\");\n\t\treturn ERROR_INVALID_DATA;\n\t}\n\n\tStream_Read_UINT16(s, rect16->left); /* left (2 bytes) */\n\tStream_Read_UINT16(s, rect16->top); /* top (2 bytes) */\n\tStream_Read_UINT16(s, rect16->right); /* right (2 bytes) */\n\tStream_Read_UINT16(s, rect16->bottom); /* bottom (2 bytes) */\n\tif (rect16->left >= rect16->right)\n\t\treturn ERROR_INVALID_DATA;\n\tif (rect16->top >= rect16->bottom)\n\t\treturn ERROR_INVALID_DATA;\n\treturn CHANNEL_RC_OK;\n}", "func_hash": 213920611407912603289460056234690246865, "file_name": "rdpgfx_common.c", "file_hash": 289155546843190690420914449033097829683, "cwe": ["CWE-190"], "cve": "CVE-2020-15103", "cve_desc": "In FreeRDP less than or equal to 2.1.2, an integer overflow exists due to missing input sanitation in rdpegfx channel. All FreeRDP clients are affected. The input rectangles from the server are not checked against local surface coordinates and blindly accepted. A malicious server can send data that will crash the client later on (invalid length arguments to a `memcpy`) This has been fixed in 2.2.0. As a workaround, stop using command line arguments /gfx, /gfx-h264 and /network:auto", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15103"} {"idx": 199894, "project": "FreeRDP", "commit_id": "0332cad015fdf7fac7e5c6863484f18a554e0fcf", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/0332cad015fdf7fac7e5c6863484f18a554e0fcf", "commit_message": "Fixed oob read in update_recv\n\nproperly use update_type_to_string to print update type.\nThanks to hac425 CVE-2020-11019", "target": 1, "func": "BOOL update_recv(rdpUpdate* update, wStream* s)\n{\n\tBOOL rc = FALSE;\n\tUINT16 updateType;\n\trdpContext* context = update->context;\n\n\tif (Stream_GetRemainingLength(s) < 2)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_GetRemainingLength(s) < 2\");\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, updateType); /* updateType (2 bytes) */\n\tWLog_Print(update->log, WLOG_TRACE, \"%s Update Data PDU\", UPDATE_TYPE_STRINGS[updateType]);\n\n\tif (!update_begin_paint(update))\n\t\tgoto fail;\n\n\tswitch (updateType)\n\t{\n\t\tcase UPDATE_TYPE_ORDERS:\n\t\t\trc = update_recv_orders(update, s);\n\t\t\tbreak;\n\n\t\tcase UPDATE_TYPE_BITMAP:\n\t\t{\n\t\t\tBITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s);\n\n\t\t\tif (!bitmap_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update);\n\t\t\tfree_bitmap_update(update->context, bitmap_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_PALETTE:\n\t\t{\n\t\t\tPALETTE_UPDATE* palette_update = update_read_palette(update, s);\n\n\t\t\tif (!palette_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_PALETTE - update_read_palette() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->Palette, context, palette_update);\n\t\t\tfree_palette_update(context, palette_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_SYNCHRONIZE:\n\t\t\tif (!update_read_synchronize(update, s))\n\t\t\t\tgoto fail;\n\t\t\trc = IFCALLRESULT(TRUE, update->Synchronize, context);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\nfail:\n\n\tif (!update_end_paint(update))\n\t\trc = FALSE;\n\n\tif (!rc)\n\t{\n\t\tWLog_ERR(TAG, \"UPDATE_TYPE %s [%\" PRIu16 \"] failed\", update_type_to_string(updateType),\n\t\t updateType);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "func_hash": 150741181422543343363423036673396803365, "file_name": "update.c", "file_hash": 217883690094549979657461135572554525212, "cwe": ["CWE-125"], "cve": "CVE-2020-11019", "cve_desc": "In FreeRDP less than or equal to 2.0.0, when running with logger set to \"WLOG_TRACE\", a possible crash of application could occur due to a read of an invalid array index. Data could be printed as string to local terminal. This has been fixed in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11019"} {"idx": 295081, "project": "FreeRDP", "commit_id": "0332cad015fdf7fac7e5c6863484f18a554e0fcf", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/0332cad015fdf7fac7e5c6863484f18a554e0fcf", "commit_message": "Fixed oob read in update_recv\n\nproperly use update_type_to_string to print update type.\nThanks to hac425 CVE-2020-11019", "target": 0, "func": "BOOL update_recv(rdpUpdate* update, wStream* s)\n{\n\tBOOL rc = FALSE;\n\tUINT16 updateType;\n\trdpContext* context = update->context;\n\n\tif (Stream_GetRemainingLength(s) < 2)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_GetRemainingLength(s) < 2\");\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, updateType); /* updateType (2 bytes) */\n\tWLog_Print(update->log, WLOG_TRACE, \"%s Update Data PDU\", update_type_to_string(updateType));\n\n\tif (!update_begin_paint(update))\n\t\tgoto fail;\n\n\tswitch (updateType)\n\t{\n\t\tcase UPDATE_TYPE_ORDERS:\n\t\t\trc = update_recv_orders(update, s);\n\t\t\tbreak;\n\n\t\tcase UPDATE_TYPE_BITMAP:\n\t\t{\n\t\t\tBITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s);\n\n\t\t\tif (!bitmap_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update);\n\t\t\tfree_bitmap_update(update->context, bitmap_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_PALETTE:\n\t\t{\n\t\t\tPALETTE_UPDATE* palette_update = update_read_palette(update, s);\n\n\t\t\tif (!palette_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_PALETTE - update_read_palette() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->Palette, context, palette_update);\n\t\t\tfree_palette_update(context, palette_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_SYNCHRONIZE:\n\t\t\tif (!update_read_synchronize(update, s))\n\t\t\t\tgoto fail;\n\t\t\trc = IFCALLRESULT(TRUE, update->Synchronize, context);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\nfail:\n\n\tif (!update_end_paint(update))\n\t\trc = FALSE;\n\n\tif (!rc)\n\t{\n\t\tWLog_ERR(TAG, \"UPDATE_TYPE %s [%\" PRIu16 \"] failed\", update_type_to_string(updateType),\n\t\t updateType);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "func_hash": 296049703695360927179430140026013290021, "file_name": "update.c", "file_hash": 234444470123092432185573051169046375309, "cwe": ["CWE-125"], "cve": "CVE-2020-11019", "cve_desc": "In FreeRDP less than or equal to 2.0.0, when running with logger set to \"WLOG_TRACE\", a possible crash of application could occur due to a read of an invalid array index. Data could be printed as string to local terminal. This has been fixed in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11019"} {"idx": 199916, "project": "linux", "commit_id": "d0cb50185ae942b03c4327be322055d622dc79f6", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d0cb50185ae942b03c4327be322055d622dc79f6", "commit_message": "do_last(): fetch directory ->i_mode and ->i_uid before it's too late\n\nmay_create_in_sticky() call is done when we already have dropped the\nreference to dir.\n\nFixes: 30aba6656f61e (namei: allow restricted O_CREAT of FIFOs and regular files)\nSigned-off-by: Al Viro ", "target": 1, "func": "static int may_create_in_sticky(struct dentry * const dir,\n\t\t\t\tstruct inode * const inode)\n{\n\tif ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||\n\t (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||\n\t likely(!(dir->d_inode->i_mode & S_ISVTX)) ||\n\t uid_eq(inode->i_uid, dir->d_inode->i_uid) ||\n\t uid_eq(current_fsuid(), inode->i_uid))\n\t\treturn 0;\n\n\tif (likely(dir->d_inode->i_mode & 0002) ||\n\t (dir->d_inode->i_mode & 0020 &&\n\t ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||\n\t (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {\n\t\tconst char *operation = S_ISFIFO(inode->i_mode) ?\n\t\t\t\t\t\"sticky_create_fifo\" :\n\t\t\t\t\t\"sticky_create_regular\";\n\t\taudit_log_path_denied(AUDIT_ANOM_CREAT, operation);\n\t\treturn -EACCES;\n\t}\n\treturn 0;\n}", "func_hash": 242730818314206719304342583061060820755, "file_name": "namei.c", "file_hash": 246187738339497330286853636914990226501, "cwe": ["CWE-284"], "cve": "CVE-2020-8428", "cve_desc": "fs/namei.c in the Linux kernel before 5.5 has a may_create_in_sticky use-after-free, which allows local users to cause a denial of service (OOPS) or possibly obtain sensitive information from kernel memory, aka CID-d0cb50185ae9. One attack vector may be an open system call for a UNIX domain socket, if the socket is being moved to a new parent directory and its old parent directory is being removed.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8428"} {"idx": 295331, "project": "linux", "commit_id": "d0cb50185ae942b03c4327be322055d622dc79f6", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d0cb50185ae942b03c4327be322055d622dc79f6", "commit_message": "do_last(): fetch directory ->i_mode and ->i_uid before it's too late\n\nmay_create_in_sticky() call is done when we already have dropped the\nreference to dir.\n\nFixes: 30aba6656f61e (namei: allow restricted O_CREAT of FIFOs and regular files)\nSigned-off-by: Al Viro ", "target": 0, "func": "static int may_create_in_sticky(umode_t dir_mode, kuid_t dir_uid,\n\t\t\t\tstruct inode * const inode)\n{\n\tif ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||\n\t (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||\n\t likely(!(dir_mode & S_ISVTX)) ||\n\t uid_eq(inode->i_uid, dir_uid) ||\n\t uid_eq(current_fsuid(), inode->i_uid))\n\t\treturn 0;\n\n\tif (likely(dir_mode & 0002) ||\n\t (dir_mode & 0020 &&\n\t ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||\n\t (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {\n\t\tconst char *operation = S_ISFIFO(inode->i_mode) ?\n\t\t\t\t\t\"sticky_create_fifo\" :\n\t\t\t\t\t\"sticky_create_regular\";\n\t\taudit_log_path_denied(AUDIT_ANOM_CREAT, operation);\n\t\treturn -EACCES;\n\t}\n\treturn 0;\n}", "func_hash": 136484522509343218799279073115962597038, "file_name": "namei.c", "file_hash": 291682867518551513385800331855928264759, "cwe": ["CWE-284"], "cve": "CVE-2020-8428", "cve_desc": "fs/namei.c in the Linux kernel before 5.5 has a may_create_in_sticky use-after-free, which allows local users to cause a denial of service (OOPS) or possibly obtain sensitive information from kernel memory, aka CID-d0cb50185ae9. One attack vector may be an open system call for a UNIX domain socket, if the socket is being moved to a new parent directory and its old parent directory is being removed.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-8428"} {"idx": 199924, "project": "hermes", "commit_id": "b2021df620824627f5a8c96615edbd1eb7fdddfc", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/b2021df620824627f5a8c96615edbd1eb7fdddfc", "commit_message": "Fix CVE-2020-1914 by using NEXTINST for SaveGeneratorLong\n\nSummary:\nIf `SaveGeneratorLong` was emitted, it would accidentally jump to the\nwrong next instruction, based on how long SaveGenerator was.\n\nMake a callout function to handle the common case, and handle the dispatch\nwithin each case of the interpreter loop.\n\nFixes CVE-2020-1914\n\nReviewed By: neildhar\n\nDifferential Revision: D24024242\n\nfbshipit-source-id: 3bcb88daa740f0d50e91771a49eb212551ce8bd8", "target": 1, "func": "CallResult Interpreter::interpretFunction(\n Runtime *runtime,\n InterpreterState &state) {\n // The interepter is re-entrant and also saves/restores its IP via the runtime\n // whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure\n // to preserve the IP across calls to interpeterFunction() disrupt interpreter\n // calls further up the C++ callstack. The RAII utility class below makes sure\n // we always do this correctly.\n //\n // TODO: The IPs stored in the C++ callstack via this holder will generally be\n // the same as in the JS stack frames via the Saved IP field. We can probably\n // get rid of one of these redundant stores. Doing this isn't completely\n // trivial as there are currently cases where we re-enter the interpreter\n // without calling Runtime::saveCallerIPInStackFrame(), and there are features\n // (I think mostly the debugger + stack traces) which implicitly rely on\n // this behavior. At least their tests break if this behavior is not\n // preserved.\n struct IPSaver {\n IPSaver(Runtime *runtime)\n : ip_(runtime->getCurrentIP()), runtime_(runtime) {}\n\n ~IPSaver() {\n runtime_->setCurrentIP(ip_);\n }\n\n private:\n const Inst *ip_;\n Runtime *runtime_;\n };\n IPSaver ipSaver(runtime);\n\n#ifndef HERMES_ENABLE_DEBUGGER\n static_assert(!SingleStep, \"can't use single-step mode without the debugger\");\n#endif\n // Make sure that the cache can use an optimization by avoiding a branch to\n // access the property storage.\n static_assert(\n HiddenClass::kDictionaryThreshold <=\n SegmentedArray::kValueToSegmentThreshold,\n \"Cannot avoid branches in cache check if the dictionary \"\n \"crossover point is larger than the inline storage\");\n\n CodeBlock *curCodeBlock = state.codeBlock;\n const Inst *ip = nullptr;\n // Holds runtime->currentFrame_.ptr()-1 which is the first local\n // register. This eliminates the indirect load from Runtime and the -1 offset.\n PinnedHermesValue *frameRegs;\n // Strictness of current function.\n bool strictMode;\n // Default flags when accessing properties.\n PropOpFlags defaultPropOpFlags;\n\n// These CAPTURE_IP* macros should wrap around any major calls out of the\n// interpeter loop. They stash and retrieve the IP via the current Runtime\n// allowing the IP to be externally observed and even altered to change the flow\n// of execution. Explicitly saving AND restoring the IP from the Runtime in this\n// way means the C++ compiler will keep IP in a register within the rest of the\n// interpeter loop.\n//\n// When assertions are enabled we take the extra step of \"invalidating\" the IP\n// between captures so we can detect if it's erroneously accessed.\n//\n// In some cases we explicitly don't want to invalidate the IP and instead want\n// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up\n// when we're performing a call operation which may re-enter the interpeter\n// loop, and so need the IP available for the saveCallerIPInStackFrame() call\n// when we next enter.\n#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP();\n\n#ifdef NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)\n\n#else // !NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#endif // NDEBUG\n\n LLVM_DEBUG(dbgs() << \"interpretFunction() called\\n\");\n\n ScopedNativeDepthTracker depthTracker{runtime};\n if (LLVM_UNLIKELY(depthTracker.overflowed())) {\n return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);\n }\n\n if (!SingleStep) {\n if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {\n return (*jitPtr)(runtime);\n }\n }\n\n GCScope gcScope(runtime);\n // Avoid allocating a handle dynamically by reusing this one.\n MutableHandle<> tmpHandle(runtime);\n CallResult res{ExecutionStatus::EXCEPTION};\n CallResult> resPH{ExecutionStatus::EXCEPTION};\n CallResult> resArgs{ExecutionStatus::EXCEPTION};\n CallResult boolRes{ExecutionStatus::EXCEPTION};\n\n // Mark the gcScope so we can clear all allocated handles.\n // Remember how many handles the scope has so we can clear them in the loop.\n static constexpr unsigned KEEP_HANDLES = 1;\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"scope has unexpected number of handles\");\n\n INIT_OPCODE_PROFILER;\n\n#if !defined(HERMESVM_PROFILER_EXTERN)\ntailCall:\n#endif\n PROFILER_ENTER_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_DEBUGGER\n runtime->getDebugger().willEnterCodeBlock(curCodeBlock);\n#endif\n\n runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);\n\n // Update function executionCount_ count\n curCodeBlock->incrementExecutionCount();\n\n if (!SingleStep) {\n auto newFrame = runtime->setCurrentFrameToTopOfStack();\n runtime->saveCallerIPInStackFrame();\n#ifndef NDEBUG\n runtime->invalidateCurrentIP();\n#endif\n\n // Point frameRegs to the first register in the new frame. Note that at this\n // moment technically it points above the top of the stack, but we are never\n // going to access it.\n frameRegs = &newFrame.getFirstLocalRef();\n\n#ifndef NDEBUG\n LLVM_DEBUG(\n dbgs() << \"function entry: stackLevel=\" << runtime->getStackLevel()\n << \", argCount=\" << runtime->getCurrentFrame().getArgCount()\n << \", frameSize=\" << curCodeBlock->getFrameSize() << \"\\n\");\n\n LLVM_DEBUG(\n dbgs() << \" callee \"\n << DumpHermesValue(\n runtime->getCurrentFrame().getCalleeClosureOrCBRef())\n << \"\\n\");\n LLVM_DEBUG(\n dbgs() << \" this \"\n << DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())\n << \"\\n\");\n for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {\n LLVM_DEBUG(\n dbgs() << \" \" << llvh::format_decimal(i, 4) << \" \"\n << DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))\n << \"\\n\");\n }\n#endif\n\n // Allocate the registers for the new frame.\n if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(\n curCodeBlock->getFrameSize() +\n StackFrameLayout::CalleeExtraRegistersAtStart,\n HermesValue::encodeUndefinedValue())))\n goto stackOverflow;\n\n ip = (Inst const *)curCodeBlock->begin();\n\n // Check for invalid invocation.\n if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(\n newFrame.isConstructorCall()))) {\n if (!newFrame.isConstructorCall()) {\n CAPTURE_IP(\n runtime->raiseTypeError(\"Class constructor invoked without new\"));\n } else {\n CAPTURE_IP(runtime->raiseTypeError(\"Function is not a constructor\"));\n }\n goto handleExceptionInParent;\n }\n } else {\n // Point frameRegs to the first register in the frame.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n ip = (Inst const *)(curCodeBlock->begin() + state.offset);\n }\n\n assert((const uint8_t *)ip < curCodeBlock->end() && \"CodeBlock is empty\");\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n#define BEFORE_OP_CODE \\\n { \\\n UPDATE_OPCODE_TIME_SPENT; \\\n HERMES_SLOW_ASSERT( \\\n curCodeBlock->contains(ip) && \"curCodeBlock must contain ip\"); \\\n HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \\\n HERMES_SLOW_ASSERT( \\\n gcScope.getHandleCountDbg() == KEEP_HANDLES && \\\n \"unaccounted handles were created\"); \\\n HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && \"tmpHandle not cleared\"); \\\n RECORD_OPCODE_START_TIME; \\\n INC_OPCODE_COUNT; \\\n }\n\n#ifdef HERMESVM_INDIRECT_THREADING\n static void *opcodeDispatch[] = {\n#define DEFINE_OPCODE(name) &&case_##name,\n#include \"hermes/BCGen/HBC/BytecodeList.def\"\n &&case__last};\n\n#define CASE(name) case_##name:\n#define DISPATCH \\\n BEFORE_OP_CODE; \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n goto *opcodeDispatch[(unsigned)ip->opCode]\n\n#else // HERMESVM_INDIRECT_THREADING\n\n#define CASE(name) case OpCode::name:\n#define DISPATCH \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n continue\n\n#endif // HERMESVM_INDIRECT_THREADING\n\n#define RUN_DEBUGGER_ASYNC_BREAK(flags) \\\n do { \\\n CAPTURE_IP_ASSIGN( \\\n auto dRes, \\\n runDebuggerUpdatingState( \\\n (uint8_t)(flags) & \\\n (uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \\\n ? Debugger::RunReason::AsyncBreakExplicit \\\n : Debugger::RunReason::AsyncBreakImplicit, \\\n runtime, \\\n curCodeBlock, \\\n ip, \\\n frameRegs)); \\\n if (dRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n } while (0)\n\n for (;;) {\n BEFORE_OP_CODE;\n\n#ifdef HERMESVM_INDIRECT_THREADING\n goto *opcodeDispatch[(unsigned)ip->opCode];\n#else\n switch (ip->opCode)\n#endif\n {\n const Inst *nextIP;\n uint32_t idVal;\n bool tryProp;\n uint32_t callArgCount;\n // This is HermesValue::getRaw(), since HermesValue cannot be assigned\n // to. It is meant to be used only for very short durations, in the\n // dispatch of call instructions, when there is definitely no possibility\n // of a GC.\n HermesValue::RawType callNewTarget;\n\n/// Handle an opcode \\p name with an out-of-line implementation in a function\n/// ExecutionStatus caseName(\n/// Runtime *,\n/// PinnedHermesValue *frameRegs,\n/// Inst *ip)\n#define CASE_OUTOFLINE(name) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \\\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary arithmetic instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"n\" appended to the name.\n/// \\param oper the C++ operator to use to actually perform the arithmetic\n/// operation.\n#define BINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N) { \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n double left = res->getDouble(); \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n O1REG(name) = \\\n HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a shift instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the shift\n/// operation.\n/// \\param lConv the conversion function for the LHS of the expression.\n/// \\param lType the type of the LHS operand.\n/// \\param returnType the type of the return value.\n#define SHIFTOP(name, oper, lConv, lType, returnType) \\\n CASE(name) { \\\n if (LLVM_LIKELY( \\\n O2REG(name).isNumber() && \\\n O3REG(name).isNumber())) { /* Fast-path. */ \\\n auto lnum = static_cast( \\\n hermes::truncateToInt32(O2REG(name).getNumber())); \\\n auto rnum = static_cast( \\\n hermes::truncateToInt32(O3REG(name).getNumber())) & \\\n 0x1f; \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto lnum = static_cast(res->getNumber()); \\\n CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto rnum = static_cast(res->getNumber()) & 0x1f; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary bitwise instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the bitwise\n/// operation.\n#define BITWISEBINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n hermes::truncateToInt32(O2REG(name).getNumber()) \\\n oper hermes::truncateToInt32(O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n int32_t left = res->getNumberAs(); \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n O1REG(name) = \\\n HermesValue::encodeNumberValue(left oper res->getNumberAs()); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison instruction.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n#define CONDOP(name, oper, operFuncName) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeBoolValue( \\\n O2REG(name).getNumber() oper O3REG(name).getNumber()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison conditional jump with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"N\" appended to the name.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (LLVM_LIKELY( \\\n O2REG(name##suffix).isNumber() && \\\n O3REG(name##suffix).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N##suffix) { \\\n if (O2REG(name##N##suffix) \\\n .getNumber() oper O3REG(name##N##suffix) \\\n .getNumber()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (boolRes.getValue()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement a strict equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement an equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n CAPTURE_IP_ASSIGN( \\\n res, \\\n abstractEqualityTest_RJS( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (res->getBool()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement the long and short forms of a conditional jump, and its negation.\n#define JCOND(name, oper, operFuncName) \\\n JCOND_IMPL( \\\n J##name, \\\n , \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name.op1), \\\n NEXTINST(J##name)); \\\n JCOND_IMPL( \\\n J##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name##Long.op1), \\\n NEXTINST(J##name##Long)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n , \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name), \\\n IPADD(ip->iJNot##name.op1)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name##Long), \\\n IPADD(ip->iJNot##name##Long.op1));\n\n/// Load a constant.\n/// \\param value is the value to store in the output register.\n#define LOAD_CONST(name, value) \\\n CASE(name) { \\\n O1REG(name) = value; \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n#define LOAD_CONST_CAPTURE_IP(name, value) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(O1REG(name), value); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n CASE(Mov) {\n O1REG(Mov) = O2REG(Mov);\n ip = NEXTINST(Mov);\n DISPATCH;\n }\n\n CASE(MovLong) {\n O1REG(MovLong) = O2REG(MovLong);\n ip = NEXTINST(MovLong);\n DISPATCH;\n }\n\n CASE(LoadParam) {\n if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n O1REG(LoadParam) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n\n CASE(LoadParamLong) {\n if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParamLong) =\n FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n\n CASE(CoerceThisNS) {\n if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {\n O1REG(CoerceThisNS) = O2REG(CoerceThisNS);\n } else if (\n O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {\n O1REG(CoerceThisNS) = runtime->global_;\n } else {\n tmpHandle = O2REG(CoerceThisNS);\n nextIP = NEXTINST(CoerceThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(CoerceThisNS);\n DISPATCH;\n }\n CASE(LoadThisNS) {\n if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {\n O1REG(LoadThisNS) = FRAME.getThisArgRef();\n } else if (\n FRAME.getThisArgRef().isNull() ||\n FRAME.getThisArgRef().isUndefined()) {\n O1REG(LoadThisNS) = runtime->global_;\n } else {\n tmpHandle = FRAME.getThisArgRef();\n nextIP = NEXTINST(LoadThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(LoadThisNS);\n DISPATCH;\n }\n coerceThisSlowPath : {\n CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CoerceThisNS) = res.getValue();\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ConstructLong) {\n callArgCount = (uint32_t)ip->iConstructLong.op3;\n nextIP = NEXTINST(ConstructLong);\n callNewTarget = O2REG(ConstructLong).getRaw();\n goto doCall;\n }\n CASE(CallLong) {\n callArgCount = (uint32_t)ip->iCallLong.op3;\n nextIP = NEXTINST(CallLong);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n // Note in Call1 through Call4, the first argument is 'this' which has\n // argument index -1.\n // Also note that we are writing to callNewTarget last, to avoid the\n // possibility of it being aliased by the arg writes.\n CASE(Call1) {\n callArgCount = 1;\n nextIP = NEXTINST(Call1);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call1);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call2) {\n callArgCount = 2;\n nextIP = NEXTINST(Call2);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call2);\n fr.getArgRefUnsafe(0) = O4REG(Call2);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call3) {\n callArgCount = 3;\n nextIP = NEXTINST(Call3);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call3);\n fr.getArgRefUnsafe(0) = O4REG(Call3);\n fr.getArgRefUnsafe(1) = O5REG(Call3);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call4) {\n callArgCount = 4;\n nextIP = NEXTINST(Call4);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call4);\n fr.getArgRefUnsafe(0) = O4REG(Call4);\n fr.getArgRefUnsafe(1) = O5REG(Call4);\n fr.getArgRefUnsafe(2) = O6REG(Call4);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Construct) {\n callArgCount = (uint32_t)ip->iConstruct.op3;\n nextIP = NEXTINST(Construct);\n callNewTarget = O2REG(Construct).getRaw();\n goto doCall;\n }\n CASE(Call) {\n callArgCount = (uint32_t)ip->iCall.op3;\n nextIP = NEXTINST(Call);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n // Fall through.\n }\n\n doCall : {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n // Subtract 1 from callArgCount as 'this' is considered an argument in the\n // instruction, but not in the frame.\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n callArgCount - 1,\n O2REG(Call),\n HermesValue::fromRaw(callNewTarget)));\n (void)newFrame;\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n if (auto *func = dyn_vmcast(O2REG(Call))) {\n assert(!SingleStep && \"can't single-step a call\");\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->pushCallStack(curCodeBlock, ip);\n#endif\n\n CodeBlock *calleeBlock = func->getCodeBlock();\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(Call) = *res;\n SLOW_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CallDirect)\n CASE(CallDirectLongIndex) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n CAPTURE_IP_ASSIGN(\n CodeBlock * calleeBlock,\n ip->opCode == OpCode::CallDirect\n ? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirect.op3)\n : curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirectLongIndex.op3));\n\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallDirect.op2 - 1,\n HermesValue::encodeNativePointer(calleeBlock),\n HermesValue::encodeUndefinedValue()));\n (void)newFrame;\n\n LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n assert(!SingleStep && \"can't single-step a call\");\n\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CallDirect) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallDirect) = *res;\n LLVM_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCallDirect.op1\n << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n\n CASE(CallBuiltin) {\n NativeFunction *nf =\n runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);\n\n CAPTURE_IP_ASSIGN(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallBuiltin.op3 - 1,\n nf,\n false));\n // \"thisArg\" is implicitly assumed to \"undefined\".\n newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallBuiltin) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCallBuiltin.op1\n << \"=\" << DumpHermesValue(O1REG(CallBuiltin)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CallBuiltin);\n DISPATCH;\n }\n\n CASE(CompleteGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n innerFn->setState(GeneratorInnerFunction::State::Completed);\n ip = NEXTINST(CompleteGenerator);\n DISPATCH;\n }\n\n CASE(SaveGenerator) {\n nextIP = IPADD(ip->iSaveGenerator.op1);\n goto doSaveGen;\n }\n CASE(SaveGeneratorLong) {\n nextIP = IPADD(ip->iSaveGeneratorLong.op1);\n goto doSaveGen;\n }\n\n doSaveGen : {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n\n innerFn->saveStack(runtime);\n innerFn->setNextIP(nextIP);\n innerFn->setState(GeneratorInnerFunction::State::SuspendedYield);\n ip = NEXTINST(SaveGenerator);\n DISPATCH;\n }\n\n CASE(StartGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n if (innerFn->getState() ==\n GeneratorInnerFunction::State::SuspendedStart) {\n nextIP = NEXTINST(StartGenerator);\n } else {\n nextIP = innerFn->getNextIP();\n innerFn->restoreStack(runtime);\n }\n innerFn->setState(GeneratorInnerFunction::State::Executing);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ResumeGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n O1REG(ResumeGenerator) = innerFn->getResult();\n O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(\n innerFn->getAction() == GeneratorInnerFunction::Action::Return);\n innerFn->clearResult(runtime);\n if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {\n runtime->setThrownValue(O1REG(ResumeGenerator));\n goto exception;\n }\n ip = NEXTINST(ResumeGenerator);\n DISPATCH;\n }\n\n CASE(Ret) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Store the return value.\n res = O1REG(Ret);\n\n ip = FRAME.getSavedIP();\n curCodeBlock = FRAME.getSavedCodeBlock();\n\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(dbgs() << \"function exit: returning to native code\\n\");\n return res;\n }\n\n// Return because of recursive calling structure\n#if defined(HERMESVM_PROFILER_EXTERN)\n return res;\n#endif\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n O1REG(Call) = res.getValue();\n ip = nextInstCall(ip);\n DISPATCH;\n }\n\n CASE(Catch) {\n assert(!runtime->thrownValue_.isEmpty() && \"Invalid thrown value\");\n assert(\n !isUncatchableError(runtime->thrownValue_) &&\n \"Uncatchable thrown value was caught\");\n O1REG(Catch) = runtime->thrownValue_;\n runtime->clearThrownValue();\n#ifdef HERMES_ENABLE_DEBUGGER\n // Signal to the debugger that we're done unwinding an exception,\n // and we can resume normal debugging flow.\n runtime->debugger_.finishedUnwindingException();\n#endif\n ip = NEXTINST(Catch);\n DISPATCH;\n }\n\n CASE(Throw) {\n runtime->thrownValue_ = O1REG(Throw);\n SLOW_DEBUG(\n dbgs() << \"Exception thrown: \"\n << DumpHermesValue(runtime->thrownValue_) << \"\\n\");\n goto exception;\n }\n\n CASE(ThrowIfUndefinedInst) {\n if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {\n SLOW_DEBUG(\n dbgs() << \"Throwing ReferenceError for undefined variable\");\n CAPTURE_IP(runtime->raiseReferenceError(\n \"accessing an uninitialized variable\"));\n goto exception;\n }\n ip = NEXTINST(ThrowIfUndefinedInst);\n DISPATCH;\n }\n\n CASE(Debugger) {\n SLOW_DEBUG(dbgs() << \"debugger statement executed\\n\");\n#ifdef HERMES_ENABLE_DEBUGGER\n {\n if (!runtime->debugger_.isDebugging()) {\n // Only run the debugger if we're not already debugging.\n // Don't want to call it again and mess with its state.\n CAPTURE_IP_ASSIGN(\n auto res,\n runDebuggerUpdatingState(\n Debugger::RunReason::Opcode,\n runtime,\n curCodeBlock,\n ip,\n frameRegs));\n if (res == ExecutionStatus::EXCEPTION) {\n // If one of the internal steps threw,\n // then handle that here by jumping to where we're supposed to go.\n // If we're in mid-step, the breakpoint at the catch point\n // will have been set by the debugger.\n // We don't want to execute this instruction because it's already\n // thrown.\n goto exception;\n }\n }\n auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);\n if (breakpointOpt.hasValue()) {\n // We're on a breakpoint but we're supposed to continue.\n curCodeBlock->uninstallBreakpointAtOffset(\n CUROFFSET, breakpointOpt->opCode);\n if (ip->opCode == OpCode::Debugger) {\n // Breakpointed a debugger instruction, so move past it\n // since we've already called the debugger on this instruction.\n ip = NEXTINST(Debugger);\n } else {\n InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus status, runtime->stepFunction(newState));\n curCodeBlock->installBreakpointAtOffset(CUROFFSET);\n if (status == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n curCodeBlock = newState.codeBlock;\n ip = newState.codeBlock->getOffsetPtr(newState.offset);\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n // Single-stepping should handle call stack management for us.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n }\n } else if (ip->opCode == OpCode::Debugger) {\n // No breakpoint here and we've already run the debugger,\n // just continue on.\n // If the current instruction is no longer a debugger instruction,\n // we're just going to keep executing from the current IP.\n ip = NEXTINST(Debugger);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n DISPATCH;\n#else\n ip = NEXTINST(Debugger);\n DISPATCH;\n#endif\n }\n\n CASE(AsyncBreakCheck) {\n if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {\n#ifdef HERMES_ENABLE_DEBUGGER\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n }\n#endif\n if (runtime->testAndClearTimeoutAsyncBreakRequest()) {\n CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());\n if (nRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n\n ip = NEXTINST(AsyncBreakCheck);\n DISPATCH;\n }\n\n CASE(ProfilePoint) {\n#ifdef HERMESVM_PROFILER_BB\n auto pointIndex = ip->iProfilePoint.op1;\n SLOW_DEBUG(llvh::dbgs() << \"ProfilePoint: \" << pointIndex << \"\\n\");\n CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(\n curCodeBlock, pointIndex));\n#endif\n ip = NEXTINST(ProfilePoint);\n DISPATCH;\n }\n\n CASE(Unreachable) {\n llvm_unreachable(\"Hermes bug: unreachable instruction\");\n }\n\n CASE(CreateClosure) {\n idVal = ip->iCreateClosure.op3;\n nextIP = NEXTINST(CreateClosure);\n goto createClosure;\n }\n CASE(CreateClosureLongIndex) {\n idVal = ip->iCreateClosureLongIndex.op3;\n nextIP = NEXTINST(CreateClosureLongIndex);\n goto createClosure;\n }\n createClosure : {\n auto *runtimeModule = curCodeBlock->getRuntimeModule();\n CAPTURE_IP_ASSIGN(\n O1REG(CreateClosure),\n JSFunction::create(\n runtime,\n runtimeModule->getDomain(runtime),\n Handle::vmcast(&runtime->functionPrototype),\n Handle::vmcast(&O2REG(CreateClosure)),\n runtimeModule->getCodeBlockMayAllocate(idVal))\n .getHermesValue());\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CreateGeneratorClosure) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosure.op3,\n Handle::vmcast(&O2REG(CreateGeneratorClosure))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosure) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosure);\n DISPATCH;\n }\n CASE(CreateGeneratorClosureLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosureLongIndex.op3,\n Handle::vmcast(\n &O2REG(CreateGeneratorClosureLongIndex))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosureLongIndex);\n DISPATCH;\n }\n\n CASE(CreateGenerator) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGenerator.op3,\n Handle::vmcast(&O2REG(CreateGenerator)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGenerator) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGenerator);\n DISPATCH;\n }\n CASE(CreateGeneratorLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGeneratorLongIndex.op3,\n Handle::vmcast(&O2REG(CreateGeneratorLongIndex)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorLongIndex);\n DISPATCH;\n }\n\n CASE(GetEnvironment) {\n // The currently executing function must exist, so get the environment.\n Environment *curEnv =\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);\n for (unsigned level = ip->iGetEnvironment.op2; level; --level) {\n assert(curEnv && \"invalid environment relative level\");\n curEnv = curEnv->getParentEnvironment(runtime);\n }\n O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);\n ip = NEXTINST(GetEnvironment);\n DISPATCH;\n }\n\n CASE(CreateEnvironment) {\n tmpHandle = HermesValue::encodeObjectValue(\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));\n\n CAPTURE_IP_ASSIGN(\n res,\n Environment::create(\n runtime,\n tmpHandle->getPointer() ? Handle::vmcast(tmpHandle)\n : Handle::vmcast_or_null(\n &runtime->nullPointer_),\n curCodeBlock->getEnvironmentSize()));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(CreateEnvironment) = *res;\n#ifdef HERMES_ENABLE_DEBUGGER\n FRAME.getDebugEnvironmentRef() = *res;\n#endif\n tmpHandle = HermesValue::encodeUndefinedValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateEnvironment);\n DISPATCH;\n }\n\n CASE(StoreToEnvironment) {\n vmcast(O1REG(StoreToEnvironment))\n ->slot(ip->iStoreToEnvironment.op2)\n .set(O3REG(StoreToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironment);\n DISPATCH;\n }\n CASE(StoreToEnvironmentL) {\n vmcast(O1REG(StoreToEnvironmentL))\n ->slot(ip->iStoreToEnvironmentL.op2)\n .set(O3REG(StoreToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironmentL);\n DISPATCH;\n }\n\n CASE(StoreNPToEnvironment) {\n vmcast(O1REG(StoreNPToEnvironment))\n ->slot(ip->iStoreNPToEnvironment.op2)\n .setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironment);\n DISPATCH;\n }\n CASE(StoreNPToEnvironmentL) {\n vmcast(O1REG(StoreNPToEnvironmentL))\n ->slot(ip->iStoreNPToEnvironmentL.op2)\n .setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironmentL);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironment) {\n O1REG(LoadFromEnvironment) =\n vmcast(O2REG(LoadFromEnvironment))\n ->slot(ip->iLoadFromEnvironment.op3);\n ip = NEXTINST(LoadFromEnvironment);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironmentL) {\n O1REG(LoadFromEnvironmentL) =\n vmcast(O2REG(LoadFromEnvironmentL))\n ->slot(ip->iLoadFromEnvironmentL.op3);\n ip = NEXTINST(LoadFromEnvironmentL);\n DISPATCH;\n }\n\n CASE(GetGlobalObject) {\n O1REG(GetGlobalObject) = runtime->global_;\n ip = NEXTINST(GetGlobalObject);\n DISPATCH;\n }\n\n CASE(GetNewTarget) {\n O1REG(GetNewTarget) = FRAME.getNewTargetRef();\n ip = NEXTINST(GetNewTarget);\n DISPATCH;\n }\n\n CASE(DeclareGlobalVar) {\n DefinePropertyFlags dpf =\n DefinePropertyFlags::getDefaultNewPropertyFlags();\n dpf.configurable = 0;\n // Do not overwrite existing globals with undefined.\n dpf.setValue = 0;\n\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineOwnProperty(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n dpf,\n Runtime::getUndefinedValue(),\n PropOpFlags().plusThrowOnError()));\n if (res == ExecutionStatus::EXCEPTION) {\n assert(\n !runtime->getGlobal()->isProxyObject() &&\n \"global can't be a proxy object\");\n // If the property already exists, this should be a noop.\n // Instead of incurring the cost to check every time, do it\n // only if an exception is thrown, and swallow the exception\n // if it exists, since we didn't want to make the call,\n // anyway. This most likely means the property is\n // non-configurable.\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::getOwnNamedDescriptor(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n desc));\n if (!res) {\n goto exception;\n } else {\n runtime->clearThrownValue();\n }\n // fall through\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(DeclareGlobalVar);\n DISPATCH;\n }\n\n CASE(TryGetByIdLong) {\n tryProp = true;\n idVal = ip->iTryGetByIdLong.op4;\n nextIP = NEXTINST(TryGetByIdLong);\n goto getById;\n }\n CASE(GetByIdLong) {\n tryProp = false;\n idVal = ip->iGetByIdLong.op4;\n nextIP = NEXTINST(GetByIdLong);\n goto getById;\n }\n CASE(GetByIdShort) {\n tryProp = false;\n idVal = ip->iGetByIdShort.op4;\n nextIP = NEXTINST(GetByIdShort);\n goto getById;\n }\n CASE(TryGetById) {\n tryProp = true;\n idVal = ip->iTryGetById.op4;\n nextIP = NEXTINST(TryGetById);\n goto getById;\n }\n CASE(GetById) {\n tryProp = false;\n idVal = ip->iGetById.op4;\n nextIP = NEXTINST(GetById);\n }\n getById : {\n ++NumGetById;\n // NOTE: it is safe to use OnREG(GetById) here because all instructions\n // have the same layout: opcode, registers, non-register operands, i.e.\n // they only differ in the width of the last \"identifier\" field.\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetById).isObject())) {\n auto *obj = vmcast(O2REG(GetById));\n auto cacheIdx = ip->iGetById.op3;\n auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n#ifndef NDEBUG\n if (clazzGCPtr.get(runtime)->isDictionary())\n ++NumGetByIdDict;\n#else\n (void)NumGetByIdDict;\n#endif\n\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumGetByIdCacheHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(\n obj, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue fastPathResult,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(\n fastPathResult.hasValue() && fastPathResult.getValue()) &&\n !desc.flags.accessor) {\n ++NumGetByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumGetByIdCacheEvicts;\n#else\n (void)NumGetByIdCacheEvicts;\n#endif\n // Cache the class, id and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP_ASSIGN(\n O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));\n ip = nextIP;\n DISPATCH;\n }\n\n // The cache may also be populated via the prototype of the object.\n // This value is only reliable if the fast path was a definite\n // not-found.\n if (fastPathResult.hasValue() && !fastPathResult.getValue() &&\n !obj->isProxyObject()) {\n CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));\n // TODO: This isLazy check is because a lazy object is reported as\n // having no properties and therefore cannot contain the property.\n // This check does not belong here, it should be merged into\n // tryGetOwnNamedDescriptorFast().\n if (parent &&\n cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&\n LLVM_LIKELY(!obj->isLazy())) {\n ++NumGetByIdProtoHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n }\n\n#ifdef HERMES_SLOW_DEBUG\n CAPTURE_IP_ASSIGN(\n JSObject * propObj,\n JSObject::getNamedDescriptor(\n Handle::vmcast(&O2REG(GetById)), runtime, id, desc));\n if (propObj) {\n if (desc.flags.accessor)\n ++NumGetByIdAccessor;\n else if (propObj != vmcast(O2REG(GetById)))\n ++NumGetByIdProto;\n } else {\n ++NumGetByIdNotFound;\n }\n#else\n (void)NumGetByIdAccessor;\n (void)NumGetByIdProto;\n (void)NumGetByIdNotFound;\n#endif\n#ifdef HERMES_SLOW_DEBUG\n auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED\n ? cacheEntry->clazz.get(runtime, &runtime->getHeap())\n : nullptr;\n#endif\n ++NumGetByIdSlow;\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetById)),\n runtime,\n id,\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist(),\n cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry\n : nullptr));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n#ifdef HERMES_SLOW_DEBUG\n if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&\n cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {\n ++NumGetByIdCacheEvicts;\n }\n#endif\n } else {\n ++NumGetByIdTransient;\n assert(!tryProp && \"TryGetById can only be used on the global object\");\n /* Slow path. */\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByIdTransient_RJS(\n runtime, Handle<>(&O2REG(GetById)), ID(idVal)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n O1REG(GetById) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(TryPutByIdLong) {\n tryProp = true;\n idVal = ip->iTryPutByIdLong.op4;\n nextIP = NEXTINST(TryPutByIdLong);\n goto putById;\n }\n CASE(PutByIdLong) {\n tryProp = false;\n idVal = ip->iPutByIdLong.op4;\n nextIP = NEXTINST(PutByIdLong);\n goto putById;\n }\n CASE(TryPutById) {\n tryProp = true;\n idVal = ip->iTryPutById.op4;\n nextIP = NEXTINST(TryPutById);\n goto putById;\n }\n CASE(PutById) {\n tryProp = false;\n idVal = ip->iPutById.op4;\n nextIP = NEXTINST(PutById);\n }\n putById : {\n ++NumPutById;\n if (LLVM_LIKELY(O1REG(PutById).isObject())) {\n auto *obj = vmcast(O1REG(PutById));\n auto cacheIdx = ip->iPutById.op3;\n auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumPutByIdCacheHits;\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, cacheEntry->slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue hasOwnProp,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&\n !desc.flags.accessor && desc.flags.writable &&\n !desc.flags.internalSetter) {\n ++NumPutByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionary()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumPutByIdCacheEvicts;\n#else\n (void)NumPutByIdCacheEvicts;\n#endif\n // Cache the class and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, desc.slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putNamed_RJS(\n Handle::vmcast(&O1REG(PutById)),\n runtime,\n id,\n Handle<>(&O2REG(PutById)),\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist()));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n ++NumPutByIdTransient;\n assert(!tryProp && \"TryPutById can only be used on the global object\");\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByIdTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutById)),\n ID(idVal),\n Handle<>(&O2REG(PutById)),\n strictMode));\n if (retStatus == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetByVal) {\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getComputed_RJS(\n Handle::vmcast(&O2REG(GetByVal)),\n runtime,\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByValTransient_RJS(\n runtime,\n Handle<>(&O2REG(GetByVal)),\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetByVal) = resPH->get();\n ip = NEXTINST(GetByVal);\n DISPATCH;\n }\n\n CASE(PutByVal) {\n if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putComputed_RJS(\n Handle::vmcast(&O1REG(PutByVal)),\n runtime,\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByValTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutByVal)),\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n strictMode));\n if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(PutByVal);\n DISPATCH;\n }\n\n CASE(PutOwnByIndexL) {\n nextIP = NEXTINST(PutOwnByIndexL);\n idVal = ip->iPutOwnByIndexL.op3;\n goto putOwnByIndex;\n }\n CASE(PutOwnByIndex) {\n nextIP = NEXTINST(PutOwnByIndex);\n idVal = ip->iPutOwnByIndex.op3;\n }\n putOwnByIndex : {\n tmpHandle = HermesValue::encodeDoubleValue(idVal);\n CAPTURE_IP(JSObject::defineOwnComputedPrimitive(\n Handle::vmcast(&O1REG(PutOwnByIndex)),\n runtime,\n tmpHandle,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n Handle<>(&O2REG(PutOwnByIndex))));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetPNameList) {\n CAPTURE_IP_ASSIGN(\n auto pRes, handleGetPNameList(runtime, frameRegs, ip));\n if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(GetPNameList);\n DISPATCH;\n }\n\n CASE(GetNextPName) {\n {\n assert(\n vmisa(O2REG(GetNextPName)) &&\n \"GetNextPName's second op must be BigStorage\");\n auto obj = Handle::vmcast(&O3REG(GetNextPName));\n auto arr = Handle::vmcast(&O2REG(GetNextPName));\n uint32_t idx = O4REG(GetNextPName).getNumber();\n uint32_t size = O5REG(GetNextPName).getNumber();\n MutableHandle propObj{runtime};\n // Loop until we find a property which is present.\n while (idx < size) {\n tmpHandle = arr->at(idx);\n ComputedPropertyDescriptor desc;\n CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(\n obj, runtime, tmpHandle, propObj, desc));\n if (LLVM_LIKELY(propObj))\n break;\n ++idx;\n }\n if (idx < size) {\n // We must return the property as a string\n if (tmpHandle->isNumber()) {\n CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));\n assert(\n status == ExecutionStatus::RETURNED &&\n \"toString on number cannot fail\");\n tmpHandle = status->getHermesValue();\n }\n O1REG(GetNextPName) = tmpHandle.get();\n O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);\n } else {\n O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(GetNextPName);\n DISPATCH;\n }\n\n CASE(ToNumber) {\n if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {\n O1REG(ToNumber) = O2REG(ToNumber);\n ip = NEXTINST(ToNumber);\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToNumber) = res.getValue();\n ip = NEXTINST(ToNumber);\n }\n DISPATCH;\n }\n\n CASE(ToInt32) {\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToInt32) = res.getValue();\n ip = NEXTINST(ToInt32);\n DISPATCH;\n }\n\n CASE(AddEmptyString) {\n if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {\n O1REG(AddEmptyString) = O2REG(AddEmptyString);\n ip = NEXTINST(AddEmptyString);\n } else {\n CAPTURE_IP_ASSIGN(\n res,\n toPrimitive_RJS(\n runtime,\n Handle<>(&O2REG(AddEmptyString)),\n PreferredType::NONE));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));\n if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(AddEmptyString) = strRes->getHermesValue();\n ip = NEXTINST(AddEmptyString);\n }\n DISPATCH;\n }\n\n CASE(Jmp) {\n ip = IPADD(ip->iJmp.op1);\n DISPATCH;\n }\n CASE(JmpLong) {\n ip = IPADD(ip->iJmpLong.op1);\n DISPATCH;\n }\n CASE(JmpTrue) {\n if (toBoolean(O2REG(JmpTrue)))\n ip = IPADD(ip->iJmpTrue.op1);\n else\n ip = NEXTINST(JmpTrue);\n DISPATCH;\n }\n CASE(JmpTrueLong) {\n if (toBoolean(O2REG(JmpTrueLong)))\n ip = IPADD(ip->iJmpTrueLong.op1);\n else\n ip = NEXTINST(JmpTrueLong);\n DISPATCH;\n }\n CASE(JmpFalse) {\n if (!toBoolean(O2REG(JmpFalse)))\n ip = IPADD(ip->iJmpFalse.op1);\n else\n ip = NEXTINST(JmpFalse);\n DISPATCH;\n }\n CASE(JmpFalseLong) {\n if (!toBoolean(O2REG(JmpFalseLong)))\n ip = IPADD(ip->iJmpFalseLong.op1);\n else\n ip = NEXTINST(JmpFalseLong);\n DISPATCH;\n }\n CASE(JmpUndefined) {\n if (O2REG(JmpUndefined).isUndefined())\n ip = IPADD(ip->iJmpUndefined.op1);\n else\n ip = NEXTINST(JmpUndefined);\n DISPATCH;\n }\n CASE(JmpUndefinedLong) {\n if (O2REG(JmpUndefinedLong).isUndefined())\n ip = IPADD(ip->iJmpUndefinedLong.op1);\n else\n ip = NEXTINST(JmpUndefinedLong);\n DISPATCH;\n }\n CASE(Add) {\n if (LLVM_LIKELY(\n O2REG(Add).isNumber() &&\n O3REG(Add).isNumber())) { /* Fast-path. */\n CASE(AddN) {\n O1REG(Add) = HermesValue::encodeDoubleValue(\n O2REG(Add).getNumber() + O3REG(Add).getNumber());\n ip = NEXTINST(Add);\n DISPATCH;\n }\n }\n CAPTURE_IP_ASSIGN(\n res,\n addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Add) = res.getValue();\n ip = NEXTINST(Add);\n DISPATCH;\n }\n\n CASE(BitNot) {\n if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~hermes::truncateToInt32(O2REG(BitNot).getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~static_cast(res->getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n\n CASE(GetArgumentsLength) {\n // If the arguments object hasn't been created yet.\n if (O2REG(GetArgumentsLength).isUndefined()) {\n O1REG(GetArgumentsLength) =\n HermesValue::encodeNumberValue(FRAME.getArgCount());\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n // The arguments object has been created, so this is a regular property\n // get.\n assert(\n O2REG(GetArgumentsLength).isObject() &&\n \"arguments lazy register is not an object\");\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetArgumentsLength)),\n runtime,\n Predefined::getSymbolID(Predefined::length)));\n if (resPH == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsLength) = resPH->get();\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n\n CASE(GetArgumentsPropByVal) {\n // If the arguments object hasn't been created yet and we have a\n // valid integer index, we use the fast path.\n if (O3REG(GetArgumentsPropByVal).isUndefined()) {\n // If this is an integer index.\n if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {\n // Is this an existing argument?\n if (*index < FRAME.getArgCount()) {\n O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n }\n }\n // Slow path.\n CAPTURE_IP_ASSIGN(\n auto res,\n getArgumentsPropByValSlowPath_RJS(\n runtime,\n &O3REG(GetArgumentsPropByVal),\n &O2REG(GetArgumentsPropByVal),\n FRAME.getCalleeClosureHandleUnsafe(),\n strictMode));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsPropByVal) = res->getHermesValue();\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n\n CASE(ReifyArguments) {\n // If the arguments object was already created, do nothing.\n if (!O1REG(ReifyArguments).isUndefined()) {\n assert(\n O1REG(ReifyArguments).isObject() &&\n \"arguments lazy register is not an object\");\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(\n resArgs,\n reifyArgumentsSlowPath(\n runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));\n if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(ReifyArguments) = resArgs->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n\n CASE(NewObject) {\n // Create a new object using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n O1REG(NewObject), JSObject::create(runtime).getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObject);\n DISPATCH;\n }\n CASE(NewObjectWithParent) {\n CAPTURE_IP_ASSIGN(\n O1REG(NewObjectWithParent),\n JSObject::create(\n runtime,\n O2REG(NewObjectWithParent).isObject()\n ? Handle::vmcast(&O2REG(NewObjectWithParent))\n : O2REG(NewObjectWithParent).isNull()\n ? Runtime::makeNullHandle()\n : Handle::vmcast(&runtime->objectPrototype))\n .getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObjectWithParent);\n DISPATCH;\n }\n\n CASE(NewObjectWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBuffer.op3,\n ip->iNewObjectWithBuffer.op4,\n ip->iNewObjectWithBuffer.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBuffer);\n DISPATCH;\n }\n\n CASE(NewObjectWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBufferLong.op3,\n ip->iNewObjectWithBufferLong.op4,\n ip->iNewObjectWithBufferLong.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBufferLong);\n DISPATCH;\n }\n\n CASE(NewArray) {\n // Create a new array using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n auto createRes,\n JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));\n if (createRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(NewArray) = createRes->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewArray);\n DISPATCH;\n }\n\n CASE(NewArrayWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBuffer.op2,\n ip->iNewArrayWithBuffer.op3,\n ip->iNewArrayWithBuffer.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBuffer);\n DISPATCH;\n }\n\n CASE(NewArrayWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBufferLong.op2,\n ip->iNewArrayWithBufferLong.op3,\n ip->iNewArrayWithBufferLong.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBufferLong);\n DISPATCH;\n }\n\n CASE(CreateThis) {\n // Registers: output, prototype, closure.\n if (LLVM_UNLIKELY(!vmisa(O3REG(CreateThis)))) {\n CAPTURE_IP(runtime->raiseTypeError(\"constructor is not callable\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto res,\n Callable::newObject(\n Handle::vmcast(&O3REG(CreateThis)),\n runtime,\n Handle::vmcast(\n O2REG(CreateThis).isObject() ? &O2REG(CreateThis)\n : &runtime->objectPrototype)));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(CreateThis) = res->getHermesValue();\n ip = NEXTINST(CreateThis);\n DISPATCH;\n }\n\n CASE(SelectObject) {\n // Registers: output, thisObject, constructorReturnValue.\n O1REG(SelectObject) = O3REG(SelectObject).isObject()\n ? O3REG(SelectObject)\n : O2REG(SelectObject);\n ip = NEXTINST(SelectObject);\n DISPATCH;\n }\n\n CASE(Eq)\n CASE(Neq) {\n CAPTURE_IP_ASSIGN(\n res,\n abstractEqualityTest_RJS(\n runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Eq) = ip->opCode == OpCode::Eq\n ? res.getValue()\n : HermesValue::encodeBoolValue(!res->getBool());\n ip = NEXTINST(Eq);\n DISPATCH;\n }\n CASE(StrictEq) {\n O1REG(StrictEq) = HermesValue::encodeBoolValue(\n strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));\n ip = NEXTINST(StrictEq);\n DISPATCH;\n }\n CASE(StrictNeq) {\n O1REG(StrictNeq) = HermesValue::encodeBoolValue(\n !strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));\n ip = NEXTINST(StrictNeq);\n DISPATCH;\n }\n CASE(Not) {\n O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));\n ip = NEXTINST(Not);\n DISPATCH;\n }\n CASE(Negate) {\n if (LLVM_LIKELY(O2REG(Negate).isNumber())) {\n O1REG(Negate) =\n HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());\n }\n ip = NEXTINST(Negate);\n DISPATCH;\n }\n CASE(TypeOf) {\n CAPTURE_IP_ASSIGN(\n O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));\n ip = NEXTINST(TypeOf);\n DISPATCH;\n }\n CASE(Mod) {\n // We use fmod here for simplicity. Theoretically fmod behaves slightly\n // differently than the ECMAScript Spec. fmod applies round-towards-zero\n // for the remainder when it's not representable by a double; while the\n // spec requires round-to-nearest. As an example, 5 % 0.7 will give\n // 0.10000000000000031 using fmod, but using the rounding style\n // described\n // by the spec, the output should really be 0.10000000000000053.\n // Such difference can be ignored in practice.\n if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {\n /* Fast-path. */\n O1REG(Mod) = HermesValue::encodeDoubleValue(\n std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n double left = res->getDouble();\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n O1REG(Mod) =\n HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CASE(InstanceOf) {\n CAPTURE_IP_ASSIGN(\n auto result,\n instanceOfOperator_RJS(\n runtime,\n Handle<>(&O2REG(InstanceOf)),\n Handle<>(&O3REG(InstanceOf))));\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(InstanceOf);\n DISPATCH;\n }\n CASE(IsIn) {\n {\n if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {\n CAPTURE_IP(runtime->raiseTypeError(\n \"right operand of 'in' is not an object\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto cr,\n JSObject::hasComputed(\n Handle::vmcast(&O3REG(IsIn)),\n runtime,\n Handle<>(&O2REG(IsIn))));\n if (cr == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(IsIn);\n DISPATCH;\n }\n\n CASE(PutNewOwnByIdShort) {\n nextIP = NEXTINST(PutNewOwnByIdShort);\n idVal = ip->iPutNewOwnByIdShort.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEByIdLong)\n CASE(PutNewOwnByIdLong) {\n nextIP = NEXTINST(PutNewOwnByIdLong);\n idVal = ip->iPutNewOwnByIdLong.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEById)\n CASE(PutNewOwnById) {\n nextIP = NEXTINST(PutNewOwnById);\n idVal = ip->iPutNewOwnById.op3;\n }\n putOwnById : {\n assert(\n O1REG(PutNewOwnById).isObject() &&\n \"Object argument of PutNewOwnById must be an object\");\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineNewOwnProperty(\n Handle::vmcast(&O1REG(PutNewOwnById)),\n runtime,\n ID(idVal),\n ip->opCode <= OpCode::PutNewOwnByIdLong\n ? PropertyFlags::defaultNewNamedPropertyFlags()\n : PropertyFlags::nonEnumerablePropertyFlags(),\n Handle<>(&O2REG(PutNewOwnById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByIdLong) {\n idVal = ip->iDelByIdLong.op3;\n nextIP = NEXTINST(DelByIdLong);\n goto DelById;\n }\n\n CASE(DelById) {\n idVal = ip->iDelById.op3;\n nextIP = NEXTINST(DelById);\n }\n DelById : {\n if (LLVM_LIKELY(O2REG(DelById).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(&O2REG(DelById)),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n // If an exception is thrown, likely we are trying to convert\n // undefined/null to an object. Passing over the name of the property\n // so that we could emit more meaningful error messages.\n CAPTURE_IP(amendPropAccessErrorMsgWithPropName(\n runtime, Handle<>(&O2REG(DelById)), \"delete\", ID(idVal)));\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(tmpHandle),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n tmpHandle.clear();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByVal) {\n if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(&O2REG(DelByVal)),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(tmpHandle),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(DelByVal);\n DISPATCH;\n }\n CASE(CreateRegExp) {\n {\n // Create the RegExp object.\n CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));\n // Initialize the regexp.\n CAPTURE_IP_ASSIGN(\n auto pattern,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op2)));\n CAPTURE_IP_ASSIGN(\n auto flags,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op3)));\n CAPTURE_IP_ASSIGN(\n auto bytecode,\n curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(\n ip->iCreateRegExp.op4));\n CAPTURE_IP_ASSIGN(\n auto initRes,\n JSRegExp::initialize(re, runtime, pattern, flags, bytecode));\n if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n // Done, return the new object.\n O1REG(CreateRegExp) = re.getHermesValue();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateRegExp);\n DISPATCH;\n }\n\n CASE(SwitchImm) {\n if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {\n double numVal = O1REG(SwitchImm).getNumber();\n uint32_t uintVal = (uint32_t)numVal;\n if (LLVM_LIKELY(numVal == uintVal) && // Only integers.\n LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.\n LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.\n {\n // Calculate the offset into the bytecode where the jump table for\n // this SwitchImm starts.\n const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(\n (const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));\n\n // Read the offset from the table.\n // Must be signed to account for backwards branching.\n const int32_t *loc =\n (const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;\n\n ip = IPADD(*loc);\n DISPATCH;\n }\n }\n // Wrong type or out of range, jump to default.\n ip = IPADD(ip->iSwitchImm.op3);\n DISPATCH;\n }\n LOAD_CONST(\n LoadConstUInt8,\n HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));\n LOAD_CONST(\n LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));\n LOAD_CONST(\n LoadConstDouble,\n HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));\n LOAD_CONST_CAPTURE_IP(\n LoadConstString,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstString.op2)));\n LOAD_CONST_CAPTURE_IP(\n LoadConstStringLongIndex,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstStringLongIndex.op2)));\n LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());\n LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());\n LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));\n LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));\n LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));\n BINOP(Sub, doSub);\n BINOP(Mul, doMult);\n BINOP(Div, doDiv);\n BITWISEBINOP(BitAnd, &);\n BITWISEBINOP(BitOr, |);\n BITWISEBINOP(BitXor, ^);\n // For LShift, we need to use toUInt32 first because lshift on negative\n // numbers is undefined behavior in theory.\n SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);\n SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);\n SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);\n CONDOP(Less, <, lessOp_RJS);\n CONDOP(LessEq, <=, lessEqualOp_RJS);\n CONDOP(Greater, >, greaterOp_RJS);\n CONDOP(GreaterEq, >=, greaterEqualOp_RJS);\n JCOND(Less, <, lessOp_RJS);\n JCOND(LessEqual, <=, lessEqualOp_RJS);\n JCOND(Greater, >, greaterOp_RJS);\n JCOND(GreaterEqual, >=, greaterEqualOp_RJS);\n\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual,\n Long,\n IPADD(ip->iJStrictEqualLong.op1),\n NEXTINST(JStrictEqualLong));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n ,\n NEXTINST(JStrictNotEqual),\n IPADD(ip->iJStrictNotEqual.op1));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n Long,\n NEXTINST(JStrictNotEqualLong),\n IPADD(ip->iJStrictNotEqualLong.op1));\n\n JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));\n JCOND_EQ_IMPL(\n JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));\n JCOND_EQ_IMPL(\n JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));\n JCOND_EQ_IMPL(\n JNotEqual,\n Long,\n NEXTINST(JNotEqualLong),\n IPADD(ip->iJNotEqualLong.op1));\n\n CASE_OUTOFLINE(PutOwnByVal);\n CASE_OUTOFLINE(PutOwnGetterSetterByVal);\n CASE_OUTOFLINE(DirectEval);\n\n CASE_OUTOFLINE(IteratorBegin);\n CASE_OUTOFLINE(IteratorNext);\n CASE(IteratorClose) {\n if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {\n // The iterator must be closed if it's still an object.\n // That means it was never an index and is not done iterating (a state\n // which is indicated by `undefined`).\n CAPTURE_IP_ASSIGN(\n auto res,\n iteratorClose(\n runtime,\n Handle::vmcast(&O1REG(IteratorClose)),\n Runtime::getEmptyValue()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n if (ip->iIteratorClose.op2 &&\n !isUncatchableError(runtime->thrownValue_)) {\n // Ignore inner exception.\n runtime->clearThrownValue();\n } else {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n ip = NEXTINST(IteratorClose);\n DISPATCH;\n }\n\n CASE(_last) {\n llvm_unreachable(\"Invalid opcode _last\");\n }\n }\n\n llvm_unreachable(\"unreachable\");\n\n // We arrive here if we couldn't allocate the registers for the current frame.\n stackOverflow:\n CAPTURE_IP(runtime->raiseStackOverflow(\n Runtime::StackOverflowKind::JSRegisterStack));\n\n // We arrive here when we raised an exception in a callee, but we don't want\n // the callee to be able to handle it.\n handleExceptionInParent:\n // Restore the caller code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop to the previous frame where technically the error happened.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n // If we are coming from native code, return.\n if (!curCodeBlock)\n return ExecutionStatus::EXCEPTION;\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n // Handle the exception.\n exception:\n UPDATE_OPCODE_TIME_SPENT;\n assert(\n !runtime->thrownValue_.isEmpty() &&\n \"thrownValue unavailable at exception\");\n\n bool catchable = true;\n // If this is an Error object that was thrown internally, it didn't have\n // access to the current codeblock and IP, so collect the stack trace here.\n if (auto *jsError = dyn_vmcast(runtime->thrownValue_)) {\n catchable = jsError->catchable();\n if (!jsError->getStackTrace()) {\n // Temporarily clear the thrown value for following operations.\n CAPTURE_IP_ASSIGN(\n auto errorHandle,\n runtime->makeHandle(vmcast(runtime->thrownValue_)));\n runtime->clearThrownValue();\n\n CAPTURE_IP(JSError::recordStackTrace(\n errorHandle, runtime, false, curCodeBlock, ip));\n\n // Restore the thrown value.\n runtime->setThrownValue(errorHandle.getHermesValue());\n }\n }\n\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n\n#ifdef HERMES_ENABLE_DEBUGGER\n if (SingleStep) {\n // If we're single stepping, don't bother with any more checks,\n // and simply signal that we should continue execution with an exception.\n state.codeBlock = curCodeBlock;\n state.offset = CUROFFSET;\n return ExecutionStatus::EXCEPTION;\n }\n\n using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;\n auto mode = runtime->debugger_.getPauseOnThrowMode();\n if (mode != PauseOnThrowMode::None) {\n if (!runtime->debugger_.isDebugging()) {\n // Determine whether the PauseOnThrowMode requires us to stop here.\n bool caught =\n runtime->debugger_\n .findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))\n .hasValue();\n bool shouldStop = mode == PauseOnThrowMode::All ||\n (mode == PauseOnThrowMode::Uncaught && !caught);\n if (shouldStop) {\n // When runDebugger is invoked after an exception,\n // stepping should never happen internally.\n // Any step is a step to an exception handler, which we do\n // directly here in the interpreter.\n // Thus, the result state should be the same as the input state.\n InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus resultStatus,\n runtime->debugger_.runDebugger(\n Debugger::RunReason::Exception, tmpState));\n (void)resultStatus;\n assert(\n tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&\n \"not allowed to step internally in a pauseOnThrow\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n }\n }\n#endif\n\n int32_t handlerOffset = 0;\n\n // If the exception is not catchable, skip found catch blocks.\n while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==\n -1) ||\n !catchable) {\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Restore the code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop a stack frame.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit with exception: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(\n dbgs()\n << \"function exit with exception: returning to native code\\n\");\n return ExecutionStatus::EXCEPTION;\n }\n\n assert(\n isCallType(ip->opCode) &&\n \"return address is not Call-type instruction\");\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n }\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n ip = IPADD(handlerOffset - CUROFFSET);\n }\n}", "func_hash": 122596422422424342473748560832019724184, "file_name": "Interpreter.cpp", "file_hash": 585902433762903371640607980760456873, "cwe": ["CWE-703"], "cve": "CVE-2020-1914", "cve_desc": "A logic vulnerability when handling the SaveGeneratorLong instruction in Facebook Hermes prior to commit b2021df620824627f5a8c96615edbd1eb7fdddfc allows attackers to potentially read out of bounds or theoretically execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1914"} {"idx": 295511, "project": "hermes", "commit_id": "b2021df620824627f5a8c96615edbd1eb7fdddfc", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/b2021df620824627f5a8c96615edbd1eb7fdddfc", "commit_message": "Fix CVE-2020-1914 by using NEXTINST for SaveGeneratorLong\n\nSummary:\nIf `SaveGeneratorLong` was emitted, it would accidentally jump to the\nwrong next instruction, based on how long SaveGenerator was.\n\nMake a callout function to handle the common case, and handle the dispatch\nwithin each case of the interpreter loop.\n\nFixes CVE-2020-1914\n\nReviewed By: neildhar\n\nDifferential Revision: D24024242\n\nfbshipit-source-id: 3bcb88daa740f0d50e91771a49eb212551ce8bd8", "target": 0, "func": "CallResult Interpreter::interpretFunction(\n Runtime *runtime,\n InterpreterState &state) {\n // The interepter is re-entrant and also saves/restores its IP via the runtime\n // whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure\n // to preserve the IP across calls to interpeterFunction() disrupt interpreter\n // calls further up the C++ callstack. The RAII utility class below makes sure\n // we always do this correctly.\n //\n // TODO: The IPs stored in the C++ callstack via this holder will generally be\n // the same as in the JS stack frames via the Saved IP field. We can probably\n // get rid of one of these redundant stores. Doing this isn't completely\n // trivial as there are currently cases where we re-enter the interpreter\n // without calling Runtime::saveCallerIPInStackFrame(), and there are features\n // (I think mostly the debugger + stack traces) which implicitly rely on\n // this behavior. At least their tests break if this behavior is not\n // preserved.\n struct IPSaver {\n IPSaver(Runtime *runtime)\n : ip_(runtime->getCurrentIP()), runtime_(runtime) {}\n\n ~IPSaver() {\n runtime_->setCurrentIP(ip_);\n }\n\n private:\n const Inst *ip_;\n Runtime *runtime_;\n };\n IPSaver ipSaver(runtime);\n\n#ifndef HERMES_ENABLE_DEBUGGER\n static_assert(!SingleStep, \"can't use single-step mode without the debugger\");\n#endif\n // Make sure that the cache can use an optimization by avoiding a branch to\n // access the property storage.\n static_assert(\n HiddenClass::kDictionaryThreshold <=\n SegmentedArray::kValueToSegmentThreshold,\n \"Cannot avoid branches in cache check if the dictionary \"\n \"crossover point is larger than the inline storage\");\n\n CodeBlock *curCodeBlock = state.codeBlock;\n const Inst *ip = nullptr;\n // Holds runtime->currentFrame_.ptr()-1 which is the first local\n // register. This eliminates the indirect load from Runtime and the -1 offset.\n PinnedHermesValue *frameRegs;\n // Strictness of current function.\n bool strictMode;\n // Default flags when accessing properties.\n PropOpFlags defaultPropOpFlags;\n\n// These CAPTURE_IP* macros should wrap around any major calls out of the\n// interpeter loop. They stash and retrieve the IP via the current Runtime\n// allowing the IP to be externally observed and even altered to change the flow\n// of execution. Explicitly saving AND restoring the IP from the Runtime in this\n// way means the C++ compiler will keep IP in a register within the rest of the\n// interpeter loop.\n//\n// When assertions are enabled we take the extra step of \"invalidating\" the IP\n// between captures so we can detect if it's erroneously accessed.\n//\n// In some cases we explicitly don't want to invalidate the IP and instead want\n// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up\n// when we're performing a call operation which may re-enter the interpeter\n// loop, and so need the IP available for the saveCallerIPInStackFrame() call\n// when we next enter.\n#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP();\n\n#ifdef NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)\n\n#else // !NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#endif // NDEBUG\n\n/// \\def DONT_CAPTURE_IP(expr)\n/// \\param expr A call expression to a function external to the interpreter. The\n/// expression should not make any allocations and the IP should be set\n/// immediately following this macro.\n#define DONT_CAPTURE_IP(expr) \\\n do { \\\n NoAllocScope noAlloc(runtime); \\\n (void)expr; \\\n } while (false)\n\n LLVM_DEBUG(dbgs() << \"interpretFunction() called\\n\");\n\n ScopedNativeDepthTracker depthTracker{runtime};\n if (LLVM_UNLIKELY(depthTracker.overflowed())) {\n return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);\n }\n\n if (!SingleStep) {\n if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {\n return (*jitPtr)(runtime);\n }\n }\n\n GCScope gcScope(runtime);\n // Avoid allocating a handle dynamically by reusing this one.\n MutableHandle<> tmpHandle(runtime);\n CallResult res{ExecutionStatus::EXCEPTION};\n CallResult> resPH{ExecutionStatus::EXCEPTION};\n CallResult> resArgs{ExecutionStatus::EXCEPTION};\n CallResult boolRes{ExecutionStatus::EXCEPTION};\n\n // Mark the gcScope so we can clear all allocated handles.\n // Remember how many handles the scope has so we can clear them in the loop.\n static constexpr unsigned KEEP_HANDLES = 1;\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"scope has unexpected number of handles\");\n\n INIT_OPCODE_PROFILER;\n\n#if !defined(HERMESVM_PROFILER_EXTERN)\ntailCall:\n#endif\n PROFILER_ENTER_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_DEBUGGER\n runtime->getDebugger().willEnterCodeBlock(curCodeBlock);\n#endif\n\n runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);\n\n // Update function executionCount_ count\n curCodeBlock->incrementExecutionCount();\n\n if (!SingleStep) {\n auto newFrame = runtime->setCurrentFrameToTopOfStack();\n runtime->saveCallerIPInStackFrame();\n#ifndef NDEBUG\n runtime->invalidateCurrentIP();\n#endif\n\n // Point frameRegs to the first register in the new frame. Note that at this\n // moment technically it points above the top of the stack, but we are never\n // going to access it.\n frameRegs = &newFrame.getFirstLocalRef();\n\n#ifndef NDEBUG\n LLVM_DEBUG(\n dbgs() << \"function entry: stackLevel=\" << runtime->getStackLevel()\n << \", argCount=\" << runtime->getCurrentFrame().getArgCount()\n << \", frameSize=\" << curCodeBlock->getFrameSize() << \"\\n\");\n\n LLVM_DEBUG(\n dbgs() << \" callee \"\n << DumpHermesValue(\n runtime->getCurrentFrame().getCalleeClosureOrCBRef())\n << \"\\n\");\n LLVM_DEBUG(\n dbgs() << \" this \"\n << DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())\n << \"\\n\");\n for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {\n LLVM_DEBUG(\n dbgs() << \" \" << llvh::format_decimal(i, 4) << \" \"\n << DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))\n << \"\\n\");\n }\n#endif\n\n // Allocate the registers for the new frame.\n if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(\n curCodeBlock->getFrameSize() +\n StackFrameLayout::CalleeExtraRegistersAtStart,\n HermesValue::encodeUndefinedValue())))\n goto stackOverflow;\n\n ip = (Inst const *)curCodeBlock->begin();\n\n // Check for invalid invocation.\n if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(\n newFrame.isConstructorCall()))) {\n if (!newFrame.isConstructorCall()) {\n CAPTURE_IP(\n runtime->raiseTypeError(\"Class constructor invoked without new\"));\n } else {\n CAPTURE_IP(runtime->raiseTypeError(\"Function is not a constructor\"));\n }\n goto handleExceptionInParent;\n }\n } else {\n // Point frameRegs to the first register in the frame.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n ip = (Inst const *)(curCodeBlock->begin() + state.offset);\n }\n\n assert((const uint8_t *)ip < curCodeBlock->end() && \"CodeBlock is empty\");\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n#define BEFORE_OP_CODE \\\n { \\\n UPDATE_OPCODE_TIME_SPENT; \\\n HERMES_SLOW_ASSERT( \\\n curCodeBlock->contains(ip) && \"curCodeBlock must contain ip\"); \\\n HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \\\n HERMES_SLOW_ASSERT( \\\n gcScope.getHandleCountDbg() == KEEP_HANDLES && \\\n \"unaccounted handles were created\"); \\\n HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && \"tmpHandle not cleared\"); \\\n RECORD_OPCODE_START_TIME; \\\n INC_OPCODE_COUNT; \\\n }\n\n#ifdef HERMESVM_INDIRECT_THREADING\n static void *opcodeDispatch[] = {\n#define DEFINE_OPCODE(name) &&case_##name,\n#include \"hermes/BCGen/HBC/BytecodeList.def\"\n &&case__last};\n\n#define CASE(name) case_##name:\n#define DISPATCH \\\n BEFORE_OP_CODE; \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n goto *opcodeDispatch[(unsigned)ip->opCode]\n\n#else // HERMESVM_INDIRECT_THREADING\n\n#define CASE(name) case OpCode::name:\n#define DISPATCH \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n continue\n\n#endif // HERMESVM_INDIRECT_THREADING\n\n#define RUN_DEBUGGER_ASYNC_BREAK(flags) \\\n do { \\\n CAPTURE_IP_ASSIGN( \\\n auto dRes, \\\n runDebuggerUpdatingState( \\\n (uint8_t)(flags) & \\\n (uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \\\n ? Debugger::RunReason::AsyncBreakExplicit \\\n : Debugger::RunReason::AsyncBreakImplicit, \\\n runtime, \\\n curCodeBlock, \\\n ip, \\\n frameRegs)); \\\n if (dRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n } while (0)\n\n for (;;) {\n BEFORE_OP_CODE;\n\n#ifdef HERMESVM_INDIRECT_THREADING\n goto *opcodeDispatch[(unsigned)ip->opCode];\n#else\n switch (ip->opCode)\n#endif\n {\n const Inst *nextIP;\n uint32_t idVal;\n bool tryProp;\n uint32_t callArgCount;\n // This is HermesValue::getRaw(), since HermesValue cannot be assigned\n // to. It is meant to be used only for very short durations, in the\n // dispatch of call instructions, when there is definitely no possibility\n // of a GC.\n HermesValue::RawType callNewTarget;\n\n/// Handle an opcode \\p name with an out-of-line implementation in a function\n/// ExecutionStatus caseName(\n/// Runtime *,\n/// PinnedHermesValue *frameRegs,\n/// Inst *ip)\n#define CASE_OUTOFLINE(name) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \\\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary arithmetic instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"n\" appended to the name.\n/// \\param oper the C++ operator to use to actually perform the arithmetic\n/// operation.\n#define BINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N) { \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n double left = res->getDouble(); \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n O1REG(name) = \\\n HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a shift instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the shift\n/// operation.\n/// \\param lConv the conversion function for the LHS of the expression.\n/// \\param lType the type of the LHS operand.\n/// \\param returnType the type of the return value.\n#define SHIFTOP(name, oper, lConv, lType, returnType) \\\n CASE(name) { \\\n if (LLVM_LIKELY( \\\n O2REG(name).isNumber() && \\\n O3REG(name).isNumber())) { /* Fast-path. */ \\\n auto lnum = static_cast( \\\n hermes::truncateToInt32(O2REG(name).getNumber())); \\\n auto rnum = static_cast( \\\n hermes::truncateToInt32(O3REG(name).getNumber())) & \\\n 0x1f; \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto lnum = static_cast(res->getNumber()); \\\n CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto rnum = static_cast(res->getNumber()) & 0x1f; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary bitwise instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the bitwise\n/// operation.\n#define BITWISEBINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n hermes::truncateToInt32(O2REG(name).getNumber()) \\\n oper hermes::truncateToInt32(O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n int32_t left = res->getNumberAs(); \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n O1REG(name) = \\\n HermesValue::encodeNumberValue(left oper res->getNumberAs()); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison instruction.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n#define CONDOP(name, oper, operFuncName) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeBoolValue( \\\n O2REG(name).getNumber() oper O3REG(name).getNumber()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison conditional jump with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"N\" appended to the name.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (LLVM_LIKELY( \\\n O2REG(name##suffix).isNumber() && \\\n O3REG(name##suffix).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N##suffix) { \\\n if (O2REG(name##N##suffix) \\\n .getNumber() oper O3REG(name##N##suffix) \\\n .getNumber()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (boolRes.getValue()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement a strict equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement an equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n CAPTURE_IP_ASSIGN( \\\n res, \\\n abstractEqualityTest_RJS( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (res->getBool()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement the long and short forms of a conditional jump, and its negation.\n#define JCOND(name, oper, operFuncName) \\\n JCOND_IMPL( \\\n J##name, \\\n , \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name.op1), \\\n NEXTINST(J##name)); \\\n JCOND_IMPL( \\\n J##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name##Long.op1), \\\n NEXTINST(J##name##Long)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n , \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name), \\\n IPADD(ip->iJNot##name.op1)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name##Long), \\\n IPADD(ip->iJNot##name##Long.op1));\n\n/// Load a constant.\n/// \\param value is the value to store in the output register.\n#define LOAD_CONST(name, value) \\\n CASE(name) { \\\n O1REG(name) = value; \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n#define LOAD_CONST_CAPTURE_IP(name, value) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(O1REG(name), value); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n CASE(Mov) {\n O1REG(Mov) = O2REG(Mov);\n ip = NEXTINST(Mov);\n DISPATCH;\n }\n\n CASE(MovLong) {\n O1REG(MovLong) = O2REG(MovLong);\n ip = NEXTINST(MovLong);\n DISPATCH;\n }\n\n CASE(LoadParam) {\n if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n O1REG(LoadParam) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n\n CASE(LoadParamLong) {\n if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParamLong) =\n FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n\n CASE(CoerceThisNS) {\n if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {\n O1REG(CoerceThisNS) = O2REG(CoerceThisNS);\n } else if (\n O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {\n O1REG(CoerceThisNS) = runtime->global_;\n } else {\n tmpHandle = O2REG(CoerceThisNS);\n nextIP = NEXTINST(CoerceThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(CoerceThisNS);\n DISPATCH;\n }\n CASE(LoadThisNS) {\n if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {\n O1REG(LoadThisNS) = FRAME.getThisArgRef();\n } else if (\n FRAME.getThisArgRef().isNull() ||\n FRAME.getThisArgRef().isUndefined()) {\n O1REG(LoadThisNS) = runtime->global_;\n } else {\n tmpHandle = FRAME.getThisArgRef();\n nextIP = NEXTINST(LoadThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(LoadThisNS);\n DISPATCH;\n }\n coerceThisSlowPath : {\n CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CoerceThisNS) = res.getValue();\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ConstructLong) {\n callArgCount = (uint32_t)ip->iConstructLong.op3;\n nextIP = NEXTINST(ConstructLong);\n callNewTarget = O2REG(ConstructLong).getRaw();\n goto doCall;\n }\n CASE(CallLong) {\n callArgCount = (uint32_t)ip->iCallLong.op3;\n nextIP = NEXTINST(CallLong);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n // Note in Call1 through Call4, the first argument is 'this' which has\n // argument index -1.\n // Also note that we are writing to callNewTarget last, to avoid the\n // possibility of it being aliased by the arg writes.\n CASE(Call1) {\n callArgCount = 1;\n nextIP = NEXTINST(Call1);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call1);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call2) {\n callArgCount = 2;\n nextIP = NEXTINST(Call2);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call2);\n fr.getArgRefUnsafe(0) = O4REG(Call2);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call3) {\n callArgCount = 3;\n nextIP = NEXTINST(Call3);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call3);\n fr.getArgRefUnsafe(0) = O4REG(Call3);\n fr.getArgRefUnsafe(1) = O5REG(Call3);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call4) {\n callArgCount = 4;\n nextIP = NEXTINST(Call4);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call4);\n fr.getArgRefUnsafe(0) = O4REG(Call4);\n fr.getArgRefUnsafe(1) = O5REG(Call4);\n fr.getArgRefUnsafe(2) = O6REG(Call4);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Construct) {\n callArgCount = (uint32_t)ip->iConstruct.op3;\n nextIP = NEXTINST(Construct);\n callNewTarget = O2REG(Construct).getRaw();\n goto doCall;\n }\n CASE(Call) {\n callArgCount = (uint32_t)ip->iCall.op3;\n nextIP = NEXTINST(Call);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n // Fall through.\n }\n\n doCall : {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n // Subtract 1 from callArgCount as 'this' is considered an argument in the\n // instruction, but not in the frame.\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n callArgCount - 1,\n O2REG(Call),\n HermesValue::fromRaw(callNewTarget)));\n (void)newFrame;\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n if (auto *func = dyn_vmcast(O2REG(Call))) {\n assert(!SingleStep && \"can't single-step a call\");\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->pushCallStack(curCodeBlock, ip);\n#endif\n\n CodeBlock *calleeBlock = func->getCodeBlock();\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(Call) = *res;\n SLOW_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CallDirect)\n CASE(CallDirectLongIndex) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n CAPTURE_IP_ASSIGN(\n CodeBlock * calleeBlock,\n ip->opCode == OpCode::CallDirect\n ? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirect.op3)\n : curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirectLongIndex.op3));\n\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallDirect.op2 - 1,\n HermesValue::encodeNativePointer(calleeBlock),\n HermesValue::encodeUndefinedValue()));\n (void)newFrame;\n\n LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n assert(!SingleStep && \"can't single-step a call\");\n\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CallDirect) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallDirect) = *res;\n LLVM_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCallDirect.op1\n << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n\n CASE(CallBuiltin) {\n NativeFunction *nf =\n runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);\n\n CAPTURE_IP_ASSIGN(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallBuiltin.op3 - 1,\n nf,\n false));\n // \"thisArg\" is implicitly assumed to \"undefined\".\n newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallBuiltin) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCallBuiltin.op1\n << \"=\" << DumpHermesValue(O1REG(CallBuiltin)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CallBuiltin);\n DISPATCH;\n }\n\n CASE(CompleteGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n innerFn->setState(GeneratorInnerFunction::State::Completed);\n ip = NEXTINST(CompleteGenerator);\n DISPATCH;\n }\n\n CASE(SaveGenerator) {\n DONT_CAPTURE_IP(\n saveGenerator(runtime, frameRegs, IPADD(ip->iSaveGenerator.op1)));\n ip = NEXTINST(SaveGenerator);\n DISPATCH;\n }\n CASE(SaveGeneratorLong) {\n DONT_CAPTURE_IP(saveGenerator(\n runtime, frameRegs, IPADD(ip->iSaveGeneratorLong.op1)));\n ip = NEXTINST(SaveGeneratorLong);\n DISPATCH;\n }\n\n CASE(StartGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n if (innerFn->getState() ==\n GeneratorInnerFunction::State::SuspendedStart) {\n nextIP = NEXTINST(StartGenerator);\n } else {\n nextIP = innerFn->getNextIP();\n innerFn->restoreStack(runtime);\n }\n innerFn->setState(GeneratorInnerFunction::State::Executing);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ResumeGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n O1REG(ResumeGenerator) = innerFn->getResult();\n O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(\n innerFn->getAction() == GeneratorInnerFunction::Action::Return);\n innerFn->clearResult(runtime);\n if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {\n runtime->setThrownValue(O1REG(ResumeGenerator));\n goto exception;\n }\n ip = NEXTINST(ResumeGenerator);\n DISPATCH;\n }\n\n CASE(Ret) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Store the return value.\n res = O1REG(Ret);\n\n ip = FRAME.getSavedIP();\n curCodeBlock = FRAME.getSavedCodeBlock();\n\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(dbgs() << \"function exit: returning to native code\\n\");\n return res;\n }\n\n// Return because of recursive calling structure\n#if defined(HERMESVM_PROFILER_EXTERN)\n return res;\n#endif\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n O1REG(Call) = res.getValue();\n ip = nextInstCall(ip);\n DISPATCH;\n }\n\n CASE(Catch) {\n assert(!runtime->thrownValue_.isEmpty() && \"Invalid thrown value\");\n assert(\n !isUncatchableError(runtime->thrownValue_) &&\n \"Uncatchable thrown value was caught\");\n O1REG(Catch) = runtime->thrownValue_;\n runtime->clearThrownValue();\n#ifdef HERMES_ENABLE_DEBUGGER\n // Signal to the debugger that we're done unwinding an exception,\n // and we can resume normal debugging flow.\n runtime->debugger_.finishedUnwindingException();\n#endif\n ip = NEXTINST(Catch);\n DISPATCH;\n }\n\n CASE(Throw) {\n runtime->thrownValue_ = O1REG(Throw);\n SLOW_DEBUG(\n dbgs() << \"Exception thrown: \"\n << DumpHermesValue(runtime->thrownValue_) << \"\\n\");\n goto exception;\n }\n\n CASE(ThrowIfUndefinedInst) {\n if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {\n SLOW_DEBUG(\n dbgs() << \"Throwing ReferenceError for undefined variable\");\n CAPTURE_IP(runtime->raiseReferenceError(\n \"accessing an uninitialized variable\"));\n goto exception;\n }\n ip = NEXTINST(ThrowIfUndefinedInst);\n DISPATCH;\n }\n\n CASE(Debugger) {\n SLOW_DEBUG(dbgs() << \"debugger statement executed\\n\");\n#ifdef HERMES_ENABLE_DEBUGGER\n {\n if (!runtime->debugger_.isDebugging()) {\n // Only run the debugger if we're not already debugging.\n // Don't want to call it again and mess with its state.\n CAPTURE_IP_ASSIGN(\n auto res,\n runDebuggerUpdatingState(\n Debugger::RunReason::Opcode,\n runtime,\n curCodeBlock,\n ip,\n frameRegs));\n if (res == ExecutionStatus::EXCEPTION) {\n // If one of the internal steps threw,\n // then handle that here by jumping to where we're supposed to go.\n // If we're in mid-step, the breakpoint at the catch point\n // will have been set by the debugger.\n // We don't want to execute this instruction because it's already\n // thrown.\n goto exception;\n }\n }\n auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);\n if (breakpointOpt.hasValue()) {\n // We're on a breakpoint but we're supposed to continue.\n curCodeBlock->uninstallBreakpointAtOffset(\n CUROFFSET, breakpointOpt->opCode);\n if (ip->opCode == OpCode::Debugger) {\n // Breakpointed a debugger instruction, so move past it\n // since we've already called the debugger on this instruction.\n ip = NEXTINST(Debugger);\n } else {\n InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus status, runtime->stepFunction(newState));\n curCodeBlock->installBreakpointAtOffset(CUROFFSET);\n if (status == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n curCodeBlock = newState.codeBlock;\n ip = newState.codeBlock->getOffsetPtr(newState.offset);\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n // Single-stepping should handle call stack management for us.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n }\n } else if (ip->opCode == OpCode::Debugger) {\n // No breakpoint here and we've already run the debugger,\n // just continue on.\n // If the current instruction is no longer a debugger instruction,\n // we're just going to keep executing from the current IP.\n ip = NEXTINST(Debugger);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n DISPATCH;\n#else\n ip = NEXTINST(Debugger);\n DISPATCH;\n#endif\n }\n\n CASE(AsyncBreakCheck) {\n if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {\n#ifdef HERMES_ENABLE_DEBUGGER\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n }\n#endif\n if (runtime->testAndClearTimeoutAsyncBreakRequest()) {\n CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());\n if (nRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n\n ip = NEXTINST(AsyncBreakCheck);\n DISPATCH;\n }\n\n CASE(ProfilePoint) {\n#ifdef HERMESVM_PROFILER_BB\n auto pointIndex = ip->iProfilePoint.op1;\n SLOW_DEBUG(llvh::dbgs() << \"ProfilePoint: \" << pointIndex << \"\\n\");\n CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(\n curCodeBlock, pointIndex));\n#endif\n ip = NEXTINST(ProfilePoint);\n DISPATCH;\n }\n\n CASE(Unreachable) {\n llvm_unreachable(\"Hermes bug: unreachable instruction\");\n }\n\n CASE(CreateClosure) {\n idVal = ip->iCreateClosure.op3;\n nextIP = NEXTINST(CreateClosure);\n goto createClosure;\n }\n CASE(CreateClosureLongIndex) {\n idVal = ip->iCreateClosureLongIndex.op3;\n nextIP = NEXTINST(CreateClosureLongIndex);\n goto createClosure;\n }\n createClosure : {\n auto *runtimeModule = curCodeBlock->getRuntimeModule();\n CAPTURE_IP_ASSIGN(\n O1REG(CreateClosure),\n JSFunction::create(\n runtime,\n runtimeModule->getDomain(runtime),\n Handle::vmcast(&runtime->functionPrototype),\n Handle::vmcast(&O2REG(CreateClosure)),\n runtimeModule->getCodeBlockMayAllocate(idVal))\n .getHermesValue());\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CreateGeneratorClosure) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosure.op3,\n Handle::vmcast(&O2REG(CreateGeneratorClosure))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosure) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosure);\n DISPATCH;\n }\n CASE(CreateGeneratorClosureLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosureLongIndex.op3,\n Handle::vmcast(\n &O2REG(CreateGeneratorClosureLongIndex))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosureLongIndex);\n DISPATCH;\n }\n\n CASE(CreateGenerator) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGenerator.op3,\n Handle::vmcast(&O2REG(CreateGenerator)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGenerator) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGenerator);\n DISPATCH;\n }\n CASE(CreateGeneratorLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGeneratorLongIndex.op3,\n Handle::vmcast(&O2REG(CreateGeneratorLongIndex)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorLongIndex);\n DISPATCH;\n }\n\n CASE(GetEnvironment) {\n // The currently executing function must exist, so get the environment.\n Environment *curEnv =\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);\n for (unsigned level = ip->iGetEnvironment.op2; level; --level) {\n assert(curEnv && \"invalid environment relative level\");\n curEnv = curEnv->getParentEnvironment(runtime);\n }\n O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);\n ip = NEXTINST(GetEnvironment);\n DISPATCH;\n }\n\n CASE(CreateEnvironment) {\n tmpHandle = HermesValue::encodeObjectValue(\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));\n\n CAPTURE_IP_ASSIGN(\n res,\n Environment::create(\n runtime,\n tmpHandle->getPointer() ? Handle::vmcast(tmpHandle)\n : Handle::vmcast_or_null(\n &runtime->nullPointer_),\n curCodeBlock->getEnvironmentSize()));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(CreateEnvironment) = *res;\n#ifdef HERMES_ENABLE_DEBUGGER\n FRAME.getDebugEnvironmentRef() = *res;\n#endif\n tmpHandle = HermesValue::encodeUndefinedValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateEnvironment);\n DISPATCH;\n }\n\n CASE(StoreToEnvironment) {\n vmcast(O1REG(StoreToEnvironment))\n ->slot(ip->iStoreToEnvironment.op2)\n .set(O3REG(StoreToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironment);\n DISPATCH;\n }\n CASE(StoreToEnvironmentL) {\n vmcast(O1REG(StoreToEnvironmentL))\n ->slot(ip->iStoreToEnvironmentL.op2)\n .set(O3REG(StoreToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironmentL);\n DISPATCH;\n }\n\n CASE(StoreNPToEnvironment) {\n vmcast(O1REG(StoreNPToEnvironment))\n ->slot(ip->iStoreNPToEnvironment.op2)\n .setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironment);\n DISPATCH;\n }\n CASE(StoreNPToEnvironmentL) {\n vmcast(O1REG(StoreNPToEnvironmentL))\n ->slot(ip->iStoreNPToEnvironmentL.op2)\n .setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironmentL);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironment) {\n O1REG(LoadFromEnvironment) =\n vmcast(O2REG(LoadFromEnvironment))\n ->slot(ip->iLoadFromEnvironment.op3);\n ip = NEXTINST(LoadFromEnvironment);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironmentL) {\n O1REG(LoadFromEnvironmentL) =\n vmcast(O2REG(LoadFromEnvironmentL))\n ->slot(ip->iLoadFromEnvironmentL.op3);\n ip = NEXTINST(LoadFromEnvironmentL);\n DISPATCH;\n }\n\n CASE(GetGlobalObject) {\n O1REG(GetGlobalObject) = runtime->global_;\n ip = NEXTINST(GetGlobalObject);\n DISPATCH;\n }\n\n CASE(GetNewTarget) {\n O1REG(GetNewTarget) = FRAME.getNewTargetRef();\n ip = NEXTINST(GetNewTarget);\n DISPATCH;\n }\n\n CASE(DeclareGlobalVar) {\n DefinePropertyFlags dpf =\n DefinePropertyFlags::getDefaultNewPropertyFlags();\n dpf.configurable = 0;\n // Do not overwrite existing globals with undefined.\n dpf.setValue = 0;\n\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineOwnProperty(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n dpf,\n Runtime::getUndefinedValue(),\n PropOpFlags().plusThrowOnError()));\n if (res == ExecutionStatus::EXCEPTION) {\n assert(\n !runtime->getGlobal()->isProxyObject() &&\n \"global can't be a proxy object\");\n // If the property already exists, this should be a noop.\n // Instead of incurring the cost to check every time, do it\n // only if an exception is thrown, and swallow the exception\n // if it exists, since we didn't want to make the call,\n // anyway. This most likely means the property is\n // non-configurable.\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::getOwnNamedDescriptor(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n desc));\n if (!res) {\n goto exception;\n } else {\n runtime->clearThrownValue();\n }\n // fall through\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(DeclareGlobalVar);\n DISPATCH;\n }\n\n CASE(TryGetByIdLong) {\n tryProp = true;\n idVal = ip->iTryGetByIdLong.op4;\n nextIP = NEXTINST(TryGetByIdLong);\n goto getById;\n }\n CASE(GetByIdLong) {\n tryProp = false;\n idVal = ip->iGetByIdLong.op4;\n nextIP = NEXTINST(GetByIdLong);\n goto getById;\n }\n CASE(GetByIdShort) {\n tryProp = false;\n idVal = ip->iGetByIdShort.op4;\n nextIP = NEXTINST(GetByIdShort);\n goto getById;\n }\n CASE(TryGetById) {\n tryProp = true;\n idVal = ip->iTryGetById.op4;\n nextIP = NEXTINST(TryGetById);\n goto getById;\n }\n CASE(GetById) {\n tryProp = false;\n idVal = ip->iGetById.op4;\n nextIP = NEXTINST(GetById);\n }\n getById : {\n ++NumGetById;\n // NOTE: it is safe to use OnREG(GetById) here because all instructions\n // have the same layout: opcode, registers, non-register operands, i.e.\n // they only differ in the width of the last \"identifier\" field.\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetById).isObject())) {\n auto *obj = vmcast(O2REG(GetById));\n auto cacheIdx = ip->iGetById.op3;\n auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n#ifndef NDEBUG\n if (clazzGCPtr.get(runtime)->isDictionary())\n ++NumGetByIdDict;\n#else\n (void)NumGetByIdDict;\n#endif\n\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumGetByIdCacheHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(\n obj, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue fastPathResult,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(\n fastPathResult.hasValue() && fastPathResult.getValue()) &&\n !desc.flags.accessor) {\n ++NumGetByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumGetByIdCacheEvicts;\n#else\n (void)NumGetByIdCacheEvicts;\n#endif\n // Cache the class, id and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP_ASSIGN(\n O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));\n ip = nextIP;\n DISPATCH;\n }\n\n // The cache may also be populated via the prototype of the object.\n // This value is only reliable if the fast path was a definite\n // not-found.\n if (fastPathResult.hasValue() && !fastPathResult.getValue() &&\n !obj->isProxyObject()) {\n CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));\n // TODO: This isLazy check is because a lazy object is reported as\n // having no properties and therefore cannot contain the property.\n // This check does not belong here, it should be merged into\n // tryGetOwnNamedDescriptorFast().\n if (parent &&\n cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&\n LLVM_LIKELY(!obj->isLazy())) {\n ++NumGetByIdProtoHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n }\n\n#ifdef HERMES_SLOW_DEBUG\n CAPTURE_IP_ASSIGN(\n JSObject * propObj,\n JSObject::getNamedDescriptor(\n Handle::vmcast(&O2REG(GetById)), runtime, id, desc));\n if (propObj) {\n if (desc.flags.accessor)\n ++NumGetByIdAccessor;\n else if (propObj != vmcast(O2REG(GetById)))\n ++NumGetByIdProto;\n } else {\n ++NumGetByIdNotFound;\n }\n#else\n (void)NumGetByIdAccessor;\n (void)NumGetByIdProto;\n (void)NumGetByIdNotFound;\n#endif\n#ifdef HERMES_SLOW_DEBUG\n auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED\n ? cacheEntry->clazz.get(runtime, &runtime->getHeap())\n : nullptr;\n#endif\n ++NumGetByIdSlow;\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetById)),\n runtime,\n id,\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist(),\n cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry\n : nullptr));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n#ifdef HERMES_SLOW_DEBUG\n if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&\n cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {\n ++NumGetByIdCacheEvicts;\n }\n#endif\n } else {\n ++NumGetByIdTransient;\n assert(!tryProp && \"TryGetById can only be used on the global object\");\n /* Slow path. */\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByIdTransient_RJS(\n runtime, Handle<>(&O2REG(GetById)), ID(idVal)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n O1REG(GetById) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(TryPutByIdLong) {\n tryProp = true;\n idVal = ip->iTryPutByIdLong.op4;\n nextIP = NEXTINST(TryPutByIdLong);\n goto putById;\n }\n CASE(PutByIdLong) {\n tryProp = false;\n idVal = ip->iPutByIdLong.op4;\n nextIP = NEXTINST(PutByIdLong);\n goto putById;\n }\n CASE(TryPutById) {\n tryProp = true;\n idVal = ip->iTryPutById.op4;\n nextIP = NEXTINST(TryPutById);\n goto putById;\n }\n CASE(PutById) {\n tryProp = false;\n idVal = ip->iPutById.op4;\n nextIP = NEXTINST(PutById);\n }\n putById : {\n ++NumPutById;\n if (LLVM_LIKELY(O1REG(PutById).isObject())) {\n auto *obj = vmcast(O1REG(PutById));\n auto cacheIdx = ip->iPutById.op3;\n auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumPutByIdCacheHits;\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, cacheEntry->slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue hasOwnProp,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&\n !desc.flags.accessor && desc.flags.writable &&\n !desc.flags.internalSetter) {\n ++NumPutByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionary()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumPutByIdCacheEvicts;\n#else\n (void)NumPutByIdCacheEvicts;\n#endif\n // Cache the class and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, desc.slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putNamed_RJS(\n Handle::vmcast(&O1REG(PutById)),\n runtime,\n id,\n Handle<>(&O2REG(PutById)),\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist()));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n ++NumPutByIdTransient;\n assert(!tryProp && \"TryPutById can only be used on the global object\");\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByIdTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutById)),\n ID(idVal),\n Handle<>(&O2REG(PutById)),\n strictMode));\n if (retStatus == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetByVal) {\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getComputed_RJS(\n Handle::vmcast(&O2REG(GetByVal)),\n runtime,\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByValTransient_RJS(\n runtime,\n Handle<>(&O2REG(GetByVal)),\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetByVal) = resPH->get();\n ip = NEXTINST(GetByVal);\n DISPATCH;\n }\n\n CASE(PutByVal) {\n if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putComputed_RJS(\n Handle::vmcast(&O1REG(PutByVal)),\n runtime,\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByValTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutByVal)),\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n strictMode));\n if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(PutByVal);\n DISPATCH;\n }\n\n CASE(PutOwnByIndexL) {\n nextIP = NEXTINST(PutOwnByIndexL);\n idVal = ip->iPutOwnByIndexL.op3;\n goto putOwnByIndex;\n }\n CASE(PutOwnByIndex) {\n nextIP = NEXTINST(PutOwnByIndex);\n idVal = ip->iPutOwnByIndex.op3;\n }\n putOwnByIndex : {\n tmpHandle = HermesValue::encodeDoubleValue(idVal);\n CAPTURE_IP(JSObject::defineOwnComputedPrimitive(\n Handle::vmcast(&O1REG(PutOwnByIndex)),\n runtime,\n tmpHandle,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n Handle<>(&O2REG(PutOwnByIndex))));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetPNameList) {\n CAPTURE_IP_ASSIGN(\n auto pRes, handleGetPNameList(runtime, frameRegs, ip));\n if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(GetPNameList);\n DISPATCH;\n }\n\n CASE(GetNextPName) {\n {\n assert(\n vmisa(O2REG(GetNextPName)) &&\n \"GetNextPName's second op must be BigStorage\");\n auto obj = Handle::vmcast(&O3REG(GetNextPName));\n auto arr = Handle::vmcast(&O2REG(GetNextPName));\n uint32_t idx = O4REG(GetNextPName).getNumber();\n uint32_t size = O5REG(GetNextPName).getNumber();\n MutableHandle propObj{runtime};\n // Loop until we find a property which is present.\n while (idx < size) {\n tmpHandle = arr->at(idx);\n ComputedPropertyDescriptor desc;\n CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(\n obj, runtime, tmpHandle, propObj, desc));\n if (LLVM_LIKELY(propObj))\n break;\n ++idx;\n }\n if (idx < size) {\n // We must return the property as a string\n if (tmpHandle->isNumber()) {\n CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));\n assert(\n status == ExecutionStatus::RETURNED &&\n \"toString on number cannot fail\");\n tmpHandle = status->getHermesValue();\n }\n O1REG(GetNextPName) = tmpHandle.get();\n O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);\n } else {\n O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(GetNextPName);\n DISPATCH;\n }\n\n CASE(ToNumber) {\n if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {\n O1REG(ToNumber) = O2REG(ToNumber);\n ip = NEXTINST(ToNumber);\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToNumber) = res.getValue();\n ip = NEXTINST(ToNumber);\n }\n DISPATCH;\n }\n\n CASE(ToInt32) {\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToInt32) = res.getValue();\n ip = NEXTINST(ToInt32);\n DISPATCH;\n }\n\n CASE(AddEmptyString) {\n if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {\n O1REG(AddEmptyString) = O2REG(AddEmptyString);\n ip = NEXTINST(AddEmptyString);\n } else {\n CAPTURE_IP_ASSIGN(\n res,\n toPrimitive_RJS(\n runtime,\n Handle<>(&O2REG(AddEmptyString)),\n PreferredType::NONE));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));\n if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(AddEmptyString) = strRes->getHermesValue();\n ip = NEXTINST(AddEmptyString);\n }\n DISPATCH;\n }\n\n CASE(Jmp) {\n ip = IPADD(ip->iJmp.op1);\n DISPATCH;\n }\n CASE(JmpLong) {\n ip = IPADD(ip->iJmpLong.op1);\n DISPATCH;\n }\n CASE(JmpTrue) {\n if (toBoolean(O2REG(JmpTrue)))\n ip = IPADD(ip->iJmpTrue.op1);\n else\n ip = NEXTINST(JmpTrue);\n DISPATCH;\n }\n CASE(JmpTrueLong) {\n if (toBoolean(O2REG(JmpTrueLong)))\n ip = IPADD(ip->iJmpTrueLong.op1);\n else\n ip = NEXTINST(JmpTrueLong);\n DISPATCH;\n }\n CASE(JmpFalse) {\n if (!toBoolean(O2REG(JmpFalse)))\n ip = IPADD(ip->iJmpFalse.op1);\n else\n ip = NEXTINST(JmpFalse);\n DISPATCH;\n }\n CASE(JmpFalseLong) {\n if (!toBoolean(O2REG(JmpFalseLong)))\n ip = IPADD(ip->iJmpFalseLong.op1);\n else\n ip = NEXTINST(JmpFalseLong);\n DISPATCH;\n }\n CASE(JmpUndefined) {\n if (O2REG(JmpUndefined).isUndefined())\n ip = IPADD(ip->iJmpUndefined.op1);\n else\n ip = NEXTINST(JmpUndefined);\n DISPATCH;\n }\n CASE(JmpUndefinedLong) {\n if (O2REG(JmpUndefinedLong).isUndefined())\n ip = IPADD(ip->iJmpUndefinedLong.op1);\n else\n ip = NEXTINST(JmpUndefinedLong);\n DISPATCH;\n }\n CASE(Add) {\n if (LLVM_LIKELY(\n O2REG(Add).isNumber() &&\n O3REG(Add).isNumber())) { /* Fast-path. */\n CASE(AddN) {\n O1REG(Add) = HermesValue::encodeDoubleValue(\n O2REG(Add).getNumber() + O3REG(Add).getNumber());\n ip = NEXTINST(Add);\n DISPATCH;\n }\n }\n CAPTURE_IP_ASSIGN(\n res,\n addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Add) = res.getValue();\n ip = NEXTINST(Add);\n DISPATCH;\n }\n\n CASE(BitNot) {\n if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~hermes::truncateToInt32(O2REG(BitNot).getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~static_cast(res->getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n\n CASE(GetArgumentsLength) {\n // If the arguments object hasn't been created yet.\n if (O2REG(GetArgumentsLength).isUndefined()) {\n O1REG(GetArgumentsLength) =\n HermesValue::encodeNumberValue(FRAME.getArgCount());\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n // The arguments object has been created, so this is a regular property\n // get.\n assert(\n O2REG(GetArgumentsLength).isObject() &&\n \"arguments lazy register is not an object\");\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetArgumentsLength)),\n runtime,\n Predefined::getSymbolID(Predefined::length)));\n if (resPH == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsLength) = resPH->get();\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n\n CASE(GetArgumentsPropByVal) {\n // If the arguments object hasn't been created yet and we have a\n // valid integer index, we use the fast path.\n if (O3REG(GetArgumentsPropByVal).isUndefined()) {\n // If this is an integer index.\n if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {\n // Is this an existing argument?\n if (*index < FRAME.getArgCount()) {\n O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n }\n }\n // Slow path.\n CAPTURE_IP_ASSIGN(\n auto res,\n getArgumentsPropByValSlowPath_RJS(\n runtime,\n &O3REG(GetArgumentsPropByVal),\n &O2REG(GetArgumentsPropByVal),\n FRAME.getCalleeClosureHandleUnsafe(),\n strictMode));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsPropByVal) = res->getHermesValue();\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n\n CASE(ReifyArguments) {\n // If the arguments object was already created, do nothing.\n if (!O1REG(ReifyArguments).isUndefined()) {\n assert(\n O1REG(ReifyArguments).isObject() &&\n \"arguments lazy register is not an object\");\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(\n resArgs,\n reifyArgumentsSlowPath(\n runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));\n if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(ReifyArguments) = resArgs->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n\n CASE(NewObject) {\n // Create a new object using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n O1REG(NewObject), JSObject::create(runtime).getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObject);\n DISPATCH;\n }\n CASE(NewObjectWithParent) {\n CAPTURE_IP_ASSIGN(\n O1REG(NewObjectWithParent),\n JSObject::create(\n runtime,\n O2REG(NewObjectWithParent).isObject()\n ? Handle::vmcast(&O2REG(NewObjectWithParent))\n : O2REG(NewObjectWithParent).isNull()\n ? Runtime::makeNullHandle()\n : Handle::vmcast(&runtime->objectPrototype))\n .getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObjectWithParent);\n DISPATCH;\n }\n\n CASE(NewObjectWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBuffer.op3,\n ip->iNewObjectWithBuffer.op4,\n ip->iNewObjectWithBuffer.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBuffer);\n DISPATCH;\n }\n\n CASE(NewObjectWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBufferLong.op3,\n ip->iNewObjectWithBufferLong.op4,\n ip->iNewObjectWithBufferLong.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBufferLong);\n DISPATCH;\n }\n\n CASE(NewArray) {\n // Create a new array using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n auto createRes,\n JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));\n if (createRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(NewArray) = createRes->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewArray);\n DISPATCH;\n }\n\n CASE(NewArrayWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBuffer.op2,\n ip->iNewArrayWithBuffer.op3,\n ip->iNewArrayWithBuffer.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBuffer);\n DISPATCH;\n }\n\n CASE(NewArrayWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBufferLong.op2,\n ip->iNewArrayWithBufferLong.op3,\n ip->iNewArrayWithBufferLong.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBufferLong);\n DISPATCH;\n }\n\n CASE(CreateThis) {\n // Registers: output, prototype, closure.\n if (LLVM_UNLIKELY(!vmisa(O3REG(CreateThis)))) {\n CAPTURE_IP(runtime->raiseTypeError(\"constructor is not callable\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto res,\n Callable::newObject(\n Handle::vmcast(&O3REG(CreateThis)),\n runtime,\n Handle::vmcast(\n O2REG(CreateThis).isObject() ? &O2REG(CreateThis)\n : &runtime->objectPrototype)));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(CreateThis) = res->getHermesValue();\n ip = NEXTINST(CreateThis);\n DISPATCH;\n }\n\n CASE(SelectObject) {\n // Registers: output, thisObject, constructorReturnValue.\n O1REG(SelectObject) = O3REG(SelectObject).isObject()\n ? O3REG(SelectObject)\n : O2REG(SelectObject);\n ip = NEXTINST(SelectObject);\n DISPATCH;\n }\n\n CASE(Eq)\n CASE(Neq) {\n CAPTURE_IP_ASSIGN(\n res,\n abstractEqualityTest_RJS(\n runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Eq) = ip->opCode == OpCode::Eq\n ? res.getValue()\n : HermesValue::encodeBoolValue(!res->getBool());\n ip = NEXTINST(Eq);\n DISPATCH;\n }\n CASE(StrictEq) {\n O1REG(StrictEq) = HermesValue::encodeBoolValue(\n strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));\n ip = NEXTINST(StrictEq);\n DISPATCH;\n }\n CASE(StrictNeq) {\n O1REG(StrictNeq) = HermesValue::encodeBoolValue(\n !strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));\n ip = NEXTINST(StrictNeq);\n DISPATCH;\n }\n CASE(Not) {\n O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));\n ip = NEXTINST(Not);\n DISPATCH;\n }\n CASE(Negate) {\n if (LLVM_LIKELY(O2REG(Negate).isNumber())) {\n O1REG(Negate) =\n HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());\n }\n ip = NEXTINST(Negate);\n DISPATCH;\n }\n CASE(TypeOf) {\n CAPTURE_IP_ASSIGN(\n O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));\n ip = NEXTINST(TypeOf);\n DISPATCH;\n }\n CASE(Mod) {\n // We use fmod here for simplicity. Theoretically fmod behaves slightly\n // differently than the ECMAScript Spec. fmod applies round-towards-zero\n // for the remainder when it's not representable by a double; while the\n // spec requires round-to-nearest. As an example, 5 % 0.7 will give\n // 0.10000000000000031 using fmod, but using the rounding style\n // described\n // by the spec, the output should really be 0.10000000000000053.\n // Such difference can be ignored in practice.\n if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {\n /* Fast-path. */\n O1REG(Mod) = HermesValue::encodeDoubleValue(\n std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n double left = res->getDouble();\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n O1REG(Mod) =\n HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CASE(InstanceOf) {\n CAPTURE_IP_ASSIGN(\n auto result,\n instanceOfOperator_RJS(\n runtime,\n Handle<>(&O2REG(InstanceOf)),\n Handle<>(&O3REG(InstanceOf))));\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(InstanceOf);\n DISPATCH;\n }\n CASE(IsIn) {\n {\n if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {\n CAPTURE_IP(runtime->raiseTypeError(\n \"right operand of 'in' is not an object\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto cr,\n JSObject::hasComputed(\n Handle::vmcast(&O3REG(IsIn)),\n runtime,\n Handle<>(&O2REG(IsIn))));\n if (cr == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(IsIn);\n DISPATCH;\n }\n\n CASE(PutNewOwnByIdShort) {\n nextIP = NEXTINST(PutNewOwnByIdShort);\n idVal = ip->iPutNewOwnByIdShort.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEByIdLong)\n CASE(PutNewOwnByIdLong) {\n nextIP = NEXTINST(PutNewOwnByIdLong);\n idVal = ip->iPutNewOwnByIdLong.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEById)\n CASE(PutNewOwnById) {\n nextIP = NEXTINST(PutNewOwnById);\n idVal = ip->iPutNewOwnById.op3;\n }\n putOwnById : {\n assert(\n O1REG(PutNewOwnById).isObject() &&\n \"Object argument of PutNewOwnById must be an object\");\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineNewOwnProperty(\n Handle::vmcast(&O1REG(PutNewOwnById)),\n runtime,\n ID(idVal),\n ip->opCode <= OpCode::PutNewOwnByIdLong\n ? PropertyFlags::defaultNewNamedPropertyFlags()\n : PropertyFlags::nonEnumerablePropertyFlags(),\n Handle<>(&O2REG(PutNewOwnById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByIdLong) {\n idVal = ip->iDelByIdLong.op3;\n nextIP = NEXTINST(DelByIdLong);\n goto DelById;\n }\n\n CASE(DelById) {\n idVal = ip->iDelById.op3;\n nextIP = NEXTINST(DelById);\n }\n DelById : {\n if (LLVM_LIKELY(O2REG(DelById).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(&O2REG(DelById)),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n // If an exception is thrown, likely we are trying to convert\n // undefined/null to an object. Passing over the name of the property\n // so that we could emit more meaningful error messages.\n CAPTURE_IP(amendPropAccessErrorMsgWithPropName(\n runtime, Handle<>(&O2REG(DelById)), \"delete\", ID(idVal)));\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(tmpHandle),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n tmpHandle.clear();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByVal) {\n if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(&O2REG(DelByVal)),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(tmpHandle),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(DelByVal);\n DISPATCH;\n }\n CASE(CreateRegExp) {\n {\n // Create the RegExp object.\n CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));\n // Initialize the regexp.\n CAPTURE_IP_ASSIGN(\n auto pattern,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op2)));\n CAPTURE_IP_ASSIGN(\n auto flags,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op3)));\n CAPTURE_IP_ASSIGN(\n auto bytecode,\n curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(\n ip->iCreateRegExp.op4));\n CAPTURE_IP_ASSIGN(\n auto initRes,\n JSRegExp::initialize(re, runtime, pattern, flags, bytecode));\n if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n // Done, return the new object.\n O1REG(CreateRegExp) = re.getHermesValue();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateRegExp);\n DISPATCH;\n }\n\n CASE(SwitchImm) {\n if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {\n double numVal = O1REG(SwitchImm).getNumber();\n uint32_t uintVal = (uint32_t)numVal;\n if (LLVM_LIKELY(numVal == uintVal) && // Only integers.\n LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.\n LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.\n {\n // Calculate the offset into the bytecode where the jump table for\n // this SwitchImm starts.\n const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(\n (const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));\n\n // Read the offset from the table.\n // Must be signed to account for backwards branching.\n const int32_t *loc =\n (const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;\n\n ip = IPADD(*loc);\n DISPATCH;\n }\n }\n // Wrong type or out of range, jump to default.\n ip = IPADD(ip->iSwitchImm.op3);\n DISPATCH;\n }\n LOAD_CONST(\n LoadConstUInt8,\n HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));\n LOAD_CONST(\n LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));\n LOAD_CONST(\n LoadConstDouble,\n HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));\n LOAD_CONST_CAPTURE_IP(\n LoadConstString,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstString.op2)));\n LOAD_CONST_CAPTURE_IP(\n LoadConstStringLongIndex,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstStringLongIndex.op2)));\n LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());\n LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());\n LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));\n LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));\n LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));\n BINOP(Sub, doSub);\n BINOP(Mul, doMult);\n BINOP(Div, doDiv);\n BITWISEBINOP(BitAnd, &);\n BITWISEBINOP(BitOr, |);\n BITWISEBINOP(BitXor, ^);\n // For LShift, we need to use toUInt32 first because lshift on negative\n // numbers is undefined behavior in theory.\n SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);\n SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);\n SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);\n CONDOP(Less, <, lessOp_RJS);\n CONDOP(LessEq, <=, lessEqualOp_RJS);\n CONDOP(Greater, >, greaterOp_RJS);\n CONDOP(GreaterEq, >=, greaterEqualOp_RJS);\n JCOND(Less, <, lessOp_RJS);\n JCOND(LessEqual, <=, lessEqualOp_RJS);\n JCOND(Greater, >, greaterOp_RJS);\n JCOND(GreaterEqual, >=, greaterEqualOp_RJS);\n\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual,\n Long,\n IPADD(ip->iJStrictEqualLong.op1),\n NEXTINST(JStrictEqualLong));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n ,\n NEXTINST(JStrictNotEqual),\n IPADD(ip->iJStrictNotEqual.op1));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n Long,\n NEXTINST(JStrictNotEqualLong),\n IPADD(ip->iJStrictNotEqualLong.op1));\n\n JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));\n JCOND_EQ_IMPL(\n JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));\n JCOND_EQ_IMPL(\n JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));\n JCOND_EQ_IMPL(\n JNotEqual,\n Long,\n NEXTINST(JNotEqualLong),\n IPADD(ip->iJNotEqualLong.op1));\n\n CASE_OUTOFLINE(PutOwnByVal);\n CASE_OUTOFLINE(PutOwnGetterSetterByVal);\n CASE_OUTOFLINE(DirectEval);\n\n CASE_OUTOFLINE(IteratorBegin);\n CASE_OUTOFLINE(IteratorNext);\n CASE(IteratorClose) {\n if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {\n // The iterator must be closed if it's still an object.\n // That means it was never an index and is not done iterating (a state\n // which is indicated by `undefined`).\n CAPTURE_IP_ASSIGN(\n auto res,\n iteratorClose(\n runtime,\n Handle::vmcast(&O1REG(IteratorClose)),\n Runtime::getEmptyValue()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n if (ip->iIteratorClose.op2 &&\n !isUncatchableError(runtime->thrownValue_)) {\n // Ignore inner exception.\n runtime->clearThrownValue();\n } else {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n ip = NEXTINST(IteratorClose);\n DISPATCH;\n }\n\n CASE(_last) {\n llvm_unreachable(\"Invalid opcode _last\");\n }\n }\n\n llvm_unreachable(\"unreachable\");\n\n // We arrive here if we couldn't allocate the registers for the current frame.\n stackOverflow:\n CAPTURE_IP(runtime->raiseStackOverflow(\n Runtime::StackOverflowKind::JSRegisterStack));\n\n // We arrive here when we raised an exception in a callee, but we don't want\n // the callee to be able to handle it.\n handleExceptionInParent:\n // Restore the caller code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop to the previous frame where technically the error happened.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n // If we are coming from native code, return.\n if (!curCodeBlock)\n return ExecutionStatus::EXCEPTION;\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n // Handle the exception.\n exception:\n UPDATE_OPCODE_TIME_SPENT;\n assert(\n !runtime->thrownValue_.isEmpty() &&\n \"thrownValue unavailable at exception\");\n\n bool catchable = true;\n // If this is an Error object that was thrown internally, it didn't have\n // access to the current codeblock and IP, so collect the stack trace here.\n if (auto *jsError = dyn_vmcast(runtime->thrownValue_)) {\n catchable = jsError->catchable();\n if (!jsError->getStackTrace()) {\n // Temporarily clear the thrown value for following operations.\n CAPTURE_IP_ASSIGN(\n auto errorHandle,\n runtime->makeHandle(vmcast(runtime->thrownValue_)));\n runtime->clearThrownValue();\n\n CAPTURE_IP(JSError::recordStackTrace(\n errorHandle, runtime, false, curCodeBlock, ip));\n\n // Restore the thrown value.\n runtime->setThrownValue(errorHandle.getHermesValue());\n }\n }\n\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n\n#ifdef HERMES_ENABLE_DEBUGGER\n if (SingleStep) {\n // If we're single stepping, don't bother with any more checks,\n // and simply signal that we should continue execution with an exception.\n state.codeBlock = curCodeBlock;\n state.offset = CUROFFSET;\n return ExecutionStatus::EXCEPTION;\n }\n\n using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;\n auto mode = runtime->debugger_.getPauseOnThrowMode();\n if (mode != PauseOnThrowMode::None) {\n if (!runtime->debugger_.isDebugging()) {\n // Determine whether the PauseOnThrowMode requires us to stop here.\n bool caught =\n runtime->debugger_\n .findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))\n .hasValue();\n bool shouldStop = mode == PauseOnThrowMode::All ||\n (mode == PauseOnThrowMode::Uncaught && !caught);\n if (shouldStop) {\n // When runDebugger is invoked after an exception,\n // stepping should never happen internally.\n // Any step is a step to an exception handler, which we do\n // directly here in the interpreter.\n // Thus, the result state should be the same as the input state.\n InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus resultStatus,\n runtime->debugger_.runDebugger(\n Debugger::RunReason::Exception, tmpState));\n (void)resultStatus;\n assert(\n tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&\n \"not allowed to step internally in a pauseOnThrow\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n }\n }\n#endif\n\n int32_t handlerOffset = 0;\n\n // If the exception is not catchable, skip found catch blocks.\n while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==\n -1) ||\n !catchable) {\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Restore the code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop a stack frame.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit with exception: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(\n dbgs()\n << \"function exit with exception: returning to native code\\n\");\n return ExecutionStatus::EXCEPTION;\n }\n\n assert(\n isCallType(ip->opCode) &&\n \"return address is not Call-type instruction\");\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n }\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n ip = IPADD(handlerOffset - CUROFFSET);\n }\n}", "func_hash": 224190035560216293056288838795317082416, "file_name": "Interpreter.cpp", "file_hash": 194778499302310956468395768712019111606, "cwe": ["CWE-703"], "cve": "CVE-2020-1914", "cve_desc": "A logic vulnerability when handling the SaveGeneratorLong instruction in Facebook Hermes prior to commit b2021df620824627f5a8c96615edbd1eb7fdddfc allows attackers to potentially read out of bounds or theoretically execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1914"} {"idx": 199948, "project": "libvncserver", "commit_id": "673c07a75ed844d74676f3ccdcfdc706a7052dba", "project_url": "https://github.com/LibVNC/libvncserver", "commit_url": "https://github.com/LibVNC/libvncserver/commit/673c07a75ed844d74676f3ccdcfdc706a7052dba", "commit_message": "libvncserver/rfbserver: fix possible divide-by-zero\n\nCloses #409", "target": 1, "func": "rfbSendRectEncodingRaw(rfbClientPtr cl,\n int x,\n int y,\n int w,\n int h)\n{\n rfbFramebufferUpdateRectHeader rect;\n int nlines;\n int bytesPerLine = w * (cl->format.bitsPerPixel / 8);\n char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)\n + (x * (cl->scaledScreen->bitsPerPixel / 8)));\n\n /* Flush the buffer to guarantee correct alignment for translateFn(). */\n if (cl->ublen > 0) {\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n }\n\n rect.r.x = Swap16IfLE(x);\n rect.r.y = Swap16IfLE(y);\n rect.r.w = Swap16IfLE(w);\n rect.r.h = Swap16IfLE(h);\n rect.encoding = Swap32IfLE(rfbEncodingRaw);\n\n memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader);\n cl->ublen += sz_rfbFramebufferUpdateRectHeader;\n\n\n rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h,\n sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n\n while (TRUE) {\n if (nlines > h)\n nlines = h;\n\n (*cl->translateFn)(cl->translateLookupTable,\n\t\t\t &(cl->screen->serverFormat),\n &cl->format, fbptr, &cl->updateBuf[cl->ublen],\n cl->scaledScreen->paddedWidthInBytes, w, nlines);\n\n cl->ublen += nlines * bytesPerLine;\n h -= nlines;\n\n if (h == 0) /* rect fitted in buffer, do next one */\n return TRUE;\n\n /* buffer full - flush partial rect and do another nlines */\n\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n\n fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n if (nlines == 0) {\n rfbErr(\"rfbSendRectEncodingRaw: send buffer too small for %d \"\n \"bytes per line\\n\", bytesPerLine);\n rfbCloseClient(cl);\n return FALSE;\n }\n }\n}", "func_hash": 208136482314523213854619058128717819041, "file_name": "rfbserver.c", "file_hash": 163207847579691217468685617129732292067, "cwe": ["CWE-369"], "cve": "CVE-2020-25708", "cve_desc": "A divide by zero issue was found to occur in libvncserver-0.9.12. A malicious client could use this flaw to send a specially crafted message that, when processed by the VNC server, would lead to a floating point exception, resulting in a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25708"} {"idx": 295864, "project": "libvncserver", "commit_id": "673c07a75ed844d74676f3ccdcfdc706a7052dba", "project_url": "https://github.com/LibVNC/libvncserver", "commit_url": "https://github.com/LibVNC/libvncserver/commit/673c07a75ed844d74676f3ccdcfdc706a7052dba", "commit_message": "libvncserver/rfbserver: fix possible divide-by-zero\n\nCloses #409", "target": 0, "func": "rfbSendRectEncodingRaw(rfbClientPtr cl,\n int x,\n int y,\n int w,\n int h)\n{\n rfbFramebufferUpdateRectHeader rect;\n int nlines;\n int bytesPerLine = w * (cl->format.bitsPerPixel / 8);\n char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)\n + (x * (cl->scaledScreen->bitsPerPixel / 8)));\n\n if(!h || !w)\n\treturn TRUE; /* nothing to send */\n\n /* Flush the buffer to guarantee correct alignment for translateFn(). */\n if (cl->ublen > 0) {\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n }\n\n rect.r.x = Swap16IfLE(x);\n rect.r.y = Swap16IfLE(y);\n rect.r.w = Swap16IfLE(w);\n rect.r.h = Swap16IfLE(h);\n rect.encoding = Swap32IfLE(rfbEncodingRaw);\n\n memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader);\n cl->ublen += sz_rfbFramebufferUpdateRectHeader;\n\n\n rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h,\n sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n\n while (TRUE) {\n if (nlines > h)\n nlines = h;\n\n (*cl->translateFn)(cl->translateLookupTable,\n\t\t\t &(cl->screen->serverFormat),\n &cl->format, fbptr, &cl->updateBuf[cl->ublen],\n cl->scaledScreen->paddedWidthInBytes, w, nlines);\n\n cl->ublen += nlines * bytesPerLine;\n h -= nlines;\n\n if (h == 0) /* rect fitted in buffer, do next one */\n return TRUE;\n\n /* buffer full - flush partial rect and do another nlines */\n\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n\n fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n if (nlines == 0) {\n rfbErr(\"rfbSendRectEncodingRaw: send buffer too small for %d \"\n \"bytes per line\\n\", bytesPerLine);\n rfbCloseClient(cl);\n return FALSE;\n }\n }\n}", "func_hash": 56954669155563957806347048732180221288, "file_name": "rfbserver.c", "file_hash": 198783253710734256171221764720987498973, "cwe": ["CWE-369"], "cve": "CVE-2020-25708", "cve_desc": "A divide by zero issue was found to occur in libvncserver-0.9.12. A malicious client could use this flaw to send a specially crafted message that, when processed by the VNC server, would lead to a floating point exception, resulting in a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25708"} {"idx": 199976, "project": "leptonica", "commit_id": "5ee24b398bb67666f6d173763eaaedd9c36fb1e5", "project_url": "https://github.com/DanBloomberg/leptonica", "commit_url": "https://github.com/DanBloomberg/leptonica/commit/5ee24b398bb67666f6d173763eaaedd9c36fb1e5", "commit_message": "Fixed issue 22140 in oss-fuzz: Heap-buffer-overflow\n* color quantized pix must be 8 bpp before extra colors are added.", "target": 1, "func": "pixFewColorsOctcubeQuantMixed(PIX *pixs,\n l_int32 level,\n l_int32 darkthresh,\n l_int32 lightthresh,\n l_int32 diffthresh,\n l_float32 minfract,\n l_int32 maxspan)\n{\nl_int32 i, j, w, h, wplc, wplm, wpld, ncolors, index;\nl_int32 rval, gval, bval, val, minval, maxval;\nl_int32 *lut;\nl_uint32 *datac, *datam, *datad, *linec, *linem, *lined;\nPIX *pixc, *pixm, *pixg, *pixd;\nPIXCMAP *cmap, *cmapd;\n\n PROCNAME(\"pixFewColorsOctcubeQuantMixed\");\n\n if (!pixs || pixGetDepth(pixs) != 32)\n return (PIX *)ERROR_PTR(\"pixs undefined or not 32 bpp\", procName, NULL);\n if (level <= 0) level = 3;\n if (level > 6)\n return (PIX *)ERROR_PTR(\"invalid level\", procName, NULL);\n if (darkthresh <= 0) darkthresh = 20;\n if (lightthresh <= 0) lightthresh = 244;\n if (diffthresh <= 0) diffthresh = 20;\n if (minfract <= 0.0) minfract = 0.05;\n if (maxspan <= 2) maxspan = 15;\n\n /* Start with a simple fixed octcube quantizer. */\n if ((pixc = pixFewColorsOctcubeQuant1(pixs, level)) == NULL)\n return (PIX *)ERROR_PTR(\"too many colors\", procName, NULL);\n\n /* Identify and save color entries in the colormap. Set up a LUT\n * that returns -1 for any gray pixel. */\n cmap = pixGetColormap(pixc);\n ncolors = pixcmapGetCount(cmap);\n cmapd = pixcmapCreate(8);\n lut = (l_int32 *)LEPT_CALLOC(256, sizeof(l_int32));\n for (i = 0; i < 256; i++)\n lut[i] = -1;\n for (i = 0, index = 0; i < ncolors; i++) {\n pixcmapGetColor(cmap, i, &rval, &gval, &bval);\n minval = L_MIN(rval, gval);\n minval = L_MIN(minval, bval);\n if (minval > lightthresh) /* near white */\n continue;\n maxval = L_MAX(rval, gval);\n maxval = L_MAX(maxval, bval);\n if (maxval < darkthresh) /* near black */\n continue;\n\n /* Use the max diff between components to test for color */\n if (maxval - minval >= diffthresh) {\n pixcmapAddColor(cmapd, rval, gval, bval);\n lut[i] = index;\n index++;\n }\n }\n\n /* Generate dest pix with just the color pixels set to their\n * colormap indices. At the same time, make a 1 bpp mask\n * of the non-color pixels */\n pixGetDimensions(pixs, &w, &h, NULL);\n pixd = pixCreate(w, h, 8);\n pixSetColormap(pixd, cmapd);\n pixm = pixCreate(w, h, 1);\n datac = pixGetData(pixc);\n datam = pixGetData(pixm);\n datad = pixGetData(pixd);\n wplc = pixGetWpl(pixc);\n wplm = pixGetWpl(pixm);\n wpld = pixGetWpl(pixd);\n for (i = 0; i < h; i++) {\n linec = datac + i * wplc;\n linem = datam + i * wplm;\n lined = datad + i * wpld;\n for (j = 0; j < w; j++) {\n val = GET_DATA_BYTE(linec, j);\n if (lut[val] == -1)\n SET_DATA_BIT(linem, j);\n else\n SET_DATA_BYTE(lined, j, lut[val]);\n }\n }\n\n /* Fill in the gray values. Use a grayscale version of pixs\n * as input, along with the mask over the actual gray pixels. */\n pixg = pixConvertTo8(pixs, 0);\n pixGrayQuantFromHisto(pixd, pixg, pixm, minfract, maxspan);\n\n LEPT_FREE(lut);\n pixDestroy(&pixc);\n pixDestroy(&pixm);\n pixDestroy(&pixg);\n return pixd;\n}", "func_hash": 293024620417475689697473925623698819254, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-36281", "cve_desc": "Leptonica before 1.80.0 allows a heap-based buffer over-read in pixFewColorsOctcubeQuantMixed in colorquant1.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36281"} {"idx": 296022, "project": "leptonica", "commit_id": "5ee24b398bb67666f6d173763eaaedd9c36fb1e5", "project_url": "https://github.com/DanBloomberg/leptonica", "commit_url": "https://github.com/DanBloomberg/leptonica/commit/5ee24b398bb67666f6d173763eaaedd9c36fb1e5", "commit_message": "Fixed issue 22140 in oss-fuzz: Heap-buffer-overflow\n* color quantized pix must be 8 bpp before extra colors are added.", "target": 0, "func": "pixFewColorsOctcubeQuantMixed(PIX *pixs,\n l_int32 level,\n l_int32 darkthresh,\n l_int32 lightthresh,\n l_int32 diffthresh,\n l_float32 minfract,\n l_int32 maxspan)\n{\nl_int32 i, j, w, h, wplc, wplm, wpld, ncolors, index;\nl_int32 rval, gval, bval, val, minval, maxval;\nl_int32 *lut;\nl_uint32 *datac, *datam, *datad, *linec, *linem, *lined;\nPIX *pix1, *pixc, *pixm, *pixg, *pixd;\nPIXCMAP *cmap, *cmapd;\n\n PROCNAME(\"pixFewColorsOctcubeQuantMixed\");\n\n if (!pixs || pixGetDepth(pixs) != 32)\n return (PIX *)ERROR_PTR(\"pixs undefined or not 32 bpp\", procName, NULL);\n if (level <= 0) level = 3;\n if (level > 6)\n return (PIX *)ERROR_PTR(\"invalid level\", procName, NULL);\n if (darkthresh <= 0) darkthresh = 20;\n if (lightthresh <= 0) lightthresh = 244;\n if (diffthresh <= 0) diffthresh = 20;\n if (minfract <= 0.0) minfract = 0.05;\n if (maxspan <= 2) maxspan = 15;\n\n /* Start with a simple fixed octcube quantizer. */\n if ((pix1 = pixFewColorsOctcubeQuant1(pixs, level)) == NULL)\n return (PIX *)ERROR_PTR(\"too many colors\", procName, NULL);\n pixc = pixConvertTo8(pix1, 1); /* must be 8 bpp */\n pixDestroy(&pix1);\n\n /* Identify and save color entries in the colormap. Set up a LUT\n * that returns -1 for any gray pixel. */\n cmap = pixGetColormap(pixc);\n ncolors = pixcmapGetCount(cmap);\n cmapd = pixcmapCreate(8);\n lut = (l_int32 *)LEPT_CALLOC(256, sizeof(l_int32));\n for (i = 0; i < 256; i++)\n lut[i] = -1;\n for (i = 0, index = 0; i < ncolors; i++) {\n pixcmapGetColor(cmap, i, &rval, &gval, &bval);\n minval = L_MIN(rval, gval);\n minval = L_MIN(minval, bval);\n if (minval > lightthresh) /* near white */\n continue;\n maxval = L_MAX(rval, gval);\n maxval = L_MAX(maxval, bval);\n if (maxval < darkthresh) /* near black */\n continue;\n\n /* Use the max diff between components to test for color */\n if (maxval - minval >= diffthresh) {\n pixcmapAddColor(cmapd, rval, gval, bval);\n lut[i] = index;\n index++;\n }\n }\n\n /* Generate dest pix with just the color pixels set to their\n * colormap indices. At the same time, make a 1 bpp mask\n * of the non-color pixels */\n pixGetDimensions(pixs, &w, &h, NULL);\n pixd = pixCreate(w, h, 8);\n pixSetColormap(pixd, cmapd);\n pixm = pixCreate(w, h, 1);\n datac = pixGetData(pixc);\n datam = pixGetData(pixm);\n datad = pixGetData(pixd);\n wplc = pixGetWpl(pixc);\n wplm = pixGetWpl(pixm);\n wpld = pixGetWpl(pixd);\n for (i = 0; i < h; i++) {\n linec = datac + i * wplc;\n linem = datam + i * wplm;\n lined = datad + i * wpld;\n for (j = 0; j < w; j++) {\n val = GET_DATA_BYTE(linec, j);\n if (lut[val] == -1)\n SET_DATA_BIT(linem, j);\n else\n SET_DATA_BYTE(lined, j, lut[val]);\n }\n }\n\n /* Fill in the gray values. Use a grayscale version of pixs\n * as input, along with the mask over the actual gray pixels. */\n pixg = pixConvertTo8(pixs, 0);\n pixGrayQuantFromHisto(pixd, pixg, pixm, minfract, maxspan);\n\n LEPT_FREE(lut);\n pixDestroy(&pixc);\n pixDestroy(&pixm);\n pixDestroy(&pixg);\n return pixd;\n}", "func_hash": 10377955507944117965995876947340760813, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-36281", "cve_desc": "Leptonica before 1.80.0 allows a heap-based buffer over-read in pixFewColorsOctcubeQuantMixed in colorquant1.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36281"} {"idx": 199993, "project": "libvncserver", "commit_id": "a6788d1da719ae006605b78d22f5a9f170b423af", "project_url": "https://github.com/LibVNC/libvncserver", "commit_url": "https://github.com/LibVNC/libvncserver/commit/a6788d1da719ae006605b78d22f5a9f170b423af", "commit_message": "libvncserver: scale: cast to 64 bit before shifting\n\nSince pixel_value is 64 bit the data type of the shift operand should\nbe 64 bit too to prevent integer overflows.", "target": 1, "func": "void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0)\n{\n int x,y,w,v,z;\n int x1, y1, w1, h1;\n int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2;\n unsigned char *srcptr, *dstptr;\n\n /* Nothing to do!!! */\n if (screen==ptr) return;\n\n x1 = x0;\n y1 = y0;\n w1 = w0;\n h1 = h0;\n\n rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, \"rfbScaledScreenUpdateRect\");\n x0 = ScaleX(ptr, screen, x1);\n y0 = ScaleY(ptr, screen, y1);\n w0 = ScaleX(ptr, screen, w1);\n h0 = ScaleY(ptr, screen, h1);\n\n bitsPerPixel = screen->bitsPerPixel;\n bytesPerPixel = bitsPerPixel / 8;\n bytesPerLine = w1 * bytesPerPixel;\n srcptr = (unsigned char *)(screen->frameBuffer +\n (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel));\n dstptr = (unsigned char *)(ptr->frameBuffer +\n ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel));\n /* The area of the source framebuffer for each destination pixel */\n areaX = ScaleX(ptr,screen,1);\n areaY = ScaleY(ptr,screen,1);\n area2 = areaX*areaY;\n\n\n /* Ensure that we do not go out of bounds */\n if ((x1+w1) > (ptr->width))\n {\n if (x1==0) w1=ptr->width; else x1 = ptr->width - w1;\n }\n if ((y1+h1) > (ptr->height))\n {\n if (y1==0) h1=ptr->height; else y1 = ptr->height - h1;\n }\n /*\n * rfbLog(\"rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\\n\",\n * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY,\n * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer);\n */\n\n if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */\n unsigned char *srcptr2;\n unsigned long pixel_value, red, green, blue;\n unsigned int redShift = screen->serverFormat.redShift;\n unsigned int greenShift = screen->serverFormat.greenShift;\n unsigned int blueShift = screen->serverFormat.blueShift;\n unsigned long redMax = screen->serverFormat.redMax;\n unsigned long greenMax = screen->serverFormat.greenMax;\n unsigned long blueMax = screen->serverFormat.blueMax;\n\n /* for each *destination* pixel... */\n for (y = 0; y < h1; y++) {\n for (x = 0; x < w1; x++) {\n red = green = blue = 0;\n /* Get the totals for rgb from the source grid... */\n for (w = 0; w < areaX; w++) {\n for (v = 0; v < areaY; v++) {\n srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) +\n (v * screen->paddedWidthInBytes)];\n pixel_value = 0;\n\n\n switch (bytesPerPixel) {\n case 4: pixel_value = *((unsigned int *)srcptr2); break;\n case 2: pixel_value = *((unsigned short *)srcptr2); break;\n case 1: pixel_value = *((unsigned char *)srcptr2); break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n pixel_value += (srcptr2[z] << (8 * z));\n break;\n }\n /*\n srcptr2 += bytesPerPixel;\n */\n\n red += ((pixel_value >> redShift) & redMax);\n green += ((pixel_value >> greenShift) & greenMax);\n blue += ((pixel_value >> blueShift) & blueMax);\n\n }\n }\n /* We now have a total for all of the colors, find the average! */\n red /= area2;\n green /= area2;\n blue /= area2;\n /* Stuff the new value back into memory */\n pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift);\n\n switch (bytesPerPixel) {\n case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break;\n case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break;\n case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n dstptr[z]=(pixel_value >> (8 * z)) & 0xff;\n break;\n }\n dstptr += bytesPerPixel;\n }\n srcptr += (screen->paddedWidthInBytes * areaY);\n dstptr += (ptr->paddedWidthInBytes - bytesPerLine);\n }\n } else\n { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */\n for (y = y1; y < (y1+h1); y++) {\n for (x = x1; x < (x1+w1); x++)\n memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)],\n &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel);\n }\n }\n}", "func_hash": 81992397040653814855990752030190572131, "file_name": "scale.c", "file_hash": 21320822142708099716896558929042945219, "cwe": ["CWE-787"], "cve": "CVE-2020-14401", "cve_desc": "An issue was discovered in LibVNCServer before 0.9.13. libvncserver/scale.c has a pixel_value integer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14401"} {"idx": 296799, "project": "libvncserver", "commit_id": "a6788d1da719ae006605b78d22f5a9f170b423af", "project_url": "https://github.com/LibVNC/libvncserver", "commit_url": "https://github.com/LibVNC/libvncserver/commit/a6788d1da719ae006605b78d22f5a9f170b423af", "commit_message": "libvncserver: scale: cast to 64 bit before shifting\n\nSince pixel_value is 64 bit the data type of the shift operand should\nbe 64 bit too to prevent integer overflows.", "target": 0, "func": "void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0)\n{\n int x,y,w,v,z;\n int x1, y1, w1, h1;\n int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2;\n unsigned char *srcptr, *dstptr;\n\n /* Nothing to do!!! */\n if (screen==ptr) return;\n\n x1 = x0;\n y1 = y0;\n w1 = w0;\n h1 = h0;\n\n rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, \"rfbScaledScreenUpdateRect\");\n x0 = ScaleX(ptr, screen, x1);\n y0 = ScaleY(ptr, screen, y1);\n w0 = ScaleX(ptr, screen, w1);\n h0 = ScaleY(ptr, screen, h1);\n\n bitsPerPixel = screen->bitsPerPixel;\n bytesPerPixel = bitsPerPixel / 8;\n bytesPerLine = w1 * bytesPerPixel;\n srcptr = (unsigned char *)(screen->frameBuffer +\n (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel));\n dstptr = (unsigned char *)(ptr->frameBuffer +\n ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel));\n /* The area of the source framebuffer for each destination pixel */\n areaX = ScaleX(ptr,screen,1);\n areaY = ScaleY(ptr,screen,1);\n area2 = areaX*areaY;\n\n\n /* Ensure that we do not go out of bounds */\n if ((x1+w1) > (ptr->width))\n {\n if (x1==0) w1=ptr->width; else x1 = ptr->width - w1;\n }\n if ((y1+h1) > (ptr->height))\n {\n if (y1==0) h1=ptr->height; else y1 = ptr->height - h1;\n }\n /*\n * rfbLog(\"rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\\n\",\n * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY,\n * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer);\n */\n\n if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */\n unsigned char *srcptr2;\n unsigned long pixel_value, red, green, blue;\n unsigned int redShift = screen->serverFormat.redShift;\n unsigned int greenShift = screen->serverFormat.greenShift;\n unsigned int blueShift = screen->serverFormat.blueShift;\n unsigned long redMax = screen->serverFormat.redMax;\n unsigned long greenMax = screen->serverFormat.greenMax;\n unsigned long blueMax = screen->serverFormat.blueMax;\n\n /* for each *destination* pixel... */\n for (y = 0; y < h1; y++) {\n for (x = 0; x < w1; x++) {\n red = green = blue = 0;\n /* Get the totals for rgb from the source grid... */\n for (w = 0; w < areaX; w++) {\n for (v = 0; v < areaY; v++) {\n srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) +\n (v * screen->paddedWidthInBytes)];\n pixel_value = 0;\n\n\n switch (bytesPerPixel) {\n case 4: pixel_value = *((unsigned int *)srcptr2); break;\n case 2: pixel_value = *((unsigned short *)srcptr2); break;\n case 1: pixel_value = *((unsigned char *)srcptr2); break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n pixel_value += ((unsigned long)srcptr2[z] << (8 * z));\n break;\n }\n /*\n srcptr2 += bytesPerPixel;\n */\n\n red += ((pixel_value >> redShift) & redMax);\n green += ((pixel_value >> greenShift) & greenMax);\n blue += ((pixel_value >> blueShift) & blueMax);\n\n }\n }\n /* We now have a total for all of the colors, find the average! */\n red /= area2;\n green /= area2;\n blue /= area2;\n /* Stuff the new value back into memory */\n pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift);\n\n switch (bytesPerPixel) {\n case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break;\n case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break;\n case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n dstptr[z]=(pixel_value >> (8 * z)) & 0xff;\n break;\n }\n dstptr += bytesPerPixel;\n }\n srcptr += (screen->paddedWidthInBytes * areaY);\n dstptr += (ptr->paddedWidthInBytes - bytesPerLine);\n }\n } else\n { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */\n for (y = y1; y < (y1+h1); y++) {\n for (x = x1; x < (x1+w1); x++)\n memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)],\n &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel);\n }\n }\n}", "func_hash": 153918360009355427790796452911524685769, "file_name": "scale.c", "file_hash": 5360116644967776075650633128053679247, "cwe": ["CWE-787"], "cve": "CVE-2020-14401", "cve_desc": "An issue was discovered in LibVNCServer before 0.9.13. libvncserver/scale.c has a pixel_value integer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14401"} {"idx": 200108, "project": "sleuthkit", "commit_id": "459ae818fc8dae717549810150de4d191ce158f1", "project_url": "https://github.com/sleuthkit/sleuthkit", "commit_url": "https://github.com/sleuthkit/sleuthkit/commit/459ae818fc8dae717549810150de4d191ce158f1", "commit_message": "Fix stack buffer overflow in yaffsfs_istat\n\nPrevent a stack buffer overflow in yaffsfs_istat by increasing the buffer size to the size required by tsk_fs_time_to_str.", "target": 1, "func": " yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum,\n TSK_DADDR_T numblock, int32_t sec_skew)\n{\n TSK_FS_META *fs_meta;\n TSK_FS_FILE *fs_file;\n YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs;\n char ls[12];\n YAFFSFS_PRINT_ADDR print;\n char timeBuf[32];\n YaffsCacheObject * obj = NULL;\n YaffsCacheVersion * version = NULL;\n YaffsHeader * header = NULL;\n\n yaffscache_version_find_by_inode(yfs, inum, &version, &obj);\n\n if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {\n return 1;\n }\n fs_meta = fs_file->meta;\n\n tsk_fprintf(hFile, \"inode: %\" PRIuINUM \"\\n\", inum);\n tsk_fprintf(hFile, \"%sAllocated\\n\",\n (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? \"\" : \"Not \");\n\n if (fs_meta->link)\n tsk_fprintf(hFile, \"symbolic link to: %s\\n\", fs_meta->link);\n\n tsk_fprintf(hFile, \"uid / gid: %\" PRIuUID \" / %\" PRIuGID \"\\n\",\n fs_meta->uid, fs_meta->gid);\n\n tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls));\n tsk_fprintf(hFile, \"mode: %s\\n\", ls);\n\n tsk_fprintf(hFile, \"size: %\" PRIdOFF \"\\n\", fs_meta->size);\n tsk_fprintf(hFile, \"num of links: %d\\n\", fs_meta->nlink);\n\n if(version != NULL){\n yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset);\n if(header != NULL){\n tsk_fprintf(hFile, \"Name: %s\\n\", header->name);\n }\n }\n\n if (sec_skew != 0) {\n tsk_fprintf(hFile, \"\\nAdjusted Inode Times:\\n\");\n fs_meta->mtime -= sec_skew;\n fs_meta->atime -= sec_skew;\n fs_meta->ctime -= sec_skew;\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n fs_meta->mtime += sec_skew;\n fs_meta->atime += sec_skew;\n fs_meta->ctime += sec_skew;\n\n tsk_fprintf(hFile, \"\\nOriginal Inode Times:\\n\");\n }\n else {\n tsk_fprintf(hFile, \"\\nInode Times:\\n\");\n }\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n if(version != NULL){\n tsk_fprintf(hFile, \"\\nHeader Chunk:\\n\");\n tsk_fprintf(hFile, \"%\" PRIuDADDR \"\\n\", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size)));\n }\n\n if (numblock > 0) {\n TSK_OFF_T lower_size = numblock * fs->block_size;\n fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size);\n }\n tsk_fprintf(hFile, \"\\nData Chunks:\\n\");\n\n\n if (flags & TSK_FS_ISTAT_RUNLIST){\n const TSK_FS_ATTR *fs_attr_default =\n tsk_fs_file_attr_get_type(fs_file,\n TSK_FS_ATTR_TYPE_DEFAULT, 0, 0);\n if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) {\n if (tsk_fs_attr_print(fs_attr_default, hFile)) {\n tsk_fprintf(hFile, \"\\nError creating run lists \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n }\n }\n else {\n print.idx = 0;\n print.hFile = hFile;\n\n if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY,\n (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) {\n tsk_fprintf(hFile, \"\\nError reading file: \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n else if (print.idx != 0) {\n tsk_fprintf(hFile, \"\\n\");\n }\n }\n\n tsk_fs_file_close(fs_file);\n\n return 0;\n}", "func_hash": 92248143357100543214880972358832417843, "file_name": "yaffs.cpp", "file_hash": 126611274587733604338707454613099579810, "cwe": ["CWE-125"], "cve": "CVE-2020-10232", "cve_desc": "In version 4.8.0 and earlier of The Sleuth Kit (TSK), there is a stack buffer overflow vulnerability in the YAFFS file timestamp parsing logic in yaffsfs_istat() in fs/yaffs.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10232"} {"idx": 299134, "project": "sleuthkit", "commit_id": "459ae818fc8dae717549810150de4d191ce158f1", "project_url": "https://github.com/sleuthkit/sleuthkit", "commit_url": "https://github.com/sleuthkit/sleuthkit/commit/459ae818fc8dae717549810150de4d191ce158f1", "commit_message": "Fix stack buffer overflow in yaffsfs_istat\n\nPrevent a stack buffer overflow in yaffsfs_istat by increasing the buffer size to the size required by tsk_fs_time_to_str.", "target": 0, "func": " yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum,\n TSK_DADDR_T numblock, int32_t sec_skew)\n{\n TSK_FS_META *fs_meta;\n TSK_FS_FILE *fs_file;\n YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs;\n char ls[12];\n YAFFSFS_PRINT_ADDR print;\n char timeBuf[128];\n YaffsCacheObject * obj = NULL;\n YaffsCacheVersion * version = NULL;\n YaffsHeader * header = NULL;\n\n yaffscache_version_find_by_inode(yfs, inum, &version, &obj);\n\n if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {\n return 1;\n }\n fs_meta = fs_file->meta;\n\n tsk_fprintf(hFile, \"inode: %\" PRIuINUM \"\\n\", inum);\n tsk_fprintf(hFile, \"%sAllocated\\n\",\n (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? \"\" : \"Not \");\n\n if (fs_meta->link)\n tsk_fprintf(hFile, \"symbolic link to: %s\\n\", fs_meta->link);\n\n tsk_fprintf(hFile, \"uid / gid: %\" PRIuUID \" / %\" PRIuGID \"\\n\",\n fs_meta->uid, fs_meta->gid);\n\n tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls));\n tsk_fprintf(hFile, \"mode: %s\\n\", ls);\n\n tsk_fprintf(hFile, \"size: %\" PRIdOFF \"\\n\", fs_meta->size);\n tsk_fprintf(hFile, \"num of links: %d\\n\", fs_meta->nlink);\n\n if(version != NULL){\n yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset);\n if(header != NULL){\n tsk_fprintf(hFile, \"Name: %s\\n\", header->name);\n }\n }\n\n if (sec_skew != 0) {\n tsk_fprintf(hFile, \"\\nAdjusted Inode Times:\\n\");\n fs_meta->mtime -= sec_skew;\n fs_meta->atime -= sec_skew;\n fs_meta->ctime -= sec_skew;\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n fs_meta->mtime += sec_skew;\n fs_meta->atime += sec_skew;\n fs_meta->ctime += sec_skew;\n\n tsk_fprintf(hFile, \"\\nOriginal Inode Times:\\n\");\n }\n else {\n tsk_fprintf(hFile, \"\\nInode Times:\\n\");\n }\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n if(version != NULL){\n tsk_fprintf(hFile, \"\\nHeader Chunk:\\n\");\n tsk_fprintf(hFile, \"%\" PRIuDADDR \"\\n\", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size)));\n }\n\n if (numblock > 0) {\n TSK_OFF_T lower_size = numblock * fs->block_size;\n fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size);\n }\n tsk_fprintf(hFile, \"\\nData Chunks:\\n\");\n\n\n if (flags & TSK_FS_ISTAT_RUNLIST){\n const TSK_FS_ATTR *fs_attr_default =\n tsk_fs_file_attr_get_type(fs_file,\n TSK_FS_ATTR_TYPE_DEFAULT, 0, 0);\n if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) {\n if (tsk_fs_attr_print(fs_attr_default, hFile)) {\n tsk_fprintf(hFile, \"\\nError creating run lists \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n }\n }\n else {\n print.idx = 0;\n print.hFile = hFile;\n\n if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY,\n (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) {\n tsk_fprintf(hFile, \"\\nError reading file: \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n else if (print.idx != 0) {\n tsk_fprintf(hFile, \"\\n\");\n }\n }\n\n tsk_fs_file_close(fs_file);\n\n return 0;\n}", "func_hash": 3936166501063874287258359268898852151, "file_name": "yaffs.cpp", "file_hash": 109597880366059238586753072182866199148, "cwe": ["CWE-125"], "cve": "CVE-2020-10232", "cve_desc": "In version 4.8.0 and earlier of The Sleuth Kit (TSK), there is a stack buffer overflow vulnerability in the YAFFS file timestamp parsing logic in yaffsfs_istat() in fs/yaffs.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10232"} {"idx": 200109, "project": "libxml2", "commit_id": "5a02583c7e683896d84878bd90641d8d9b0d0549", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://gitlab.gnome.org/GNOME/libxml2/commit/5a02583c7e683896d84878bd90641d8d9b0d0549", "commit_message": "Fix memory leak in xmlParseBalancedChunkMemoryRecover\n\nWhen doc is NULL, namespace created in xmlTreeEnsureXMLDecl\nis bind to newDoc->oldNs, in this case, set newDoc->oldNs to\nNULL and free newDoc will cause a memory leak.\n\nFound with libFuzzer.\n\nCloses #82.", "target": 1, "func": "xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,\n void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst,\n int recover) {\n xmlParserCtxtPtr ctxt;\n xmlDocPtr newDoc;\n xmlSAXHandlerPtr oldsax = NULL;\n xmlNodePtr content, newRoot;\n int size;\n int ret = 0;\n\n if (depth > 40) {\n\treturn(XML_ERR_ENTITY_LOOP);\n }\n\n\n if (lst != NULL)\n *lst = NULL;\n if (string == NULL)\n return(-1);\n\n size = xmlStrlen(string);\n\n ctxt = xmlCreateMemoryParserCtxt((char *) string, size);\n if (ctxt == NULL) return(-1);\n ctxt->userData = ctxt;\n if (sax != NULL) {\n\toldsax = ctxt->sax;\n ctxt->sax = sax;\n\tif (user_data != NULL)\n\t ctxt->userData = user_data;\n }\n newDoc = xmlNewDoc(BAD_CAST \"1.0\");\n if (newDoc == NULL) {\n\txmlFreeParserCtxt(ctxt);\n\treturn(-1);\n }\n newDoc->properties = XML_DOC_INTERNAL;\n if ((doc != NULL) && (doc->dict != NULL)) {\n xmlDictFree(ctxt->dict);\n\tctxt->dict = doc->dict;\n\txmlDictReference(ctxt->dict);\n\tctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST \"xml\", 3);\n\tctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST \"xmlns\", 5);\n\tctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);\n\tctxt->dictNames = 1;\n } else {\n\txmlCtxtUseOptionsInternal(ctxt, XML_PARSE_NODICT, NULL);\n }\n if (doc != NULL) {\n\tnewDoc->intSubset = doc->intSubset;\n\tnewDoc->extSubset = doc->extSubset;\n }\n newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST \"pseudoroot\", NULL);\n if (newRoot == NULL) {\n\tif (sax != NULL)\n\t ctxt->sax = oldsax;\n\txmlFreeParserCtxt(ctxt);\n\tnewDoc->intSubset = NULL;\n\tnewDoc->extSubset = NULL;\n xmlFreeDoc(newDoc);\n\treturn(-1);\n }\n xmlAddChild((xmlNodePtr) newDoc, newRoot);\n nodePush(ctxt, newRoot);\n if (doc == NULL) {\n\tctxt->myDoc = newDoc;\n } else {\n\tctxt->myDoc = newDoc;\n\tnewDoc->children->doc = doc;\n\t/* Ensure that doc has XML spec namespace */\n\txmlSearchNsByHref(doc, (xmlNodePtr)doc, XML_XML_NAMESPACE);\n\tnewDoc->oldNs = doc->oldNs;\n }\n ctxt->instate = XML_PARSER_CONTENT;\n ctxt->input_id = 2;\n ctxt->depth = depth;\n\n /*\n * Doing validity checking on chunk doesn't make sense\n */\n ctxt->validate = 0;\n ctxt->loadsubset = 0;\n xmlDetectSAX2(ctxt);\n\n if ( doc != NULL ){\n content = doc->children;\n doc->children = NULL;\n xmlParseContent(ctxt);\n doc->children = content;\n }\n else {\n xmlParseContent(ctxt);\n }\n if ((RAW == '<') && (NXT(1) == '/')) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n } else if (RAW != 0) {\n\txmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);\n }\n if (ctxt->node != newDoc->children) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n }\n\n if (!ctxt->wellFormed) {\n if (ctxt->errNo == 0)\n\t ret = 1;\n\telse\n\t ret = ctxt->errNo;\n } else {\n ret = 0;\n }\n\n if ((lst != NULL) && ((ret == 0) || (recover == 1))) {\n\txmlNodePtr cur;\n\n\t/*\n\t * Return the newly created nodeset after unlinking it from\n\t * they pseudo parent.\n\t */\n\tcur = newDoc->children->children;\n\t*lst = cur;\n\twhile (cur != NULL) {\n\t xmlSetTreeDoc(cur, doc);\n\t cur->parent = NULL;\n\t cur = cur->next;\n\t}\n\tnewDoc->children->children = NULL;\n }\n\n if (sax != NULL)\n\tctxt->sax = oldsax;\n xmlFreeParserCtxt(ctxt);\n newDoc->intSubset = NULL;\n newDoc->extSubset = NULL;\n newDoc->oldNs = NULL;\n xmlFreeDoc(newDoc);\n\n return(ret);\n}", "func_hash": 136435035049957767071922037065629278679, "file_name": "parser.c", "file_hash": 36062316163357891541018473353621501529, "cwe": ["CWE-401"], "cve": "CVE-2019-19956", "cve_desc": "xmlParseBalancedChunkMemoryRecover in parser.c in libxml2 before 2.9.10 has a memory leak related to newDoc->oldNs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19956"} {"idx": 299179, "project": "libxml2", "commit_id": "5a02583c7e683896d84878bd90641d8d9b0d0549", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://gitlab.gnome.org/GNOME/libxml2/commit/5a02583c7e683896d84878bd90641d8d9b0d0549", "commit_message": "Fix memory leak in xmlParseBalancedChunkMemoryRecover\n\nWhen doc is NULL, namespace created in xmlTreeEnsureXMLDecl\nis bind to newDoc->oldNs, in this case, set newDoc->oldNs to\nNULL and free newDoc will cause a memory leak.\n\nFound with libFuzzer.\n\nCloses #82.", "target": 0, "func": "xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,\n void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst,\n int recover) {\n xmlParserCtxtPtr ctxt;\n xmlDocPtr newDoc;\n xmlSAXHandlerPtr oldsax = NULL;\n xmlNodePtr content, newRoot;\n int size;\n int ret = 0;\n\n if (depth > 40) {\n\treturn(XML_ERR_ENTITY_LOOP);\n }\n\n\n if (lst != NULL)\n *lst = NULL;\n if (string == NULL)\n return(-1);\n\n size = xmlStrlen(string);\n\n ctxt = xmlCreateMemoryParserCtxt((char *) string, size);\n if (ctxt == NULL) return(-1);\n ctxt->userData = ctxt;\n if (sax != NULL) {\n\toldsax = ctxt->sax;\n ctxt->sax = sax;\n\tif (user_data != NULL)\n\t ctxt->userData = user_data;\n }\n newDoc = xmlNewDoc(BAD_CAST \"1.0\");\n if (newDoc == NULL) {\n\txmlFreeParserCtxt(ctxt);\n\treturn(-1);\n }\n newDoc->properties = XML_DOC_INTERNAL;\n if ((doc != NULL) && (doc->dict != NULL)) {\n xmlDictFree(ctxt->dict);\n\tctxt->dict = doc->dict;\n\txmlDictReference(ctxt->dict);\n\tctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST \"xml\", 3);\n\tctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST \"xmlns\", 5);\n\tctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);\n\tctxt->dictNames = 1;\n } else {\n\txmlCtxtUseOptionsInternal(ctxt, XML_PARSE_NODICT, NULL);\n }\n if (doc != NULL) {\n\tnewDoc->intSubset = doc->intSubset;\n\tnewDoc->extSubset = doc->extSubset;\n }\n newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST \"pseudoroot\", NULL);\n if (newRoot == NULL) {\n\tif (sax != NULL)\n\t ctxt->sax = oldsax;\n\txmlFreeParserCtxt(ctxt);\n\tnewDoc->intSubset = NULL;\n\tnewDoc->extSubset = NULL;\n xmlFreeDoc(newDoc);\n\treturn(-1);\n }\n xmlAddChild((xmlNodePtr) newDoc, newRoot);\n nodePush(ctxt, newRoot);\n if (doc == NULL) {\n\tctxt->myDoc = newDoc;\n } else {\n\tctxt->myDoc = newDoc;\n\tnewDoc->children->doc = doc;\n\t/* Ensure that doc has XML spec namespace */\n\txmlSearchNsByHref(doc, (xmlNodePtr)doc, XML_XML_NAMESPACE);\n\tnewDoc->oldNs = doc->oldNs;\n }\n ctxt->instate = XML_PARSER_CONTENT;\n ctxt->input_id = 2;\n ctxt->depth = depth;\n\n /*\n * Doing validity checking on chunk doesn't make sense\n */\n ctxt->validate = 0;\n ctxt->loadsubset = 0;\n xmlDetectSAX2(ctxt);\n\n if ( doc != NULL ){\n content = doc->children;\n doc->children = NULL;\n xmlParseContent(ctxt);\n doc->children = content;\n }\n else {\n xmlParseContent(ctxt);\n }\n if ((RAW == '<') && (NXT(1) == '/')) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n } else if (RAW != 0) {\n\txmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);\n }\n if (ctxt->node != newDoc->children) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n }\n\n if (!ctxt->wellFormed) {\n if (ctxt->errNo == 0)\n\t ret = 1;\n\telse\n\t ret = ctxt->errNo;\n } else {\n ret = 0;\n }\n\n if ((lst != NULL) && ((ret == 0) || (recover == 1))) {\n\txmlNodePtr cur;\n\n\t/*\n\t * Return the newly created nodeset after unlinking it from\n\t * they pseudo parent.\n\t */\n\tcur = newDoc->children->children;\n\t*lst = cur;\n\twhile (cur != NULL) {\n\t xmlSetTreeDoc(cur, doc);\n\t cur->parent = NULL;\n\t cur = cur->next;\n\t}\n\tnewDoc->children->children = NULL;\n }\n\n if (sax != NULL)\n\tctxt->sax = oldsax;\n xmlFreeParserCtxt(ctxt);\n newDoc->intSubset = NULL;\n newDoc->extSubset = NULL;\n if(doc != NULL)\n\tnewDoc->oldNs = NULL;\n xmlFreeDoc(newDoc);\n\n return(ret);\n}", "func_hash": 89505202099799774002130053838916739399, "file_name": "parser.c", "file_hash": 94749456943421859029117488228902722018, "cwe": ["CWE-401"], "cve": "CVE-2019-19956", "cve_desc": "xmlParseBalancedChunkMemoryRecover in parser.c in libxml2 before 2.9.10 has a memory leak related to newDoc->oldNs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19956"} {"idx": 200327, "project": "php-src", "commit_id": "0a8f28b43212cc2ddbc1f2df710e37b1bec0addd", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=0a8f28b43212cc2ddbc1f2df710e37b1bec0addd", "commit_message": "Fixed bug #68677 (Use After Free in OPcache)\n\n(cherry picked from commit 777c39f4042327eac4b63c7ee87dc1c7a09a3115)", "target": 1, "func": "void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source TSRMLS_DC)\n{\n\tvoid **old_p, *retval;\n\n\tif (zend_hash_index_find(&xlat_table, (ulong)source, (void **)&old_p) == SUCCESS) {\n\t\t/* we already duplicated this pointer */\n\t\treturn *old_p;\n\t}\n\tretval = ZCG(mem);;\n\tZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size));\n\tmemcpy(retval, source, size);\n\tif (free_source) {\n\t\tinterned_efree((char*)source);\n\t}\n\tzend_shared_alloc_register_xlat_entry(source, retval);\n\treturn retval;\n}", "func_hash": 17768246758959610132321916033440736481, "file_name": "zend_shared_alloc.c", "file_hash": 289857511524402435551459454830826162233, "cwe": ["CWE-416"], "cve": "CVE-2015-1351", "cve_desc": "Use-after-free vulnerability in the _zend_shared_memdup function in zend_shared_alloc.c in the OPcache extension in PHP through 5.6.7 allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-1351"} {"idx": 301530, "project": "php-src", "commit_id": "0a8f28b43212cc2ddbc1f2df710e37b1bec0addd", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=0a8f28b43212cc2ddbc1f2df710e37b1bec0addd", "commit_message": "Fixed bug #68677 (Use After Free in OPcache)\n\n(cherry picked from commit 777c39f4042327eac4b63c7ee87dc1c7a09a3115)", "target": 0, "func": "void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source TSRMLS_DC)\n{\n\tvoid **old_p, *retval;\n\n\tif (zend_hash_index_find(&xlat_table, (ulong)source, (void **)&old_p) == SUCCESS) {\n\t\t/* we already duplicated this pointer */\n\t\treturn *old_p;\n\t}\n\tretval = ZCG(mem);;\n\tZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size));\n\tmemcpy(retval, source, size);\n\tzend_shared_alloc_register_xlat_entry(source, retval);\n\tif (free_source) {\n\t\tinterned_efree((char*)source);\n\t}\n\treturn retval;\n}", "func_hash": 215243459894091856292675742843447579835, "file_name": "zend_shared_alloc.c", "file_hash": 146039954277126663166115420983339222537, "cwe": ["CWE-416"], "cve": "CVE-2015-1351", "cve_desc": "Use-after-free vulnerability in the _zend_shared_memdup function in zend_shared_alloc.c in the OPcache extension in PHP through 5.6.7 allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-1351"} {"idx": 200381, "project": "libxml2", "commit_id": "bf22713507fe1fc3a2c4b525cf0a88c2dc87a3a2", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://gitlab.gnome.org/GNOME/libxml2/-/commit/bf22713507fe1fc3a2c4b525cf0a88c2dc87a3a2", "commit_message": "Validate UTF8 in xmlEncodeEntities\n\nCode is currently assuming UTF-8 without validating. Truncated UTF-8\ninput can cause out-of-bounds array access.\n\nAdds further checks to partial fix in 50f06b3e.\n\nFixes #178", "target": 1, "func": "xmlEncodeEntitiesInternal(xmlDocPtr doc, const xmlChar *input, int attr) {\n const xmlChar *cur = input;\n xmlChar *buffer = NULL;\n xmlChar *out = NULL;\n size_t buffer_size = 0;\n int html = 0;\n\n if (input == NULL) return(NULL);\n if (doc != NULL)\n html = (doc->type == XML_HTML_DOCUMENT_NODE);\n\n /*\n * allocate an translation buffer.\n */\n buffer_size = 1000;\n buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar));\n if (buffer == NULL) {\n xmlEntitiesErrMemory(\"xmlEncodeEntities: malloc failed\");\n\treturn(NULL);\n }\n out = buffer;\n\n while (*cur != '\\0') {\n size_t indx = out - buffer;\n if (indx + 100 > buffer_size) {\n\n\t growBufferReentrant();\n\t out = &buffer[indx];\n\t}\n\n\t/*\n\t * By default one have to encode at least '<', '>', '\"' and '&' !\n\t */\n\tif (*cur == '<') {\n\t const xmlChar *end;\n\n\t /*\n\t * Special handling of server side include in HTML attributes\n\t */\n\t if (html && attr &&\n\t (cur[1] == '!') && (cur[2] == '-') && (cur[3] == '-') &&\n\t ((end = xmlStrstr(cur, BAD_CAST \"-->\")) != NULL)) {\n\t while (cur != end) {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'l';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '>') {\n\t *out++ = '&';\n\t *out++ = 'g';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '&') {\n\t /*\n\t * Special handling of &{...} construct from HTML 4, see\n\t * http://www.w3.org/TR/html401/appendix/notes.html#h-B.7.1\n\t */\n\t if (html && attr && (cur[1] == '{') &&\n\t (strchr((const char *) cur, '}'))) {\n\t while (*cur != '}') {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'a';\n\t *out++ = 'm';\n\t *out++ = 'p';\n\t *out++ = ';';\n\t} else if (((*cur >= 0x20) && (*cur < 0x80)) ||\n\t (*cur == '\\n') || (*cur == '\\t') || ((html) && (*cur == '\\r'))) {\n\t /*\n\t * default case, just copy !\n\t */\n\t *out++ = *cur;\n\t} else if (*cur >= 0x80) {\n\t if (((doc != NULL) && (doc->encoding != NULL)) || (html)) {\n\t\t/*\n\t\t * Bj\u00f8rn Reese provided the patch\n\t xmlChar xc;\n\t xc = (*cur & 0x3F) << 6;\n\t if (cur[1] != 0) {\n\t\t xc += *(++cur) & 0x3F;\n\t\t *out++ = xc;\n\t } else\n\t\t */\n\t\t*out++ = *cur;\n\t } else {\n\t\t/*\n\t\t * We assume we have UTF-8 input.\n\t\t */\n\t\tchar buf[11], *ptr;\n\t\tint val = 0, l = 1;\n\n\t\tif (*cur < 0xC0) {\n\t\t xmlEntitiesErr(XML_CHECK_NOT_UTF8,\n\t\t\t \"xmlEncodeEntities: input not UTF-8\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t} else if (*cur < 0xE0) {\n val = (cur[0]) & 0x1F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t l = 2;\n\t\t} else if (*cur < 0xF0) {\n val = (cur[0]) & 0x0F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t l = 3;\n\t\t} else if (*cur < 0xF8) {\n val = (cur[0]) & 0x07;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[3]) & 0x3F;\n\t\t l = 4;\n\t\t}\n\t\tif ((l == 1) || (!IS_CHAR(val))) {\n\t\t xmlEntitiesErr(XML_ERR_INVALID_CHAR,\n\t\t\t\"xmlEncodeEntities: char out of range\\n\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t}\n\t\t/*\n\t\t * We could do multiple things here. Just save as a char ref\n\t\t */\n\t\tsnprintf(buf, sizeof(buf), \"&#x%X;\", val);\n\t\tbuf[sizeof(buf) - 1] = 0;\n\t\tptr = buf;\n\t\twhile (*ptr != 0) *out++ = *ptr++;\n\t\tcur += l;\n\t\tcontinue;\n\t }\n\t} else if (IS_BYTE_CHAR(*cur)) {\n\t char buf[11], *ptr;\n\n\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t buf[sizeof(buf) - 1] = 0;\n ptr = buf;\n\t while (*ptr != 0) *out++ = *ptr++;\n\t}\n\tcur++;\n }\n *out = 0;\n return(buffer);\n\nmem_error:\n xmlEntitiesErrMemory(\"xmlEncodeEntities: realloc failed\");\n xmlFree(buffer);\n return(NULL);\n}", "func_hash": 310682276665054082113621031069113208608, "file_name": "entities.c", "file_hash": 175880634662023636292931347840570376698, "cwe": ["CWE-787"], "cve": "CVE-2021-3517", "cve_desc": "There is a flaw in the xml entity encoding functionality of libxml2 in versions before 2.9.11. An attacker who is able to supply a crafted file to be processed by an application linked with the affected functionality of libxml2 could trigger an out-of-bounds read. The most likely impact of this flaw is to application availability, with some potential impact to confidentiality and integrity if an attacker is able to use memory information to further exploit the application.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3517"} {"idx": 302155, "project": "libxml2", "commit_id": "bf22713507fe1fc3a2c4b525cf0a88c2dc87a3a2", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://gitlab.gnome.org/GNOME/libxml2/-/commit/bf22713507fe1fc3a2c4b525cf0a88c2dc87a3a2", "commit_message": "Validate UTF8 in xmlEncodeEntities\n\nCode is currently assuming UTF-8 without validating. Truncated UTF-8\ninput can cause out-of-bounds array access.\n\nAdds further checks to partial fix in 50f06b3e.\n\nFixes #178", "target": 0, "func": "xmlEncodeEntitiesInternal(xmlDocPtr doc, const xmlChar *input, int attr) {\n const xmlChar *cur = input;\n xmlChar *buffer = NULL;\n xmlChar *out = NULL;\n size_t buffer_size = 0;\n int html = 0;\n\n if (input == NULL) return(NULL);\n if (doc != NULL)\n html = (doc->type == XML_HTML_DOCUMENT_NODE);\n\n /*\n * allocate an translation buffer.\n */\n buffer_size = 1000;\n buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar));\n if (buffer == NULL) {\n xmlEntitiesErrMemory(\"xmlEncodeEntities: malloc failed\");\n\treturn(NULL);\n }\n out = buffer;\n\n while (*cur != '\\0') {\n size_t indx = out - buffer;\n if (indx + 100 > buffer_size) {\n\n\t growBufferReentrant();\n\t out = &buffer[indx];\n\t}\n\n\t/*\n\t * By default one have to encode at least '<', '>', '\"' and '&' !\n\t */\n\tif (*cur == '<') {\n\t const xmlChar *end;\n\n\t /*\n\t * Special handling of server side include in HTML attributes\n\t */\n\t if (html && attr &&\n\t (cur[1] == '!') && (cur[2] == '-') && (cur[3] == '-') &&\n\t ((end = xmlStrstr(cur, BAD_CAST \"-->\")) != NULL)) {\n\t while (cur != end) {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'l';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '>') {\n\t *out++ = '&';\n\t *out++ = 'g';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '&') {\n\t /*\n\t * Special handling of &{...} construct from HTML 4, see\n\t * http://www.w3.org/TR/html401/appendix/notes.html#h-B.7.1\n\t */\n\t if (html && attr && (cur[1] == '{') &&\n\t (strchr((const char *) cur, '}'))) {\n\t while (*cur != '}') {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'a';\n\t *out++ = 'm';\n\t *out++ = 'p';\n\t *out++ = ';';\n\t} else if (((*cur >= 0x20) && (*cur < 0x80)) ||\n\t (*cur == '\\n') || (*cur == '\\t') || ((html) && (*cur == '\\r'))) {\n\t /*\n\t * default case, just copy !\n\t */\n\t *out++ = *cur;\n\t} else if (*cur >= 0x80) {\n\t if (((doc != NULL) && (doc->encoding != NULL)) || (html)) {\n\t\t/*\n\t\t * Bj\u00f8rn Reese provided the patch\n\t xmlChar xc;\n\t xc = (*cur & 0x3F) << 6;\n\t if (cur[1] != 0) {\n\t\t xc += *(++cur) & 0x3F;\n\t\t *out++ = xc;\n\t } else\n\t\t */\n\t\t*out++ = *cur;\n\t } else {\n\t\t/*\n\t\t * We assume we have UTF-8 input.\n\t\t * It must match either:\n\t\t * 110xxxxx 10xxxxxx\n\t\t * 1110xxxx 10xxxxxx 10xxxxxx\n\t\t * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\t\t * That is:\n\t\t * cur[0] is 11xxxxxx\n\t\t * cur[1] is 10xxxxxx\n\t\t * cur[2] is 10xxxxxx if cur[0] is 111xxxxx\n\t\t * cur[3] is 10xxxxxx if cur[0] is 1111xxxx\n\t\t * cur[0] is not 11111xxx\n\t\t */\n\t\tchar buf[11], *ptr;\n\t\tint val = 0, l = 1;\n\n\t\tif (((cur[0] & 0xC0) != 0xC0) ||\n\t\t ((cur[1] & 0xC0) != 0x80) ||\n\t\t (((cur[0] & 0xE0) == 0xE0) && ((cur[2] & 0xC0) != 0x80)) ||\n\t\t (((cur[0] & 0xF0) == 0xF0) && ((cur[3] & 0xC0) != 0x80)) ||\n\t\t (((cur[0] & 0xF8) == 0xF8))) {\n\t\t xmlEntitiesErr(XML_CHECK_NOT_UTF8,\n\t\t\t \"xmlEncodeEntities: input not UTF-8\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t} else if (*cur < 0xE0) {\n val = (cur[0]) & 0x1F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t l = 2;\n\t\t} else if (*cur < 0xF0) {\n val = (cur[0]) & 0x0F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t l = 3;\n\t\t} else if (*cur < 0xF8) {\n val = (cur[0]) & 0x07;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[3]) & 0x3F;\n\t\t l = 4;\n\t\t}\n\t\tif ((l == 1) || (!IS_CHAR(val))) {\n\t\t xmlEntitiesErr(XML_ERR_INVALID_CHAR,\n\t\t\t\"xmlEncodeEntities: char out of range\\n\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t}\n\t\t/*\n\t\t * We could do multiple things here. Just save as a char ref\n\t\t */\n\t\tsnprintf(buf, sizeof(buf), \"&#x%X;\", val);\n\t\tbuf[sizeof(buf) - 1] = 0;\n\t\tptr = buf;\n\t\twhile (*ptr != 0) *out++ = *ptr++;\n\t\tcur += l;\n\t\tcontinue;\n\t }\n\t} else if (IS_BYTE_CHAR(*cur)) {\n\t char buf[11], *ptr;\n\n\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t buf[sizeof(buf) - 1] = 0;\n ptr = buf;\n\t while (*ptr != 0) *out++ = *ptr++;\n\t}\n\tcur++;\n }\n *out = 0;\n return(buffer);\n\nmem_error:\n xmlEntitiesErrMemory(\"xmlEncodeEntities: realloc failed\");\n xmlFree(buffer);\n return(NULL);\n}", "func_hash": 163601582764118669413346225710757787967, "file_name": "entities.c", "file_hash": 271360069297698071462560919549381537695, "cwe": ["CWE-787"], "cve": "CVE-2021-3517", "cve_desc": "There is a flaw in the xml entity encoding functionality of libxml2 in versions before 2.9.11. An attacker who is able to supply a crafted file to be processed by an application linked with the affected functionality of libxml2 could trigger an out-of-bounds read. The most likely impact of this flaw is to application availability, with some potential impact to confidentiality and integrity if an attacker is able to use memory information to further exploit the application.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3517"} {"idx": 200413, "project": "389-ds-base", "commit_id": "2e5b526012612d1d6ccace46398bee679a730271", "project_url": "https://github.com/389ds/389-ds-base", "commit_url": "https://github.com/389ds/389-ds-base/commit/2e5b526012612d1d6ccace46398bee679a730271", "commit_message": "Issue 4711 - SIGSEV with sync_repl (#4738)\n\nBug description:\n\tsync_repl sends back entries identified with a unique\n\tidentifier that is 'nsuniqueid'. If 'nsuniqueid' is\n\tmissing, then it may crash\n\nFix description:\n\tCheck a nsuniqueid is available else returns OP_ERR\n\nrelates: https://github.com/389ds/389-ds-base/issues/4711\n\nReviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!)\n\nPlatforms tested: F33", "target": 1, "func": "sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie)\n{\n int rc;\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n Slapi_Attr *attr;\n Slapi_Value *val;\n\n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = NULL;\n\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n if ((rc = ber_printf(ber, \"{eo\", type, uuid, 16)) != -1) {\n if (cookie) {\n char *cookiestr = sync_cookie2str(cookie);\n rc = ber_printf(ber, \"s}\", cookiestr);\n slapi_ch_free((void **)&cookiestr);\n } else {\n rc = ber_printf(ber, \"}\");\n }\n }\n if (rc != -1) {\n rc = ber_flatten(ber, &bvp);\n }\n ber_free(ber, 1);\n slapi_ch_free((void **)&uuid);\n\n if (rc == -1) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl));\n (*ctrlp)->ldctl_iscritical = 0;\n (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE);\n (*ctrlp)->ldctl_value = *bvp; /* struct copy */\n\n bvp->bv_val = NULL;\n ber_bvfree(bvp);\n\n return (LDAP_SUCCESS);\n}", "func_hash": 110726464127124093063399856853884546982, "file_name": "sync_util.c", "file_hash": 218263701701128163956572134774631501370, "cwe": ["CWE-476"], "cve": "CVE-2021-3514", "cve_desc": "When using a sync_repl client in 389-ds-base, an authenticated attacker can cause a NULL pointer dereference using a specially crafted query, causing a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3514"} {"idx": 302826, "project": "389-ds-base", "commit_id": "2e5b526012612d1d6ccace46398bee679a730271", "project_url": "https://github.com/389ds/389-ds-base", "commit_url": "https://github.com/389ds/389-ds-base/commit/2e5b526012612d1d6ccace46398bee679a730271", "commit_message": "Issue 4711 - SIGSEV with sync_repl (#4738)\n\nBug description:\n\tsync_repl sends back entries identified with a unique\n\tidentifier that is 'nsuniqueid'. If 'nsuniqueid' is\n\tmissing, then it may crash\n\nFix description:\n\tCheck a nsuniqueid is available else returns OP_ERR\n\nrelates: https://github.com/389ds/389-ds-base/issues/4711\n\nReviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!)\n\nPlatforms tested: F33", "target": 0, "func": "sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie)\n{\n int rc;\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n Slapi_Attr *attr = NULL;\n Slapi_Value *val = NULL;\n\n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = NULL;\n\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n if ((attr == NULL) || (val == NULL)) {\n /* It may happen with entries in special backends\n * such like cn=config, cn=shema, cn=monitor...\n */\n slapi_log_err(SLAPI_LOG_ERR, SYNC_PLUGIN_SUBSYSTEM,\n\t\t \"sync_create_state_control - Entries are missing nsuniqueid. Unable to proceed.\\n\");\n return (LDAP_OPERATIONS_ERROR);\n }\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n if ((rc = ber_printf(ber, \"{eo\", type, uuid, 16)) != -1) {\n if (cookie) {\n char *cookiestr = sync_cookie2str(cookie);\n rc = ber_printf(ber, \"s}\", cookiestr);\n slapi_ch_free((void **)&cookiestr);\n } else {\n rc = ber_printf(ber, \"}\");\n }\n }\n if (rc != -1) {\n rc = ber_flatten(ber, &bvp);\n }\n ber_free(ber, 1);\n slapi_ch_free((void **)&uuid);\n\n if (rc == -1) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl));\n (*ctrlp)->ldctl_iscritical = 0;\n (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE);\n (*ctrlp)->ldctl_value = *bvp; /* struct copy */\n\n bvp->bv_val = NULL;\n ber_bvfree(bvp);\n\n return (LDAP_SUCCESS);\n}", "func_hash": 293169324599919152537369805566756188991, "file_name": "sync_util.c", "file_hash": 30507893687761669352900151740869906774, "cwe": ["CWE-476"], "cve": "CVE-2021-3514", "cve_desc": "When using a sync_repl client in 389-ds-base, an authenticated attacker can cause a NULL pointer dereference using a specially crafted query, causing a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3514"} {"idx": 200450, "project": "c-blosc2", "commit_id": "c4c6470e88210afc95262c8b9fcc27e30ca043ee", "project_url": "https://github.com/Blosc/c-blosc2", "commit_url": "https://github.com/Blosc/c-blosc2/commit/c4c6470e88210afc95262c8b9fcc27e30ca043ee", "commit_message": "Fixed asan heap buffer overflow when not enough space to write compressed block size.", "target": 1, "func": "static int blosc_c(struct thread_context* thread_context, int32_t bsize,\n int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes,\n const uint8_t* src, const int32_t offset, uint8_t* dest,\n uint8_t* tmp, uint8_t* tmp2) {\n blosc2_context* context = thread_context->parent_context;\n int dont_split = (context->header_flags & 0x10) >> 4;\n int dict_training = context->use_dict && context->dict_cdict == NULL;\n int32_t j, neblock, nstreams;\n int32_t cbytes; /* number of compressed bytes in split */\n int32_t ctbytes = 0; /* number of compressed bytes in block */\n int64_t maxout;\n int32_t typesize = context->typesize;\n const char* compname;\n int accel;\n const uint8_t* _src;\n uint8_t *_tmp = tmp, *_tmp2 = tmp2;\n uint8_t *_tmp3 = thread_context->tmp4;\n int last_filter_index = last_filter(context->filters, 'c');\n bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED;\n\n if (last_filter_index >= 0 || context->prefilter != NULL) {\n /* Apply the filter pipeline just for the prefilter */\n if (memcpyed && context->prefilter != NULL) {\n // We only need the prefilter output\n _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n return bsize;\n }\n /* Apply regular filter pipeline */\n _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n } else {\n _src = src + offset;\n }\n\n assert(context->clevel > 0);\n\n /* Calculate acceleration for different compressors */\n accel = get_accel(context);\n\n /* The number of compressed data streams for this block */\n if (!dont_split && !leftoverblock && !dict_training) {\n nstreams = (int32_t)typesize;\n }\n else {\n nstreams = 1;\n }\n neblock = bsize / nstreams;\n for (j = 0; j < nstreams; j++) {\n if (!dict_training) {\n dest += sizeof(int32_t);\n ntbytes += sizeof(int32_t);\n ctbytes += sizeof(int32_t);\n }\n\n // See if we have a run here\n const uint8_t* ip = (uint8_t*)_src + j * neblock;\n const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock;\n if (get_run(ip, ipbound)) {\n // A run. Encode the repeated byte as a negative length in the length of the split.\n int32_t value = _src[j * neblock];\n _sw32(dest - 4, -value);\n continue;\n }\n\n maxout = neblock;\n #if defined(HAVE_SNAPPY)\n if (context->compcode == BLOSC_SNAPPY) {\n maxout = (int32_t)snappy_max_compressed_length((size_t)neblock);\n }\n #endif /* HAVE_SNAPPY */\n if (ntbytes + maxout > maxbytes) {\n /* avoid buffer * overrun */\n maxout = (int64_t)maxbytes - (int64_t)ntbytes;\n if (maxout <= 0) {\n return 0; /* non-compressible block */\n }\n }\n if (dict_training) {\n // We are in the build dict state, so don't compress\n // TODO: copy only a percentage for sampling\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = (int32_t)neblock;\n }\n else if (context->compcode == BLOSC_BLOSCLZ) {\n cbytes = blosclz_compress(context->clevel, _src + j * neblock,\n (int)neblock, dest, (int)maxout);\n }\n #if defined(HAVE_LZ4)\n else if (context->compcode == BLOSC_LZ4) {\n void *hash_table = NULL;\n #ifdef HAVE_IPP\n hash_table = (void*)thread_context->lz4_hash_table;\n #endif\n cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel, hash_table);\n }\n else if (context->compcode == BLOSC_LZ4HC) {\n cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_LZ4 */\n #if defined(HAVE_LIZARD)\n else if (context->compcode == BLOSC_LIZARD) {\n cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel);\n }\n #endif /* HAVE_LIZARD */\n #if defined(HAVE_SNAPPY)\n else if (context->compcode == BLOSC_SNAPPY) {\n cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout);\n }\n #endif /* HAVE_SNAPPY */\n #if defined(HAVE_ZLIB)\n else if (context->compcode == BLOSC_ZLIB) {\n cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZLIB */\n #if defined(HAVE_ZSTD)\n else if (context->compcode == BLOSC_ZSTD) {\n cbytes = zstd_wrap_compress(thread_context,\n (char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZSTD */\n\n else {\n blosc_compcode_to_compname(context->compcode, &compname);\n fprintf(stderr, \"Blosc has not been compiled with '%s' \", compname);\n fprintf(stderr, \"compression support. Please use one having it.\");\n return -5; /* signals no compression support */\n }\n\n if (cbytes > maxout) {\n /* Buffer overrun caused by compression (should never happen) */\n return -1;\n }\n if (cbytes < 0) {\n /* cbytes should never be negative */\n return -2;\n }\n if (!dict_training) {\n if (cbytes == 0 || cbytes == neblock) {\n /* The compressor has been unable to compress data at all. */\n /* Before doing the copy, check that we are not running into a\n buffer overflow. */\n if ((ntbytes + neblock) > maxbytes) {\n return 0; /* Non-compressible data */\n }\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = neblock;\n }\n _sw32(dest - 4, cbytes);\n }\n dest += cbytes;\n ntbytes += cbytes;\n ctbytes += cbytes;\n } /* Closes j < nstreams */\n\n //printf(\"c%d\", ctbytes);\n return ctbytes;\n}", "func_hash": 153008353506829764039961684614721484126, "file_name": "blosc2.c", "file_hash": 331917798945165920464521464550552016978, "cwe": ["CWE-787"], "cve": "CVE-2020-29367", "cve_desc": "blosc2.c in Blosc C-Blosc2 through 2.0.0.beta.5 has a heap-based buffer overflow when there is a lack of space to write compressed data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29367"} {"idx": 303085, "project": "c-blosc2", "commit_id": "c4c6470e88210afc95262c8b9fcc27e30ca043ee", "project_url": "https://github.com/Blosc/c-blosc2", "commit_url": "https://github.com/Blosc/c-blosc2/commit/c4c6470e88210afc95262c8b9fcc27e30ca043ee", "commit_message": "Fixed asan heap buffer overflow when not enough space to write compressed block size.", "target": 0, "func": "static int blosc_c(struct thread_context* thread_context, int32_t bsize,\n int32_t leftoverblock, int32_t ntbytes, int32_t destsize,\n const uint8_t* src, const int32_t offset, uint8_t* dest,\n uint8_t* tmp, uint8_t* tmp2) {\n blosc2_context* context = thread_context->parent_context;\n int dont_split = (context->header_flags & 0x10) >> 4;\n int dict_training = context->use_dict && context->dict_cdict == NULL;\n int32_t j, neblock, nstreams;\n int32_t cbytes; /* number of compressed bytes in split */\n int32_t ctbytes = 0; /* number of compressed bytes in block */\n int64_t maxout;\n int32_t typesize = context->typesize;\n const char* compname;\n int accel;\n const uint8_t* _src;\n uint8_t *_tmp = tmp, *_tmp2 = tmp2;\n uint8_t *_tmp3 = thread_context->tmp4;\n int last_filter_index = last_filter(context->filters, 'c');\n bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED;\n\n if (last_filter_index >= 0 || context->prefilter != NULL) {\n /* Apply the filter pipeline just for the prefilter */\n if (memcpyed && context->prefilter != NULL) {\n // We only need the prefilter output\n _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n return bsize;\n }\n /* Apply regular filter pipeline */\n _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n } else {\n _src = src + offset;\n }\n\n assert(context->clevel > 0);\n\n /* Calculate acceleration for different compressors */\n accel = get_accel(context);\n\n /* The number of compressed data streams for this block */\n if (!dont_split && !leftoverblock && !dict_training) {\n nstreams = (int32_t)typesize;\n }\n else {\n nstreams = 1;\n }\n neblock = bsize / nstreams;\n for (j = 0; j < nstreams; j++) {\n if (!dict_training) {\n dest += sizeof(int32_t);\n ntbytes += sizeof(int32_t);\n ctbytes += sizeof(int32_t);\n }\n\n // See if we have a run here\n const uint8_t* ip = (uint8_t*)_src + j * neblock;\n const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock;\n if (get_run(ip, ipbound)) {\n // A run. Encode the repeated byte as a negative length in the length of the split.\n int32_t value = _src[j * neblock];\n if (ntbytes > destsize) {\n /* Not enough space to write out compressed block size */\n return -1;\n }\n _sw32(dest - 4, -value);\n continue;\n }\n\n maxout = neblock;\n #if defined(HAVE_SNAPPY)\n if (context->compcode == BLOSC_SNAPPY) {\n maxout = (int32_t)snappy_max_compressed_length((size_t)neblock);\n }\n #endif /* HAVE_SNAPPY */\n if (ntbytes + maxout > destsize) {\n /* avoid buffer * overrun */\n maxout = (int64_t)destsize - (int64_t)ntbytes;\n if (maxout <= 0) {\n return 0; /* non-compressible block */\n }\n }\n if (dict_training) {\n // We are in the build dict state, so don't compress\n // TODO: copy only a percentage for sampling\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = (int32_t)neblock;\n }\n else if (context->compcode == BLOSC_BLOSCLZ) {\n cbytes = blosclz_compress(context->clevel, _src + j * neblock,\n (int)neblock, dest, (int)maxout);\n }\n #if defined(HAVE_LZ4)\n else if (context->compcode == BLOSC_LZ4) {\n void *hash_table = NULL;\n #ifdef HAVE_IPP\n hash_table = (void*)thread_context->lz4_hash_table;\n #endif\n cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel, hash_table);\n }\n else if (context->compcode == BLOSC_LZ4HC) {\n cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_LZ4 */\n #if defined(HAVE_LIZARD)\n else if (context->compcode == BLOSC_LIZARD) {\n cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel);\n }\n #endif /* HAVE_LIZARD */\n #if defined(HAVE_SNAPPY)\n else if (context->compcode == BLOSC_SNAPPY) {\n cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout);\n }\n #endif /* HAVE_SNAPPY */\n #if defined(HAVE_ZLIB)\n else if (context->compcode == BLOSC_ZLIB) {\n cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZLIB */\n #if defined(HAVE_ZSTD)\n else if (context->compcode == BLOSC_ZSTD) {\n cbytes = zstd_wrap_compress(thread_context,\n (char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZSTD */\n\n else {\n blosc_compcode_to_compname(context->compcode, &compname);\n fprintf(stderr, \"Blosc has not been compiled with '%s' \", compname);\n fprintf(stderr, \"compression support. Please use one having it.\");\n return -5; /* signals no compression support */\n }\n\n if (cbytes > maxout) {\n /* Buffer overrun caused by compression (should never happen) */\n return -1;\n }\n if (cbytes < 0) {\n /* cbytes should never be negative */\n return -2;\n }\n if (!dict_training) {\n if (cbytes == 0 || cbytes == neblock) {\n /* The compressor has been unable to compress data at all. */\n /* Before doing the copy, check that we are not running into a\n buffer overflow. */\n if ((ntbytes + neblock) > destsize) {\n return 0; /* Non-compressible data */\n }\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = neblock;\n }\n _sw32(dest - 4, cbytes);\n }\n dest += cbytes;\n ntbytes += cbytes;\n ctbytes += cbytes;\n } /* Closes j < nstreams */\n\n //printf(\"c%d\", ctbytes);\n return ctbytes;\n}", "func_hash": 115516254152514051219505653860288086591, "file_name": "blosc2.c", "file_hash": 71255240756088001732314900901556283516, "cwe": ["CWE-787"], "cve": "CVE-2020-29367", "cve_desc": "blosc2.c in Blosc C-Blosc2 through 2.0.0.beta.5 has a heap-based buffer overflow when there is a lack of space to write compressed data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29367"} {"idx": 200462, "project": "gnutls", "commit_id": "21f89efad7014a5ee0debd4cd3d59e27774b29e6", "project_url": "http://git.savannah.gnu.org/cgit/gnutls", "commit_url": "https://gitlab.com/gnutls/gnutls/commit/21f89efad7014a5ee0debd4cd3d59e27774b29e6", "commit_message": "handshake: add FALLBACK_SCSV priority option\n\nThis allows clients to enable the TLS_FALLBACK_SCSV mechanism during\nthe handshake, as defined in RFC7507.", "target": 1, "func": "copy_ciphersuites(gnutls_session_t session,\n\t\t gnutls_buffer_st * cdata, int add_scsv)\n{\n\tint ret;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE + 2]; /* allow space for SCSV */\n\tint cipher_suites_size;\n\tsize_t init_length = cdata->length;\n\n\tret =\n\t _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t sizeof(cipher_suites) - 2);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (eg SRP).\n\t */\n\tret =\n\t _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t ret, NULL, 0);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* If no cipher suites were enabled.\n\t */\n\tif (ret == 0)\n\t\treturn\n\t\t gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);\n\n\tcipher_suites_size = ret;\n\tif (add_scsv) {\n\t\tcipher_suites[cipher_suites_size] = 0x00;\n\t\tcipher_suites[cipher_suites_size + 1] = 0xff;\n\t\tcipher_suites_size += 2;\n\n\t\tret = _gnutls_ext_sr_send_cs(session);\n\t\tif (ret < 0)\n\t\t\treturn gnutls_assert_val(ret);\n\t}\n\n\tret =\n\t _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites,\n\t\t\t\t\t cipher_suites_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret = cdata->length - init_length;\n\n\treturn ret;\n}", "func_hash": 269856106136387551798958410827844130160, "file_name": "gnutls_handshake.c", "file_hash": 5037197622656434447785947328289753724, "cwe": ["CWE-310"], "cve": "CVE-2014-3566", "cve_desc": "The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other products, uses nondeterministic CBC padding, which makes it easier for man-in-the-middle attackers to obtain cleartext data via a padding-oracle attack, aka the \"POODLE\" issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-3566"} {"idx": 303482, "project": "gnutls", "commit_id": "21f89efad7014a5ee0debd4cd3d59e27774b29e6", "project_url": "http://git.savannah.gnu.org/cgit/gnutls", "commit_url": "https://gitlab.com/gnutls/gnutls/commit/21f89efad7014a5ee0debd4cd3d59e27774b29e6", "commit_message": "handshake: add FALLBACK_SCSV priority option\n\nThis allows clients to enable the TLS_FALLBACK_SCSV mechanism during\nthe handshake, as defined in RFC7507.", "target": 0, "func": "copy_ciphersuites(gnutls_session_t session,\n\t\t gnutls_buffer_st * cdata, int add_scsv)\n{\n\tint ret;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE + 4]; /* allow space for SCSV */\n\tint cipher_suites_size;\n\tsize_t init_length = cdata->length;\n\n\tret =\n\t _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t sizeof(cipher_suites) - 2);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (eg SRP).\n\t */\n\tret =\n\t _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t ret, NULL, 0);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* If no cipher suites were enabled.\n\t */\n\tif (ret == 0)\n\t\treturn\n\t\t gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);\n\n\tcipher_suites_size = ret;\n\tif (add_scsv) {\n\t\tcipher_suites[cipher_suites_size] = 0x00;\n\t\tcipher_suites[cipher_suites_size + 1] = 0xff;\n\t\tcipher_suites_size += 2;\n\n\t\tret = _gnutls_ext_sr_send_cs(session);\n\t\tif (ret < 0)\n\t\t\treturn gnutls_assert_val(ret);\n\t}\n\n\tif (session->internals.priorities.fallback) {\n\t\tcipher_suites[cipher_suites_size] =\n\t\t\tGNUTLS_FALLBACK_SCSV_MAJOR;\n\t\tcipher_suites[cipher_suites_size + 1] =\n\t\t\tGNUTLS_FALLBACK_SCSV_MINOR;\n\t\tcipher_suites_size += 2;\n\t}\n\n\tret =\n\t _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites,\n\t\t\t\t\t cipher_suites_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret = cdata->length - init_length;\n\n\treturn ret;\n}", "func_hash": 42510810097626829682680496590075781519, "file_name": "gnutls_handshake.c", "file_hash": 33222600436004333309471609542396279978, "cwe": ["CWE-310"], "cve": "CVE-2014-3566", "cve_desc": "The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other products, uses nondeterministic CBC padding, which makes it easier for man-in-the-middle attackers to obtain cleartext data via a padding-oracle attack, aka the \"POODLE\" issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-3566"} {"idx": 200525, "project": "php-src", "commit_id": "cf4753691dc55999373d1c576f62ecb298723420", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=cf4753691dc55999373d1c576f62ecb298723420", "commit_message": "Fixed Bug #66901 php-gd 'c_color' NULL pointer dereference\n\nUpstream https://bitbucket.org/libgd/gd-libgd/commits/463c3bd09bfe8e924e19acad7a2a6af16953a704\n\nNotice: this fix don't manage monochrome/monovisual values\nbut just fix the security issue CVE-2014-2497\nfailing when trying to load such an image", "target": 1, "func": "gdImagePtr gdImageCreateFromXpm (char *filename)\n{\n\tXpmInfo info;\n\tXpmImage image;\n\tint i, j, k, number;\n\tchar buf[5];\n\tgdImagePtr im = 0;\n\tint *pointer;\n\tint red = 0, green = 0, blue = 0;\n\tint *colors;\n\tint ret;\n\n\tret = XpmReadFileToXpmImage(filename, &image, &info);\n\tif (ret != XpmSuccess) {\n\t\treturn 0;\n\t}\n\n\tif (!(im = gdImageCreate(image.width, image.height))) {\n\t\tgoto done;\n\t}\n\n\tnumber = image.ncolors;\n\tcolors = (int *) safe_emalloc(number, sizeof(int), 0);\n\tfor (i = 0; i < number; i++) {\n\t\tswitch (strlen (image.colorTable[i].c_color)) {\n\t\t\tcase 4:\n\t\t\t\tbuf[1] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[2];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 7:\n\t\t\t\tbuf[2] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[4];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 10:\n\t\t\t\tbuf[3] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[4];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[6];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[8];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[9];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 64;\n\t\t\t\tbreak;\n\n\t\t\tcase 13:\n\t\t\t\tbuf[4] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[4];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[8];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[9];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[10];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[11];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[12];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 256;\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tcolors[i] = gdImageColorResolve(im, red, green, blue);\n\t}\n\n\tpointer = (int *) image.data;\n\tfor (i = 0; i < image.height; i++) {\n\t\tfor (j = 0; j < image.width; j++) {\n\t\t\tk = *pointer++;\n\t\t\tgdImageSetPixel(im, j, i, colors[k]);\n\t\t}\n\t}\n\n\tgdFree(colors);\n done:\n\tXpmFreeXpmImage(&image);\n\tXpmFreeXpmInfo(&info);\n\treturn im;\n}", "func_hash": 41690390745015318319645985364999561526, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2014-2497", "cve_desc": "The gdImageCreateFromXpm function in gdxpm.c in libgd, as used in PHP 5.4.26 and earlier, allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted color table in an XPM file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-2497"} {"idx": 304857, "project": "php-src", "commit_id": "cf4753691dc55999373d1c576f62ecb298723420", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=cf4753691dc55999373d1c576f62ecb298723420", "commit_message": "Fixed Bug #66901 php-gd 'c_color' NULL pointer dereference\n\nUpstream https://bitbucket.org/libgd/gd-libgd/commits/463c3bd09bfe8e924e19acad7a2a6af16953a704\n\nNotice: this fix don't manage monochrome/monovisual values\nbut just fix the security issue CVE-2014-2497\nfailing when trying to load such an image", "target": 0, "func": "gdImagePtr gdImageCreateFromXpm (char *filename)\n{\n\tXpmInfo info;\n\tXpmImage image;\n\tint i, j, k, number;\n\tchar buf[5];\n\tgdImagePtr im = 0;\n\tint *pointer;\n\tint red = 0, green = 0, blue = 0;\n\tint *colors;\n\tint ret;\n\n\tret = XpmReadFileToXpmImage(filename, &image, &info);\n\tif (ret != XpmSuccess) {\n\t\treturn 0;\n\t}\n\tnumber = image.ncolors;\n\tfor(i = 0; i < number; i++) {\n\t\tif (!image.colorTable[i].c_color) {\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\tif (!(im = gdImageCreate(image.width, image.height))) {\n\t\tgoto done;\n\t}\n\n\tcolors = (int *) safe_emalloc(number, sizeof(int), 0);\n\tfor (i = 0; i < number; i++) {\n\t\tswitch (strlen (image.colorTable[i].c_color)) {\n\t\t\tcase 4:\n\t\t\t\tbuf[1] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[2];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 7:\n\t\t\t\tbuf[2] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[4];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 10:\n\t\t\t\tbuf[3] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[4];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[6];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[8];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[9];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 64;\n\t\t\t\tbreak;\n\n\t\t\tcase 13:\n\t\t\t\tbuf[4] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[4];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[8];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[9];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[10];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[11];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[12];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 256;\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tcolors[i] = gdImageColorResolve(im, red, green, blue);\n\t}\n\n\tpointer = (int *) image.data;\n\tfor (i = 0; i < image.height; i++) {\n\t\tfor (j = 0; j < image.width; j++) {\n\t\t\tk = *pointer++;\n\t\t\tgdImageSetPixel(im, j, i, colors[k]);\n\t\t}\n\t}\n\n\tgdFree(colors);\n done:\n\tXpmFreeXpmImage(&image);\n\tXpmFreeXpmInfo(&info);\n\treturn im;\n}", "func_hash": 143050624887079423993447971521904288613, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2014-2497", "cve_desc": "The gdImageCreateFromXpm function in gdxpm.c in libgd, as used in PHP 5.4.26 and earlier, allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted color table in an XPM file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-2497"} {"idx": 200621, "project": "linux", "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/998912346c0da53a6dbb71fab3a138586b596b30", "commit_message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "func": "static void ov511_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size, fps, needed;\n\tint interlaced = 0;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\treg_w(sd, R51x_FIFO_PSIZE, packet_size >> 5);\n\n\treg_w(sd, R511_CAM_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_OPTS, 0x03);\n\n\t/* Here I'm assuming that snapshot size == image size.\n\t * I hope that's always true. --claudio\n\t */\n\thsegs = (sd->gspca_dev.pixfmt.width >> 3) - 1;\n\tvsegs = (sd->gspca_dev.pixfmt.height >> 3) - 1;\n\n\treg_w(sd, R511_CAM_PXCNT, hsegs);\n\treg_w(sd, R511_CAM_LNCNT, vsegs);\n\treg_w(sd, R511_CAM_PXDIV, 0x00);\n\treg_w(sd, R511_CAM_LNDIV, 0x00);\n\n\t/* YUV420, low pass filter on */\n\treg_w(sd, R511_CAM_OPTS, 0x03);\n\n\t/* Snapshot additions */\n\treg_w(sd, R511_SNAP_PXCNT, hsegs);\n\treg_w(sd, R511_SNAP_LNCNT, vsegs);\n\treg_w(sd, R511_SNAP_PXDIV, 0x00);\n\treg_w(sd, R511_SNAP_LNDIV, 0x00);\n\n\t/******** Set the framerate ********/\n\tif (frame_rate > 0)\n\t\tsd->frame_rate = frame_rate;\n\n\tswitch (sd->sensor) {\n\tcase SEN_OV6620:\n\t\t/* No framerate control, doesn't like higher rates yet */\n\t\tsd->clockdiv = 3;\n\t\tbreak;\n\n\t/* Note once the FIXME's in mode_init_ov_sensor_regs() are fixed\n\t for more sensors we need to do this for them too */\n\tcase SEN_OV7620:\n\tcase SEN_OV7620AE:\n\tcase SEN_OV7640:\n\tcase SEN_OV7648:\n\tcase SEN_OV76BE:\n\t\tif (sd->gspca_dev.pixfmt.width == 320)\n\t\t\tinterlaced = 1;\n\t\t/* Fall through */\n\tcase SEN_OV6630:\n\tcase SEN_OV7610:\n\tcase SEN_OV7670:\n\t\tswitch (sd->frame_rate) {\n\t\tcase 30:\n\t\tcase 25:\n\t\t\t/* Not enough bandwidth to do 640x480 @ 30 fps */\n\t\t\tif (sd->gspca_dev.pixfmt.width != 640) {\n\t\t\t\tsd->clockdiv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* For 640x480 case */\n\t\t\t/* fall through */\n\t\tdefault:\n/*\t\tcase 20: */\n/*\t\tcase 15: */\n\t\t\tsd->clockdiv = 1;\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\tsd->clockdiv = 2;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tsd->clockdiv = 5;\n\t\t\tbreak;\n\t\t}\n\t\tif (interlaced) {\n\t\t\tsd->clockdiv = (sd->clockdiv + 1) * 2 - 1;\n\t\t\t/* Higher then 10 does not work */\n\t\t\tif (sd->clockdiv > 10)\n\t\t\t\tsd->clockdiv = 10;\n\t\t}\n\t\tbreak;\n\n\tcase SEN_OV8610:\n\t\t/* No framerate control ?? */\n\t\tsd->clockdiv = 0;\n\t\tbreak;\n\t}\n\n\t/* Check if we have enough bandwidth to disable compression */\n\tfps = (interlaced ? 60 : 30) / (sd->clockdiv + 1) + 1;\n\tneeded = fps * sd->gspca_dev.pixfmt.width *\n\t\t\tsd->gspca_dev.pixfmt.height * 3 / 2;\n\t/* 1000 isoc packets/sec */\n\tif (needed > 1000 * packet_size) {\n\t\t/* Enable Y and UV quantization and compression */\n\t\treg_w(sd, R511_COMP_EN, 0x07);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x03);\n\t} else {\n\t\treg_w(sd, R511_COMP_EN, 0x06);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x00);\n\t}\n\n\treg_w(sd, R51x_SYS_RESET, OV511_RESET_OMNICE);\n\treg_w(sd, R51x_SYS_RESET, 0);\n}", "func_hash": 197853624489333539747119038282157115620, "file_name": "ov519.c", "file_hash": 168022336431298181820544829608556424720, "cwe": ["CWE-476"], "cve": "CVE-2020-11608", "cve_desc": "An issue was discovered in the Linux kernel before 5.6.1. drivers/media/usb/gspca/ov519.c allows NULL pointer dereferences in ov511_mode_init_regs and ov518_mode_init_regs when there are zero endpoints, aka CID-998912346c0d.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11608"} {"idx": 306343, "project": "linux", "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/998912346c0da53a6dbb71fab3a138586b596b30", "commit_message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "func": "static void ov511_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size, fps, needed;\n\tint interlaced = 0;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tif (alt->desc.bNumEndpoints < 1) {\n\t\tsd->gspca_dev.usb_err = -ENODEV;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\treg_w(sd, R51x_FIFO_PSIZE, packet_size >> 5);\n\n\treg_w(sd, R511_CAM_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_OPTS, 0x03);\n\n\t/* Here I'm assuming that snapshot size == image size.\n\t * I hope that's always true. --claudio\n\t */\n\thsegs = (sd->gspca_dev.pixfmt.width >> 3) - 1;\n\tvsegs = (sd->gspca_dev.pixfmt.height >> 3) - 1;\n\n\treg_w(sd, R511_CAM_PXCNT, hsegs);\n\treg_w(sd, R511_CAM_LNCNT, vsegs);\n\treg_w(sd, R511_CAM_PXDIV, 0x00);\n\treg_w(sd, R511_CAM_LNDIV, 0x00);\n\n\t/* YUV420, low pass filter on */\n\treg_w(sd, R511_CAM_OPTS, 0x03);\n\n\t/* Snapshot additions */\n\treg_w(sd, R511_SNAP_PXCNT, hsegs);\n\treg_w(sd, R511_SNAP_LNCNT, vsegs);\n\treg_w(sd, R511_SNAP_PXDIV, 0x00);\n\treg_w(sd, R511_SNAP_LNDIV, 0x00);\n\n\t/******** Set the framerate ********/\n\tif (frame_rate > 0)\n\t\tsd->frame_rate = frame_rate;\n\n\tswitch (sd->sensor) {\n\tcase SEN_OV6620:\n\t\t/* No framerate control, doesn't like higher rates yet */\n\t\tsd->clockdiv = 3;\n\t\tbreak;\n\n\t/* Note once the FIXME's in mode_init_ov_sensor_regs() are fixed\n\t for more sensors we need to do this for them too */\n\tcase SEN_OV7620:\n\tcase SEN_OV7620AE:\n\tcase SEN_OV7640:\n\tcase SEN_OV7648:\n\tcase SEN_OV76BE:\n\t\tif (sd->gspca_dev.pixfmt.width == 320)\n\t\t\tinterlaced = 1;\n\t\t/* Fall through */\n\tcase SEN_OV6630:\n\tcase SEN_OV7610:\n\tcase SEN_OV7670:\n\t\tswitch (sd->frame_rate) {\n\t\tcase 30:\n\t\tcase 25:\n\t\t\t/* Not enough bandwidth to do 640x480 @ 30 fps */\n\t\t\tif (sd->gspca_dev.pixfmt.width != 640) {\n\t\t\t\tsd->clockdiv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* For 640x480 case */\n\t\t\t/* fall through */\n\t\tdefault:\n/*\t\tcase 20: */\n/*\t\tcase 15: */\n\t\t\tsd->clockdiv = 1;\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\tsd->clockdiv = 2;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tsd->clockdiv = 5;\n\t\t\tbreak;\n\t\t}\n\t\tif (interlaced) {\n\t\t\tsd->clockdiv = (sd->clockdiv + 1) * 2 - 1;\n\t\t\t/* Higher then 10 does not work */\n\t\t\tif (sd->clockdiv > 10)\n\t\t\t\tsd->clockdiv = 10;\n\t\t}\n\t\tbreak;\n\n\tcase SEN_OV8610:\n\t\t/* No framerate control ?? */\n\t\tsd->clockdiv = 0;\n\t\tbreak;\n\t}\n\n\t/* Check if we have enough bandwidth to disable compression */\n\tfps = (interlaced ? 60 : 30) / (sd->clockdiv + 1) + 1;\n\tneeded = fps * sd->gspca_dev.pixfmt.width *\n\t\t\tsd->gspca_dev.pixfmt.height * 3 / 2;\n\t/* 1000 isoc packets/sec */\n\tif (needed > 1000 * packet_size) {\n\t\t/* Enable Y and UV quantization and compression */\n\t\treg_w(sd, R511_COMP_EN, 0x07);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x03);\n\t} else {\n\t\treg_w(sd, R511_COMP_EN, 0x06);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x00);\n\t}\n\n\treg_w(sd, R51x_SYS_RESET, OV511_RESET_OMNICE);\n\treg_w(sd, R51x_SYS_RESET, 0);\n}", "func_hash": 255535301371122414286094825884150534470, "file_name": "ov519.c", "file_hash": 129729512525278036186256450974839667727, "cwe": ["CWE-476"], "cve": "CVE-2020-11608", "cve_desc": "An issue was discovered in the Linux kernel before 5.6.1. drivers/media/usb/gspca/ov519.c allows NULL pointer dereferences in ov511_mode_init_regs and ov518_mode_init_regs when there are zero endpoints, aka CID-998912346c0d.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11608"} {"idx": 200622, "project": "linux", "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/998912346c0da53a6dbb71fab3a138586b596b30", "commit_message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "func": "static void ov518_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\tov518_reg_w32(sd, R51x_FIFO_PSIZE, packet_size & ~7, 2);\n\n\t/******** Set the mode ********/\n\treg_w(sd, 0x2b, 0);\n\treg_w(sd, 0x2c, 0);\n\treg_w(sd, 0x2d, 0);\n\treg_w(sd, 0x2e, 0);\n\treg_w(sd, 0x3b, 0);\n\treg_w(sd, 0x3c, 0);\n\treg_w(sd, 0x3d, 0);\n\treg_w(sd, 0x3e, 0);\n\n\tif (sd->bridge == BRIDGE_OV518) {\n\t\t/* Set 8-bit (YVYU) input format */\n\t\treg_w_mask(sd, 0x20, 0x08, 0x08);\n\n\t\t/* Set 12-bit (4:2:0) output format */\n\t\treg_w_mask(sd, 0x28, 0x80, 0xf0);\n\t\treg_w_mask(sd, 0x38, 0x80, 0xf0);\n\t} else {\n\t\treg_w(sd, 0x28, 0x80);\n\t\treg_w(sd, 0x38, 0x80);\n\t}\n\n\thsegs = sd->gspca_dev.pixfmt.width / 16;\n\tvsegs = sd->gspca_dev.pixfmt.height / 4;\n\n\treg_w(sd, 0x29, hsegs);\n\treg_w(sd, 0x2a, vsegs);\n\n\treg_w(sd, 0x39, hsegs);\n\treg_w(sd, 0x3a, vsegs);\n\n\t/* Windows driver does this here; who knows why */\n\treg_w(sd, 0x2f, 0x80);\n\n\t/******** Set the framerate ********/\n\tif (sd->bridge == BRIDGE_OV518PLUS && sd->revision == 0 &&\n\t\t\t\t\t sd->sensor == SEN_OV7620AE)\n\t\tsd->clockdiv = 0;\n\telse\n\t\tsd->clockdiv = 1;\n\n\t/* Mode independent, but framerate dependent, regs */\n\t/* 0x51: Clock divider; Only works on some cams which use 2 crystals */\n\treg_w(sd, 0x51, 0x04);\n\treg_w(sd, 0x22, 0x18);\n\treg_w(sd, 0x23, 0xff);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\tswitch (sd->sensor) {\n\t\tcase SEN_OV7620AE:\n\t\t\t/*\n\t\t\t * HdG: 640x480 needs special handling on device\n\t\t\t * revision 2, we check for device revision > 0 to\n\t\t\t * avoid regressions, as we don't know the correct\n\t\t\t * thing todo for revision 1.\n\t\t\t *\n\t\t\t * Also this likely means we don't need to\n\t\t\t * differentiate between the OV7620 and OV7620AE,\n\t\t\t * earlier testing hitting this same problem likely\n\t\t\t * happened to be with revision < 2 cams using an\n\t\t\t * OV7620 and revision 2 cams using an OV7620AE.\n\t\t\t */\n\t\t\tif (sd->revision > 0 &&\n\t\t\t\t\tsd->gspca_dev.pixfmt.width == 640) {\n\t\t\t\treg_w(sd, 0x20, 0x60);\n\t\t\t\treg_w(sd, 0x21, 0x1f);\n\t\t\t} else {\n\t\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SEN_OV7620:\n\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t}\n\t} else\n\t\treg_w(sd, 0x71, 0x17);\t/* Compression-related? */\n\n\t/* FIXME: Sensor-specific */\n\t/* Bit 5 is what matters here. Of course, it is \"reserved\" */\n\ti2c_w(sd, 0x54, 0x23);\n\n\treg_w(sd, 0x2f, 0x80);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\treg_w(sd, 0x24, 0x94);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc7, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc8, 108, 2);\t/* 6ch */\n\t\tov518_reg_w32(sd, 0xca, 131098, 3);\t/* 2001ah */\n\t\tov518_reg_w32(sd, 0xcb, 532, 2);\t/* 214h */\n\t\tov518_reg_w32(sd, 0xcc, 2400, 2);\t/* 960h */\n\t\tov518_reg_w32(sd, 0xcd, 32, 2);\t/* 20h */\n\t\tov518_reg_w32(sd, 0xce, 608, 2);\t/* 260h */\n\t} else {\n\t\treg_w(sd, 0x24, 0x9f);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc7, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc8, 128, 2);\t/* 80h */\n\t\tov518_reg_w32(sd, 0xca, 183331, 3);\t/* 2cc23h */\n\t\tov518_reg_w32(sd, 0xcb, 746, 2);\t/* 2eah */\n\t\tov518_reg_w32(sd, 0xcc, 1750, 2);\t/* 6d6h */\n\t\tov518_reg_w32(sd, 0xcd, 45, 2);\t/* 2dh */\n\t\tov518_reg_w32(sd, 0xce, 851, 2);\t/* 353h */\n\t}\n\n\treg_w(sd, 0x2f, 0x80);\n}", "func_hash": 200939870293468753970598592704563750884, "file_name": "ov519.c", "file_hash": 168022336431298181820544829608556424720, "cwe": ["CWE-476"], "cve": "CVE-2020-11608", "cve_desc": "An issue was discovered in the Linux kernel before 5.6.1. drivers/media/usb/gspca/ov519.c allows NULL pointer dereferences in ov511_mode_init_regs and ov518_mode_init_regs when there are zero endpoints, aka CID-998912346c0d.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11608"} {"idx": 306292, "project": "linux", "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/998912346c0da53a6dbb71fab3a138586b596b30", "commit_message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "func": "static void ov518_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tif (alt->desc.bNumEndpoints < 1) {\n\t\tsd->gspca_dev.usb_err = -ENODEV;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\tov518_reg_w32(sd, R51x_FIFO_PSIZE, packet_size & ~7, 2);\n\n\t/******** Set the mode ********/\n\treg_w(sd, 0x2b, 0);\n\treg_w(sd, 0x2c, 0);\n\treg_w(sd, 0x2d, 0);\n\treg_w(sd, 0x2e, 0);\n\treg_w(sd, 0x3b, 0);\n\treg_w(sd, 0x3c, 0);\n\treg_w(sd, 0x3d, 0);\n\treg_w(sd, 0x3e, 0);\n\n\tif (sd->bridge == BRIDGE_OV518) {\n\t\t/* Set 8-bit (YVYU) input format */\n\t\treg_w_mask(sd, 0x20, 0x08, 0x08);\n\n\t\t/* Set 12-bit (4:2:0) output format */\n\t\treg_w_mask(sd, 0x28, 0x80, 0xf0);\n\t\treg_w_mask(sd, 0x38, 0x80, 0xf0);\n\t} else {\n\t\treg_w(sd, 0x28, 0x80);\n\t\treg_w(sd, 0x38, 0x80);\n\t}\n\n\thsegs = sd->gspca_dev.pixfmt.width / 16;\n\tvsegs = sd->gspca_dev.pixfmt.height / 4;\n\n\treg_w(sd, 0x29, hsegs);\n\treg_w(sd, 0x2a, vsegs);\n\n\treg_w(sd, 0x39, hsegs);\n\treg_w(sd, 0x3a, vsegs);\n\n\t/* Windows driver does this here; who knows why */\n\treg_w(sd, 0x2f, 0x80);\n\n\t/******** Set the framerate ********/\n\tif (sd->bridge == BRIDGE_OV518PLUS && sd->revision == 0 &&\n\t\t\t\t\t sd->sensor == SEN_OV7620AE)\n\t\tsd->clockdiv = 0;\n\telse\n\t\tsd->clockdiv = 1;\n\n\t/* Mode independent, but framerate dependent, regs */\n\t/* 0x51: Clock divider; Only works on some cams which use 2 crystals */\n\treg_w(sd, 0x51, 0x04);\n\treg_w(sd, 0x22, 0x18);\n\treg_w(sd, 0x23, 0xff);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\tswitch (sd->sensor) {\n\t\tcase SEN_OV7620AE:\n\t\t\t/*\n\t\t\t * HdG: 640x480 needs special handling on device\n\t\t\t * revision 2, we check for device revision > 0 to\n\t\t\t * avoid regressions, as we don't know the correct\n\t\t\t * thing todo for revision 1.\n\t\t\t *\n\t\t\t * Also this likely means we don't need to\n\t\t\t * differentiate between the OV7620 and OV7620AE,\n\t\t\t * earlier testing hitting this same problem likely\n\t\t\t * happened to be with revision < 2 cams using an\n\t\t\t * OV7620 and revision 2 cams using an OV7620AE.\n\t\t\t */\n\t\t\tif (sd->revision > 0 &&\n\t\t\t\t\tsd->gspca_dev.pixfmt.width == 640) {\n\t\t\t\treg_w(sd, 0x20, 0x60);\n\t\t\t\treg_w(sd, 0x21, 0x1f);\n\t\t\t} else {\n\t\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SEN_OV7620:\n\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t}\n\t} else\n\t\treg_w(sd, 0x71, 0x17);\t/* Compression-related? */\n\n\t/* FIXME: Sensor-specific */\n\t/* Bit 5 is what matters here. Of course, it is \"reserved\" */\n\ti2c_w(sd, 0x54, 0x23);\n\n\treg_w(sd, 0x2f, 0x80);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\treg_w(sd, 0x24, 0x94);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc7, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc8, 108, 2);\t/* 6ch */\n\t\tov518_reg_w32(sd, 0xca, 131098, 3);\t/* 2001ah */\n\t\tov518_reg_w32(sd, 0xcb, 532, 2);\t/* 214h */\n\t\tov518_reg_w32(sd, 0xcc, 2400, 2);\t/* 960h */\n\t\tov518_reg_w32(sd, 0xcd, 32, 2);\t/* 20h */\n\t\tov518_reg_w32(sd, 0xce, 608, 2);\t/* 260h */\n\t} else {\n\t\treg_w(sd, 0x24, 0x9f);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc7, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc8, 128, 2);\t/* 80h */\n\t\tov518_reg_w32(sd, 0xca, 183331, 3);\t/* 2cc23h */\n\t\tov518_reg_w32(sd, 0xcb, 746, 2);\t/* 2eah */\n\t\tov518_reg_w32(sd, 0xcc, 1750, 2);\t/* 6d6h */\n\t\tov518_reg_w32(sd, 0xcd, 45, 2);\t/* 2dh */\n\t\tov518_reg_w32(sd, 0xce, 851, 2);\t/* 353h */\n\t}\n\n\treg_w(sd, 0x2f, 0x80);\n}", "func_hash": 268955524866920375201721358609221033791, "file_name": "ov519.c", "file_hash": 129729512525278036186256450974839667727, "cwe": ["CWE-476"], "cve": "CVE-2020-11608", "cve_desc": "An issue was discovered in the Linux kernel before 5.6.1. drivers/media/usb/gspca/ov519.c allows NULL pointer dereferences in ov511_mode_init_regs and ov518_mode_init_regs when there are zero endpoints, aka CID-998912346c0d.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11608"} {"idx": 200632, "project": "squid", "commit_id": "47a085ff06598b64817875769022b8707a0af7db", "project_url": "https://github.com/squid-cache/squid", "commit_url": "https://github.com/squid-cache/squid/commit/47a085ff06598b64817875769022b8707a0af7db", "commit_message": "Bug 5104: Memory leak in RFC 2169 response parsing (#778)\n\nA temporary parsing buffer was not being released when\nparsing completed.", "target": 1, "func": "urnParseReply(const char *inbuf, const HttpRequestMethod& m)\n{\n char *buf = xstrdup(inbuf);\n char *token;\n url_entry *list;\n url_entry *old;\n int n = 32;\n int i = 0;\n debugs(52, 3, \"urnParseReply\");\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n\n for (token = strtok(buf, crlf); token; token = strtok(NULL, crlf)) {\n debugs(52, 3, \"urnParseReply: got '\" << token << \"'\");\n\n if (i == n) {\n old = list;\n n <<= 2;\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n memcpy(list, old, i * sizeof(*list));\n safe_free(old);\n }\n\n AnyP::Uri uri;\n if (!uri.parse(m, SBuf(token)) || !*uri.host())\n continue;\n\n#if USE_ICMP\n list[i].rtt = netdbHostRtt(uri.host());\n\n if (0 == list[i].rtt) {\n debugs(52, 3, \"Pinging \" << uri.host());\n netdbPingSite(uri.host());\n }\n#else\n list[i].rtt = 0;\n#endif\n\n list[i].url = xstrdup(uri.absolute().c_str());\n list[i].host = xstrdup(uri.host());\n // TODO: Use storeHas() or lock/unlock entry to avoid creating unlocked\n // ones.\n list[i].flags.cached = storeGetPublic(list[i].url, m) ? 1 : 0;\n ++i;\n }\n\n debugs(52, 3, \"urnParseReply: Found \" << i << \" URLs\");\n return list;\n}", "func_hash": 212623979741835546301538373334803039552, "file_name": "urn.cc", "file_hash": 30104583732595791651863515807051143944, "cwe": ["CWE-401"], "cve": "CVE-2021-28651", "cve_desc": "An issue was discovered in Squid before 4.15 and 5.x before 5.0.6. Due to a buffer-management bug, it allows a denial of service. When resolving a request with the urn: scheme, the parser leaks a small amount of memory. However, there is an unspecified attack methodology that can easily trigger a large amount of memory consumption.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28651"} {"idx": 306747, "project": "squid", "commit_id": "47a085ff06598b64817875769022b8707a0af7db", "project_url": "https://github.com/squid-cache/squid", "commit_url": "https://github.com/squid-cache/squid/commit/47a085ff06598b64817875769022b8707a0af7db", "commit_message": "Bug 5104: Memory leak in RFC 2169 response parsing (#778)\n\nA temporary parsing buffer was not being released when\nparsing completed.", "target": 0, "func": "urnParseReply(const char *inbuf, const HttpRequestMethod& m)\n{\n char *buf = xstrdup(inbuf);\n char *token;\n url_entry *list;\n url_entry *old;\n int n = 32;\n int i = 0;\n debugs(52, 3, \"urnParseReply\");\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n\n for (token = strtok(buf, crlf); token; token = strtok(NULL, crlf)) {\n debugs(52, 3, \"urnParseReply: got '\" << token << \"'\");\n\n if (i == n) {\n old = list;\n n <<= 2;\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n memcpy(list, old, i * sizeof(*list));\n safe_free(old);\n }\n\n AnyP::Uri uri;\n if (!uri.parse(m, SBuf(token)) || !*uri.host())\n continue;\n\n#if USE_ICMP\n list[i].rtt = netdbHostRtt(uri.host());\n\n if (0 == list[i].rtt) {\n debugs(52, 3, \"Pinging \" << uri.host());\n netdbPingSite(uri.host());\n }\n#else\n list[i].rtt = 0;\n#endif\n\n list[i].url = xstrdup(uri.absolute().c_str());\n list[i].host = xstrdup(uri.host());\n // TODO: Use storeHas() or lock/unlock entry to avoid creating unlocked\n // ones.\n list[i].flags.cached = storeGetPublic(list[i].url, m) ? 1 : 0;\n ++i;\n }\n\n debugs(52, 3, \"urnParseReply: Found \" << i << \" URLs\");\n xfree(buf);\n return list;\n}", "func_hash": 10946121827644275104333266248408152786, "file_name": "urn.cc", "file_hash": 276010083395102545576699913622414589854, "cwe": ["CWE-401"], "cve": "CVE-2021-28651", "cve_desc": "An issue was discovered in Squid before 4.15 and 5.x before 5.0.6. Due to a buffer-management bug, it allows a denial of service. When resolving a request with the urn: scheme, the parser leaks a small amount of memory. However, there is an unspecified attack methodology that can easily trigger a large amount of memory consumption.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28651"} {"idx": 200711, "project": "libexpat", "commit_id": "c4bf96bb51dd2a1b0e185374362ee136fe2c9d7f", "project_url": "https://github.com/libexpat/libexpat", "commit_url": "https://github.com/libexpat/libexpat/commit/c4bf96bb51dd2a1b0e185374362ee136fe2c9d7f", "commit_message": "xmlparse.c: Fix external entity infinite loop bug (CVE-2017-9233)", "target": 1, "func": "entityValueInitProcessor(XML_Parser parser,\n const char *s,\n const char *end,\n const char **nextPtr)\n{\n int tok;\n const char *start = s;\n const char *next = start;\n eventPtr = start;\n\n for (;;) {\n tok = XmlPrologTok(encoding, start, end, &next);\n eventEndPtr = next;\n if (tok <= 0) {\n if (!ps_finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, encoding, s, end);\n }\n else if (tok == XML_TOK_XML_DECL) {\n enum XML_Error result;\n result = processXmlDecl(parser, 0, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n switch (ps_parsing) {\n case XML_SUSPENDED:\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n default:\n *nextPtr = next;\n }\n /* stop scanning for text declaration - we found one */\n processor = entityValueProcessor;\n return entityValueProcessor(parser, next, end, nextPtr);\n }\n /* If we are at the end of the buffer, this would cause XmlPrologTok to\n return XML_TOK_NONE on the next call, which would then cause the\n function to exit with *nextPtr set to s - that is what we want for other\n tokens, but not for the BOM - we would rather like to skip it;\n then, when this routine is entered the next time, XmlPrologTok will\n return XML_TOK_INVALID, since the BOM is still in the buffer\n */\n else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n start = next;\n eventPtr = start;\n }\n}", "func_hash": 336470296503333027798344364330838893913, "file_name": "xmlparse.c", "file_hash": 213537407245657366556238438609946297655, "cwe": ["CWE-611"], "cve": "CVE-2017-9233", "cve_desc": "XML External Entity vulnerability in libexpat 2.2.0 and earlier (Expat XML Parser Library) allows attackers to put the parser in an infinite loop using a malformed external entity definition from an external DTD.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-9233"} {"idx": 308321, "project": "libexpat", "commit_id": "c4bf96bb51dd2a1b0e185374362ee136fe2c9d7f", "project_url": "https://github.com/libexpat/libexpat", "commit_url": "https://github.com/libexpat/libexpat/commit/c4bf96bb51dd2a1b0e185374362ee136fe2c9d7f", "commit_message": "xmlparse.c: Fix external entity infinite loop bug (CVE-2017-9233)", "target": 0, "func": "entityValueInitProcessor(XML_Parser parser,\n const char *s,\n const char *end,\n const char **nextPtr)\n{\n int tok;\n const char *start = s;\n const char *next = start;\n eventPtr = start;\n\n for (;;) {\n tok = XmlPrologTok(encoding, start, end, &next);\n eventEndPtr = next;\n if (tok <= 0) {\n if (!ps_finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, encoding, s, end);\n }\n else if (tok == XML_TOK_XML_DECL) {\n enum XML_Error result;\n result = processXmlDecl(parser, 0, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n switch (ps_parsing) {\n case XML_SUSPENDED:\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n default:\n *nextPtr = next;\n }\n /* stop scanning for text declaration - we found one */\n processor = entityValueProcessor;\n return entityValueProcessor(parser, next, end, nextPtr);\n }\n /* If we are at the end of the buffer, this would cause XmlPrologTok to\n return XML_TOK_NONE on the next call, which would then cause the\n function to exit with *nextPtr set to s - that is what we want for other\n tokens, but not for the BOM - we would rather like to skip it;\n then, when this routine is entered the next time, XmlPrologTok will\n return XML_TOK_INVALID, since the BOM is still in the buffer\n */\n else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n /* If we get this token, we have the start of what might be a\n normal tag, but not a declaration (i.e. it doesn't begin with\n \"H2 should use :authority only\nif the original request was in authority form. This leaves some gray\narea in the middle of the chain for fully valid H2 requests arboring a\nHost header that are forwarded to the other side where it's possible to\ndrop the Host header and use the authority only after forwarding to a\nsecond H2 layer, thus possibly seeing two different values of Host at\na different stage. There's no such issue when forwarding from H2 to H1\nas the authority is dropped only only the Host is kept.\n\nNote that the following request is sufficient to re-normalize such a\nrequest:\n\n http-request set-header host %[req.hdr(host)]\n\nThe new spec in progress (draft-ietf-httpbis-http2bis-03) addresses\nthis trouble by being a bit is stricter on these rules. It clarifies\nthat :authority must always be used instead of Host and that Host ought\nto be ignored. This is much saner as it avoids to convey two distinct\nvalues along the chain. This becomes the protocol-level equivalent of:\n\n http-request set-uri %[url]\n\nSo this patch does exactly this, which we were initially a bit reluctant\nto do initially by lack of visibility about other implementations'\nexpectations. In addition it slightly simplifies the Host header field\ncreation by always placing it first in the list of headers instead of\nlast; this could also speed up the look up a little bit.\n\nThis needs to be backported to 2.0. Non-HTX versions are safe regarding\nthis because they drop the URI during the conversion to HTTP/1.1 so\nonly Host is used and transmitted.\n\nThanks to Tim D\u00fcsterhus for reporting that one.", "target": 1, "func": "int h2_make_htx_request(struct http_hdr *list, struct htx *htx, unsigned int *msgf, unsigned long long *body_len)\n{\n\tstruct ist phdr_val[H2_PHDR_NUM_ENTRIES];\n\tuint32_t fields; /* bit mask of H2_PHDR_FND_* */\n\tuint32_t idx;\n\tint ck, lck; /* cookie index and last cookie index */\n\tint phdr;\n\tint ret;\n\tint i;\n\tstruct htx_sl *sl = NULL;\n\tunsigned int sl_flags = 0;\n\tconst char *ctl;\n\n\tlck = ck = -1; // no cookie for now\n\tfields = 0;\n\tfor (idx = 0; list[idx].n.len != 0; idx++) {\n\t\tif (!list[idx].n.ptr) {\n\t\t\t/* this is an indexed pseudo-header */\n\t\t\tphdr = list[idx].n.len;\n\t\t}\n\t\telse {\n\t\t\t/* this can be any type of header */\n\t\t\t/* RFC7540#8.1.2: upper case not allowed in header field names.\n\t\t\t * #10.3: header names must be valid (i.e. match a token).\n\t\t\t * For pseudo-headers we check from 2nd char and for other ones\n\t\t\t * from the first char, because HTTP_IS_TOKEN() also excludes\n\t\t\t * the colon.\n\t\t\t */\n\t\t\tphdr = h2_str_to_phdr(list[idx].n);\n\n\t\t\tfor (i = !!phdr; i < list[idx].n.len; i++)\n\t\t\t\tif ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A' || !HTTP_IS_TOKEN(list[idx].n.ptr[i]))\n\t\t\t\t\tgoto fail;\n\t\t}\n\n\t\t/* RFC7540#10.3: intermediaries forwarding to HTTP/1 must take care of\n\t\t * rejecting NUL, CR and LF characters.\n\t\t */\n\t\tctl = ist_find_ctl(list[idx].v);\n\t\tif (unlikely(ctl) && has_forbidden_char(list[idx].v, ctl))\n\t\t\tgoto fail;\n\n\t\tif (phdr > 0 && phdr < H2_PHDR_NUM_ENTRIES) {\n\t\t\t/* insert a pseudo header by its index (in phdr) and value (in value) */\n\t\t\tif (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) {\n\t\t\t\tif (fields & H2_PHDR_FND_NONE) {\n\t\t\t\t\t/* pseudo header field after regular headers */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* repeated pseudo header field */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfields |= 1 << phdr;\n\t\t\tphdr_val[phdr] = list[idx].v;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (phdr != 0) {\n\t\t\t/* invalid pseudo header -- should never happen here */\n\t\t\tgoto fail;\n\t\t}\n\n\t\t/* regular header field in (name,value) */\n\t\tif (unlikely(!(fields & H2_PHDR_FND_NONE))) {\n\t\t\t/* no more pseudo-headers, time to build the request line */\n\t\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\t\tif (!sl)\n\t\t\t\tgoto fail;\n\t\t\tfields |= H2_PHDR_FND_NONE;\n\t\t}\n\n\t\tif (isteq(list[idx].n, ist(\"host\")))\n\t\t\tfields |= H2_PHDR_FND_HOST;\n\n\t\tif (isteq(list[idx].n, ist(\"content-length\"))) {\n\t\t\tret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto fail;\n\n\t\t\tsl_flags |= HTX_SL_F_CLEN;\n\t\t\tif (ret == 0)\n\t\t\t\tcontinue; // skip this duplicate\n\t\t}\n\n\t\t/* these ones are forbidden in requests (RFC7540#8.1.2.2) */\n\t\tif (isteq(list[idx].n, ist(\"connection\")) ||\n\t\t isteq(list[idx].n, ist(\"proxy-connection\")) ||\n\t\t isteq(list[idx].n, ist(\"keep-alive\")) ||\n\t\t isteq(list[idx].n, ist(\"upgrade\")) ||\n\t\t isteq(list[idx].n, ist(\"transfer-encoding\")))\n\t\t\tgoto fail;\n\n\t\tif (isteq(list[idx].n, ist(\"te\")) && !isteq(list[idx].v, ist(\"trailers\")))\n\t\t\tgoto fail;\n\n\t\t/* cookie requires special processing at the end */\n\t\tif (isteq(list[idx].n, ist(\"cookie\"))) {\n\t\t\tlist[idx].n.len = -1;\n\n\t\t\tif (ck < 0)\n\t\t\t\tck = idx;\n\t\t\telse\n\t\t\t\tlist[lck].n.len = idx;\n\n\t\t\tlck = idx;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!htx_add_header(htx, list[idx].n, list[idx].v))\n\t\t\tgoto fail;\n\t}\n\n\t/* RFC7540#8.1.2.1 mandates to reject response pseudo-headers (:status) */\n\tif (fields & H2_PHDR_FND_STAT)\n\t\tgoto fail;\n\n\t/* Let's dump the request now if not yet emitted. */\n\tif (!(fields & H2_PHDR_FND_NONE)) {\n\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\tif (!sl)\n\t\t\tgoto fail;\n\t}\n\n\tif (*msgf & H2_MSGF_BODY_TUNNEL)\n\t\t*msgf &= ~(H2_MSGF_BODY|H2_MSGF_BODY_CL);\n\n\tif (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0) ||\n\t (*msgf & H2_MSGF_BODY_TUNNEL)) {\n\t\t/* Request without body or tunnel requested */\n\t\tsl_flags |= HTX_SL_F_BODYLESS;\n\t\thtx->flags |= HTX_FL_EOM;\n\t}\n\n\tif (*msgf & H2_MSGF_EXT_CONNECT) {\n\t\tif (!htx_add_header(htx, ist(\"upgrade\"), phdr_val[H2_PHDR_IDX_PROT]))\n\t\t\tgoto fail;\n\t\tif (!htx_add_header(htx, ist(\"connection\"), ist(\"upgrade\")))\n\t\t\tgoto fail;\n\t\tsl_flags |= HTX_SL_F_CONN_UPG;\n\t}\n\n\t/* update the start line with last detected header info */\n\tsl->flags |= sl_flags;\n\n\t/* complete with missing Host if needed */\n\tif ((fields & (H2_PHDR_FND_HOST|H2_PHDR_FND_AUTH)) == H2_PHDR_FND_AUTH) {\n\t\t/* missing Host field, use :authority instead */\n\t\tif (!htx_add_header(htx, ist(\"host\"), phdr_val[H2_PHDR_IDX_AUTH]))\n\t\t\tgoto fail;\n\t}\n\n\t/* now we may have to build a cookie list. We'll dump the values of all\n\t * visited headers.\n\t */\n\tif (ck >= 0) {\n\t\tuint32_t fs; // free space\n\t\tuint32_t bs; // block size\n\t\tuint32_t vl; // value len\n\t\tuint32_t tl; // total length\n\t\tstruct htx_blk *blk;\n\n\t\tblk = htx_add_header(htx, ist(\"cookie\"), list[ck].v);\n\t\tif (!blk)\n\t\t\tgoto fail;\n\n\t\ttl = list[ck].v.len;\n\t\tfs = htx_free_data_space(htx);\n\t\tbs = htx_get_blksz(blk);\n\n\t\t/* for each extra cookie, we'll extend the cookie's value and\n\t\t * insert \"; \" before the new value.\n\t\t */\n\t\tfs += tl; // first one is already counted\n\t\twhile ((ck = list[ck].n.len) >= 0) {\n\t\t\tvl = list[ck].v.len;\n\t\t\ttl += vl + 2;\n\t\t\tif (tl > fs)\n\t\t\t\tgoto fail;\n\n\t\t\thtx_change_blk_value_len(htx, blk, tl);\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 0) = ';';\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 1) = ' ';\n\t\t\tmemcpy(htx_get_blk_ptr(htx, blk) + bs + 2, list[ck].v.ptr, vl);\n\t\t\tbs += vl + 2;\n\t\t}\n\n\t}\n\n\t/* now send the end of headers marker */\n\tif (!htx_add_endof(htx, HTX_BLK_EOH))\n\t\tgoto fail;\n\n\t/* proceed to scheme-based normalization on target-URI */\n\tif (fields & H2_PHDR_FND_SCHM)\n\t\thttp_scheme_based_normalize(htx);\n\n\tret = 1;\n\treturn ret;\n\n fail:\n\treturn -1;\n}", "func_hash": 314641792440761920579971242721069280553, "file_name": "h2.c", "file_hash": 314856915346767508556356436320647276464, "cwe": ["CWE-755"], "cve": "CVE-2021-39242", "cve_desc": "An issue was discovered in HAProxy 2.2 before 2.2.16, 2.3 before 2.3.13, and 2.4 before 2.4.3. It can lead to a situation with an attacker-controlled HTTP Host header, because a mismatch between Host and authority is mishandled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-39242"} {"idx": 309702, "project": "haproxy", "commit_id": "b5d2b9e154d78e4075db163826c5e0f6d31b2ab1", "project_url": "https://github.com/haproxy/haproxy", "commit_url": "https://git.haproxy.org/?p=haproxy.git;a=commit;h=b5d2b9e154d78e4075db163826c5e0f6d31b2ab1", "commit_message": "BUG/MEDIUM: h2: give :authority precedence over Host\n\nThe wording regarding Host vs :authority in RFC7540 is ambiguous as it\nsays that an intermediary must produce a host header from :authority if\nHost is missing, but, contrary to HTTP/1.1, doesn't say anything regarding\nthe possibility that Host and :authority differ, which leaves Host with\nhigher precedence there. In addition it mentions that clients should use\n:authority *instead* of Host, and that H1->H2 should use :authority only\nif the original request was in authority form. This leaves some gray\narea in the middle of the chain for fully valid H2 requests arboring a\nHost header that are forwarded to the other side where it's possible to\ndrop the Host header and use the authority only after forwarding to a\nsecond H2 layer, thus possibly seeing two different values of Host at\na different stage. There's no such issue when forwarding from H2 to H1\nas the authority is dropped only only the Host is kept.\n\nNote that the following request is sufficient to re-normalize such a\nrequest:\n\n http-request set-header host %[req.hdr(host)]\n\nThe new spec in progress (draft-ietf-httpbis-http2bis-03) addresses\nthis trouble by being a bit is stricter on these rules. It clarifies\nthat :authority must always be used instead of Host and that Host ought\nto be ignored. This is much saner as it avoids to convey two distinct\nvalues along the chain. This becomes the protocol-level equivalent of:\n\n http-request set-uri %[url]\n\nSo this patch does exactly this, which we were initially a bit reluctant\nto do initially by lack of visibility about other implementations'\nexpectations. In addition it slightly simplifies the Host header field\ncreation by always placing it first in the list of headers instead of\nlast; this could also speed up the look up a little bit.\n\nThis needs to be backported to 2.0. Non-HTX versions are safe regarding\nthis because they drop the URI during the conversion to HTTP/1.1 so\nonly Host is used and transmitted.\n\nThanks to Tim D\u00fcsterhus for reporting that one.", "target": 0, "func": "int h2_make_htx_request(struct http_hdr *list, struct htx *htx, unsigned int *msgf, unsigned long long *body_len)\n{\n\tstruct ist phdr_val[H2_PHDR_NUM_ENTRIES];\n\tuint32_t fields; /* bit mask of H2_PHDR_FND_* */\n\tuint32_t idx;\n\tint ck, lck; /* cookie index and last cookie index */\n\tint phdr;\n\tint ret;\n\tint i;\n\tstruct htx_sl *sl = NULL;\n\tunsigned int sl_flags = 0;\n\tconst char *ctl;\n\n\tlck = ck = -1; // no cookie for now\n\tfields = 0;\n\tfor (idx = 0; list[idx].n.len != 0; idx++) {\n\t\tif (!list[idx].n.ptr) {\n\t\t\t/* this is an indexed pseudo-header */\n\t\t\tphdr = list[idx].n.len;\n\t\t}\n\t\telse {\n\t\t\t/* this can be any type of header */\n\t\t\t/* RFC7540#8.1.2: upper case not allowed in header field names.\n\t\t\t * #10.3: header names must be valid (i.e. match a token).\n\t\t\t * For pseudo-headers we check from 2nd char and for other ones\n\t\t\t * from the first char, because HTTP_IS_TOKEN() also excludes\n\t\t\t * the colon.\n\t\t\t */\n\t\t\tphdr = h2_str_to_phdr(list[idx].n);\n\n\t\t\tfor (i = !!phdr; i < list[idx].n.len; i++)\n\t\t\t\tif ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A' || !HTTP_IS_TOKEN(list[idx].n.ptr[i]))\n\t\t\t\t\tgoto fail;\n\t\t}\n\n\t\t/* RFC7540#10.3: intermediaries forwarding to HTTP/1 must take care of\n\t\t * rejecting NUL, CR and LF characters.\n\t\t */\n\t\tctl = ist_find_ctl(list[idx].v);\n\t\tif (unlikely(ctl) && has_forbidden_char(list[idx].v, ctl))\n\t\t\tgoto fail;\n\n\t\tif (phdr > 0 && phdr < H2_PHDR_NUM_ENTRIES) {\n\t\t\t/* insert a pseudo header by its index (in phdr) and value (in value) */\n\t\t\tif (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) {\n\t\t\t\tif (fields & H2_PHDR_FND_NONE) {\n\t\t\t\t\t/* pseudo header field after regular headers */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* repeated pseudo header field */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfields |= 1 << phdr;\n\t\t\tphdr_val[phdr] = list[idx].v;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (phdr != 0) {\n\t\t\t/* invalid pseudo header -- should never happen here */\n\t\t\tgoto fail;\n\t\t}\n\n\t\t/* regular header field in (name,value) */\n\t\tif (unlikely(!(fields & H2_PHDR_FND_NONE))) {\n\t\t\t/* no more pseudo-headers, time to build the request line */\n\t\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\t\tif (!sl)\n\t\t\t\tgoto fail;\n\t\t\tfields |= H2_PHDR_FND_NONE;\n\n\t\t\t/* http2bis draft recommends to drop Host in favor of :authority when\n\t\t\t * the latter is present. This is required to make sure there is no\n\t\t\t * discrepancy between the authority and the host header, especially\n\t\t\t * since routing rules usually involve Host. Here we already know if\n\t\t\t * :authority was found so we can emit it right now and mark the host\n\t\t\t * as filled so that it's skipped later.\n\t\t\t */\n\t\t\tif (fields & H2_PHDR_FND_AUTH) {\n\t\t\t\tif (!htx_add_header(htx, ist(\"host\"), phdr_val[H2_PHDR_IDX_AUTH]))\n\t\t\t\t\tgoto fail;\n\t\t\t\tfields |= H2_PHDR_FND_HOST;\n\t\t\t}\n\t\t}\n\n\t\tif (isteq(list[idx].n, ist(\"host\"))) {\n\t\t\tif (fields & H2_PHDR_FND_HOST)\n\t\t\t\tcontinue;\n\n\t\t\tfields |= H2_PHDR_FND_HOST;\n\t\t}\n\n\t\tif (isteq(list[idx].n, ist(\"content-length\"))) {\n\t\t\tret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto fail;\n\n\t\t\tsl_flags |= HTX_SL_F_CLEN;\n\t\t\tif (ret == 0)\n\t\t\t\tcontinue; // skip this duplicate\n\t\t}\n\n\t\t/* these ones are forbidden in requests (RFC7540#8.1.2.2) */\n\t\tif (isteq(list[idx].n, ist(\"connection\")) ||\n\t\t isteq(list[idx].n, ist(\"proxy-connection\")) ||\n\t\t isteq(list[idx].n, ist(\"keep-alive\")) ||\n\t\t isteq(list[idx].n, ist(\"upgrade\")) ||\n\t\t isteq(list[idx].n, ist(\"transfer-encoding\")))\n\t\t\tgoto fail;\n\n\t\tif (isteq(list[idx].n, ist(\"te\")) && !isteq(list[idx].v, ist(\"trailers\")))\n\t\t\tgoto fail;\n\n\t\t/* cookie requires special processing at the end */\n\t\tif (isteq(list[idx].n, ist(\"cookie\"))) {\n\t\t\tlist[idx].n.len = -1;\n\n\t\t\tif (ck < 0)\n\t\t\t\tck = idx;\n\t\t\telse\n\t\t\t\tlist[lck].n.len = idx;\n\n\t\t\tlck = idx;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!htx_add_header(htx, list[idx].n, list[idx].v))\n\t\t\tgoto fail;\n\t}\n\n\t/* RFC7540#8.1.2.1 mandates to reject response pseudo-headers (:status) */\n\tif (fields & H2_PHDR_FND_STAT)\n\t\tgoto fail;\n\n\t/* Let's dump the request now if not yet emitted. */\n\tif (!(fields & H2_PHDR_FND_NONE)) {\n\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\tif (!sl)\n\t\t\tgoto fail;\n\t}\n\n\tif (*msgf & H2_MSGF_BODY_TUNNEL)\n\t\t*msgf &= ~(H2_MSGF_BODY|H2_MSGF_BODY_CL);\n\n\tif (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0) ||\n\t (*msgf & H2_MSGF_BODY_TUNNEL)) {\n\t\t/* Request without body or tunnel requested */\n\t\tsl_flags |= HTX_SL_F_BODYLESS;\n\t\thtx->flags |= HTX_FL_EOM;\n\t}\n\n\tif (*msgf & H2_MSGF_EXT_CONNECT) {\n\t\tif (!htx_add_header(htx, ist(\"upgrade\"), phdr_val[H2_PHDR_IDX_PROT]))\n\t\t\tgoto fail;\n\t\tif (!htx_add_header(htx, ist(\"connection\"), ist(\"upgrade\")))\n\t\t\tgoto fail;\n\t\tsl_flags |= HTX_SL_F_CONN_UPG;\n\t}\n\n\t/* update the start line with last detected header info */\n\tsl->flags |= sl_flags;\n\n\t/* complete with missing Host if needed (we may validate this test if\n\t * no regular header was found).\n\t */\n\tif ((fields & (H2_PHDR_FND_HOST|H2_PHDR_FND_AUTH)) == H2_PHDR_FND_AUTH) {\n\t\t/* missing Host field, use :authority instead */\n\t\tif (!htx_add_header(htx, ist(\"host\"), phdr_val[H2_PHDR_IDX_AUTH]))\n\t\t\tgoto fail;\n\t}\n\n\t/* now we may have to build a cookie list. We'll dump the values of all\n\t * visited headers.\n\t */\n\tif (ck >= 0) {\n\t\tuint32_t fs; // free space\n\t\tuint32_t bs; // block size\n\t\tuint32_t vl; // value len\n\t\tuint32_t tl; // total length\n\t\tstruct htx_blk *blk;\n\n\t\tblk = htx_add_header(htx, ist(\"cookie\"), list[ck].v);\n\t\tif (!blk)\n\t\t\tgoto fail;\n\n\t\ttl = list[ck].v.len;\n\t\tfs = htx_free_data_space(htx);\n\t\tbs = htx_get_blksz(blk);\n\n\t\t/* for each extra cookie, we'll extend the cookie's value and\n\t\t * insert \"; \" before the new value.\n\t\t */\n\t\tfs += tl; // first one is already counted\n\t\twhile ((ck = list[ck].n.len) >= 0) {\n\t\t\tvl = list[ck].v.len;\n\t\t\ttl += vl + 2;\n\t\t\tif (tl > fs)\n\t\t\t\tgoto fail;\n\n\t\t\thtx_change_blk_value_len(htx, blk, tl);\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 0) = ';';\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 1) = ' ';\n\t\t\tmemcpy(htx_get_blk_ptr(htx, blk) + bs + 2, list[ck].v.ptr, vl);\n\t\t\tbs += vl + 2;\n\t\t}\n\n\t}\n\n\t/* now send the end of headers marker */\n\tif (!htx_add_endof(htx, HTX_BLK_EOH))\n\t\tgoto fail;\n\n\t/* proceed to scheme-based normalization on target-URI */\n\tif (fields & H2_PHDR_FND_SCHM)\n\t\thttp_scheme_based_normalize(htx);\n\n\tret = 1;\n\treturn ret;\n\n fail:\n\treturn -1;\n}", "func_hash": 90014521593875335153131281847544251236, "file_name": "None", "file_hash": null, "cwe": ["CWE-755"], "cve": "CVE-2021-39242", "cve_desc": "An issue was discovered in HAProxy 2.2 before 2.2.16, 2.3 before 2.3.13, and 2.4 before 2.4.3. It can lead to a situation with an attacker-controlled HTTP Host header, because a mismatch between Host and authority is mishandled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-39242"} {"idx": 200929, "project": "vim", "commit_id": "0c8485f0e4931463c0f7986e1ea84a7d79f10c75", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/0c8485f0e4931463c0f7986e1ea84a7d79f10c75", "commit_message": "patch 8.0.0378: possible overflow when reading corrupted undo file\n\nProblem: Another possible overflow when reading corrupted undo file.\nSolution: Check if allocated size is not too big. (King)", "target": 1, "func": "unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name)\n{\n int\t\ti;\n u_entry_T\t*uep;\n char_u\t**array;\n char_u\t*line;\n int\t\tline_len;\n\n uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T));\n if (uep == NULL)\n\treturn NULL;\n vim_memset(uep, 0, sizeof(u_entry_T));\n#ifdef U_DEBUG\n uep->ue_magic = UE_MAGIC;\n#endif\n uep->ue_top = undo_read_4c(bi);\n uep->ue_bot = undo_read_4c(bi);\n uep->ue_lcount = undo_read_4c(bi);\n uep->ue_size = undo_read_4c(bi);\n if (uep->ue_size > 0)\n {\n\tarray = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size);\n\tif (array == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tvim_memset(array, 0, sizeof(char_u *) * uep->ue_size);\n }\n else\n\tarray = NULL;\n uep->ue_array = array;\n\n for (i = 0; i < uep->ue_size; ++i)\n {\n\tline_len = undo_read_4c(bi);\n\tif (line_len >= 0)\n\t line = read_string_decrypt(bi, line_len);\n\telse\n\t{\n\t line = NULL;\n\t corruption_error(\"line length\", file_name);\n\t}\n\tif (line == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tarray[i] = line;\n }\n return uep;\n}", "func_hash": 327197400748192645919858737355823275930, "file_name": "undo.c", "file_hash": 82858483916048105139054621003874665376, "cwe": ["CWE-190"], "cve": "CVE-2017-6350", "cve_desc": "An integer overflow at an unserialize_uep memory allocation site would occur for vim before patch 8.0.0378, if it does not properly validate values for tree length when reading a corrupted undo file, which may lead to resultant buffer overflows.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-6350"} {"idx": 313017, "project": "vim", "commit_id": "0c8485f0e4931463c0f7986e1ea84a7d79f10c75", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/0c8485f0e4931463c0f7986e1ea84a7d79f10c75", "commit_message": "patch 8.0.0378: possible overflow when reading corrupted undo file\n\nProblem: Another possible overflow when reading corrupted undo file.\nSolution: Check if allocated size is not too big. (King)", "target": 0, "func": "unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name)\n{\n int\t\ti;\n u_entry_T\t*uep;\n char_u\t**array = NULL;\n char_u\t*line;\n int\t\tline_len;\n\n uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T));\n if (uep == NULL)\n\treturn NULL;\n vim_memset(uep, 0, sizeof(u_entry_T));\n#ifdef U_DEBUG\n uep->ue_magic = UE_MAGIC;\n#endif\n uep->ue_top = undo_read_4c(bi);\n uep->ue_bot = undo_read_4c(bi);\n uep->ue_lcount = undo_read_4c(bi);\n uep->ue_size = undo_read_4c(bi);\n if (uep->ue_size > 0)\n {\n\tif (uep->ue_size < LONG_MAX / (int)sizeof(char_u *))\n\t array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size);\n\tif (array == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tvim_memset(array, 0, sizeof(char_u *) * uep->ue_size);\n }\n uep->ue_array = array;\n\n for (i = 0; i < uep->ue_size; ++i)\n {\n\tline_len = undo_read_4c(bi);\n\tif (line_len >= 0)\n\t line = read_string_decrypt(bi, line_len);\n\telse\n\t{\n\t line = NULL;\n\t corruption_error(\"line length\", file_name);\n\t}\n\tif (line == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tarray[i] = line;\n }\n return uep;\n}", "func_hash": 315225075710334621750009659022015663659, "file_name": "undo.c", "file_hash": 123186806903507924417943183038515182978, "cwe": ["CWE-190"], "cve": "CVE-2017-6350", "cve_desc": "An integer overflow at an unserialize_uep memory allocation site would occur for vim before patch 8.0.0378, if it does not properly validate values for tree length when reading a corrupted undo file, which may lead to resultant buffer overflows.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-6350"} {"idx": 201328, "project": "c-ares", "commit_id": "18ea99693d63f957ecb670045adbd2c1da8a4641", "project_url": "https://github.com/c-ares/c-ares", "commit_url": "https://github.com/c-ares/c-ares/commit/18ea99693d63f957ecb670045adbd2c1da8a4641", "commit_message": "ares_parse_naptr_reply: make buffer length check more accurate\n\n9478908a490a6bf009ba58d81de8c1d06d50a117 introduced a length check\nfor records parsed by `ares_parse_naptr_reply()`. However, that\nfunction is designed to parse replies which also contain non-NAPTR\nrecords; for A records, the `rr_len > 7` check will fail as there\nare only 4 bytes of payload.\nIn particular, parsing ANY replies for NAPTR records was broken\nby that patch.\n\nFix that by moving the check into the case in which it is already\nknown that the record is a NAPTR record.", "target": 1, "func": "ares_parse_naptr_reply (const unsigned char *abuf, int alen,\n struct ares_naptr_reply **naptr_out)\n{\n unsigned int qdcount, ancount, i;\n const unsigned char *aptr, *vptr;\n int status, rr_type, rr_class, rr_len;\n long len;\n char *hostname = NULL, *rr_name = NULL;\n struct ares_naptr_reply *naptr_head = NULL;\n struct ares_naptr_reply *naptr_last = NULL;\n struct ares_naptr_reply *naptr_curr;\n\n /* Set *naptr_out to NULL for all failure cases. */\n *naptr_out = NULL;\n\n /* Give up if abuf doesn't have room for a header. */\n if (alen < HFIXEDSZ)\n return ARES_EBADRESP;\n\n /* Fetch the question and answer count from the header. */\n qdcount = DNS_HEADER_QDCOUNT (abuf);\n ancount = DNS_HEADER_ANCOUNT (abuf);\n if (qdcount != 1)\n return ARES_EBADRESP;\n if (ancount == 0)\n return ARES_ENODATA;\n\n /* Expand the name from the question, and skip past the question. */\n aptr = abuf + HFIXEDSZ;\n status = ares_expand_name (aptr, abuf, alen, &hostname, &len);\n if (status != ARES_SUCCESS)\n return status;\n\n if (aptr + len + QFIXEDSZ > abuf + alen)\n {\n ares_free (hostname);\n return ARES_EBADRESP;\n }\n aptr += len + QFIXEDSZ;\n\n /* Examine each answer resource record (RR) in turn. */\n for (i = 0; i < ancount; i++)\n {\n /* Decode the RR up to the data field. */\n status = ares_expand_name (aptr, abuf, alen, &rr_name, &len);\n if (status != ARES_SUCCESS)\n {\n break;\n }\n aptr += len;\n if (aptr + RRFIXEDSZ > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n rr_type = DNS_RR_TYPE (aptr);\n rr_class = DNS_RR_CLASS (aptr);\n rr_len = DNS_RR_LEN (aptr);\n aptr += RRFIXEDSZ;\n if (aptr + rr_len > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n /* RR must contain at least 7 bytes = 2 x int16 + 3 x name */\n if (rr_len < 7)\n {\n status = ARES_EBADRESP;\n break;\n }\n\n /* Check if we are really looking at a NAPTR record */\n if (rr_class == C_IN && rr_type == T_NAPTR)\n {\n /* parse the NAPTR record itself */\n\n /* Allocate storage for this NAPTR answer appending it to the list */\n naptr_curr = ares_malloc_data(ARES_DATATYPE_NAPTR_REPLY);\n if (!naptr_curr)\n {\n status = ARES_ENOMEM;\n break;\n }\n if (naptr_last)\n {\n naptr_last->next = naptr_curr;\n }\n else\n {\n naptr_head = naptr_curr;\n }\n naptr_last = naptr_curr;\n\n vptr = aptr;\n naptr_curr->order = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n naptr_curr->preference = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->flags, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->service, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->regexp, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_name(vptr, abuf, alen, &naptr_curr->replacement, &len);\n if (status != ARES_SUCCESS)\n break;\n }\n\n /* Don't lose memory in the next iteration */\n ares_free (rr_name);\n rr_name = NULL;\n\n /* Move on to the next record */\n aptr += rr_len;\n }\n\n if (hostname)\n ares_free (hostname);\n if (rr_name)\n ares_free (rr_name);\n\n /* clean up on error */\n if (status != ARES_SUCCESS)\n {\n if (naptr_head)\n ares_free_data (naptr_head);\n return status;\n }\n\n /* everything looks fine, return the data */\n *naptr_out = naptr_head;\n\n return ARES_SUCCESS;\n}", "func_hash": 239962327114070830281735821595885335202, "file_name": "ares_parse_naptr_reply.c", "file_hash": 9627407212040676727554488602649022092, "cwe": ["CWE-200"], "cve": "CVE-2017-1000381", "cve_desc": "The c-ares function `ares_parse_naptr_reply()`, which is used for parsing NAPTR responses, could be triggered to read memory outside of the given input buffer if the passed in DNS response packet was crafted in a particular way.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-1000381"} {"idx": 316665, "project": "c-ares", "commit_id": "18ea99693d63f957ecb670045adbd2c1da8a4641", "project_url": "https://github.com/c-ares/c-ares", "commit_url": "https://github.com/c-ares/c-ares/commit/18ea99693d63f957ecb670045adbd2c1da8a4641", "commit_message": "ares_parse_naptr_reply: make buffer length check more accurate\n\n9478908a490a6bf009ba58d81de8c1d06d50a117 introduced a length check\nfor records parsed by `ares_parse_naptr_reply()`. However, that\nfunction is designed to parse replies which also contain non-NAPTR\nrecords; for A records, the `rr_len > 7` check will fail as there\nare only 4 bytes of payload.\nIn particular, parsing ANY replies for NAPTR records was broken\nby that patch.\n\nFix that by moving the check into the case in which it is already\nknown that the record is a NAPTR record.", "target": 0, "func": "ares_parse_naptr_reply (const unsigned char *abuf, int alen,\n struct ares_naptr_reply **naptr_out)\n{\n unsigned int qdcount, ancount, i;\n const unsigned char *aptr, *vptr;\n int status, rr_type, rr_class, rr_len;\n long len;\n char *hostname = NULL, *rr_name = NULL;\n struct ares_naptr_reply *naptr_head = NULL;\n struct ares_naptr_reply *naptr_last = NULL;\n struct ares_naptr_reply *naptr_curr;\n\n /* Set *naptr_out to NULL for all failure cases. */\n *naptr_out = NULL;\n\n /* Give up if abuf doesn't have room for a header. */\n if (alen < HFIXEDSZ)\n return ARES_EBADRESP;\n\n /* Fetch the question and answer count from the header. */\n qdcount = DNS_HEADER_QDCOUNT (abuf);\n ancount = DNS_HEADER_ANCOUNT (abuf);\n if (qdcount != 1)\n return ARES_EBADRESP;\n if (ancount == 0)\n return ARES_ENODATA;\n\n /* Expand the name from the question, and skip past the question. */\n aptr = abuf + HFIXEDSZ;\n status = ares_expand_name (aptr, abuf, alen, &hostname, &len);\n if (status != ARES_SUCCESS)\n return status;\n\n if (aptr + len + QFIXEDSZ > abuf + alen)\n {\n ares_free (hostname);\n return ARES_EBADRESP;\n }\n aptr += len + QFIXEDSZ;\n\n /* Examine each answer resource record (RR) in turn. */\n for (i = 0; i < ancount; i++)\n {\n /* Decode the RR up to the data field. */\n status = ares_expand_name (aptr, abuf, alen, &rr_name, &len);\n if (status != ARES_SUCCESS)\n {\n break;\n }\n aptr += len;\n if (aptr + RRFIXEDSZ > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n rr_type = DNS_RR_TYPE (aptr);\n rr_class = DNS_RR_CLASS (aptr);\n rr_len = DNS_RR_LEN (aptr);\n aptr += RRFIXEDSZ;\n if (aptr + rr_len > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n\n /* Check if we are really looking at a NAPTR record */\n if (rr_class == C_IN && rr_type == T_NAPTR)\n {\n /* parse the NAPTR record itself */\n\n /* RR must contain at least 7 bytes = 2 x int16 + 3 x name */\n if (rr_len < 7)\n {\n status = ARES_EBADRESP;\n break;\n }\n\n /* Allocate storage for this NAPTR answer appending it to the list */\n naptr_curr = ares_malloc_data(ARES_DATATYPE_NAPTR_REPLY);\n if (!naptr_curr)\n {\n status = ARES_ENOMEM;\n break;\n }\n if (naptr_last)\n {\n naptr_last->next = naptr_curr;\n }\n else\n {\n naptr_head = naptr_curr;\n }\n naptr_last = naptr_curr;\n\n vptr = aptr;\n naptr_curr->order = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n naptr_curr->preference = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->flags, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->service, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->regexp, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_name(vptr, abuf, alen, &naptr_curr->replacement, &len);\n if (status != ARES_SUCCESS)\n break;\n }\n\n /* Don't lose memory in the next iteration */\n ares_free (rr_name);\n rr_name = NULL;\n\n /* Move on to the next record */\n aptr += rr_len;\n }\n\n if (hostname)\n ares_free (hostname);\n if (rr_name)\n ares_free (rr_name);\n\n /* clean up on error */\n if (status != ARES_SUCCESS)\n {\n if (naptr_head)\n ares_free_data (naptr_head);\n return status;\n }\n\n /* everything looks fine, return the data */\n *naptr_out = naptr_head;\n\n return ARES_SUCCESS;\n}", "func_hash": 266802922176439515845504006942178821916, "file_name": "ares_parse_naptr_reply.c", "file_hash": 159776909466970404229846251567582869936, "cwe": ["CWE-200"], "cve": "CVE-2017-1000381", "cve_desc": "The c-ares function `ares_parse_naptr_reply()`, which is used for parsing NAPTR responses, could be triggered to read memory outside of the given input buffer if the passed in DNS response packet was crafted in a particular way.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-1000381"} {"idx": 201363, "project": "rpm", "commit_id": "8f4b3c3cab8922a2022b9e47c71f1ecf906077ef", "project_url": "https://github.com/rpm-software-management/rpm", "commit_url": "https://github.com/rpm-software-management/rpm/commit/8f4b3c3cab8922a2022b9e47c71f1ecf906077ef", "commit_message": "hdrblobInit() needs bounds checks too\n\nUsers can pass untrusted data to hdrblobInit() and it must be robust\nagainst this.", "target": 1, "func": "rpmRC hdrblobInit(const void *uh, size_t uc,\n\t\trpmTagVal regionTag, int exact_size,\n\t\tstruct hdrblob_s *blob, char **emsg)\n{\n rpmRC rc = RPMRC_FAIL;\n\n memset(blob, 0, sizeof(*blob));\n blob->ei = (int32_t *) uh; /* discards const */\n blob->il = ntohl(blob->ei[0]);\n blob->dl = ntohl(blob->ei[1]);\n blob->pe = (entryInfo) &(blob->ei[2]);\n blob->pvlen = sizeof(blob->il) + sizeof(blob->dl) +\n\t\t (blob->il * sizeof(*blob->pe)) + blob->dl;\n blob->dataStart = (uint8_t *) (blob->pe + blob->il);\n blob->dataEnd = blob->dataStart + blob->dl;\n\n /* Is the blob the right size? */\n if (blob->pvlen >= headerMaxbytes || (uc && blob->pvlen != uc)) {\n\trasprintf(emsg, _(\"blob size(%d): BAD, 8 + 16 * il(%d) + dl(%d)\"),\n\t\t\tblob->pvlen, blob->il, blob->dl);\n\tgoto exit;\n }\n\n if (hdrblobVerifyRegion(regionTag, exact_size, blob, emsg) == RPMRC_FAIL)\n\tgoto exit;\n\n /* Sanity check the rest of the header structure. */\n if (hdrblobVerifyInfo(blob, emsg))\n\tgoto exit;\n\n rc = RPMRC_OK;\n\nexit:\n return rc;\n}", "func_hash": 301716865365339247392542035183086942109, "file_name": "header.c", "file_hash": 322670567468519059954113434368615292630, "cwe": ["CWE-125"], "cve": "CVE-2021-20266", "cve_desc": "A flaw was found in RPM's hdrblobInit() in lib/header.c. This flaw allows an attacker who can modify the rpmdb to cause an out-of-bounds read. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20266"} {"idx": 318167, "project": "rpm", "commit_id": "8f4b3c3cab8922a2022b9e47c71f1ecf906077ef", "project_url": "https://github.com/rpm-software-management/rpm", "commit_url": "https://github.com/rpm-software-management/rpm/commit/8f4b3c3cab8922a2022b9e47c71f1ecf906077ef", "commit_message": "hdrblobInit() needs bounds checks too\n\nUsers can pass untrusted data to hdrblobInit() and it must be robust\nagainst this.", "target": 0, "func": "rpmRC hdrblobInit(const void *uh, size_t uc,\n\t\trpmTagVal regionTag, int exact_size,\n\t\tstruct hdrblob_s *blob, char **emsg)\n{\n rpmRC rc = RPMRC_FAIL;\n memset(blob, 0, sizeof(*blob));\n if (uc && uc < 8) {\n\trasprintf(emsg, _(\"hdr length: BAD\"));\n\tgoto exit;\n }\n\n blob->ei = (int32_t *) uh; /* discards const */\n blob->il = ntohl((uint32_t)(blob->ei[0]));\n blob->dl = ntohl((uint32_t)(blob->ei[1]));\n if (hdrblobVerifyLengths(regionTag, blob->il, blob->dl, emsg) != RPMRC_OK)\n\tgoto exit;\n\n blob->pe = (entryInfo) &(blob->ei[2]);\n blob->pvlen = sizeof(blob->il) + sizeof(blob->dl) +\n\t\t (blob->il * sizeof(*blob->pe)) + blob->dl;\n blob->dataStart = (uint8_t *) (blob->pe + blob->il);\n blob->dataEnd = blob->dataStart + blob->dl;\n\n /* Is the blob the right size? */\n if (blob->pvlen >= headerMaxbytes || (uc && blob->pvlen != uc)) {\n\trasprintf(emsg, _(\"blob size(%d): BAD, 8 + 16 * il(%d) + dl(%d)\"),\n\t\t\tblob->pvlen, blob->il, blob->dl);\n\tgoto exit;\n }\n\n if (hdrblobVerifyRegion(regionTag, exact_size, blob, emsg) == RPMRC_FAIL)\n\tgoto exit;\n\n /* Sanity check the rest of the header structure. */\n if (hdrblobVerifyInfo(blob, emsg))\n\tgoto exit;\n\n rc = RPMRC_OK;\n\nexit:\n return rc;\n}", "func_hash": 84581467962749687354660841962582143700, "file_name": "header.c", "file_hash": 234999524695128281049278621731368042043, "cwe": ["CWE-125"], "cve": "CVE-2021-20266", "cve_desc": "A flaw was found in RPM's hdrblobInit() in lib/header.c. This flaw allows an attacker who can modify the rpmdb to cause an out-of-bounds read. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20266"} {"idx": 201415, "project": "LibRaw", "commit_id": "11c4db253ef2c9bb44247b578f5caa57c66a1eeb", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/11c4db253ef2c9bb44247b578f5caa57c66a1eeb", "commit_message": "X3F: check huffman tree size", "target": 1, "func": "static x3f_huffnode_t *new_node(x3f_hufftree_t *tree)\n{\n x3f_huffnode_t *t = &tree->nodes[tree->free_node_index];\n\n t->branch[0] = NULL;\n t->branch[1] = NULL;\n t->leaf = UNDEFINED_LEAF;\n\n tree->free_node_index++;\n\n return t;\n}", "func_hash": 252086069676656631933860697580841125653, "file_name": "x3f_utils_patched.cpp", "file_hash": 125502382285238969186382809517472205856, "cwe": ["CWE-125"], "cve": "CVE-2020-35530", "cve_desc": "In LibRaw, there is an out-of-bounds write vulnerability within the \"new_node()\" function (libraw\\src\\x3f\\x3f_utils_patched.cpp) that can be triggered via a crafted X3F file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35530"} {"idx": 319168, "project": "LibRaw", "commit_id": "11c4db253ef2c9bb44247b578f5caa57c66a1eeb", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/11c4db253ef2c9bb44247b578f5caa57c66a1eeb", "commit_message": "X3F: check huffman tree size", "target": 0, "func": "static x3f_huffnode_t *new_node(x3f_hufftree_t *tree)\n{\n\tif (tree->free_node_index >= tree->total_node_index)\n\t\tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\n x3f_huffnode_t *t = &tree->nodes[tree->free_node_index];\n\n t->branch[0] = NULL;\n t->branch[1] = NULL;\n t->leaf = UNDEFINED_LEAF;\n\n tree->free_node_index++;\n\n return t;\n}", "func_hash": 52977493947480414184767633449624564721, "file_name": "x3f_utils_patched.cpp", "file_hash": 63954127465419972213528503005419330449, "cwe": ["CWE-125"], "cve": "CVE-2020-35530", "cve_desc": "In LibRaw, there is an out-of-bounds write vulnerability within the \"new_node()\" function (libraw\\src\\x3f\\x3f_utils_patched.cpp) that can be triggered via a crafted X3F file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35530"} {"idx": 201423, "project": "linux", "commit_id": "26896f01467a28651f7a536143fe5ac8449d4041", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/26896f01467a28651f7a536143fe5ac8449d4041", "commit_message": "net/nfc/rawsock.c: add CAP_NET_RAW check.\n\nWhen creating a raw AF_NFC socket, CAP_NET_RAW needs to be checked first.\n\nSigned-off-by: Qingyu Li \nSigned-off-by: David S. Miller ", "target": 1, "func": "static int rawsock_create(struct net *net, struct socket *sock,\n\t\t\t const struct nfc_protocol *nfc_proto, int kern)\n{\n\tstruct sock *sk;\n\n\tpr_debug(\"sock=%p\\n\", sock);\n\n\tif ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW))\n\t\treturn -ESOCKTNOSUPPORT;\n\n\tif (sock->type == SOCK_RAW)\n\t\tsock->ops = &rawsock_raw_ops;\n\telse\n\t\tsock->ops = &rawsock_ops;\n\n\tsk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern);\n\tif (!sk)\n\t\treturn -ENOMEM;\n\n\tsock_init_data(sock, sk);\n\tsk->sk_protocol = nfc_proto->id;\n\tsk->sk_destruct = rawsock_destruct;\n\tsock->state = SS_UNCONNECTED;\n\tif (sock->type == SOCK_RAW)\n\t\tnfc_sock_link(&raw_sk_list, sk);\n\telse {\n\t\tINIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work);\n\t\tnfc_rawsock(sk)->tx_work_scheduled = false;\n\t}\n\n\treturn 0;\n}", "func_hash": 8839472821818158110276114932140898937, "file_name": "rawsock.c", "file_hash": 126921203043664712142730181497904427678, "cwe": ["CWE-703"], "cve": "CVE-2020-26088", "cve_desc": "A missing CAP_NET_RAW check in NFC socket creation in net/nfc/rawsock.c in the Linux kernel before 5.8.2 could be used by local attackers to create raw sockets, bypassing security mechanisms, aka CID-26896f01467a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-26088"} {"idx": 319215, "project": "linux", "commit_id": "26896f01467a28651f7a536143fe5ac8449d4041", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/26896f01467a28651f7a536143fe5ac8449d4041", "commit_message": "net/nfc/rawsock.c: add CAP_NET_RAW check.\n\nWhen creating a raw AF_NFC socket, CAP_NET_RAW needs to be checked first.\n\nSigned-off-by: Qingyu Li \nSigned-off-by: David S. Miller ", "target": 0, "func": "static int rawsock_create(struct net *net, struct socket *sock,\n\t\t\t const struct nfc_protocol *nfc_proto, int kern)\n{\n\tstruct sock *sk;\n\n\tpr_debug(\"sock=%p\\n\", sock);\n\n\tif ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW))\n\t\treturn -ESOCKTNOSUPPORT;\n\n\tif (sock->type == SOCK_RAW) {\n\t\tif (!capable(CAP_NET_RAW))\n\t\t\treturn -EPERM;\n\t\tsock->ops = &rawsock_raw_ops;\n\t} else {\n\t\tsock->ops = &rawsock_ops;\n\t}\n\n\tsk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern);\n\tif (!sk)\n\t\treturn -ENOMEM;\n\n\tsock_init_data(sock, sk);\n\tsk->sk_protocol = nfc_proto->id;\n\tsk->sk_destruct = rawsock_destruct;\n\tsock->state = SS_UNCONNECTED;\n\tif (sock->type == SOCK_RAW)\n\t\tnfc_sock_link(&raw_sk_list, sk);\n\telse {\n\t\tINIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work);\n\t\tnfc_rawsock(sk)->tx_work_scheduled = false;\n\t}\n\n\treturn 0;\n}", "func_hash": 209495892720533065264478328264560655892, "file_name": "rawsock.c", "file_hash": 175288876723148485653017060371161222961, "cwe": ["CWE-703"], "cve": "CVE-2020-26088", "cve_desc": "A missing CAP_NET_RAW check in NFC socket creation in net/nfc/rawsock.c in the Linux kernel before 5.8.2 could be used by local attackers to create raw sockets, bypassing security mechanisms, aka CID-26896f01467a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-26088"} {"idx": 201452, "project": "LibRaw", "commit_id": "a6937d4046a7c4742b683a04c8564605fd9be4fb", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/a6937d4046a7c4742b683a04c8564605fd9be4fb", "commit_message": "more room for ljpeg row", "target": 1, "func": "int LibRaw::ljpeg_start(struct jhead *jh, int info_only)\n{\n ushort c, tag, len;\n int cnt = 0;\n uchar data[0x10000];\n const uchar *dp;\n\n memset(jh, 0, sizeof *jh);\n jh->restart = INT_MAX;\n if ((fgetc(ifp), fgetc(ifp)) != 0xd8)\n return 0;\n do\n {\n if (feof(ifp))\n return 0;\n if (cnt++ > 1024)\n return 0; // 1024 tags limit\n if (!fread(data, 2, 2, ifp))\n return 0;\n tag = data[0] << 8 | data[1];\n len = (data[2] << 8 | data[3]) - 2;\n if (tag <= 0xff00)\n return 0;\n fread(data, 1, len, ifp);\n switch (tag)\n {\n case 0xffc3: // start of frame; lossless, Huffman\n jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;\n case 0xffc1:\n case 0xffc0:\n jh->algo = tag & 0xff;\n jh->bits = data[0];\n jh->high = data[1] << 8 | data[2];\n jh->wide = data[3] << 8 | data[4];\n jh->clrs = data[5] + jh->sraw;\n if (len == 9 && !dng_version)\n getc(ifp);\n break;\n case 0xffc4: // define Huffman tables\n if (info_only)\n break;\n for (dp = data; dp < data + len && !((c = *dp++) & -20);)\n jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);\n break;\n case 0xffda: // start of scan\n jh->psv = data[1 + data[0] * 2];\n jh->bits -= data[3 + data[0] * 2] & 15;\n break;\n case 0xffdb:\n FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];\n break;\n case 0xffdd:\n jh->restart = data[0] << 8 | data[1];\n }\n } while (tag != 0xffda);\n if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide ||\n !jh->clrs)\n return 0;\n if (info_only)\n return 1;\n if (!jh->huff[0])\n return 0;\n FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];\n if (jh->sraw)\n {\n FORC(4) jh->huff[2 + c] = jh->huff[1];\n FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];\n }\n jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);\n merror(jh->row, \"ljpeg_start()\");\n return zero_after_ff = 1;\n}", "func_hash": 322743651220168797219003515176534035921, "file_name": "decoders_dcraw.cpp", "file_hash": 48736225669100654754252650108618211565, "cwe": ["CWE-125"], "cve": "CVE-2020-35533", "cve_desc": "In LibRaw, an out-of-bounds read vulnerability exists within the \"LibRaw::adobe_copy_pixel()\" function (libraw\\src\\decoders\\dng.cpp) when reading data from the image file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35533"} {"idx": 319453, "project": "LibRaw", "commit_id": "a6937d4046a7c4742b683a04c8564605fd9be4fb", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/a6937d4046a7c4742b683a04c8564605fd9be4fb", "commit_message": "more room for ljpeg row", "target": 0, "func": "int LibRaw::ljpeg_start(struct jhead *jh, int info_only)\n{\n ushort c, tag, len;\n int cnt = 0;\n uchar data[0x10000];\n const uchar *dp;\n\n memset(jh, 0, sizeof *jh);\n jh->restart = INT_MAX;\n if ((fgetc(ifp), fgetc(ifp)) != 0xd8)\n return 0;\n do\n {\n if (feof(ifp))\n return 0;\n if (cnt++ > 1024)\n return 0; // 1024 tags limit\n if (!fread(data, 2, 2, ifp))\n return 0;\n tag = data[0] << 8 | data[1];\n len = (data[2] << 8 | data[3]) - 2;\n if (tag <= 0xff00)\n return 0;\n fread(data, 1, len, ifp);\n switch (tag)\n {\n case 0xffc3: // start of frame; lossless, Huffman\n jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;\n case 0xffc1:\n case 0xffc0:\n jh->algo = tag & 0xff;\n jh->bits = data[0];\n jh->high = data[1] << 8 | data[2];\n jh->wide = data[3] << 8 | data[4];\n jh->clrs = data[5] + jh->sraw;\n if (len == 9 && !dng_version)\n getc(ifp);\n break;\n case 0xffc4: // define Huffman tables\n if (info_only)\n break;\n for (dp = data; dp < data + len && !((c = *dp++) & -20);)\n jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);\n break;\n case 0xffda: // start of scan\n jh->psv = data[1 + data[0] * 2];\n jh->bits -= data[3 + data[0] * 2] & 15;\n break;\n case 0xffdb:\n FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];\n break;\n case 0xffdd:\n jh->restart = data[0] << 8 | data[1];\n }\n } while (tag != 0xffda);\n if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide ||\n !jh->clrs)\n return 0;\n if (info_only)\n return 1;\n if (!jh->huff[0])\n return 0;\n FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];\n if (jh->sraw)\n {\n FORC(4) jh->huff[2 + c] = jh->huff[1];\n FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];\n }\n jh->row = (ushort *)calloc(jh->wide * jh->clrs, 16);\n merror(jh->row, \"ljpeg_start()\");\n return zero_after_ff = 1;\n}", "func_hash": 29863719933186884290123318021370944200, "file_name": "decoders_dcraw.cpp", "file_hash": 265244345354502091486817281655032198705, "cwe": ["CWE-125"], "cve": "CVE-2020-35533", "cve_desc": "In LibRaw, an out-of-bounds read vulnerability exists within the \"LibRaw::adobe_copy_pixel()\" function (libraw\\src\\decoders\\dng.cpp) when reading data from the image file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35533"} {"idx": 201788, "project": "linux", "commit_id": "5bfea2d9b17f1034a68147a8b03b9789af5700f9", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5bfea2d9b17f1034a68147a8b03b9789af5700f9", "commit_message": "mm: Fix mremap not considering huge pmd devmap\n\nThe original code in mm/mremap.c checks huge pmd by:\n\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) {\n\nHowever, a DAX mapped nvdimm is mapped as huge page (by default) but it\nis not transparent huge page (_PAGE_PSE | PAGE_DEVMAP). This commit\nchanges the condition to include the case.\n\nThis addresses CVE-2020-10757.\n\nFixes: 5c7fb56e5e3f (\"mm, dax: dax-pmd vs thp-pmd vs hugetlbfs-pmd\")\nCc: \nReported-by: Fan Yang \nSigned-off-by: Fan Yang \nTested-by: Fan Yang \nTested-by: Dan Williams \nReviewed-by: Dan Williams \nAcked-by: Kirill A. Shutemov \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "unsigned long move_page_tables(struct vm_area_struct *vma,\n\t\tunsigned long old_addr, struct vm_area_struct *new_vma,\n\t\tunsigned long new_addr, unsigned long len,\n\t\tbool need_rmap_locks)\n{\n\tunsigned long extent, next, old_end;\n\tstruct mmu_notifier_range range;\n\tpmd_t *old_pmd, *new_pmd;\n\n\told_end = old_addr + len;\n\tflush_cache_range(vma, old_addr, old_end);\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,\n\t\t\t\told_addr, old_end);\n\tmmu_notifier_invalidate_range_start(&range);\n\n\tfor (; old_addr < old_end; old_addr += extent, new_addr += extent) {\n\t\tcond_resched();\n\t\tnext = (old_addr + PMD_SIZE) & PMD_MASK;\n\t\t/* even if next overflowed, extent below will be ok */\n\t\textent = next - old_addr;\n\t\tif (extent > old_end - old_addr)\n\t\t\textent = old_end - old_addr;\n\t\told_pmd = get_old_pmd(vma->vm_mm, old_addr);\n\t\tif (!old_pmd)\n\t\t\tcontinue;\n\t\tnew_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr);\n\t\tif (!new_pmd)\n\t\t\tbreak;\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) {\n\t\t\tif (extent == HPAGE_PMD_SIZE) {\n\t\t\t\tbool moved;\n\t\t\t\t/* See comment in move_ptes() */\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\ttake_rmap_locks(vma);\n\t\t\t\tmoved = move_huge_pmd(vma, old_addr, new_addr,\n\t\t\t\t\t\t old_end, old_pmd, new_pmd);\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\tdrop_rmap_locks(vma);\n\t\t\t\tif (moved)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsplit_huge_pmd(vma, old_pmd, old_addr);\n\t\t\tif (pmd_trans_unstable(old_pmd))\n\t\t\t\tcontinue;\n\t\t} else if (extent == PMD_SIZE) {\n#ifdef CONFIG_HAVE_MOVE_PMD\n\t\t\t/*\n\t\t\t * If the extent is PMD-sized, try to speed the move by\n\t\t\t * moving at the PMD level if possible.\n\t\t\t */\n\t\t\tbool moved;\n\n\t\t\tif (need_rmap_locks)\n\t\t\t\ttake_rmap_locks(vma);\n\t\t\tmoved = move_normal_pmd(vma, old_addr, new_addr,\n\t\t\t\t\told_end, old_pmd, new_pmd);\n\t\t\tif (need_rmap_locks)\n\t\t\t\tdrop_rmap_locks(vma);\n\t\t\tif (moved)\n\t\t\t\tcontinue;\n#endif\n\t\t}\n\n\t\tif (pte_alloc(new_vma->vm_mm, new_pmd))\n\t\t\tbreak;\n\t\tnext = (new_addr + PMD_SIZE) & PMD_MASK;\n\t\tif (extent > next - new_addr)\n\t\t\textent = next - new_addr;\n\t\tmove_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma,\n\t\t\t new_pmd, new_addr, need_rmap_locks);\n\t}\n\n\tmmu_notifier_invalidate_range_end(&range);\n\n\treturn len + old_addr - old_end;\t/* how much done */\n}", "func_hash": 217628362247811983438295314022266063868, "file_name": "mremap.c", "file_hash": 125293753059907057832882238869154600994, "cwe": ["CWE-119"], "cve": "CVE-2020-10757", "cve_desc": "A flaw was found in the Linux Kernel in versions after 4.5-rc1 in the way mremap handled DAX Huge Pages. This flaw allows a local attacker with access to a DAX enabled storage to escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10757"} {"idx": 321574, "project": "linux", "commit_id": "5bfea2d9b17f1034a68147a8b03b9789af5700f9", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5bfea2d9b17f1034a68147a8b03b9789af5700f9", "commit_message": "mm: Fix mremap not considering huge pmd devmap\n\nThe original code in mm/mremap.c checks huge pmd by:\n\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) {\n\nHowever, a DAX mapped nvdimm is mapped as huge page (by default) but it\nis not transparent huge page (_PAGE_PSE | PAGE_DEVMAP). This commit\nchanges the condition to include the case.\n\nThis addresses CVE-2020-10757.\n\nFixes: 5c7fb56e5e3f (\"mm, dax: dax-pmd vs thp-pmd vs hugetlbfs-pmd\")\nCc: \nReported-by: Fan Yang \nSigned-off-by: Fan Yang \nTested-by: Fan Yang \nTested-by: Dan Williams \nReviewed-by: Dan Williams \nAcked-by: Kirill A. Shutemov \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "unsigned long move_page_tables(struct vm_area_struct *vma,\n\t\tunsigned long old_addr, struct vm_area_struct *new_vma,\n\t\tunsigned long new_addr, unsigned long len,\n\t\tbool need_rmap_locks)\n{\n\tunsigned long extent, next, old_end;\n\tstruct mmu_notifier_range range;\n\tpmd_t *old_pmd, *new_pmd;\n\n\told_end = old_addr + len;\n\tflush_cache_range(vma, old_addr, old_end);\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,\n\t\t\t\told_addr, old_end);\n\tmmu_notifier_invalidate_range_start(&range);\n\n\tfor (; old_addr < old_end; old_addr += extent, new_addr += extent) {\n\t\tcond_resched();\n\t\tnext = (old_addr + PMD_SIZE) & PMD_MASK;\n\t\t/* even if next overflowed, extent below will be ok */\n\t\textent = next - old_addr;\n\t\tif (extent > old_end - old_addr)\n\t\t\textent = old_end - old_addr;\n\t\told_pmd = get_old_pmd(vma->vm_mm, old_addr);\n\t\tif (!old_pmd)\n\t\t\tcontinue;\n\t\tnew_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr);\n\t\tif (!new_pmd)\n\t\t\tbreak;\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd) || pmd_devmap(*old_pmd)) {\n\t\t\tif (extent == HPAGE_PMD_SIZE) {\n\t\t\t\tbool moved;\n\t\t\t\t/* See comment in move_ptes() */\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\ttake_rmap_locks(vma);\n\t\t\t\tmoved = move_huge_pmd(vma, old_addr, new_addr,\n\t\t\t\t\t\t old_end, old_pmd, new_pmd);\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\tdrop_rmap_locks(vma);\n\t\t\t\tif (moved)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsplit_huge_pmd(vma, old_pmd, old_addr);\n\t\t\tif (pmd_trans_unstable(old_pmd))\n\t\t\t\tcontinue;\n\t\t} else if (extent == PMD_SIZE) {\n#ifdef CONFIG_HAVE_MOVE_PMD\n\t\t\t/*\n\t\t\t * If the extent is PMD-sized, try to speed the move by\n\t\t\t * moving at the PMD level if possible.\n\t\t\t */\n\t\t\tbool moved;\n\n\t\t\tif (need_rmap_locks)\n\t\t\t\ttake_rmap_locks(vma);\n\t\t\tmoved = move_normal_pmd(vma, old_addr, new_addr,\n\t\t\t\t\told_end, old_pmd, new_pmd);\n\t\t\tif (need_rmap_locks)\n\t\t\t\tdrop_rmap_locks(vma);\n\t\t\tif (moved)\n\t\t\t\tcontinue;\n#endif\n\t\t}\n\n\t\tif (pte_alloc(new_vma->vm_mm, new_pmd))\n\t\t\tbreak;\n\t\tnext = (new_addr + PMD_SIZE) & PMD_MASK;\n\t\tif (extent > next - new_addr)\n\t\t\textent = next - new_addr;\n\t\tmove_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma,\n\t\t\t new_pmd, new_addr, need_rmap_locks);\n\t}\n\n\tmmu_notifier_invalidate_range_end(&range);\n\n\treturn len + old_addr - old_end;\t/* how much done */\n}", "func_hash": 153037476615333102957042536877006509705, "file_name": "mremap.c", "file_hash": 42990208681723589760474842454090377628, "cwe": ["CWE-119"], "cve": "CVE-2020-10757", "cve_desc": "A flaw was found in the Linux Kernel in versions after 4.5-rc1 in the way mremap handled DAX Huge Pages. This flaw allows a local attacker with access to a DAX enabled storage to escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10757"} {"idx": 201806, "project": "ast", "commit_id": "c7de8b641266bac7c77942239ac659edfee9ecd2", "project_url": "https://github.com/att/ast", "commit_url": "https://github.com/att/ast/commit/c7de8b641266bac7c77942239ac659edfee9ecd2", "commit_message": "Harden env var imports", "target": 1, "func": "Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {\n Sfdouble_t d;\n char *last;\n\n if (*str == 0) {\n if (ptr) *ptr = (char *)str;\n return 0;\n }\n errno = 0;\n d = number(str, &last, shp->inarith ? 0 : 10, NULL);\n if (*last) {\n if (*last != '.' || last[1] != '.') {\n d = strval(shp, str, &last, arith, mode);\n Varsubscript = true;\n }\n if (!ptr && *last && mode > 0) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);\n } else if (!d && *str == '-') {\n d = -0.0;\n }\n if (ptr) *ptr = last;\n return d;\n}", "func_hash": 215836460638118486199662295702618331319, "file_name": "arith.c", "file_hash": 235402452855340028707061123441434771796, "cwe": ["CWE-77"], "cve": "CVE-2019-14868", "cve_desc": "In ksh version 20120801, a flaw was found in the way it evaluates certain environment variables. An attacker could use this flaw to override or bypass environment restrictions to execute shell commands. Services and applications that allow remote unauthenticated attackers to provide one of those environment variables could allow them to exploit this issue remotely.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14868"} {"idx": 321871, "project": "ast", "commit_id": "c7de8b641266bac7c77942239ac659edfee9ecd2", "project_url": "https://github.com/att/ast", "commit_url": "https://github.com/att/ast/commit/c7de8b641266bac7c77942239ac659edfee9ecd2", "commit_message": "Harden env var imports", "target": 0, "func": "Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {\n Sfdouble_t d;\n char *last;\n\n if (*str == 0) {\n d = 0.0;\n last = (char *)str;\n } else {\n d = number(str, &last, shp->inarith ? 0 : 10, NULL);\n if (*last && !shp->inarith && sh_isstate(shp, SH_INIT)) {\n // This call is to handle \"base#value\" literals if we're importing untrusted env vars.\n d = number(str, &last, 0, NULL);\n }\n if (*last) {\n if (sh_isstate(shp, SH_INIT)) {\n // Initializing means importing untrusted env vars. Since the string does not appear\n // to be a recognized numeric literal give up. We can't safely call strval() since\n // that allows arbitrary expressions which would create a security vulnerability.\n d = 0.0;\n } else {\n if (*last != '.' || last[1] != '.') {\n d = strval(shp, str, &last, arith, mode);\n Varsubscript = true;\n }\n if (!ptr && *last && mode > 0) {\n errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);\n }\n }\n } else if (d == 0.0 && *str == '-') {\n d = -0.0;\n }\n }\n if (ptr) *ptr = last;\n return d;\n}", "func_hash": 304332889864012666049724416347009997018, "file_name": "arith.c", "file_hash": 63870330715861933674648393598455092934, "cwe": ["CWE-77"], "cve": "CVE-2019-14868", "cve_desc": "In ksh version 20120801, a flaw was found in the way it evaluates certain environment variables. An attacker could use this flaw to override or bypass environment restrictions to execute shell commands. Services and applications that allow remote unauthenticated attackers to provide one of those environment variables could allow them to exploit this issue remotely.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14868"} {"idx": 201848, "project": "slurm", "commit_id": "07309deb45c33e735e191faf9dd31cca1054a15c", "project_url": "https://github.com/SchedMD/slurm", "commit_url": "https://github.com/SchedMD/slurm/commit/07309deb45c33e735e191faf9dd31cca1054a15c", "commit_message": "X11 forwarding - avoid unsafe use of magic cookie as arg to xauth command.\n\nMagic cookie can leak through /proc this way. There is a race here between\nthis usually short-lived xauth command running and an attacker scraping\nthe value from /proc. This can be exacerbated through use of\nX11Parameters=home_xauthority on a cluster with a shared home directory\nunder heavy load.\n\nCVE-2020-27746.", "target": 1, "func": "extern int x11_set_xauth(char *xauthority, char *cookie,\n\t\t\t char *host, uint16_t display)\n{\n\tint i=0, status;\n\tchar *result;\n\tchar **xauth_argv;\n\n\txauth_argv = xmalloc(sizeof(char *) * 10);\n\txauth_argv[i++] = xstrdup(\"xauth\");\n\txauth_argv[i++] = xstrdup(\"-v\");\n\txauth_argv[i++] = xstrdup(\"-f\");\n\txauth_argv[i++] = xstrdup(xauthority);\n\txauth_argv[i++] = xstrdup(\"add\");\n\txauth_argv[i++] = xstrdup_printf(\"%s/unix:%u\", host, display);\n\txauth_argv[i++] = xstrdup(\"MIT-MAGIC-COOKIE-1\");\n\txauth_argv[i++] = xstrdup(cookie);\n\txauth_argv[i++] = NULL;\n\txassert(i < 10);\n\n\tresult = run_command(\"xauth\", XAUTH_PATH, xauth_argv, 10000, 0,\n\t\t\t &status);\n\n\tfree_command_argv(xauth_argv);\n\n\tdebug2(\"%s: result from xauth: %s\", __func__, result);\n\txfree(result);\n\n\treturn status;\n}", "func_hash": 73336430247539137344480406259513148651, "file_name": "x11_util.c", "file_hash": 180288568161978377004156056960102887284, "cwe": ["CWE-362"], "cve": "CVE-2020-27746", "cve_desc": "Slurm before 19.05.8 and 20.x before 20.02.6 exposes Sensitive Information to an Unauthorized Actor because xauth for X11 magic cookies is affected by a race condition in a read operation on the /proc filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27746"} {"idx": 323088, "project": "slurm", "commit_id": "07309deb45c33e735e191faf9dd31cca1054a15c", "project_url": "https://github.com/SchedMD/slurm", "commit_url": "https://github.com/SchedMD/slurm/commit/07309deb45c33e735e191faf9dd31cca1054a15c", "commit_message": "X11 forwarding - avoid unsafe use of magic cookie as arg to xauth command.\n\nMagic cookie can leak through /proc this way. There is a race here between\nthis usually short-lived xauth command running and an attacker scraping\nthe value from /proc. This can be exacerbated through use of\nX11Parameters=home_xauthority on a cluster with a shared home directory\nunder heavy load.\n\nCVE-2020-27746.", "target": 0, "func": "extern int x11_delete_xauth(char *xauthority, char *host, uint16_t display)\n{\n\tint i=0, status;\n\tchar *result;\n\tchar **xauth_argv;\n\n\txauth_argv = xmalloc(sizeof(char *) * 10);\n\txauth_argv[i++] = xstrdup(\"xauth\");\n\txauth_argv[i++] = xstrdup(\"-v\");\n\txauth_argv[i++] = xstrdup(\"-f\");\n\txauth_argv[i++] = xstrdup(xauthority);\n\txauth_argv[i++] = xstrdup(\"remove\");\n\txauth_argv[i++] = xstrdup_printf(\"%s/unix:%u\", host, display);\n\txauth_argv[i++] = NULL;\n\txassert(i < 10);\n\n\tresult = run_command(\"xauth\", XAUTH_PATH, xauth_argv, 10000, 0,\n\t\t\t &status);\n\n\tfree_command_argv(xauth_argv);\n\n\tdebug2(\"%s: result from xauth: %s\", __func__, result);\n\txfree(result);\n\n\treturn status;\n}", "func_hash": 106614588847172832919347175399049946864, "file_name": "x11_util.c", "file_hash": 78234020228006056307672467892700877519, "cwe": ["CWE-362"], "cve": "CVE-2020-27746", "cve_desc": "Slurm before 19.05.8 and 20.x before 20.02.6 exposes Sensitive Information to an Unauthorized Actor because xauth for X11 magic cookies is affected by a race condition in a read operation on the /proc filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27746"} {"idx": 201874, "project": "libarchive", "commit_id": "4f085eea879e2be745f4d9bf57e8513ae48157f4", "project_url": "https://github.com/libarchive/libarchive", "commit_url": "https://github.com/libarchive/libarchive/commit/4f085eea879e2be745f4d9bf57e8513ae48157f4", "commit_message": "Fix a possible heap-buffer-overflow in archive_string_append_from_wcs()\n\nWhen we grow the archive_string buffer, we have to make sure it fits\nat least one maximum-sized multibyte character in the current locale\nand the null character.\n\nFixes #1298", "target": 1, "func": "archive_string_append_from_wcs(struct archive_string *as,\n const wchar_t *w, size_t len)\n{\n\t/* We cannot use the standard wcstombs() here because it\n\t * cannot tell us how big the output buffer should be. So\n\t * I've built a loop around wcrtomb() or wctomb() that\n\t * converts a character at a time and resizes the string as\n\t * needed. We prefer wcrtomb() when it's available because\n\t * it's thread-safe. */\n\tint n, ret_val = 0;\n\tchar *p;\n\tchar *end;\n#if HAVE_WCRTOMB\n\tmbstate_t shift_state;\n\n\tmemset(&shift_state, 0, sizeof(shift_state));\n#else\n\t/* Clear the shift state before starting. */\n\twctomb(NULL, L'\\0');\n#endif\n\t/*\n\t * Allocate buffer for MBS.\n\t * We need this allocation here since it is possible that\n\t * as->s is still NULL.\n\t */\n\tif (archive_string_ensure(as, as->length + len + 1) == NULL)\n\t\treturn (-1);\n\n\tp = as->s + as->length;\n\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\twhile (*w != L'\\0' && len > 0) {\n\t\tif (p >= end) {\n\t\t\tas->length = p - as->s;\n\t\t\tas->s[as->length] = '\\0';\n\t\t\t/* Re-allocate buffer for MBS. */\n\t\t\tif (archive_string_ensure(as,\n\t\t\t as->length + len * 2 + 1) == NULL)\n\t\t\t\treturn (-1);\n\t\t\tp = as->s + as->length;\n\t\t\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\t\t}\n#if HAVE_WCRTOMB\n\t\tn = wcrtomb(p, *w++, &shift_state);\n#else\n\t\tn = wctomb(p, *w++);\n#endif\n\t\tif (n == -1) {\n\t\t\tif (errno == EILSEQ) {\n\t\t\t\t/* Skip an illegal wide char. */\n\t\t\t\t*p++ = '?';\n\t\t\t\tret_val = -1;\n\t\t\t} else {\n\t\t\t\tret_val = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else\n\t\t\tp += n;\n\t\tlen--;\n\t}\n\tas->length = p - as->s;\n\tas->s[as->length] = '\\0';\n\treturn (ret_val);\n}", "func_hash": 223655065655317390802766047784365479378, "file_name": "archive_string.c", "file_hash": 233256051783430844011232738668285210112, "cwe": ["CWE-787"], "cve": "CVE-2020-21674", "cve_desc": "Heap-based buffer overflow in archive_string_append_from_wcs() (archive_string.c) in libarchive-3.4.1dev allows remote attackers to cause a denial of service (out-of-bounds write in heap memory resulting into a crash) via a crafted archive file. NOTE: this only affects users who downloaded the development code from GitHub. Users of the product's official releases are unaffected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-21674"} {"idx": 325834, "project": "libarchive", "commit_id": "4f085eea879e2be745f4d9bf57e8513ae48157f4", "project_url": "https://github.com/libarchive/libarchive", "commit_url": "https://github.com/libarchive/libarchive/commit/4f085eea879e2be745f4d9bf57e8513ae48157f4", "commit_message": "Fix a possible heap-buffer-overflow in archive_string_append_from_wcs()\n\nWhen we grow the archive_string buffer, we have to make sure it fits\nat least one maximum-sized multibyte character in the current locale\nand the null character.\n\nFixes #1298", "target": 0, "func": "archive_string_append_from_wcs(struct archive_string *as,\n const wchar_t *w, size_t len)\n{\n\t/* We cannot use the standard wcstombs() here because it\n\t * cannot tell us how big the output buffer should be. So\n\t * I've built a loop around wcrtomb() or wctomb() that\n\t * converts a character at a time and resizes the string as\n\t * needed. We prefer wcrtomb() when it's available because\n\t * it's thread-safe. */\n\tint n, ret_val = 0;\n\tchar *p;\n\tchar *end;\n#if HAVE_WCRTOMB\n\tmbstate_t shift_state;\n\n\tmemset(&shift_state, 0, sizeof(shift_state));\n#else\n\t/* Clear the shift state before starting. */\n\twctomb(NULL, L'\\0');\n#endif\n\t/*\n\t * Allocate buffer for MBS.\n\t * We need this allocation here since it is possible that\n\t * as->s is still NULL.\n\t */\n\tif (archive_string_ensure(as, as->length + len + 1) == NULL)\n\t\treturn (-1);\n\n\tp = as->s + as->length;\n\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\twhile (*w != L'\\0' && len > 0) {\n\t\tif (p >= end) {\n\t\t\tas->length = p - as->s;\n\t\t\tas->s[as->length] = '\\0';\n\t\t\t/* Re-allocate buffer for MBS. */\n\t\t\tif (archive_string_ensure(as,\n\t\t\t as->length + max(len * 2,\n\t\t\t (size_t)MB_CUR_MAX) + 1) == NULL)\n\t\t\t\treturn (-1);\n\t\t\tp = as->s + as->length;\n\t\t\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\t\t}\n#if HAVE_WCRTOMB\n\t\tn = wcrtomb(p, *w++, &shift_state);\n#else\n\t\tn = wctomb(p, *w++);\n#endif\n\t\tif (n == -1) {\n\t\t\tif (errno == EILSEQ) {\n\t\t\t\t/* Skip an illegal wide char. */\n\t\t\t\t*p++ = '?';\n\t\t\t\tret_val = -1;\n\t\t\t} else {\n\t\t\t\tret_val = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else\n\t\t\tp += n;\n\t\tlen--;\n\t}\n\tas->length = p - as->s;\n\tas->s[as->length] = '\\0';\n\treturn (ret_val);\n}", "func_hash": 226751694832564774371497868812408854812, "file_name": "archive_string.c", "file_hash": 269537639274720765125798955104141606353, "cwe": ["CWE-787"], "cve": "CVE-2020-21674", "cve_desc": "Heap-based buffer overflow in archive_string_append_from_wcs() (archive_string.c) in libarchive-3.4.1dev allows remote attackers to cause a denial of service (out-of-bounds write in heap memory resulting into a crash) via a crafted archive file. NOTE: this only affects users who downloaded the development code from GitHub. Users of the product's official releases are unaffected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-21674"} {"idx": 201881, "project": "linux", "commit_id": "c8bcd9c5be24fb9e6132e97da5a35e55a83e36b9", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c8bcd9c5be24fb9e6132e97da5a35e55a83e36b9", "commit_message": "tty: Fix ->session locking\n\nCurrently, locking of ->session is very inconsistent; most places\nprotect it using the legacy tty mutex, but disassociate_ctty(),\n__do_SAK(), tiocspgrp() and tiocgsid() don't.\nTwo of the writers hold the ctrl_lock (because they already need it for\n->pgrp), but __proc_set_tty() doesn't do that yet.\n\nOn a PREEMPT=y system, an unprivileged user can theoretically abuse\nthis broken locking to read 4 bytes of freed memory via TIOCGSID if\ntiocgsid() is preempted long enough at the right point. (Other things\nmight also go wrong, especially if root-only ioctls are involved; I'm\nnot sure about that.)\n\nChange the locking on ->session such that:\n\n - tty_lock() is held by all writers: By making disassociate_ctty()\n hold it. This should be fine because the same lock can already be\n taken through the call to tty_vhangup_session().\n The tricky part is that we need to shorten the area covered by\n siglock to be able to take tty_lock() without ugly retry logic; as\n far as I can tell, this should be fine, since nothing in the\n signal_struct is touched in the `if (tty)` branch.\n - ctrl_lock is held by all writers: By changing __proc_set_tty() to\n hold the lock a little longer.\n - All readers that aren't holding tty_lock() hold ctrl_lock: By\n adding locking to tiocgsid() and __do_SAK(), and expanding the area\n covered by ctrl_lock in tiocspgrp().\n\nCc: stable@kernel.org\nSigned-off-by: Jann Horn \nReviewed-by: Jiri Slaby \nSigned-off-by: Greg Kroah-Hartman ", "target": 1, "func": "void __do_SAK(struct tty_struct *tty)\n{\n#ifdef TTY_SOFT_SAK\n\ttty_hangup(tty);\n#else\n\tstruct task_struct *g, *p;\n\tstruct pid *session;\n\tint\t\ti;\n\n\tif (!tty)\n\t\treturn;\n\tsession = tty->session;\n\n\ttty_ldisc_flush(tty);\n\n\ttty_driver_flush_buffer(tty);\n\n\tread_lock(&tasklist_lock);\n\t/* Kill the entire session */\n\tdo_each_pid_task(session, PIDTYPE_SID, p) {\n\t\ttty_notice(tty, \"SAK: killed process %d (%s): by session\\n\",\n\t\t\t task_pid_nr(p), p->comm);\n\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t} while_each_pid_task(session, PIDTYPE_SID, p);\n\n\t/* Now kill any processes that happen to have the tty open */\n\tdo_each_thread(g, p) {\n\t\tif (p->signal->tty == tty) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by controlling tty\\n\",\n\t\t\t\t task_pid_nr(p), p->comm);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t\tcontinue;\n\t\t}\n\t\ttask_lock(p);\n\t\ti = iterate_fd(p->files, 0, this_tty, tty);\n\t\tif (i != 0) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by fd#%d\\n\",\n\t\t\t\t task_pid_nr(p), p->comm, i - 1);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t}\n\t\ttask_unlock(p);\n\t} while_each_thread(g, p);\n\tread_unlock(&tasklist_lock);\n#endif\n}", "func_hash": 178760904661699809404538664666807961439, "file_name": "tty_io.c", "file_hash": 98270805827484335141777503277318600725, "cwe": ["CWE-416"], "cve": "CVE-2020-29660", "cve_desc": "A locking inconsistency issue was discovered in the tty subsystem of the Linux kernel through 5.9.13. drivers/tty/tty_io.c and drivers/tty/tty_jobctrl.c may allow a read-after-free attack against TIOCGSID, aka CID-c8bcd9c5be24.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29660"} {"idx": 326074, "project": "linux", "commit_id": "c8bcd9c5be24fb9e6132e97da5a35e55a83e36b9", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c8bcd9c5be24fb9e6132e97da5a35e55a83e36b9", "commit_message": "tty: Fix ->session locking\n\nCurrently, locking of ->session is very inconsistent; most places\nprotect it using the legacy tty mutex, but disassociate_ctty(),\n__do_SAK(), tiocspgrp() and tiocgsid() don't.\nTwo of the writers hold the ctrl_lock (because they already need it for\n->pgrp), but __proc_set_tty() doesn't do that yet.\n\nOn a PREEMPT=y system, an unprivileged user can theoretically abuse\nthis broken locking to read 4 bytes of freed memory via TIOCGSID if\ntiocgsid() is preempted long enough at the right point. (Other things\nmight also go wrong, especially if root-only ioctls are involved; I'm\nnot sure about that.)\n\nChange the locking on ->session such that:\n\n - tty_lock() is held by all writers: By making disassociate_ctty()\n hold it. This should be fine because the same lock can already be\n taken through the call to tty_vhangup_session().\n The tricky part is that we need to shorten the area covered by\n siglock to be able to take tty_lock() without ugly retry logic; as\n far as I can tell, this should be fine, since nothing in the\n signal_struct is touched in the `if (tty)` branch.\n - ctrl_lock is held by all writers: By changing __proc_set_tty() to\n hold the lock a little longer.\n - All readers that aren't holding tty_lock() hold ctrl_lock: By\n adding locking to tiocgsid() and __do_SAK(), and expanding the area\n covered by ctrl_lock in tiocspgrp().\n\nCc: stable@kernel.org\nSigned-off-by: Jann Horn \nReviewed-by: Jiri Slaby \nSigned-off-by: Greg Kroah-Hartman ", "target": 0, "func": "void __do_SAK(struct tty_struct *tty)\n{\n#ifdef TTY_SOFT_SAK\n\ttty_hangup(tty);\n#else\n\tstruct task_struct *g, *p;\n\tstruct pid *session;\n\tint\t\ti;\n\tunsigned long flags;\n\n\tif (!tty)\n\t\treturn;\n\n\tspin_lock_irqsave(&tty->ctrl_lock, flags);\n\tsession = get_pid(tty->session);\n\tspin_unlock_irqrestore(&tty->ctrl_lock, flags);\n\n\ttty_ldisc_flush(tty);\n\n\ttty_driver_flush_buffer(tty);\n\n\tread_lock(&tasklist_lock);\n\t/* Kill the entire session */\n\tdo_each_pid_task(session, PIDTYPE_SID, p) {\n\t\ttty_notice(tty, \"SAK: killed process %d (%s): by session\\n\",\n\t\t\t task_pid_nr(p), p->comm);\n\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t} while_each_pid_task(session, PIDTYPE_SID, p);\n\n\t/* Now kill any processes that happen to have the tty open */\n\tdo_each_thread(g, p) {\n\t\tif (p->signal->tty == tty) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by controlling tty\\n\",\n\t\t\t\t task_pid_nr(p), p->comm);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t\tcontinue;\n\t\t}\n\t\ttask_lock(p);\n\t\ti = iterate_fd(p->files, 0, this_tty, tty);\n\t\tif (i != 0) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by fd#%d\\n\",\n\t\t\t\t task_pid_nr(p), p->comm, i - 1);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t}\n\t\ttask_unlock(p);\n\t} while_each_thread(g, p);\n\tread_unlock(&tasklist_lock);\n\tput_pid(session);\n#endif\n}", "func_hash": 335075220719264816552461170609035422062, "file_name": "tty_io.c", "file_hash": 214496444960570201189847801795043994632, "cwe": ["CWE-416"], "cve": "CVE-2020-29660", "cve_desc": "A locking inconsistency issue was discovered in the tty subsystem of the Linux kernel through 5.9.13. drivers/tty/tty_io.c and drivers/tty/tty_jobctrl.c may allow a read-after-free attack against TIOCGSID, aka CID-c8bcd9c5be24.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29660"} {"idx": 201892, "project": "libuv", "commit_id": "b7466e31e4bee160d82a68fca11b1f61d46debae", "project_url": "https://github.com/libuv/libuv", "commit_url": "https://github.com/libuv/libuv/commit/b7466e31e4bee160d82a68fca11b1f61d46debae", "commit_message": "idna: fix OOB read in punycode decoder\n\nlibuv was vulnerable to out-of-bounds reads in the uv__idna_toascii()\nfunction which is used to convert strings to ASCII. This is called by\nthe DNS resolution function and can lead to information disclosures or\ncrashes.\n\nReported by Eric Sesterhenn in collaboration with Cure53 and ExpressVPN.\n\nReported-By: Eric Sesterhenn \nFixes: https://github.com/libuv/libuv/issues/3147\nPR-URL: https://github.com/libuv/libuv-private/pull/1\nRefs: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22918\nReviewed-By: Colin Ihrig \nReviewed-By: Richard Lau ", "target": 1, "func": "long uv__idna_toascii(const char* s, const char* se, char* d, char* de) {\n const char* si;\n const char* st;\n unsigned c;\n char* ds;\n int rc;\n\n ds = d;\n\n for (si = s; si < se; /* empty */) {\n st = si;\n c = uv__utf8_decode1(&si, se);\n\n if (c != '.')\n if (c != 0x3002) /* \u3002 */\n if (c != 0xFF0E) /* \uff0e */\n if (c != 0xFF61) /* \uff61 */\n continue;\n\n rc = uv__idna_toascii_label(s, st, &d, de);\n\n if (rc < 0)\n return rc;\n\n if (d < de)\n *d++ = '.';\n\n s = si;\n }\n\n if (s < se) {\n rc = uv__idna_toascii_label(s, se, &d, de);\n\n if (rc < 0)\n return rc;\n }\n\n if (d < de)\n *d++ = '\\0';\n\n return d - ds; /* Number of bytes written. */\n}", "func_hash": 20654774781797044554932147898782101634, "file_name": "idna.c", "file_hash": 237898039862759279684337161179142521107, "cwe": ["CWE-125"], "cve": "CVE-2021-22918", "cve_desc": "Node.js before 16.4.1, 14.17.2, 12.22.2 is vulnerable to an out-of-bounds read when uv__idna_toascii() is used to convert strings to ASCII. The pointer p is read and increased without checking whether it is beyond pe, with the latter holding a pointer to the end of the buffer. This can lead to information disclosures or crashes. This function can be triggered via uv_getaddrinfo().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22918"} {"idx": 326145, "project": "libuv", "commit_id": "b7466e31e4bee160d82a68fca11b1f61d46debae", "project_url": "https://github.com/libuv/libuv", "commit_url": "https://github.com/libuv/libuv/commit/b7466e31e4bee160d82a68fca11b1f61d46debae", "commit_message": "idna: fix OOB read in punycode decoder\n\nlibuv was vulnerable to out-of-bounds reads in the uv__idna_toascii()\nfunction which is used to convert strings to ASCII. This is called by\nthe DNS resolution function and can lead to information disclosures or\ncrashes.\n\nReported by Eric Sesterhenn in collaboration with Cure53 and ExpressVPN.\n\nReported-By: Eric Sesterhenn \nFixes: https://github.com/libuv/libuv/issues/3147\nPR-URL: https://github.com/libuv/libuv-private/pull/1\nRefs: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22918\nReviewed-By: Colin Ihrig \nReviewed-By: Richard Lau ", "target": 0, "func": "long uv__idna_toascii(const char* s, const char* se, char* d, char* de) {\n const char* si;\n const char* st;\n unsigned c;\n char* ds;\n int rc;\n\n ds = d;\n\n si = s;\n while (si < se) {\n st = si;\n c = uv__utf8_decode1(&si, se);\n\n if (c == -1u)\n return UV_EINVAL;\n\n if (c != '.')\n if (c != 0x3002) /* \u3002 */\n if (c != 0xFF0E) /* \uff0e */\n if (c != 0xFF61) /* \uff61 */\n continue;\n\n rc = uv__idna_toascii_label(s, st, &d, de);\n\n if (rc < 0)\n return rc;\n\n if (d < de)\n *d++ = '.';\n\n s = si;\n }\n\n if (s < se) {\n rc = uv__idna_toascii_label(s, se, &d, de);\n\n if (rc < 0)\n return rc;\n }\n\n if (d < de)\n *d++ = '\\0';\n\n return d - ds; /* Number of bytes written. */\n}", "func_hash": 311670606202772522438359305663499572655, "file_name": "idna.c", "file_hash": 15268315331650200361814627835962764399, "cwe": ["CWE-125"], "cve": "CVE-2021-22918", "cve_desc": "Node.js before 16.4.1, 14.17.2, 12.22.2 is vulnerable to an out-of-bounds read when uv__idna_toascii() is used to convert strings to ASCII. The pointer p is read and increased without checking whether it is beyond pe, with the latter holding a pointer to the end of the buffer. This can lead to information disclosures or crashes. This function can be triggered via uv_getaddrinfo().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22918"} {"idx": 202069, "project": "linux", "commit_id": "ad9f151e560b016b6ad3280b48e42fa11e1a5440", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ad9f151e560b016b6ad3280b48e42fa11e1a5440", "commit_message": "netfilter: nf_tables: initialize set before expression setup\n\nnft_set_elem_expr_alloc() needs an initialized set if expression sets on\nthe NFT_EXPR_GC flag. Move set fields initialization before expression\nsetup.\n\n[4512935.019450] ==================================================================\n[4512935.019456] BUG: KASAN: null-ptr-deref in nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019487] Read of size 8 at addr 0000000000000070 by task nft/23532\n[4512935.019494] CPU: 1 PID: 23532 Comm: nft Not tainted 5.12.0-rc4+ #48\n[...]\n[4512935.019502] Call Trace:\n[4512935.019505] dump_stack+0x89/0xb4\n[4512935.019512] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019536] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019560] kasan_report.cold.12+0x5f/0xd8\n[4512935.019566] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019590] nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019615] nf_tables_newset+0xc7f/0x1460 [nf_tables]\n\nReported-by: syzbot+ce96ca2b1d0b37c6422d@syzkaller.appspotmail.com\nFixes: 65038428b2c6 (\"netfilter: nf_tables: allow to specify stateful expression in set definition\")\nSigned-off-by: Pablo Neira Ayuso ", "target": 1, "func": "static int nf_tables_newset(struct sk_buff *skb, const struct nfnl_info *info,\n\t\t\t const struct nlattr * const nla[])\n{\n\tconst struct nfgenmsg *nfmsg = nlmsg_data(info->nlh);\n\tu32 ktype, dtype, flags, policy, gc_int, objtype;\n\tstruct netlink_ext_ack *extack = info->extack;\n\tu8 genmask = nft_genmask_next(info->net);\n\tint family = nfmsg->nfgen_family;\n\tconst struct nft_set_ops *ops;\n\tstruct nft_expr *expr = NULL;\n\tstruct net *net = info->net;\n\tstruct nft_set_desc desc;\n\tstruct nft_table *table;\n\tunsigned char *udata;\n\tstruct nft_set *set;\n\tstruct nft_ctx ctx;\n\tsize_t alloc_size;\n\tu64 timeout;\n\tchar *name;\n\tint err, i;\n\tu16 udlen;\n\tu64 size;\n\n\tif (nla[NFTA_SET_TABLE] == NULL ||\n\t nla[NFTA_SET_NAME] == NULL ||\n\t nla[NFTA_SET_KEY_LEN] == NULL ||\n\t nla[NFTA_SET_ID] == NULL)\n\t\treturn -EINVAL;\n\n\tmemset(&desc, 0, sizeof(desc));\n\n\tktype = NFT_DATA_VALUE;\n\tif (nla[NFTA_SET_KEY_TYPE] != NULL) {\n\t\tktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));\n\t\tif ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)\n\t\t\treturn -EINVAL;\n\t}\n\n\tdesc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));\n\tif (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)\n\t\treturn -EINVAL;\n\n\tflags = 0;\n\tif (nla[NFTA_SET_FLAGS] != NULL) {\n\t\tflags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));\n\t\tif (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |\n\t\t\t NFT_SET_INTERVAL | NFT_SET_TIMEOUT |\n\t\t\t NFT_SET_MAP | NFT_SET_EVAL |\n\t\t\t NFT_SET_OBJECT | NFT_SET_CONCAT | NFT_SET_EXPR))\n\t\t\treturn -EOPNOTSUPP;\n\t\t/* Only one of these operations is supported */\n\t\tif ((flags & (NFT_SET_MAP | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_MAP | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t\tif ((flags & (NFT_SET_EVAL | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_EVAL | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t}\n\n\tdtype = 0;\n\tif (nla[NFTA_SET_DATA_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_MAP))\n\t\t\treturn -EINVAL;\n\n\t\tdtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));\n\t\tif ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&\n\t\t dtype != NFT_DATA_VERDICT)\n\t\t\treturn -EINVAL;\n\n\t\tif (dtype != NFT_DATA_VERDICT) {\n\t\t\tif (nla[NFTA_SET_DATA_LEN] == NULL)\n\t\t\t\treturn -EINVAL;\n\t\t\tdesc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));\n\t\t\tif (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)\n\t\t\t\treturn -EINVAL;\n\t\t} else\n\t\t\tdesc.dlen = sizeof(struct nft_verdict);\n\t} else if (flags & NFT_SET_MAP)\n\t\treturn -EINVAL;\n\n\tif (nla[NFTA_SET_OBJ_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_OBJECT))\n\t\t\treturn -EINVAL;\n\n\t\tobjtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));\n\t\tif (objtype == NFT_OBJECT_UNSPEC ||\n\t\t objtype > NFT_OBJECT_MAX)\n\t\t\treturn -EOPNOTSUPP;\n\t} else if (flags & NFT_SET_OBJECT)\n\t\treturn -EINVAL;\n\telse\n\t\tobjtype = NFT_OBJECT_UNSPEC;\n\n\ttimeout = 0;\n\tif (nla[NFTA_SET_TIMEOUT] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\n\t\terr = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\tgc_int = 0;\n\tif (nla[NFTA_SET_GC_INTERVAL] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\t\tgc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));\n\t}\n\n\tpolicy = NFT_SET_POL_PERFORMANCE;\n\tif (nla[NFTA_SET_POLICY] != NULL)\n\t\tpolicy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));\n\n\tif (nla[NFTA_SET_DESC] != NULL) {\n\t\terr = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (nla[NFTA_SET_EXPR] || nla[NFTA_SET_EXPRESSIONS])\n\t\tdesc.expr = true;\n\n\ttable = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask,\n\t\t\t\t NETLINK_CB(skb).portid);\n\tif (IS_ERR(table)) {\n\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);\n\t\treturn PTR_ERR(table);\n\t}\n\n\tnft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);\n\n\tset = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);\n\tif (IS_ERR(set)) {\n\t\tif (PTR_ERR(set) != -ENOENT) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn PTR_ERR(set);\n\t\t}\n\t} else {\n\t\tif (info->nlh->nlmsg_flags & NLM_F_EXCL) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn -EEXIST;\n\t\t}\n\t\tif (info->nlh->nlmsg_flags & NLM_F_REPLACE)\n\t\t\treturn -EOPNOTSUPP;\n\n\t\treturn 0;\n\t}\n\n\tif (!(info->nlh->nlmsg_flags & NLM_F_CREATE))\n\t\treturn -ENOENT;\n\n\tops = nft_select_set_ops(&ctx, nla, &desc, policy);\n\tif (IS_ERR(ops))\n\t\treturn PTR_ERR(ops);\n\n\tudlen = 0;\n\tif (nla[NFTA_SET_USERDATA])\n\t\tudlen = nla_len(nla[NFTA_SET_USERDATA]);\n\n\tsize = 0;\n\tif (ops->privsize != NULL)\n\t\tsize = ops->privsize(nla, &desc);\n\talloc_size = sizeof(*set) + size + udlen;\n\tif (alloc_size < size)\n\t\treturn -ENOMEM;\n\tset = kvzalloc(alloc_size, GFP_KERNEL);\n\tif (!set)\n\t\treturn -ENOMEM;\n\n\tname = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);\n\tif (!name) {\n\t\terr = -ENOMEM;\n\t\tgoto err_set_name;\n\t}\n\n\terr = nf_tables_set_alloc_name(&ctx, set, name);\n\tkfree(name);\n\tif (err < 0)\n\t\tgoto err_set_alloc_name;\n\n\tif (nla[NFTA_SET_EXPR]) {\n\t\texpr = nft_set_elem_expr_alloc(&ctx, set, nla[NFTA_SET_EXPR]);\n\t\tif (IS_ERR(expr)) {\n\t\t\terr = PTR_ERR(expr);\n\t\t\tgoto err_set_alloc_name;\n\t\t}\n\t\tset->exprs[0] = expr;\n\t\tset->num_exprs++;\n\t} else if (nla[NFTA_SET_EXPRESSIONS]) {\n\t\tstruct nft_expr *expr;\n\t\tstruct nlattr *tmp;\n\t\tint left;\n\n\t\tif (!(flags & NFT_SET_EXPR)) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto err_set_alloc_name;\n\t\t}\n\t\ti = 0;\n\t\tnla_for_each_nested(tmp, nla[NFTA_SET_EXPRESSIONS], left) {\n\t\t\tif (i == NFT_SET_EXPR_MAX) {\n\t\t\t\terr = -E2BIG;\n\t\t\t\tgoto err_set_init;\n\t\t\t}\n\t\t\tif (nla_type(tmp) != NFTA_LIST_ELEM) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto err_set_init;\n\t\t\t}\n\t\t\texpr = nft_set_elem_expr_alloc(&ctx, set, tmp);\n\t\t\tif (IS_ERR(expr)) {\n\t\t\t\terr = PTR_ERR(expr);\n\t\t\t\tgoto err_set_init;\n\t\t\t}\n\t\t\tset->exprs[i++] = expr;\n\t\t\tset->num_exprs++;\n\t\t}\n\t}\n\n\tudata = NULL;\n\tif (udlen) {\n\t\tudata = set->data + size;\n\t\tnla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);\n\t}\n\n\tINIT_LIST_HEAD(&set->bindings);\n\tINIT_LIST_HEAD(&set->catchall_list);\n\tset->table = table;\n\twrite_pnet(&set->net, net);\n\tset->ops = ops;\n\tset->ktype = ktype;\n\tset->klen = desc.klen;\n\tset->dtype = dtype;\n\tset->objtype = objtype;\n\tset->dlen = desc.dlen;\n\tset->flags = flags;\n\tset->size = desc.size;\n\tset->policy = policy;\n\tset->udlen = udlen;\n\tset->udata = udata;\n\tset->timeout = timeout;\n\tset->gc_int = gc_int;\n\tset->handle = nf_tables_alloc_handle(table);\n\n\tset->field_count = desc.field_count;\n\tfor (i = 0; i < desc.field_count; i++)\n\t\tset->field_len[i] = desc.field_len[i];\n\n\terr = ops->init(set, &desc, nla);\n\tif (err < 0)\n\t\tgoto err_set_init;\n\n\terr = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);\n\tif (err < 0)\n\t\tgoto err_set_trans;\n\n\tlist_add_tail_rcu(&set->list, &table->sets);\n\ttable->use++;\n\treturn 0;\n\nerr_set_trans:\n\tops->destroy(set);\nerr_set_init:\n\tfor (i = 0; i < set->num_exprs; i++)\n\t\tnft_expr_destroy(&ctx, set->exprs[i]);\nerr_set_alloc_name:\n\tkfree(set->name);\nerr_set_name:\n\tkvfree(set);\n\treturn err;\n}", "func_hash": 146697796216247628668893323755174270853, "file_name": "nf_tables_api.c", "file_hash": 330173190135227039268334668110309126422, "cwe": ["CWE-665"], "cve": "CVE-2021-46283", "cve_desc": "nf_tables_newset in net/netfilter/nf_tables_api.c in the Linux kernel before 5.12.13 allows local users to cause a denial of service (NULL pointer dereference and general protection fault) because of the missing initialization for nft_set_elem_expr_alloc. A local user can set a netfilter table expression in their own namespace.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46283"} {"idx": 328360, "project": "linux", "commit_id": "ad9f151e560b016b6ad3280b48e42fa11e1a5440", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ad9f151e560b016b6ad3280b48e42fa11e1a5440", "commit_message": "netfilter: nf_tables: initialize set before expression setup\n\nnft_set_elem_expr_alloc() needs an initialized set if expression sets on\nthe NFT_EXPR_GC flag. Move set fields initialization before expression\nsetup.\n\n[4512935.019450] ==================================================================\n[4512935.019456] BUG: KASAN: null-ptr-deref in nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019487] Read of size 8 at addr 0000000000000070 by task nft/23532\n[4512935.019494] CPU: 1 PID: 23532 Comm: nft Not tainted 5.12.0-rc4+ #48\n[...]\n[4512935.019502] Call Trace:\n[4512935.019505] dump_stack+0x89/0xb4\n[4512935.019512] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019536] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019560] kasan_report.cold.12+0x5f/0xd8\n[4512935.019566] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019590] nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019615] nf_tables_newset+0xc7f/0x1460 [nf_tables]\n\nReported-by: syzbot+ce96ca2b1d0b37c6422d@syzkaller.appspotmail.com\nFixes: 65038428b2c6 (\"netfilter: nf_tables: allow to specify stateful expression in set definition\")\nSigned-off-by: Pablo Neira Ayuso ", "target": 0, "func": "static int nf_tables_newset(struct sk_buff *skb, const struct nfnl_info *info,\n\t\t\t const struct nlattr * const nla[])\n{\n\tconst struct nfgenmsg *nfmsg = nlmsg_data(info->nlh);\n\tu32 ktype, dtype, flags, policy, gc_int, objtype;\n\tstruct netlink_ext_ack *extack = info->extack;\n\tu8 genmask = nft_genmask_next(info->net);\n\tint family = nfmsg->nfgen_family;\n\tconst struct nft_set_ops *ops;\n\tstruct nft_expr *expr = NULL;\n\tstruct net *net = info->net;\n\tstruct nft_set_desc desc;\n\tstruct nft_table *table;\n\tunsigned char *udata;\n\tstruct nft_set *set;\n\tstruct nft_ctx ctx;\n\tsize_t alloc_size;\n\tu64 timeout;\n\tchar *name;\n\tint err, i;\n\tu16 udlen;\n\tu64 size;\n\n\tif (nla[NFTA_SET_TABLE] == NULL ||\n\t nla[NFTA_SET_NAME] == NULL ||\n\t nla[NFTA_SET_KEY_LEN] == NULL ||\n\t nla[NFTA_SET_ID] == NULL)\n\t\treturn -EINVAL;\n\n\tmemset(&desc, 0, sizeof(desc));\n\n\tktype = NFT_DATA_VALUE;\n\tif (nla[NFTA_SET_KEY_TYPE] != NULL) {\n\t\tktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));\n\t\tif ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)\n\t\t\treturn -EINVAL;\n\t}\n\n\tdesc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));\n\tif (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)\n\t\treturn -EINVAL;\n\n\tflags = 0;\n\tif (nla[NFTA_SET_FLAGS] != NULL) {\n\t\tflags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));\n\t\tif (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |\n\t\t\t NFT_SET_INTERVAL | NFT_SET_TIMEOUT |\n\t\t\t NFT_SET_MAP | NFT_SET_EVAL |\n\t\t\t NFT_SET_OBJECT | NFT_SET_CONCAT | NFT_SET_EXPR))\n\t\t\treturn -EOPNOTSUPP;\n\t\t/* Only one of these operations is supported */\n\t\tif ((flags & (NFT_SET_MAP | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_MAP | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t\tif ((flags & (NFT_SET_EVAL | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_EVAL | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t}\n\n\tdtype = 0;\n\tif (nla[NFTA_SET_DATA_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_MAP))\n\t\t\treturn -EINVAL;\n\n\t\tdtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));\n\t\tif ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&\n\t\t dtype != NFT_DATA_VERDICT)\n\t\t\treturn -EINVAL;\n\n\t\tif (dtype != NFT_DATA_VERDICT) {\n\t\t\tif (nla[NFTA_SET_DATA_LEN] == NULL)\n\t\t\t\treturn -EINVAL;\n\t\t\tdesc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));\n\t\t\tif (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)\n\t\t\t\treturn -EINVAL;\n\t\t} else\n\t\t\tdesc.dlen = sizeof(struct nft_verdict);\n\t} else if (flags & NFT_SET_MAP)\n\t\treturn -EINVAL;\n\n\tif (nla[NFTA_SET_OBJ_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_OBJECT))\n\t\t\treturn -EINVAL;\n\n\t\tobjtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));\n\t\tif (objtype == NFT_OBJECT_UNSPEC ||\n\t\t objtype > NFT_OBJECT_MAX)\n\t\t\treturn -EOPNOTSUPP;\n\t} else if (flags & NFT_SET_OBJECT)\n\t\treturn -EINVAL;\n\telse\n\t\tobjtype = NFT_OBJECT_UNSPEC;\n\n\ttimeout = 0;\n\tif (nla[NFTA_SET_TIMEOUT] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\n\t\terr = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\tgc_int = 0;\n\tif (nla[NFTA_SET_GC_INTERVAL] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\t\tgc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));\n\t}\n\n\tpolicy = NFT_SET_POL_PERFORMANCE;\n\tif (nla[NFTA_SET_POLICY] != NULL)\n\t\tpolicy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));\n\n\tif (nla[NFTA_SET_DESC] != NULL) {\n\t\terr = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (nla[NFTA_SET_EXPR] || nla[NFTA_SET_EXPRESSIONS])\n\t\tdesc.expr = true;\n\n\ttable = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask,\n\t\t\t\t NETLINK_CB(skb).portid);\n\tif (IS_ERR(table)) {\n\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);\n\t\treturn PTR_ERR(table);\n\t}\n\n\tnft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);\n\n\tset = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);\n\tif (IS_ERR(set)) {\n\t\tif (PTR_ERR(set) != -ENOENT) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn PTR_ERR(set);\n\t\t}\n\t} else {\n\t\tif (info->nlh->nlmsg_flags & NLM_F_EXCL) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn -EEXIST;\n\t\t}\n\t\tif (info->nlh->nlmsg_flags & NLM_F_REPLACE)\n\t\t\treturn -EOPNOTSUPP;\n\n\t\treturn 0;\n\t}\n\n\tif (!(info->nlh->nlmsg_flags & NLM_F_CREATE))\n\t\treturn -ENOENT;\n\n\tops = nft_select_set_ops(&ctx, nla, &desc, policy);\n\tif (IS_ERR(ops))\n\t\treturn PTR_ERR(ops);\n\n\tudlen = 0;\n\tif (nla[NFTA_SET_USERDATA])\n\t\tudlen = nla_len(nla[NFTA_SET_USERDATA]);\n\n\tsize = 0;\n\tif (ops->privsize != NULL)\n\t\tsize = ops->privsize(nla, &desc);\n\talloc_size = sizeof(*set) + size + udlen;\n\tif (alloc_size < size)\n\t\treturn -ENOMEM;\n\tset = kvzalloc(alloc_size, GFP_KERNEL);\n\tif (!set)\n\t\treturn -ENOMEM;\n\n\tname = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);\n\tif (!name) {\n\t\terr = -ENOMEM;\n\t\tgoto err_set_name;\n\t}\n\n\terr = nf_tables_set_alloc_name(&ctx, set, name);\n\tkfree(name);\n\tif (err < 0)\n\t\tgoto err_set_name;\n\n\tudata = NULL;\n\tif (udlen) {\n\t\tudata = set->data + size;\n\t\tnla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);\n\t}\n\n\tINIT_LIST_HEAD(&set->bindings);\n\tINIT_LIST_HEAD(&set->catchall_list);\n\tset->table = table;\n\twrite_pnet(&set->net, net);\n\tset->ops = ops;\n\tset->ktype = ktype;\n\tset->klen = desc.klen;\n\tset->dtype = dtype;\n\tset->objtype = objtype;\n\tset->dlen = desc.dlen;\n\tset->flags = flags;\n\tset->size = desc.size;\n\tset->policy = policy;\n\tset->udlen = udlen;\n\tset->udata = udata;\n\tset->timeout = timeout;\n\tset->gc_int = gc_int;\n\n\tset->field_count = desc.field_count;\n\tfor (i = 0; i < desc.field_count; i++)\n\t\tset->field_len[i] = desc.field_len[i];\n\n\terr = ops->init(set, &desc, nla);\n\tif (err < 0)\n\t\tgoto err_set_init;\n\n\tif (nla[NFTA_SET_EXPR]) {\n\t\texpr = nft_set_elem_expr_alloc(&ctx, set, nla[NFTA_SET_EXPR]);\n\t\tif (IS_ERR(expr)) {\n\t\t\terr = PTR_ERR(expr);\n\t\t\tgoto err_set_expr_alloc;\n\t\t}\n\t\tset->exprs[0] = expr;\n\t\tset->num_exprs++;\n\t} else if (nla[NFTA_SET_EXPRESSIONS]) {\n\t\tstruct nft_expr *expr;\n\t\tstruct nlattr *tmp;\n\t\tint left;\n\n\t\tif (!(flags & NFT_SET_EXPR)) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto err_set_expr_alloc;\n\t\t}\n\t\ti = 0;\n\t\tnla_for_each_nested(tmp, nla[NFTA_SET_EXPRESSIONS], left) {\n\t\t\tif (i == NFT_SET_EXPR_MAX) {\n\t\t\t\terr = -E2BIG;\n\t\t\t\tgoto err_set_expr_alloc;\n\t\t\t}\n\t\t\tif (nla_type(tmp) != NFTA_LIST_ELEM) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto err_set_expr_alloc;\n\t\t\t}\n\t\t\texpr = nft_set_elem_expr_alloc(&ctx, set, tmp);\n\t\t\tif (IS_ERR(expr)) {\n\t\t\t\terr = PTR_ERR(expr);\n\t\t\t\tgoto err_set_expr_alloc;\n\t\t\t}\n\t\t\tset->exprs[i++] = expr;\n\t\t\tset->num_exprs++;\n\t\t}\n\t}\n\n\tset->handle = nf_tables_alloc_handle(table);\n\n\terr = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);\n\tif (err < 0)\n\t\tgoto err_set_expr_alloc;\n\n\tlist_add_tail_rcu(&set->list, &table->sets);\n\ttable->use++;\n\treturn 0;\n\nerr_set_expr_alloc:\n\tfor (i = 0; i < set->num_exprs; i++)\n\t\tnft_expr_destroy(&ctx, set->exprs[i]);\n\n\tops->destroy(set);\nerr_set_init:\n\tkfree(set->name);\nerr_set_name:\n\tkvfree(set);\n\treturn err;\n}", "func_hash": 148093596022743537616091337187707171014, "file_name": "nf_tables_api.c", "file_hash": 240934795933474880133223486110809737536, "cwe": ["CWE-665"], "cve": "CVE-2021-46283", "cve_desc": "nf_tables_newset in net/netfilter/nf_tables_api.c in the Linux kernel before 5.12.13 allows local users to cause a denial of service (NULL pointer dereference and general protection fault) because of the missing initialization for nft_set_elem_expr_alloc. A local user can set a netfilter table expression in their own namespace.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46283"} {"idx": 202076, "project": "linux", "commit_id": "5b9fbeb75b6a98955f628e205ac26689bcb1383e", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/5b9fbeb75b6a98955f628e205ac26689bcb1383e", "commit_message": "bpf: Fix scalar32_min_max_or bounds tracking\n\nSimon reported an issue with the current scalar32_min_max_or() implementation.\nThat is, compared to the other 32 bit subreg tracking functions, the code in\nscalar32_min_max_or() stands out that it's using the 64 bit registers instead\nof 32 bit ones. This leads to bounds tracking issues, for example:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x1; 0x700000000),s32_max_value=1,u32_max_value=1) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nThe bound tests on the map value force the upper unsigned bound to be 25769803777\nin 64 bit (0b11000000000000000000000000000000001) and then lower one to be 1. By\nusing OR they are truncated and thus result in the range [1,1] for the 32 bit reg\ntracker. This is incorrect given the only thing we know is that the value must be\npositive and thus 2147483647 (0b1111111111111111111111111111111) at max for the\nsubregs. Fix it by using the {u,s}32_{min,max}_value vars instead. This also makes\nsense, for example, for the case where we update dst_reg->s32_{min,max}_value in\nthe else branch we need to use the newly computed dst_reg->u32_{min,max}_value as\nwe know that these are positive. Previously, in the else branch the 64 bit values\nof umin_value=1 and umax_value=32212254719 were used and latter got truncated to\nbe 1 as upper bound there. After the fix the subreg range is now correct:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nFixes: 3f50f132d840 (\"bpf: Verifier, do explicit ALU32 bounds tracking\")\nReported-by: Simon Scannell \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nAcked-by: Alexei Starovoitov ", "target": 1, "func": "static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,\n\t\t\t\tstruct bpf_reg_state *src_reg)\n{\n\tbool src_known = tnum_subreg_is_const(src_reg->var_off);\n\tbool dst_known = tnum_subreg_is_const(dst_reg->var_off);\n\tstruct tnum var32_off = tnum_subreg(dst_reg->var_off);\n\ts32 smin_val = src_reg->smin_value;\n\tu32 umin_val = src_reg->umin_value;\n\n\t/* Assuming scalar64_min_max_or will be called so it is safe\n\t * to skip updating register for known case.\n\t */\n\tif (src_known && dst_known)\n\t\treturn;\n\n\t/* We get our maximum from the var_off, and our minimum is the\n\t * maximum of the operands' minima\n\t */\n\tdst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);\n\tdst_reg->u32_max_value = var32_off.value | var32_off.mask;\n\tif (dst_reg->s32_min_value < 0 || smin_val < 0) {\n\t\t/* Lose signed bounds when ORing negative numbers,\n\t\t * ain't nobody got time for that.\n\t\t */\n\t\tdst_reg->s32_min_value = S32_MIN;\n\t\tdst_reg->s32_max_value = S32_MAX;\n\t} else {\n\t\t/* ORing two positives gives a positive, so safe to\n\t\t * cast result into s64.\n\t\t */\n\t\tdst_reg->s32_min_value = dst_reg->umin_value;\n\t\tdst_reg->s32_max_value = dst_reg->umax_value;\n\t}\n}", "func_hash": 19633563468635077293613021812983853734, "file_name": "verifier.c", "file_hash": 161658915333373669300764750295440553696, "cwe": ["CWE-787"], "cve": "CVE-2020-27194", "cve_desc": "An issue was discovered in the Linux kernel before 5.8.15. scalar32_min_max_or in kernel/bpf/verifier.c mishandles bounds tracking during use of 64-bit values, aka CID-5b9fbeb75b6a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27194"} {"idx": 328523, "project": "linux", "commit_id": "5b9fbeb75b6a98955f628e205ac26689bcb1383e", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/5b9fbeb75b6a98955f628e205ac26689bcb1383e", "commit_message": "bpf: Fix scalar32_min_max_or bounds tracking\n\nSimon reported an issue with the current scalar32_min_max_or() implementation.\nThat is, compared to the other 32 bit subreg tracking functions, the code in\nscalar32_min_max_or() stands out that it's using the 64 bit registers instead\nof 32 bit ones. This leads to bounds tracking issues, for example:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x1; 0x700000000),s32_max_value=1,u32_max_value=1) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nThe bound tests on the map value force the upper unsigned bound to be 25769803777\nin 64 bit (0b11000000000000000000000000000000001) and then lower one to be 1. By\nusing OR they are truncated and thus result in the range [1,1] for the 32 bit reg\ntracker. This is incorrect given the only thing we know is that the value must be\npositive and thus 2147483647 (0b1111111111111111111111111111111) at max for the\nsubregs. Fix it by using the {u,s}32_{min,max}_value vars instead. This also makes\nsense, for example, for the case where we update dst_reg->s32_{min,max}_value in\nthe else branch we need to use the newly computed dst_reg->u32_{min,max}_value as\nwe know that these are positive. Previously, in the else branch the 64 bit values\nof umin_value=1 and umax_value=32212254719 were used and latter got truncated to\nbe 1 as upper bound there. After the fix the subreg range is now correct:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nFixes: 3f50f132d840 (\"bpf: Verifier, do explicit ALU32 bounds tracking\")\nReported-by: Simon Scannell \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nAcked-by: Alexei Starovoitov ", "target": 0, "func": "static void scalar_min_max_or(struct bpf_reg_state *dst_reg,\n\t\t\t struct bpf_reg_state *src_reg)\n{\n\tbool src_known = tnum_is_const(src_reg->var_off);\n\tbool dst_known = tnum_is_const(dst_reg->var_off);\n\ts64 smin_val = src_reg->smin_value;\n\tu64 umin_val = src_reg->umin_value;\n\n\tif (src_known && dst_known) {\n\t\t__mark_reg_known(dst_reg, dst_reg->var_off.value |\n\t\t\t\t\t src_reg->var_off.value);\n\t\treturn;\n\t}\n\n\t/* We get our maximum from the var_off, and our minimum is the\n\t * maximum of the operands' minima\n\t */\n\tdst_reg->umin_value = max(dst_reg->umin_value, umin_val);\n\tdst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;\n\tif (dst_reg->smin_value < 0 || smin_val < 0) {\n\t\t/* Lose signed bounds when ORing negative numbers,\n\t\t * ain't nobody got time for that.\n\t\t */\n\t\tdst_reg->smin_value = S64_MIN;\n\t\tdst_reg->smax_value = S64_MAX;\n\t} else {\n\t\t/* ORing two positives gives a positive, so safe to\n\t\t * cast result into s64.\n\t\t */\n\t\tdst_reg->smin_value = dst_reg->umin_value;\n\t\tdst_reg->smax_value = dst_reg->umax_value;\n\t}\n\t/* We may learn something more from the var_off */\n\t__update_reg_bounds(dst_reg);\n}", "func_hash": 298975021554830400331430853327011001834, "file_name": "verifier.c", "file_hash": 195478231516509462341935320666181666157, "cwe": ["CWE-787"], "cve": "CVE-2020-27194", "cve_desc": "An issue was discovered in the Linux kernel before 5.8.15. scalar32_min_max_or in kernel/bpf/verifier.c mishandles bounds tracking during use of 64-bit values, aka CID-5b9fbeb75b6a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27194"} {"idx": 202129, "project": "openldap", "commit_id": "4c774220a752bf8e3284984890dc0931fe73165d", "project_url": "https://github.com/openldap/openldap", "commit_url": "https://git.openldap.org/openldap/openldap/-/commit/4c774220a752bf8e3284984890dc0931fe73165d", "commit_message": "ITS#9370 check for equality rule on old_rdn\n\nJust skip normalization if there's no equality rule. We accept\nDNs without equality rules already.", "target": 1, "func": "slap_modrdn2mods(\n\tOperation\t*op,\n\tSlapReply\t*rs )\n{\n\tint\t\ta_cnt, d_cnt;\n\tLDAPRDN\t\told_rdn = NULL;\n\tLDAPRDN\t\tnew_rdn = NULL;\n\n\tassert( !BER_BVISEMPTY( &op->oq_modrdn.rs_newrdn ) );\n\n\t/* if requestDN is empty, silently reset deleteOldRDN */\n\tif ( BER_BVISEMPTY( &op->o_req_dn ) ) op->orr_deleteoldrdn = 0;\n\n\tif ( ldap_bv2rdn_x( &op->oq_modrdn.rs_newrdn, &new_rdn,\n\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\"type(s)/value(s) of newrdn\\n\",\n\t\t\top->o_log_prefix, 0, 0 );\n\t\trs->sr_err = LDAP_INVALID_DN_SYNTAX;\n\t\trs->sr_text = \"unknown type(s)/value(s) used in RDN\";\n\t\tgoto done;\n\t}\n\n\tif ( op->oq_modrdn.rs_deleteoldrdn ) {\n\t\tif ( ldap_bv2rdn_x( &op->o_req_dn, &old_rdn,\n\t\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\t\"type(s)/value(s) of oldrdn\\n\",\n\t\t\t\top->o_log_prefix, 0, 0 );\n\t\t\trs->sr_err = LDAP_OTHER;\n\t\t\trs->sr_text = \"cannot parse RDN from old DN\";\n\t\t\tgoto done;\n\t\t}\n\t}\n\trs->sr_text = NULL;\n\n\t/* Add new attribute values to the entry */\n\tfor ( a_cnt = 0; new_rdn[a_cnt]; a_cnt++ ) {\n\t\tAttributeDescription\t*desc = NULL;\n\t\tModifications \t\t*mod_tmp;\n\n\t\trs->sr_err = slap_bv2ad( &new_rdn[a_cnt]->la_attr, &desc, &rs->sr_text );\n\n\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\tgoto done;\t\t\n\t\t}\n\n\t\tif ( !desc->ad_type->sat_equality ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\trs->sr_text = \"naming attribute has no equality matching rule\";\n\t\t\trs->sr_err = LDAP_NAMING_VIOLATION;\n\t\t\tgoto done;\n\t\t}\n\n\t\t/* Apply modification */\n\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\tmod_tmp->sml_desc = desc;\n\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\tmod_tmp->sml_numvals = 1;\n\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\tber_dupbv( &mod_tmp->sml_values[0], &new_rdn[a_cnt]->la_value );\n\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\tif( desc->ad_type->sat_equality->smr_normalize) {\n\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\trs->sr_err = desc->ad_type->sat_equality->smr_normalize(\n\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\tif (rs->sr_err != LDAP_SUCCESS) {\n\t\t\t\tch_free(mod_tmp->sml_nvalues);\n\t\t\t\tch_free(mod_tmp->sml_values[0].bv_val);\n\t\t\t\tch_free(mod_tmp->sml_values);\n\t\t\t\tch_free(mod_tmp);\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t} else {\n\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t}\n\t\tmod_tmp->sml_op = SLAP_MOD_SOFTADD;\n\t\tmod_tmp->sml_flags = 0;\n\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\top->orr_modlist = mod_tmp;\n\t}\n\n\t/* Remove old rdn value if required */\n\tif ( op->orr_deleteoldrdn ) {\n\t\tfor ( d_cnt = 0; old_rdn[d_cnt]; d_cnt++ ) {\n\t\t\tAttributeDescription\t*desc = NULL;\n\t\t\tModifications \t\t*mod_tmp;\n\n\t\t\trs->sr_err = slap_bv2ad( &old_rdn[d_cnt]->la_attr, &desc, &rs->sr_text );\n\t\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\t\"%s slap_modrdn2mods: %s: %s (old)\\n\",\n\t\t\t\t\top->o_log_prefix,\n\t\t\t\t\trs->sr_text, \n\t\t\t\t\told_rdn[d_cnt]->la_attr.bv_val );\n\t\t\t\tgoto done;\t\t\n\t\t\t}\n\n\t\t\t/* Apply modification */\n\t\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\t\tmod_tmp->sml_desc = desc;\n\t\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\t\tmod_tmp->sml_numvals = 1;\n\t\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\tber_dupbv( &mod_tmp->sml_values[0], &old_rdn[d_cnt]->la_value );\n\t\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\t\tif( desc->ad_type->sat_equality->smr_normalize) {\n\t\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\t\t(void) (*desc->ad_type->sat_equality->smr_normalize)(\n\t\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t\t} else {\n\t\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t\t}\n\t\t\tmod_tmp->sml_op = LDAP_MOD_DELETE;\n\t\t\tmod_tmp->sml_flags = 0;\n\t\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\t\top->orr_modlist = mod_tmp;\n\t\t}\n\t}\n\t\ndone:\n\n\t/* LDAP v2 supporting correct attribute handling. */\n\tif ( rs->sr_err != LDAP_SUCCESS && op->orr_modlist != NULL ) {\n\t\tModifications *tmp;\n\n\t\tfor ( ; op->orr_modlist != NULL; op->orr_modlist = tmp ) {\n\t\t\ttmp = op->orr_modlist->sml_next;\n\t\t\tch_free( op->orr_modlist );\n\t\t}\n\t}\n\n\tif ( new_rdn != NULL ) {\n\t\tldap_rdnfree_x( new_rdn, op->o_tmpmemctx );\n\t}\n\tif ( old_rdn != NULL ) {\n\t\tldap_rdnfree_x( old_rdn, op->o_tmpmemctx );\n\t}\n\n\treturn rs->sr_err;\n}", "func_hash": 286494162767114340446649927820912714805, "file_name": "modrdn.c", "file_hash": 4267217379486581671013238310692629595, "cwe": ["CWE-476"], "cve": "CVE-2020-25692", "cve_desc": "A NULL pointer dereference was found in OpenLDAP server and was fixed in openldap 2.4.55, during a request for renaming RDNs. An unauthenticated attacker could remotely crash the slapd process by sending a specially crafted request, causing a Denial of Service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25692"} {"idx": 329989, "project": "openldap", "commit_id": "4c774220a752bf8e3284984890dc0931fe73165d", "project_url": "https://github.com/openldap/openldap", "commit_url": "https://git.openldap.org/openldap/openldap/-/commit/4c774220a752bf8e3284984890dc0931fe73165d", "commit_message": "ITS#9370 check for equality rule on old_rdn\n\nJust skip normalization if there's no equality rule. We accept\nDNs without equality rules already.", "target": 0, "func": "slap_modrdn2mods(\n\tOperation\t*op,\n\tSlapReply\t*rs )\n{\n\tint\t\ta_cnt, d_cnt;\n\tLDAPRDN\t\told_rdn = NULL;\n\tLDAPRDN\t\tnew_rdn = NULL;\n\n\tassert( !BER_BVISEMPTY( &op->oq_modrdn.rs_newrdn ) );\n\n\t/* if requestDN is empty, silently reset deleteOldRDN */\n\tif ( BER_BVISEMPTY( &op->o_req_dn ) ) op->orr_deleteoldrdn = 0;\n\n\tif ( ldap_bv2rdn_x( &op->oq_modrdn.rs_newrdn, &new_rdn,\n\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\"type(s)/value(s) of newrdn\\n\",\n\t\t\top->o_log_prefix, 0, 0 );\n\t\trs->sr_err = LDAP_INVALID_DN_SYNTAX;\n\t\trs->sr_text = \"unknown type(s)/value(s) used in RDN\";\n\t\tgoto done;\n\t}\n\n\tif ( op->oq_modrdn.rs_deleteoldrdn ) {\n\t\tif ( ldap_bv2rdn_x( &op->o_req_dn, &old_rdn,\n\t\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\t\"type(s)/value(s) of oldrdn\\n\",\n\t\t\t\top->o_log_prefix, 0, 0 );\n\t\t\trs->sr_err = LDAP_OTHER;\n\t\t\trs->sr_text = \"cannot parse RDN from old DN\";\n\t\t\tgoto done;\n\t\t}\n\t}\n\trs->sr_text = NULL;\n\n\t/* Add new attribute values to the entry */\n\tfor ( a_cnt = 0; new_rdn[a_cnt]; a_cnt++ ) {\n\t\tAttributeDescription\t*desc = NULL;\n\t\tModifications \t\t*mod_tmp;\n\n\t\trs->sr_err = slap_bv2ad( &new_rdn[a_cnt]->la_attr, &desc, &rs->sr_text );\n\n\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\tgoto done;\t\t\n\t\t}\n\n\t\tif ( !desc->ad_type->sat_equality ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\trs->sr_text = \"naming attribute has no equality matching rule\";\n\t\t\trs->sr_err = LDAP_NAMING_VIOLATION;\n\t\t\tgoto done;\n\t\t}\n\n\t\t/* Apply modification */\n\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\tmod_tmp->sml_desc = desc;\n\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\tmod_tmp->sml_numvals = 1;\n\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\tber_dupbv( &mod_tmp->sml_values[0], &new_rdn[a_cnt]->la_value );\n\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\tif( desc->ad_type->sat_equality->smr_normalize) {\n\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\trs->sr_err = desc->ad_type->sat_equality->smr_normalize(\n\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\tif (rs->sr_err != LDAP_SUCCESS) {\n\t\t\t\tch_free(mod_tmp->sml_nvalues);\n\t\t\t\tch_free(mod_tmp->sml_values[0].bv_val);\n\t\t\t\tch_free(mod_tmp->sml_values);\n\t\t\t\tch_free(mod_tmp);\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t} else {\n\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t}\n\t\tmod_tmp->sml_op = SLAP_MOD_SOFTADD;\n\t\tmod_tmp->sml_flags = 0;\n\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\top->orr_modlist = mod_tmp;\n\t}\n\n\t/* Remove old rdn value if required */\n\tif ( op->orr_deleteoldrdn ) {\n\t\tfor ( d_cnt = 0; old_rdn[d_cnt]; d_cnt++ ) {\n\t\t\tAttributeDescription\t*desc = NULL;\n\t\t\tModifications \t\t*mod_tmp;\n\n\t\t\trs->sr_err = slap_bv2ad( &old_rdn[d_cnt]->la_attr, &desc, &rs->sr_text );\n\t\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\t\"%s slap_modrdn2mods: %s: %s (old)\\n\",\n\t\t\t\t\top->o_log_prefix,\n\t\t\t\t\trs->sr_text, \n\t\t\t\t\told_rdn[d_cnt]->la_attr.bv_val );\n\t\t\t\tgoto done;\t\t\n\t\t\t}\n\n\t\t\t/* Apply modification */\n\t\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\t\tmod_tmp->sml_desc = desc;\n\t\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\t\tmod_tmp->sml_numvals = 1;\n\t\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\tber_dupbv( &mod_tmp->sml_values[0], &old_rdn[d_cnt]->la_value );\n\t\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\t\tif( desc->ad_type->sat_equality && desc->ad_type->sat_equality->smr_normalize) {\n\t\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\t\t(void) (*desc->ad_type->sat_equality->smr_normalize)(\n\t\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t\t} else {\n\t\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t\t}\n\t\t\tmod_tmp->sml_op = LDAP_MOD_DELETE;\n\t\t\tmod_tmp->sml_flags = 0;\n\t\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\t\top->orr_modlist = mod_tmp;\n\t\t}\n\t}\n\t\ndone:\n\n\t/* LDAP v2 supporting correct attribute handling. */\n\tif ( rs->sr_err != LDAP_SUCCESS && op->orr_modlist != NULL ) {\n\t\tModifications *tmp;\n\n\t\tfor ( ; op->orr_modlist != NULL; op->orr_modlist = tmp ) {\n\t\t\ttmp = op->orr_modlist->sml_next;\n\t\t\tch_free( op->orr_modlist );\n\t\t}\n\t}\n\n\tif ( new_rdn != NULL ) {\n\t\tldap_rdnfree_x( new_rdn, op->o_tmpmemctx );\n\t}\n\tif ( old_rdn != NULL ) {\n\t\tldap_rdnfree_x( old_rdn, op->o_tmpmemctx );\n\t}\n\n\treturn rs->sr_err;\n}", "func_hash": 130395506805320800712942663169466487219, "file_name": "modrdn.c", "file_hash": 27660542098986847529619564439519451657, "cwe": ["CWE-476"], "cve": "CVE-2020-25692", "cve_desc": "A NULL pointer dereference was found in OpenLDAP server and was fixed in openldap 2.4.55, during a request for renaming RDNs. An unauthenticated attacker could remotely crash the slapd process by sending a specially crafted request, causing a Denial of Service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25692"} {"idx": 202140, "project": "ImageMagick", "commit_id": "94174beff065cb5683d09d79e992c3ebbdead311", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/94174beff065cb5683d09d79e992c3ebbdead311", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 1, "func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,const PixelInterpolateMethod method,\n ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *canvas_image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *canvas_image,\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n canvas_image=CloneImage(image,0,0,MagickTrue,exception);\n if (canvas_image == (Image *) NULL)\n return((Image *) NULL);\n if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&\n (canvas_image->background_color.alpha != OpaqueAlpha))\n (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception);\n wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t)\n (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n return((Image *) NULL);\n }\n if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)/wave_length));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n canvas_image_view=AcquireVirtualCacheView(canvas_image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(canvas_image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(canvas_image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n const Quantum\n *magick_restrict p;\n\n Quantum\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1,\n exception);\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolatePixelChannels(canvas_image,canvas_image_view,\n wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception);\n if (status == MagickFalse)\n break;\n p+=GetPixelChannels(canvas_image);\n q+=GetPixelChannels(wave_image);\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(canvas_image,WaveImageTag,progress,\n canvas_image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n canvas_image_view=DestroyCacheView(canvas_image_view);\n canvas_image=DestroyImage(canvas_image);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "func_hash": 297225065081774005375523816476164848645, "file_name": "visual-effects.c", "file_hash": 243134469175298035815320169272144192832, "cwe": ["CWE-369"], "cve": "CVE-2021-20309", "cve_desc": "A flaw was found in ImageMagick in versions before 7.0.11 and before 6.9.12, where a division by zero in WaveImage() of MagickCore/visual-effects.c may trigger undefined behavior via a crafted image file submitted to an application using ImageMagick. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20309"} {"idx": 330274, "project": "ImageMagick", "commit_id": "94174beff065cb5683d09d79e992c3ebbdead311", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/94174beff065cb5683d09d79e992c3ebbdead311", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 0, "func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,const PixelInterpolateMethod method,\n ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *canvas_image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *canvas_image,\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n canvas_image=CloneImage(image,0,0,MagickTrue,exception);\n if (canvas_image == (Image *) NULL)\n return((Image *) NULL);\n if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&\n (canvas_image->background_color.alpha != OpaqueAlpha))\n (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception);\n wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t)\n (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n return((Image *) NULL);\n }\n if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)*PerceptibleReciprocal(wave_length)));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n canvas_image_view=AcquireVirtualCacheView(canvas_image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(canvas_image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(canvas_image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n const Quantum\n *magick_restrict p;\n\n Quantum\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1,\n exception);\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolatePixelChannels(canvas_image,canvas_image_view,\n wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception);\n if (status == MagickFalse)\n break;\n p+=GetPixelChannels(canvas_image);\n q+=GetPixelChannels(wave_image);\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(canvas_image,WaveImageTag,progress,\n canvas_image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n canvas_image_view=DestroyCacheView(canvas_image_view);\n canvas_image=DestroyImage(canvas_image);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "func_hash": 30440761873709244249325874728602063978, "file_name": "visual-effects.c", "file_hash": 35069357116713017849294933330007150955, "cwe": ["CWE-369"], "cve": "CVE-2021-20309", "cve_desc": "A flaw was found in ImageMagick in versions before 7.0.11 and before 6.9.12, where a division by zero in WaveImage() of MagickCore/visual-effects.c may trigger undefined behavior via a crafted image file submitted to an application using ImageMagick. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20309"} {"idx": 202143, "project": "linux", "commit_id": "acf69c946233259ab4d64f8869d4037a198c7f06", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=acf69c946233259ab4d64f8869d4037a198c7f06", "commit_message": "net/packet: fix overflow in tpacket_rcv\n\nUsing tp_reserve to calculate netoff can overflow as\ntp_reserve is unsigned int and netoff is unsigned short.\n\nThis may lead to macoff receving a smaller value then\nsizeof(struct virtio_net_hdr), and if po->has_vnet_hdr\nis set, an out-of-bounds write will occur when\ncalling virtio_net_hdr_from_skb.\n\nThe bug is fixed by converting netoff to unsigned int\nand checking if it exceeds USHRT_MAX.\n\nThis addresses CVE-2020-14386\n\nFixes: 8913336a7e8d (\"packet: add PACKET_RESERVE sockopt\")\nSigned-off-by: Or Cohen \nSigned-off-by: Eric Dumazet \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,\n\t\t struct packet_type *pt, struct net_device *orig_dev)\n{\n\tstruct sock *sk;\n\tstruct packet_sock *po;\n\tstruct sockaddr_ll *sll;\n\tunion tpacket_uhdr h;\n\tu8 *skb_head = skb->data;\n\tint skb_len = skb->len;\n\tunsigned int snaplen, res;\n\tunsigned long status = TP_STATUS_USER;\n\tunsigned short macoff, netoff, hdrlen;\n\tstruct sk_buff *copy_skb = NULL;\n\tstruct timespec64 ts;\n\t__u32 ts_status;\n\tbool is_drop_n_account = false;\n\tunsigned int slot_id = 0;\n\tbool do_vnet = false;\n\n\t/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.\n\t * We may add members to them until current aligned size without forcing\n\t * userspace to call getsockopt(..., PACKET_HDRLEN, ...).\n\t */\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);\n\n\tif (skb->pkt_type == PACKET_LOOPBACK)\n\t\tgoto drop;\n\n\tsk = pt->af_packet_priv;\n\tpo = pkt_sk(sk);\n\n\tif (!net_eq(dev_net(dev), sock_net(sk)))\n\t\tgoto drop;\n\n\tif (dev->header_ops) {\n\t\tif (sk->sk_type != SOCK_DGRAM)\n\t\t\tskb_push(skb, skb->data - skb_mac_header(skb));\n\t\telse if (skb->pkt_type == PACKET_OUTGOING) {\n\t\t\t/* Special case: outgoing packets have ll header at head */\n\t\t\tskb_pull(skb, skb_network_offset(skb));\n\t\t}\n\t}\n\n\tsnaplen = skb->len;\n\n\tres = run_filter(skb, sk, snaplen);\n\tif (!res)\n\t\tgoto drop_n_restore;\n\n\t/* If we are flooded, just give up */\n\tif (__packet_rcv_has_room(po, skb) == ROOM_NONE) {\n\t\tatomic_inc(&po->tp_drops);\n\t\tgoto drop_n_restore;\n\t}\n\n\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\tstatus |= TP_STATUS_CSUMNOTREADY;\n\telse if (skb->pkt_type != PACKET_OUTGOING &&\n\t\t (skb->ip_summed == CHECKSUM_COMPLETE ||\n\t\t skb_csum_unnecessary(skb)))\n\t\tstatus |= TP_STATUS_CSUM_VALID;\n\n\tif (snaplen > res)\n\t\tsnaplen = res;\n\n\tif (sk->sk_type == SOCK_DGRAM) {\n\t\tmacoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +\n\t\t\t\t po->tp_reserve;\n\t} else {\n\t\tunsigned int maclen = skb_network_offset(skb);\n\t\tnetoff = TPACKET_ALIGN(po->tp_hdrlen +\n\t\t\t\t (maclen < 16 ? 16 : maclen)) +\n\t\t\t\t po->tp_reserve;\n\t\tif (po->has_vnet_hdr) {\n\t\t\tnetoff += sizeof(struct virtio_net_hdr);\n\t\t\tdo_vnet = true;\n\t\t}\n\t\tmacoff = netoff - maclen;\n\t}\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tif (macoff + snaplen > po->rx_ring.frame_size) {\n\t\t\tif (po->copy_thresh &&\n\t\t\t atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {\n\t\t\t\tif (skb_shared(skb)) {\n\t\t\t\t\tcopy_skb = skb_clone(skb, GFP_ATOMIC);\n\t\t\t\t} else {\n\t\t\t\t\tcopy_skb = skb_get(skb);\n\t\t\t\t\tskb_head = skb->data;\n\t\t\t\t}\n\t\t\t\tif (copy_skb)\n\t\t\t\t\tskb_set_owner_r(copy_skb, sk);\n\t\t\t}\n\t\t\tsnaplen = po->rx_ring.frame_size - macoff;\n\t\t\tif ((int)snaplen < 0) {\n\t\t\t\tsnaplen = 0;\n\t\t\t\tdo_vnet = false;\n\t\t\t}\n\t\t}\n\t} else if (unlikely(macoff + snaplen >\n\t\t\t GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {\n\t\tu32 nval;\n\n\t\tnval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;\n\t\tpr_err_once(\"tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\\n\",\n\t\t\t snaplen, nval, macoff);\n\t\tsnaplen = nval;\n\t\tif (unlikely((int)snaplen < 0)) {\n\t\t\tsnaplen = 0;\n\t\t\tmacoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;\n\t\t\tdo_vnet = false;\n\t\t}\n\t}\n\tspin_lock(&sk->sk_receive_queue.lock);\n\th.raw = packet_current_rx_frame(po, skb,\n\t\t\t\t\tTP_STATUS_KERNEL, (macoff+snaplen));\n\tif (!h.raw)\n\t\tgoto drop_n_account;\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tslot_id = po->rx_ring.head;\n\t\tif (test_bit(slot_id, po->rx_ring.rx_owner_map))\n\t\t\tgoto drop_n_account;\n\t\t__set_bit(slot_id, po->rx_ring.rx_owner_map);\n\t}\n\n\tif (do_vnet &&\n\t virtio_net_hdr_from_skb(skb, h.raw + macoff -\n\t\t\t\t sizeof(struct virtio_net_hdr),\n\t\t\t\t vio_le(), true, 0)) {\n\t\tif (po->tp_version == TPACKET_V3)\n\t\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t\tgoto drop_n_account;\n\t}\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tpacket_increment_rx_head(po, &po->rx_ring);\n\t/*\n\t * LOSING will be reported till you read the stats,\n\t * because it's COR - Clear On Read.\n\t * Anyways, moving it for V1/V2 only as V3 doesn't need this\n\t * at packet level.\n\t */\n\t\tif (atomic_read(&po->tp_drops))\n\t\t\tstatus |= TP_STATUS_LOSING;\n\t}\n\n\tpo->stats.stats1.tp_packets++;\n\tif (copy_skb) {\n\t\tstatus |= TP_STATUS_COPY;\n\t\t__skb_queue_tail(&sk->sk_receive_queue, copy_skb);\n\t}\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\n\tskb_copy_bits(skb, 0, h.raw + macoff, snaplen);\n\n\tif (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))\n\t\tktime_get_real_ts64(&ts);\n\n\tstatus |= ts_status;\n\n\tswitch (po->tp_version) {\n\tcase TPACKET_V1:\n\t\th.h1->tp_len = skb->len;\n\t\th.h1->tp_snaplen = snaplen;\n\t\th.h1->tp_mac = macoff;\n\t\th.h1->tp_net = netoff;\n\t\th.h1->tp_sec = ts.tv_sec;\n\t\th.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;\n\t\thdrlen = sizeof(*h.h1);\n\t\tbreak;\n\tcase TPACKET_V2:\n\t\th.h2->tp_len = skb->len;\n\t\th.h2->tp_snaplen = snaplen;\n\t\th.h2->tp_mac = macoff;\n\t\th.h2->tp_net = netoff;\n\t\th.h2->tp_sec = ts.tv_sec;\n\t\th.h2->tp_nsec = ts.tv_nsec;\n\t\tif (skb_vlan_tag_present(skb)) {\n\t\t\th.h2->tp_vlan_tci = skb_vlan_tag_get(skb);\n\t\t\th.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);\n\t\t\tstatus |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;\n\t\t} else {\n\t\t\th.h2->tp_vlan_tci = 0;\n\t\t\th.h2->tp_vlan_tpid = 0;\n\t\t}\n\t\tmemset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));\n\t\thdrlen = sizeof(*h.h2);\n\t\tbreak;\n\tcase TPACKET_V3:\n\t\t/* tp_nxt_offset,vlan are already populated above.\n\t\t * So DONT clear those fields here\n\t\t */\n\t\th.h3->tp_status |= status;\n\t\th.h3->tp_len = skb->len;\n\t\th.h3->tp_snaplen = snaplen;\n\t\th.h3->tp_mac = macoff;\n\t\th.h3->tp_net = netoff;\n\t\th.h3->tp_sec = ts.tv_sec;\n\t\th.h3->tp_nsec = ts.tv_nsec;\n\t\tmemset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));\n\t\thdrlen = sizeof(*h.h3);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\tsll = h.raw + TPACKET_ALIGN(hdrlen);\n\tsll->sll_halen = dev_parse_header(skb, sll->sll_addr);\n\tsll->sll_family = AF_PACKET;\n\tsll->sll_hatype = dev->type;\n\tsll->sll_protocol = skb->protocol;\n\tsll->sll_pkttype = skb->pkt_type;\n\tif (unlikely(po->origdev))\n\t\tsll->sll_ifindex = orig_dev->ifindex;\n\telse\n\t\tsll->sll_ifindex = dev->ifindex;\n\n\tsmp_mb();\n\n#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tu8 *start, *end;\n\n\t\tend = (u8 *) PAGE_ALIGN((unsigned long) h.raw +\n\t\t\t\t\tmacoff + snaplen);\n\n\t\tfor (start = h.raw; start < end; start += PAGE_SIZE)\n\t\t\tflush_dcache_page(pgv_to_page(start));\n\t}\n\tsmp_wmb();\n#endif\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tspin_lock(&sk->sk_receive_queue.lock);\n\t\t__packet_set_status(po, h.raw, status);\n\t\t__clear_bit(slot_id, po->rx_ring.rx_owner_map);\n\t\tspin_unlock(&sk->sk_receive_queue.lock);\n\t\tsk->sk_data_ready(sk);\n\t} else if (po->tp_version == TPACKET_V3) {\n\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t}\n\ndrop_n_restore:\n\tif (skb_head != skb->data && skb_shared(skb)) {\n\t\tskb->data = skb_head;\n\t\tskb->len = skb_len;\n\t}\ndrop:\n\tif (!is_drop_n_account)\n\t\tconsume_skb(skb);\n\telse\n\t\tkfree_skb(skb);\n\treturn 0;\n\ndrop_n_account:\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\tatomic_inc(&po->tp_drops);\n\tis_drop_n_account = true;\n\n\tsk->sk_data_ready(sk);\n\tkfree_skb(copy_skb);\n\tgoto drop_n_restore;\n}", "func_hash": 286817046731601394534824133919186413957, "file_name": "af_packet.c", "file_hash": 166327228651815924658944232668272230422, "cwe": ["CWE-787"], "cve": "CVE-2020-14386", "cve_desc": "A flaw was found in the Linux kernel before 5.9-rc4. Memory corruption can be exploited to gain root privileges from unprivileged processes. The highest threat from this vulnerability is to data confidentiality and integrity.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14386"} {"idx": 330393, "project": "linux", "commit_id": "acf69c946233259ab4d64f8869d4037a198c7f06", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=acf69c946233259ab4d64f8869d4037a198c7f06", "commit_message": "net/packet: fix overflow in tpacket_rcv\n\nUsing tp_reserve to calculate netoff can overflow as\ntp_reserve is unsigned int and netoff is unsigned short.\n\nThis may lead to macoff receving a smaller value then\nsizeof(struct virtio_net_hdr), and if po->has_vnet_hdr\nis set, an out-of-bounds write will occur when\ncalling virtio_net_hdr_from_skb.\n\nThe bug is fixed by converting netoff to unsigned int\nand checking if it exceeds USHRT_MAX.\n\nThis addresses CVE-2020-14386\n\nFixes: 8913336a7e8d (\"packet: add PACKET_RESERVE sockopt\")\nSigned-off-by: Or Cohen \nSigned-off-by: Eric Dumazet \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,\n\t\t struct packet_type *pt, struct net_device *orig_dev)\n{\n\tstruct sock *sk;\n\tstruct packet_sock *po;\n\tstruct sockaddr_ll *sll;\n\tunion tpacket_uhdr h;\n\tu8 *skb_head = skb->data;\n\tint skb_len = skb->len;\n\tunsigned int snaplen, res;\n\tunsigned long status = TP_STATUS_USER;\n\tunsigned short macoff, hdrlen;\n\tunsigned int netoff;\n\tstruct sk_buff *copy_skb = NULL;\n\tstruct timespec64 ts;\n\t__u32 ts_status;\n\tbool is_drop_n_account = false;\n\tunsigned int slot_id = 0;\n\tbool do_vnet = false;\n\n\t/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.\n\t * We may add members to them until current aligned size without forcing\n\t * userspace to call getsockopt(..., PACKET_HDRLEN, ...).\n\t */\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);\n\n\tif (skb->pkt_type == PACKET_LOOPBACK)\n\t\tgoto drop;\n\n\tsk = pt->af_packet_priv;\n\tpo = pkt_sk(sk);\n\n\tif (!net_eq(dev_net(dev), sock_net(sk)))\n\t\tgoto drop;\n\n\tif (dev->header_ops) {\n\t\tif (sk->sk_type != SOCK_DGRAM)\n\t\t\tskb_push(skb, skb->data - skb_mac_header(skb));\n\t\telse if (skb->pkt_type == PACKET_OUTGOING) {\n\t\t\t/* Special case: outgoing packets have ll header at head */\n\t\t\tskb_pull(skb, skb_network_offset(skb));\n\t\t}\n\t}\n\n\tsnaplen = skb->len;\n\n\tres = run_filter(skb, sk, snaplen);\n\tif (!res)\n\t\tgoto drop_n_restore;\n\n\t/* If we are flooded, just give up */\n\tif (__packet_rcv_has_room(po, skb) == ROOM_NONE) {\n\t\tatomic_inc(&po->tp_drops);\n\t\tgoto drop_n_restore;\n\t}\n\n\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\tstatus |= TP_STATUS_CSUMNOTREADY;\n\telse if (skb->pkt_type != PACKET_OUTGOING &&\n\t\t (skb->ip_summed == CHECKSUM_COMPLETE ||\n\t\t skb_csum_unnecessary(skb)))\n\t\tstatus |= TP_STATUS_CSUM_VALID;\n\n\tif (snaplen > res)\n\t\tsnaplen = res;\n\n\tif (sk->sk_type == SOCK_DGRAM) {\n\t\tmacoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +\n\t\t\t\t po->tp_reserve;\n\t} else {\n\t\tunsigned int maclen = skb_network_offset(skb);\n\t\tnetoff = TPACKET_ALIGN(po->tp_hdrlen +\n\t\t\t\t (maclen < 16 ? 16 : maclen)) +\n\t\t\t\t po->tp_reserve;\n\t\tif (po->has_vnet_hdr) {\n\t\t\tnetoff += sizeof(struct virtio_net_hdr);\n\t\t\tdo_vnet = true;\n\t\t}\n\t\tmacoff = netoff - maclen;\n\t}\n\tif (netoff > USHRT_MAX) {\n\t\tatomic_inc(&po->tp_drops);\n\t\tgoto drop_n_restore;\n\t}\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tif (macoff + snaplen > po->rx_ring.frame_size) {\n\t\t\tif (po->copy_thresh &&\n\t\t\t atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {\n\t\t\t\tif (skb_shared(skb)) {\n\t\t\t\t\tcopy_skb = skb_clone(skb, GFP_ATOMIC);\n\t\t\t\t} else {\n\t\t\t\t\tcopy_skb = skb_get(skb);\n\t\t\t\t\tskb_head = skb->data;\n\t\t\t\t}\n\t\t\t\tif (copy_skb)\n\t\t\t\t\tskb_set_owner_r(copy_skb, sk);\n\t\t\t}\n\t\t\tsnaplen = po->rx_ring.frame_size - macoff;\n\t\t\tif ((int)snaplen < 0) {\n\t\t\t\tsnaplen = 0;\n\t\t\t\tdo_vnet = false;\n\t\t\t}\n\t\t}\n\t} else if (unlikely(macoff + snaplen >\n\t\t\t GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {\n\t\tu32 nval;\n\n\t\tnval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;\n\t\tpr_err_once(\"tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\\n\",\n\t\t\t snaplen, nval, macoff);\n\t\tsnaplen = nval;\n\t\tif (unlikely((int)snaplen < 0)) {\n\t\t\tsnaplen = 0;\n\t\t\tmacoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;\n\t\t\tdo_vnet = false;\n\t\t}\n\t}\n\tspin_lock(&sk->sk_receive_queue.lock);\n\th.raw = packet_current_rx_frame(po, skb,\n\t\t\t\t\tTP_STATUS_KERNEL, (macoff+snaplen));\n\tif (!h.raw)\n\t\tgoto drop_n_account;\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tslot_id = po->rx_ring.head;\n\t\tif (test_bit(slot_id, po->rx_ring.rx_owner_map))\n\t\t\tgoto drop_n_account;\n\t\t__set_bit(slot_id, po->rx_ring.rx_owner_map);\n\t}\n\n\tif (do_vnet &&\n\t virtio_net_hdr_from_skb(skb, h.raw + macoff -\n\t\t\t\t sizeof(struct virtio_net_hdr),\n\t\t\t\t vio_le(), true, 0)) {\n\t\tif (po->tp_version == TPACKET_V3)\n\t\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t\tgoto drop_n_account;\n\t}\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tpacket_increment_rx_head(po, &po->rx_ring);\n\t/*\n\t * LOSING will be reported till you read the stats,\n\t * because it's COR - Clear On Read.\n\t * Anyways, moving it for V1/V2 only as V3 doesn't need this\n\t * at packet level.\n\t */\n\t\tif (atomic_read(&po->tp_drops))\n\t\t\tstatus |= TP_STATUS_LOSING;\n\t}\n\n\tpo->stats.stats1.tp_packets++;\n\tif (copy_skb) {\n\t\tstatus |= TP_STATUS_COPY;\n\t\t__skb_queue_tail(&sk->sk_receive_queue, copy_skb);\n\t}\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\n\tskb_copy_bits(skb, 0, h.raw + macoff, snaplen);\n\n\tif (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))\n\t\tktime_get_real_ts64(&ts);\n\n\tstatus |= ts_status;\n\n\tswitch (po->tp_version) {\n\tcase TPACKET_V1:\n\t\th.h1->tp_len = skb->len;\n\t\th.h1->tp_snaplen = snaplen;\n\t\th.h1->tp_mac = macoff;\n\t\th.h1->tp_net = netoff;\n\t\th.h1->tp_sec = ts.tv_sec;\n\t\th.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;\n\t\thdrlen = sizeof(*h.h1);\n\t\tbreak;\n\tcase TPACKET_V2:\n\t\th.h2->tp_len = skb->len;\n\t\th.h2->tp_snaplen = snaplen;\n\t\th.h2->tp_mac = macoff;\n\t\th.h2->tp_net = netoff;\n\t\th.h2->tp_sec = ts.tv_sec;\n\t\th.h2->tp_nsec = ts.tv_nsec;\n\t\tif (skb_vlan_tag_present(skb)) {\n\t\t\th.h2->tp_vlan_tci = skb_vlan_tag_get(skb);\n\t\t\th.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);\n\t\t\tstatus |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;\n\t\t} else {\n\t\t\th.h2->tp_vlan_tci = 0;\n\t\t\th.h2->tp_vlan_tpid = 0;\n\t\t}\n\t\tmemset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));\n\t\thdrlen = sizeof(*h.h2);\n\t\tbreak;\n\tcase TPACKET_V3:\n\t\t/* tp_nxt_offset,vlan are already populated above.\n\t\t * So DONT clear those fields here\n\t\t */\n\t\th.h3->tp_status |= status;\n\t\th.h3->tp_len = skb->len;\n\t\th.h3->tp_snaplen = snaplen;\n\t\th.h3->tp_mac = macoff;\n\t\th.h3->tp_net = netoff;\n\t\th.h3->tp_sec = ts.tv_sec;\n\t\th.h3->tp_nsec = ts.tv_nsec;\n\t\tmemset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));\n\t\thdrlen = sizeof(*h.h3);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\tsll = h.raw + TPACKET_ALIGN(hdrlen);\n\tsll->sll_halen = dev_parse_header(skb, sll->sll_addr);\n\tsll->sll_family = AF_PACKET;\n\tsll->sll_hatype = dev->type;\n\tsll->sll_protocol = skb->protocol;\n\tsll->sll_pkttype = skb->pkt_type;\n\tif (unlikely(po->origdev))\n\t\tsll->sll_ifindex = orig_dev->ifindex;\n\telse\n\t\tsll->sll_ifindex = dev->ifindex;\n\n\tsmp_mb();\n\n#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tu8 *start, *end;\n\n\t\tend = (u8 *) PAGE_ALIGN((unsigned long) h.raw +\n\t\t\t\t\tmacoff + snaplen);\n\n\t\tfor (start = h.raw; start < end; start += PAGE_SIZE)\n\t\t\tflush_dcache_page(pgv_to_page(start));\n\t}\n\tsmp_wmb();\n#endif\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tspin_lock(&sk->sk_receive_queue.lock);\n\t\t__packet_set_status(po, h.raw, status);\n\t\t__clear_bit(slot_id, po->rx_ring.rx_owner_map);\n\t\tspin_unlock(&sk->sk_receive_queue.lock);\n\t\tsk->sk_data_ready(sk);\n\t} else if (po->tp_version == TPACKET_V3) {\n\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t}\n\ndrop_n_restore:\n\tif (skb_head != skb->data && skb_shared(skb)) {\n\t\tskb->data = skb_head;\n\t\tskb->len = skb_len;\n\t}\ndrop:\n\tif (!is_drop_n_account)\n\t\tconsume_skb(skb);\n\telse\n\t\tkfree_skb(skb);\n\treturn 0;\n\ndrop_n_account:\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\tatomic_inc(&po->tp_drops);\n\tis_drop_n_account = true;\n\n\tsk->sk_data_ready(sk);\n\tkfree_skb(copy_skb);\n\tgoto drop_n_restore;\n}", "func_hash": 179707520114082691635512663133585931281, "file_name": "af_packet.c", "file_hash": 99369369370132391276939486288134797134, "cwe": ["CWE-787"], "cve": "CVE-2020-14386", "cve_desc": "A flaw was found in the Linux kernel before 5.9-rc4. Memory corruption can be exploited to gain root privileges from unprivileged processes. The highest threat from this vulnerability is to data confidentiality and integrity.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14386"} {"idx": 202305, "project": "libsolv", "commit_id": "fdb9c9c03508990e4583046b590c30d958f272da", "project_url": "https://github.com/openSUSE/libsolv", "commit_url": "https://github.com/openSUSE/libsolv/commit/fdb9c9c03508990e4583046b590c30d958f272da", "commit_message": "repodata_schema2id: fix heap-buffer-overflow in memcmp\n\nWhen the length of last schema in data->schemadata is\nless than length of input schema, we got a read overflow\nin asan test.\n\nSigned-off-by: Zhipeng Xie ", "target": 1, "func": "repodata_schema2id(Repodata *data, Id *schema, int create)\n{\n int h, len, i;\n Id *sp, cid;\n Id *schematahash;\n\n if (!*schema)\n return 0;\t/* XXX: allow empty schema? */\n if ((schematahash = data->schematahash) == 0)\n {\n data->schematahash = schematahash = solv_calloc(256, sizeof(Id));\n for (i = 1; i < data->nschemata; i++)\n\t{\n\t for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)\n\t h = h * 7 + *sp++;\n\t h &= 255;\n\t schematahash[h] = i;\n\t}\n data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);\n }\n\n for (sp = schema, len = 0, h = 0; *sp; len++)\n h = h * 7 + *sp++;\n h &= 255;\n len++;\n\n cid = schematahash[h];\n if (cid)\n {\n if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */\n if (!create)\n return 0;\n data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);\n /* add schema */\n memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));\n data->schemata[data->nschemata] = data->schemadatalen;\n data->schemadatalen += len;\n schematahash[h] = data->nschemata;\n#if 0\nfprintf(stderr, \"schema2id: new schema\\n\");\n#endif\n return data->nschemata++;\n}", "func_hash": 223701282236869488560678017310270472659, "file_name": "repodata.c", "file_hash": 82972260300685973504162230933965575200, "cwe": ["CWE-125"], "cve": "CVE-2019-20387", "cve_desc": "repodata_schema2id in repodata.c in libsolv before 0.7.6 has a heap-based buffer over-read via a last schema whose length is less than the length of the input schema.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20387"} {"idx": 333146, "project": "libsolv", "commit_id": "fdb9c9c03508990e4583046b590c30d958f272da", "project_url": "https://github.com/openSUSE/libsolv", "commit_url": "https://github.com/openSUSE/libsolv/commit/fdb9c9c03508990e4583046b590c30d958f272da", "commit_message": "repodata_schema2id: fix heap-buffer-overflow in memcmp\n\nWhen the length of last schema in data->schemadata is\nless than length of input schema, we got a read overflow\nin asan test.\n\nSigned-off-by: Zhipeng Xie ", "target": 0, "func": "repodata_schema2id(Repodata *data, Id *schema, int create)\n{\n int h, len, i;\n Id *sp, cid;\n Id *schematahash;\n\n if (!*schema)\n return 0;\t/* XXX: allow empty schema? */\n if ((schematahash = data->schematahash) == 0)\n {\n data->schematahash = schematahash = solv_calloc(256, sizeof(Id));\n for (i = 1; i < data->nschemata; i++)\n\t{\n\t for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)\n\t h = h * 7 + *sp++;\n\t h &= 255;\n\t schematahash[h] = i;\n\t}\n data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);\n }\n\n for (sp = schema, len = 0, h = 0; *sp; len++)\n h = h * 7 + *sp++;\n h &= 255;\n len++;\n\n cid = schematahash[h];\n if (cid)\n {\n if ((data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n if ((data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t\t!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */\n if (!create)\n return 0;\n data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);\n /* add schema */\n memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));\n data->schemata[data->nschemata] = data->schemadatalen;\n data->schemadatalen += len;\n schematahash[h] = data->nschemata;\n#if 0\nfprintf(stderr, \"schema2id: new schema\\n\");\n#endif\n return data->nschemata++;\n}", "func_hash": 249288304853674571767969633623429082558, "file_name": "repodata.c", "file_hash": 116185689098076357643977082057535053495, "cwe": ["CWE-125"], "cve": "CVE-2019-20387", "cve_desc": "repodata_schema2id in repodata.c in libsolv before 0.7.6 has a heap-based buffer over-read via a last schema whose length is less than the length of the input schema.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20387"} {"idx": 202401, "project": "Pillow", "commit_id": "3fee28eb9479bf7d59e0fa08068f9cc4a6e2f04c", "project_url": "https://github.com/python-pillow/Pillow", "commit_url": "https://github.com/python-pillow/Pillow/commit/3fee28eb9479bf7d59e0fa08068f9cc4a6e2f04c", "commit_message": "Incorrect error code checking in TiffDecode.c\n\n* since Pillow 8.1.0\n* CVE-2021-25289", "target": 1, "func": "_decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) {\n // To avoid dealing with YCbCr subsampling, let libtiff handle it\n // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle\n // all of the conversion. Metadata read from the TIFFRGBAImage could\n // be different from the metadata that the base tiff returns.\n\n INT32 strip_row;\n UINT8 *new_data;\n UINT32 rows_per_strip, row_byte_size, rows_to_read;\n int ret;\n TIFFRGBAImage img;\n char emsg[1024] = \"\";\n\n ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);\n if (ret != 1) {\n rows_per_strip = state->ysize;\n }\n TRACE((\"RowsPerStrip: %u \\n\", rows_per_strip));\n\n if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) {\n TRACE((\"Decode error, msg: %s\", emsg));\n state->errcode = IMAGING_CODEC_BROKEN;\n // nothing to clean up, just return\n return -1;\n }\n\n img.req_orientation = ORIENTATION_TOPLEFT;\n img.col_offset = 0;\n\n if (state->xsize != img.width || state->ysize != img.height) {\n TRACE(\n (\"Inconsistent Image Error: %d =? %d, %d =? %d\",\n state->xsize,\n img.width,\n state->ysize,\n img.height));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n /* overflow check for row byte size */\n if (INT_MAX / 4 < img.width) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n // TiffRGBAImages are 32bits/pixel.\n row_byte_size = img.width * 4;\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < rows_per_strip) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->bytes = rows_per_strip * row_byte_size;\n\n TRACE((\"StripSize: %d \\n\", state->bytes));\n\n /* realloc to fit whole strip */\n /* malloc check above */\n new_data = realloc(state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->buffer = new_data;\n\n for (; state->y < state->ysize; state->y += rows_per_strip) {\n img.row_offset = state->y;\n rows_to_read = min(rows_per_strip, img.height - state->y);\n\n if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) ==\n -1) {\n TRACE((\"Decode Error, y: %d\\n\", state->y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n TRACE((\"Decoded strip for row %d \\n\", state->y));\n\n // iterate over each row in the strip and stuff data into image\n for (strip_row = 0;\n strip_row < min((INT32)rows_per_strip, state->ysize - state->y);\n strip_row++) {\n TRACE((\"Writing data into line %d ; \\n\", state->y + strip_row));\n\n // UINT8 * bbb = state->buffer + strip_row * (state->bytes /\n // rows_per_strip); TRACE((\"chars: %x %x %x %x\\n\", ((UINT8 *)bbb)[0],\n // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle(\n (UINT8 *)im->image[state->y + state->yoff + strip_row] +\n state->xoff * im->pixelsize,\n state->buffer + strip_row * row_byte_size,\n state->xsize);\n }\n }\n\ndecodeycbcr_err:\n TIFFRGBAImageEnd(&img);\n if (state->errcode != 0) {\n return -1;\n }\n return 0;\n}", "func_hash": 76360972069845183295553755875742716845, "file_name": "TiffDecode.c", "file_hash": 160465138231271821765101532377940209528, "cwe": ["CWE-787"], "cve": "CVE-2021-25289", "cve_desc": "An issue was discovered in Pillow before 8.1.1. TiffDecode has a heap-based buffer overflow when decoding crafted YCbCr files because of certain interpretation conflicts with LibTIFF in RGBA mode. NOTE: this issue exists because of an incomplete fix for CVE-2020-35654.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-25289"} {"idx": 333841, "project": "Pillow", "commit_id": "3fee28eb9479bf7d59e0fa08068f9cc4a6e2f04c", "project_url": "https://github.com/python-pillow/Pillow", "commit_url": "https://github.com/python-pillow/Pillow/commit/3fee28eb9479bf7d59e0fa08068f9cc4a6e2f04c", "commit_message": "Incorrect error code checking in TiffDecode.c\n\n* since Pillow 8.1.0\n* CVE-2021-25289", "target": 0, "func": "_decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) {\n // To avoid dealing with YCbCr subsampling, let libtiff handle it\n // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle\n // all of the conversion. Metadata read from the TIFFRGBAImage could\n // be different from the metadata that the base tiff returns.\n\n INT32 strip_row;\n UINT8 *new_data;\n UINT32 rows_per_strip, row_byte_size, rows_to_read;\n int ret;\n TIFFRGBAImage img;\n char emsg[1024] = \"\";\n\n ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);\n if (ret != 1) {\n rows_per_strip = state->ysize;\n }\n TRACE((\"RowsPerStrip: %u \\n\", rows_per_strip));\n\n if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) {\n TRACE((\"Decode error, msg: %s\", emsg));\n state->errcode = IMAGING_CODEC_BROKEN;\n // nothing to clean up, just return\n return -1;\n }\n\n img.req_orientation = ORIENTATION_TOPLEFT;\n img.col_offset = 0;\n\n if (state->xsize != img.width || state->ysize != img.height) {\n TRACE(\n (\"Inconsistent Image Error: %d =? %d, %d =? %d\",\n state->xsize,\n img.width,\n state->ysize,\n img.height));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n /* overflow check for row byte size */\n if (INT_MAX / 4 < img.width) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n // TiffRGBAImages are 32bits/pixel.\n row_byte_size = img.width * 4;\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < rows_per_strip) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->bytes = rows_per_strip * row_byte_size;\n\n TRACE((\"StripSize: %d \\n\", state->bytes));\n\n /* realloc to fit whole strip */\n /* malloc check above */\n new_data = realloc(state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->buffer = new_data;\n\n for (; state->y < state->ysize; state->y += rows_per_strip) {\n img.row_offset = state->y;\n rows_to_read = min(rows_per_strip, img.height - state->y);\n\n if (!TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read)) {\n TRACE((\"Decode Error, y: %d\\n\", state->y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n TRACE((\"Decoded strip for row %d \\n\", state->y));\n\n // iterate over each row in the strip and stuff data into image\n for (strip_row = 0;\n strip_row < min((INT32)rows_per_strip, state->ysize - state->y);\n strip_row++) {\n TRACE((\"Writing data into line %d ; \\n\", state->y + strip_row));\n\n // UINT8 * bbb = state->buffer + strip_row * (state->bytes /\n // rows_per_strip); TRACE((\"chars: %x %x %x %x\\n\", ((UINT8 *)bbb)[0],\n // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle(\n (UINT8 *)im->image[state->y + state->yoff + strip_row] +\n state->xoff * im->pixelsize,\n state->buffer + strip_row * row_byte_size,\n state->xsize);\n }\n }\n\ndecodeycbcr_err:\n TIFFRGBAImageEnd(&img);\n if (state->errcode != 0) {\n return -1;\n }\n return 0;\n}", "func_hash": 308592840620255987109906406884589357316, "file_name": "TiffDecode.c", "file_hash": 233618010246282223642363735502818553637, "cwe": ["CWE-787"], "cve": "CVE-2021-25289", "cve_desc": "An issue was discovered in Pillow before 8.1.1. TiffDecode has a heap-based buffer overflow when decoding crafted YCbCr files because of certain interpretation conflicts with LibTIFF in RGBA mode. NOTE: this issue exists because of an incomplete fix for CVE-2020-35654.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-25289"} {"idx": 202574, "project": "tip", "commit_id": "511885d7061eda3eb1faf3f57dcc936ff75863f1", "project_url": "http://git.kernel.org/cgit/linux/kernel/git/tip/tip", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?id=511885d7061eda3eb1faf3f57dcc936ff75863f1", "commit_message": "lib/timerqueue: Rely on rbtree semantics for next timer\n\nSimplify the timerqueue code by using cached rbtrees and rely on the tree\nleftmost node semantics to get the timer with earliest expiration time.\nThis is a drop in conversion, and therefore semantics remain untouched.\n\nThe runtime overhead of cached rbtrees is be pretty much the same as the\ncurrent head->next method, noting that when removing the leftmost node,\na common operation for the timerqueue, the rb_next(leftmost) is O(1) as\nwell, so the next timer will either be the right node or its parent.\nTherefore no extra pointer chasing. Finally, the size of the struct\ntimerqueue_head remains the same.\n\nPasses several hours of rcutorture.\n\nSigned-off-by: Davidlohr Bueso \nSigned-off-by: Thomas Gleixner \nLink: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5", "target": 1, "func": "bool timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)\n{\n\tstruct rb_node **p = &head->head.rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct timerqueue_node *ptr;\n\n\t/* Make sure we don't add nodes that are already added */\n\tWARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));\n\n\twhile (*p) {\n\t\tparent = *p;\n\t\tptr = rb_entry(parent, struct timerqueue_node, node);\n\t\tif (node->expires < ptr->expires)\n\t\t\tp = &(*p)->rb_left;\n\t\telse\n\t\t\tp = &(*p)->rb_right;\n\t}\n\trb_link_node(&node->node, parent, p);\n\trb_insert_color(&node->node, &head->head);\n\n\tif (!head->next || node->expires < head->next->expires) {\n\t\thead->next = node;\n\t\treturn true;\n\t}\n\treturn false;\n}", "func_hash": 313507551150056367472710702350649146350, "file_name": "timerqueue.c", "file_hash": 301773358683850959308223272073776940507, "cwe": ["CWE-665"], "cve": "CVE-2021-20317", "cve_desc": "A flaw was found in the Linux kernel. A corrupted timer tree caused the task wakeup to be missing in the timerqueue_add function in lib/timerqueue.c. This flaw allows a local attacker with special user privileges to cause a denial of service, slowing and eventually stopping the system while running OSP.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20317"} {"idx": 335107, "project": "tip", "commit_id": "511885d7061eda3eb1faf3f57dcc936ff75863f1", "project_url": "http://git.kernel.org/cgit/linux/kernel/git/tip/tip", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?id=511885d7061eda3eb1faf3f57dcc936ff75863f1", "commit_message": "lib/timerqueue: Rely on rbtree semantics for next timer\n\nSimplify the timerqueue code by using cached rbtrees and rely on the tree\nleftmost node semantics to get the timer with earliest expiration time.\nThis is a drop in conversion, and therefore semantics remain untouched.\n\nThe runtime overhead of cached rbtrees is be pretty much the same as the\ncurrent head->next method, noting that when removing the leftmost node,\na common operation for the timerqueue, the rb_next(leftmost) is O(1) as\nwell, so the next timer will either be the right node or its parent.\nTherefore no extra pointer chasing. Finally, the size of the struct\ntimerqueue_head remains the same.\n\nPasses several hours of rcutorture.\n\nSigned-off-by: Davidlohr Bueso \nSigned-off-by: Thomas Gleixner \nLink: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5", "target": 0, "func": "bool timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)\n{\n\tstruct rb_node **p = &head->rb_root.rb_root.rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct timerqueue_node *ptr;\n\tbool leftmost = true;\n\n\t/* Make sure we don't add nodes that are already added */\n\tWARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));\n\n\twhile (*p) {\n\t\tparent = *p;\n\t\tptr = rb_entry(parent, struct timerqueue_node, node);\n\t\tif (node->expires < ptr->expires) {\n\t\t\tp = &(*p)->rb_left;\n\t\t} else {\n\t\t\tp = &(*p)->rb_right;\n\t\t\tleftmost = false;\n\t\t}\n\t}\n\trb_link_node(&node->node, parent, p);\n\trb_insert_color_cached(&node->node, &head->rb_root, leftmost);\n\n\treturn leftmost;\n}", "func_hash": 190970933600539908405062495900719546556, "file_name": "timerqueue.c", "file_hash": 339539458035692235660892160646669809643, "cwe": ["CWE-665"], "cve": "CVE-2021-20317", "cve_desc": "A flaw was found in the Linux kernel. A corrupted timer tree caused the task wakeup to be missing in the timerqueue_add function in lib/timerqueue.c. This flaw allows a local attacker with special user privileges to cause a denial of service, slowing and eventually stopping the system while running OSP.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20317"} {"idx": 202609, "project": "wireshark", "commit_id": "618661b22e34a59b21117db723d8ff91e064d4ba", "project_url": "https://github.com/wireshark/wireshark", "commit_url": "https://gitlab.com/wireshark/wireshark/-/commit/618661b22e34a59b21117db723d8ff91e064d4ba", "commit_message": "dnp: plug a memory leak.\n\nIf we're throwing away the data, *throw away the data* - free it, as\nwe're not using it as the backing data for a tvbuff.", "target": 1, "func": "dissect_dnp3_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n proto_item *ti, *tdl, *tc, *hidden_item;\n proto_tree *dnp3_tree, *dl_tree, *field_tree;\n int offset = 0, temp_offset = 0;\n gboolean dl_prm;\n guint8 dl_len, dl_ctl, dl_func;\n const gchar *func_code_str;\n guint16 dl_dst, dl_src, calc_dl_crc;\n\n /* Make entries in Protocol column and Info column on summary display */\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"DNP 3.0\");\n col_clear(pinfo->cinfo, COL_INFO);\n\n /* Skip \"0x0564\" header bytes */\n temp_offset += 2;\n\n dl_len = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_ctl = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_dst = tvb_get_letohs(tvb, temp_offset);\n temp_offset += 2;\n\n dl_src = tvb_get_letohs(tvb, temp_offset);\n\n dl_func = dl_ctl & DNP3_CTL_FUNC;\n dl_prm = dl_ctl & DNP3_CTL_PRM;\n func_code_str = val_to_str(dl_func, dl_prm ? dnp3_ctl_func_pri_vals : dnp3_ctl_func_sec_vals,\n \"Unknown function (0x%02x)\");\n\n /* Make sure source and dest are always in the info column */\n col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, \"len=%u, %s\", dl_len, func_code_str);\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dnp3, tvb, offset, -1, ENC_NA);\n dnp3_tree = proto_item_add_subtree(ti, ett_dnp3);\n\n /* Create Subtree for Data Link Layer */\n dl_tree = proto_tree_add_subtree_format(dnp3_tree, tvb, offset, DNP_HDR_LEN, ett_dnp3_dl, &tdl,\n \"Data Link Layer, Len: %u, From: %u, To: %u, \", dl_len, dl_src, dl_dst);\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tdl, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tdl, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tdl, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tdl, \"DFC, \");\n }\n proto_item_append_text(tdl, \"%s\", func_code_str);\n\n /* start bytes */\n proto_tree_add_item(dl_tree, hf_dnp3_start, tvb, offset, 2, ENC_BIG_ENDIAN);\n offset += 2;\n\n /* add length field */\n proto_tree_add_item(dl_tree, hf_dnp3_len, tvb, offset, 1, ENC_BIG_ENDIAN);\n offset += 1;\n\n /* Add Control Byte Subtree */\n tc = proto_tree_add_uint_format_value(dl_tree, hf_dnp3_ctl, tvb, offset, 1, dl_ctl,\n \"0x%02x (\", dl_ctl);\n /* Add Text to Control Byte Subtree Header */\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tc, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tc, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tc, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tc, \"DFC, \");\n }\n proto_item_append_text(tc, \"%s)\", func_code_str );\n field_tree = proto_item_add_subtree(tc, ett_dnp3_dl_ctl);\n\n /* Add Control Byte Subtree Items */\n if (dl_prm) {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcb, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcv, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prifunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n else {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dfc, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_secfunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n offset += 1;\n\n /* add destination and source addresses */\n proto_tree_add_item(dl_tree, hf_dnp3_dst, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n proto_tree_add_item(dl_tree, hf_dnp3_src, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n\n /* and header CRC */\n calc_dl_crc = calculateCRCtvb(tvb, 0, DNP_HDR_LEN - 2);\n proto_tree_add_checksum(dl_tree, tvb, offset, hf_dnp3_data_hdr_crc,\n hf_dnp3_data_hdr_crc_status, &ei_dnp3_data_hdr_crc_incorrect,\n pinfo, calc_dl_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n offset += 2;\n\n /* If the DataLink function is 'Request Link Status' or 'Status of Link',\n or 'Reset Link' we don't expect any Transport or Application Layer Data\n NOTE: This code should probably check what DOES have TR or AL data */\n if ((dl_func != DL_FUNC_LINK_STAT) && (dl_func != DL_FUNC_STAT_LINK) &&\n (dl_func != DL_FUNC_RESET_LINK) && (dl_func != DL_FUNC_ACK))\n {\n proto_tree *data_tree;\n proto_item *data_ti;\n guint8 tr_ctl, tr_seq;\n gboolean tr_fir, tr_fin;\n guint8 *al_buffer, *al_buffer_ptr;\n guint8 data_len;\n int data_start = offset;\n int tl_offset;\n gboolean crc_OK = FALSE;\n tvbuff_t *next_tvb;\n guint i;\n static int * const transport_flags[] = {\n &hf_dnp3_tr_fin,\n &hf_dnp3_tr_fir,\n &hf_dnp3_tr_seq,\n NULL\n };\n\n /* get the transport layer byte */\n tr_ctl = tvb_get_guint8(tvb, offset);\n tr_seq = tr_ctl & DNP3_TR_SEQ;\n tr_fir = tr_ctl & DNP3_TR_FIR;\n tr_fin = tr_ctl & DNP3_TR_FIN;\n\n /* Add Transport Layer Tree */\n tc = proto_tree_add_bitmask(dnp3_tree, tvb, offset, hf_dnp3_tr_ctl, ett_dnp3_tr_ctl, transport_flags, ENC_BIG_ENDIAN);\n proto_item_append_text(tc, \"(\");\n if (tr_fir) proto_item_append_text(tc, \"FIR, \");\n if (tr_fin) proto_item_append_text(tc, \"FIN, \");\n proto_item_append_text(tc, \"Sequence %u)\", tr_seq);\n\n /* Add data chunk tree */\n data_tree = proto_tree_add_subtree(dnp3_tree, tvb, offset, -1, ett_dnp3_dl_data, &data_ti, \"Data Chunks\");\n\n /* extract the application layer data, validating the CRCs */\n\n /* XXX - check for dl_len <= 5 */\n data_len = dl_len - 5;\n al_buffer = (guint8 *)wmem_alloc(pinfo->pool, data_len);\n al_buffer_ptr = al_buffer;\n i = 0;\n tl_offset = 1; /* skip the initial transport layer byte when assembling chunks for the application layer tvb */\n while (data_len > 0)\n {\n guint8 chk_size;\n const guint8 *chk_ptr;\n proto_tree *chk_tree;\n proto_item *chk_len_ti;\n guint16 calc_crc, act_crc;\n\n chk_size = MIN(data_len, AL_MAX_CHUNK_SIZE);\n chk_ptr = tvb_get_ptr(tvb, offset, chk_size);\n memcpy(al_buffer_ptr, chk_ptr + tl_offset, chk_size - tl_offset);\n al_buffer_ptr += chk_size - tl_offset;\n\n chk_tree = proto_tree_add_subtree_format(data_tree, tvb, offset, chk_size + 2, ett_dnp3_dl_chunk, NULL, \"Data Chunk: %u\", i);\n proto_tree_add_item(chk_tree, hf_dnp3_data_chunk, tvb, offset, chk_size, ENC_NA);\n chk_len_ti = proto_tree_add_uint(chk_tree, hf_dnp3_data_chunk_len, tvb, offset, 0, chk_size);\n proto_item_set_generated(chk_len_ti);\n\n offset += chk_size;\n\n calc_crc = calculateCRC(chk_ptr, chk_size);\n proto_tree_add_checksum(chk_tree, tvb, offset, hf_dnp3_data_chunk_crc,\n hf_dnp3_data_chunk_crc_status, &ei_dnp3_data_chunk_crc_incorrect,\n pinfo, calc_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n act_crc = tvb_get_letohs(tvb, offset);\n offset += 2;\n crc_OK = calc_crc == act_crc;\n if (!crc_OK)\n {\n /* Don't trust the rest of the data, get out of here */\n break;\n }\n data_len -= chk_size;\n i++;\n tl_offset = 0; /* copy all the data in the rest of the chunks */\n }\n proto_item_set_len(data_ti, offset - data_start);\n\n /* if crc OK, set up new tvb */\n if (crc_OK)\n {\n tvbuff_t *al_tvb;\n gboolean save_fragmented;\n\n al_tvb = tvb_new_child_real_data(tvb, al_buffer, (guint) (al_buffer_ptr-al_buffer), (gint) (al_buffer_ptr-al_buffer));\n\n /* Check for fragmented packet */\n save_fragmented = pinfo->fragmented;\n\n /* Reassemble AL fragments */\n static guint al_max_fragments = 60;\n static guint al_fragment_aging = 64; /* sequence numbers only 6 bit */\n fragment_head *frag_al = NULL;\n pinfo->fragmented = TRUE;\n if (!pinfo->fd->visited)\n {\n frag_al = fragment_add_seq_single_aging(&al_reassembly_table,\n al_tvb, 0, pinfo, tr_seq, NULL,\n tvb_reported_length(al_tvb), /* As this is a constructed tvb, all of it is ok */\n tr_fir, tr_fin,\n al_max_fragments, al_fragment_aging);\n }\n else\n {\n frag_al = fragment_get_reassembled_id(&al_reassembly_table, pinfo, tr_seq);\n }\n next_tvb = process_reassembled_data(al_tvb, 0, pinfo,\n \"Reassembled DNP 3.0 Application Layer message\", frag_al, &dnp3_frag_items,\n NULL, dnp3_tree);\n\n if (frag_al)\n {\n if (pinfo->num == frag_al->reassembled_in && pinfo->curr_layer_num == frag_al->reas_in_layer_num)\n {\n /* As a complete AL message will have cleared the info column,\n make sure source and dest are always in the info column */\n //col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n //col_set_fence(pinfo->cinfo, COL_INFO);\n dissect_dnp3_al(next_tvb, pinfo, dnp3_tree);\n }\n else\n {\n /* Lock any column info set by the DL and TL */\n col_set_fence(pinfo->cinfo, COL_INFO);\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer fragment %u, reassembled in packet %u)\",\n tr_seq, frag_al->reassembled_in);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n }\n else\n {\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer Unreassembled fragment %u)\",\n tr_seq);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n\n pinfo->fragmented = save_fragmented;\n }\n else\n {\n /* CRC error - throw away the data. */\n next_tvb = NULL;\n }\n }\n\n /* Set the length of the message */\n proto_item_set_len(ti, offset);\n return offset;\n}", "func_hash": 222226241109696044308617047039431880797, "file_name": "packet-dnp.c", "file_hash": 153102365492846544332269488686877903594, "cwe": ["CWE-835"], "cve": "CVE-2021-22235", "cve_desc": "Crash in DNP dissector in Wireshark 3.4.0 to 3.4.6 and 3.2.0 to 3.2.14 allows denial of service via packet injection or crafted capture file", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22235"} {"idx": 335510, "project": "wireshark", "commit_id": "618661b22e34a59b21117db723d8ff91e064d4ba", "project_url": "https://github.com/wireshark/wireshark", "commit_url": "https://gitlab.com/wireshark/wireshark/-/commit/618661b22e34a59b21117db723d8ff91e064d4ba", "commit_message": "dnp: plug a memory leak.\n\nIf we're throwing away the data, *throw away the data* - free it, as\nwe're not using it as the backing data for a tvbuff.", "target": 0, "func": "dissect_dnp3_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n proto_item *ti, *tdl, *tc, *hidden_item;\n proto_tree *dnp3_tree, *dl_tree, *field_tree;\n int offset = 0, temp_offset = 0;\n gboolean dl_prm;\n guint8 dl_len, dl_ctl, dl_func;\n const gchar *func_code_str;\n guint16 dl_dst, dl_src, calc_dl_crc;\n\n /* Make entries in Protocol column and Info column on summary display */\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"DNP 3.0\");\n col_clear(pinfo->cinfo, COL_INFO);\n\n /* Skip \"0x0564\" header bytes */\n temp_offset += 2;\n\n dl_len = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_ctl = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_dst = tvb_get_letohs(tvb, temp_offset);\n temp_offset += 2;\n\n dl_src = tvb_get_letohs(tvb, temp_offset);\n\n dl_func = dl_ctl & DNP3_CTL_FUNC;\n dl_prm = dl_ctl & DNP3_CTL_PRM;\n func_code_str = val_to_str(dl_func, dl_prm ? dnp3_ctl_func_pri_vals : dnp3_ctl_func_sec_vals,\n \"Unknown function (0x%02x)\");\n\n /* Make sure source and dest are always in the info column */\n col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, \"len=%u, %s\", dl_len, func_code_str);\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dnp3, tvb, offset, -1, ENC_NA);\n dnp3_tree = proto_item_add_subtree(ti, ett_dnp3);\n\n /* Create Subtree for Data Link Layer */\n dl_tree = proto_tree_add_subtree_format(dnp3_tree, tvb, offset, DNP_HDR_LEN, ett_dnp3_dl, &tdl,\n \"Data Link Layer, Len: %u, From: %u, To: %u, \", dl_len, dl_src, dl_dst);\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tdl, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tdl, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tdl, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tdl, \"DFC, \");\n }\n proto_item_append_text(tdl, \"%s\", func_code_str);\n\n /* start bytes */\n proto_tree_add_item(dl_tree, hf_dnp3_start, tvb, offset, 2, ENC_BIG_ENDIAN);\n offset += 2;\n\n /* add length field */\n proto_tree_add_item(dl_tree, hf_dnp3_len, tvb, offset, 1, ENC_BIG_ENDIAN);\n offset += 1;\n\n /* Add Control Byte Subtree */\n tc = proto_tree_add_uint_format_value(dl_tree, hf_dnp3_ctl, tvb, offset, 1, dl_ctl,\n \"0x%02x (\", dl_ctl);\n /* Add Text to Control Byte Subtree Header */\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tc, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tc, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tc, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tc, \"DFC, \");\n }\n proto_item_append_text(tc, \"%s)\", func_code_str );\n field_tree = proto_item_add_subtree(tc, ett_dnp3_dl_ctl);\n\n /* Add Control Byte Subtree Items */\n if (dl_prm) {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcb, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcv, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prifunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n else {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dfc, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_secfunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n offset += 1;\n\n /* add destination and source addresses */\n proto_tree_add_item(dl_tree, hf_dnp3_dst, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n proto_tree_add_item(dl_tree, hf_dnp3_src, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n\n /* and header CRC */\n calc_dl_crc = calculateCRCtvb(tvb, 0, DNP_HDR_LEN - 2);\n proto_tree_add_checksum(dl_tree, tvb, offset, hf_dnp3_data_hdr_crc,\n hf_dnp3_data_hdr_crc_status, &ei_dnp3_data_hdr_crc_incorrect,\n pinfo, calc_dl_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n offset += 2;\n\n /* If the DataLink function is 'Request Link Status' or 'Status of Link',\n or 'Reset Link' we don't expect any Transport or Application Layer Data\n NOTE: This code should probably check what DOES have TR or AL data */\n if ((dl_func != DL_FUNC_LINK_STAT) && (dl_func != DL_FUNC_STAT_LINK) &&\n (dl_func != DL_FUNC_RESET_LINK) && (dl_func != DL_FUNC_ACK))\n {\n proto_tree *data_tree;\n proto_item *data_ti;\n guint8 tr_ctl, tr_seq;\n gboolean tr_fir, tr_fin;\n guint8 *al_buffer, *al_buffer_ptr;\n guint8 data_len;\n int data_start = offset;\n int tl_offset;\n gboolean crc_OK = FALSE;\n tvbuff_t *next_tvb;\n guint i;\n static int * const transport_flags[] = {\n &hf_dnp3_tr_fin,\n &hf_dnp3_tr_fir,\n &hf_dnp3_tr_seq,\n NULL\n };\n\n /* get the transport layer byte */\n tr_ctl = tvb_get_guint8(tvb, offset);\n tr_seq = tr_ctl & DNP3_TR_SEQ;\n tr_fir = tr_ctl & DNP3_TR_FIR;\n tr_fin = tr_ctl & DNP3_TR_FIN;\n\n /* Add Transport Layer Tree */\n tc = proto_tree_add_bitmask(dnp3_tree, tvb, offset, hf_dnp3_tr_ctl, ett_dnp3_tr_ctl, transport_flags, ENC_BIG_ENDIAN);\n proto_item_append_text(tc, \"(\");\n if (tr_fir) proto_item_append_text(tc, \"FIR, \");\n if (tr_fin) proto_item_append_text(tc, \"FIN, \");\n proto_item_append_text(tc, \"Sequence %u)\", tr_seq);\n\n /* Add data chunk tree */\n data_tree = proto_tree_add_subtree(dnp3_tree, tvb, offset, -1, ett_dnp3_dl_data, &data_ti, \"Data Chunks\");\n\n /* extract the application layer data, validating the CRCs */\n\n /* XXX - check for dl_len <= 5 */\n data_len = dl_len - 5;\n al_buffer = (guint8 *)wmem_alloc(pinfo->pool, data_len);\n al_buffer_ptr = al_buffer;\n i = 0;\n tl_offset = 1; /* skip the initial transport layer byte when assembling chunks for the application layer tvb */\n while (data_len > 0)\n {\n guint8 chk_size;\n const guint8 *chk_ptr;\n proto_tree *chk_tree;\n proto_item *chk_len_ti;\n guint16 calc_crc, act_crc;\n\n chk_size = MIN(data_len, AL_MAX_CHUNK_SIZE);\n chk_ptr = tvb_get_ptr(tvb, offset, chk_size);\n memcpy(al_buffer_ptr, chk_ptr + tl_offset, chk_size - tl_offset);\n al_buffer_ptr += chk_size - tl_offset;\n\n chk_tree = proto_tree_add_subtree_format(data_tree, tvb, offset, chk_size + 2, ett_dnp3_dl_chunk, NULL, \"Data Chunk: %u\", i);\n proto_tree_add_item(chk_tree, hf_dnp3_data_chunk, tvb, offset, chk_size, ENC_NA);\n chk_len_ti = proto_tree_add_uint(chk_tree, hf_dnp3_data_chunk_len, tvb, offset, 0, chk_size);\n proto_item_set_generated(chk_len_ti);\n\n offset += chk_size;\n\n calc_crc = calculateCRC(chk_ptr, chk_size);\n proto_tree_add_checksum(chk_tree, tvb, offset, hf_dnp3_data_chunk_crc,\n hf_dnp3_data_chunk_crc_status, &ei_dnp3_data_chunk_crc_incorrect,\n pinfo, calc_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n act_crc = tvb_get_letohs(tvb, offset);\n offset += 2;\n crc_OK = calc_crc == act_crc;\n if (!crc_OK)\n {\n /* Don't trust the rest of the data, get out of here */\n break;\n }\n data_len -= chk_size;\n i++;\n tl_offset = 0; /* copy all the data in the rest of the chunks */\n }\n proto_item_set_len(data_ti, offset - data_start);\n\n /* if crc OK, set up new tvb */\n if (crc_OK)\n {\n tvbuff_t *al_tvb;\n gboolean save_fragmented;\n\n al_tvb = tvb_new_child_real_data(tvb, al_buffer, (guint) (al_buffer_ptr-al_buffer), (gint) (al_buffer_ptr-al_buffer));\n\n /* Check for fragmented packet */\n save_fragmented = pinfo->fragmented;\n\n /* Reassemble AL fragments */\n static guint al_max_fragments = 60;\n static guint al_fragment_aging = 64; /* sequence numbers only 6 bit */\n fragment_head *frag_al = NULL;\n pinfo->fragmented = TRUE;\n if (!pinfo->fd->visited)\n {\n frag_al = fragment_add_seq_single_aging(&al_reassembly_table,\n al_tvb, 0, pinfo, tr_seq, NULL,\n tvb_reported_length(al_tvb), /* As this is a constructed tvb, all of it is ok */\n tr_fir, tr_fin,\n al_max_fragments, al_fragment_aging);\n }\n else\n {\n frag_al = fragment_get_reassembled_id(&al_reassembly_table, pinfo, tr_seq);\n }\n next_tvb = process_reassembled_data(al_tvb, 0, pinfo,\n \"Reassembled DNP 3.0 Application Layer message\", frag_al, &dnp3_frag_items,\n NULL, dnp3_tree);\n\n if (frag_al)\n {\n if (pinfo->num == frag_al->reassembled_in && pinfo->curr_layer_num == frag_al->reas_in_layer_num)\n {\n /* As a complete AL message will have cleared the info column,\n make sure source and dest are always in the info column */\n //col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n //col_set_fence(pinfo->cinfo, COL_INFO);\n dissect_dnp3_al(next_tvb, pinfo, dnp3_tree);\n }\n else\n {\n /* Lock any column info set by the DL and TL */\n col_set_fence(pinfo->cinfo, COL_INFO);\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer fragment %u, reassembled in packet %u)\",\n tr_seq, frag_al->reassembled_in);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n }\n else\n {\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer Unreassembled fragment %u)\",\n tr_seq);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n\n pinfo->fragmented = save_fragmented;\n }\n else\n {\n /* CRC error - throw away the data. */\n g_free(al_buffer);\n next_tvb = NULL;\n }\n }\n\n /* Set the length of the message */\n proto_item_set_len(ti, offset);\n return offset;\n}", "func_hash": 280764657448669889876265028315945797098, "file_name": "packet-dnp.c", "file_hash": 236821705284523135136483509040357906459, "cwe": ["CWE-835"], "cve": "CVE-2021-22235", "cve_desc": "Crash in DNP dissector in Wireshark 3.4.0 to 3.4.6 and 3.2.0 to 3.2.14 allows denial of service via packet injection or crafted capture file", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22235"} {"idx": 202665, "project": "linux", "commit_id": "52c479697c9b73f628140dcdfcd39ea302d05482", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=52c479697c9b73f628140dcdfcd39ea302d05482", "commit_message": "do_epoll_ctl(): clean the failure exits up a bit\n\nSigned-off-by: Al Viro ", "target": 1, "func": "int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,\n\t\t bool nonblock)\n{\n\tint error;\n\tint full_check = 0;\n\tstruct fd f, tf;\n\tstruct eventpoll *ep;\n\tstruct epitem *epi;\n\tstruct eventpoll *tep = NULL;\n\n\terror = -EBADF;\n\tf = fdget(epfd);\n\tif (!f.file)\n\t\tgoto error_return;\n\n\t/* Get the \"struct file *\" for the target file */\n\ttf = fdget(fd);\n\tif (!tf.file)\n\t\tgoto error_fput;\n\n\t/* The target file descriptor must support poll */\n\terror = -EPERM;\n\tif (!file_can_poll(tf.file))\n\t\tgoto error_tgt_fput;\n\n\t/* Check if EPOLLWAKEUP is allowed */\n\tif (ep_op_has_event(op))\n\t\tep_take_care_of_epollwakeup(epds);\n\n\t/*\n\t * We have to check that the file structure underneath the file descriptor\n\t * the user passed to us _is_ an eventpoll file. And also we do not permit\n\t * adding an epoll file descriptor inside itself.\n\t */\n\terror = -EINVAL;\n\tif (f.file == tf.file || !is_file_epoll(f.file))\n\t\tgoto error_tgt_fput;\n\n\t/*\n\t * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,\n\t * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.\n\t * Also, we do not currently supported nested exclusive wakeups.\n\t */\n\tif (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) {\n\t\tif (op == EPOLL_CTL_MOD)\n\t\t\tgoto error_tgt_fput;\n\t\tif (op == EPOLL_CTL_ADD && (is_file_epoll(tf.file) ||\n\t\t\t\t(epds->events & ~EPOLLEXCLUSIVE_OK_BITS)))\n\t\t\tgoto error_tgt_fput;\n\t}\n\n\t/*\n\t * At this point it is safe to assume that the \"private_data\" contains\n\t * our own data structure.\n\t */\n\tep = f.file->private_data;\n\n\t/*\n\t * When we insert an epoll file descriptor, inside another epoll file\n\t * descriptor, there is the change of creating closed loops, which are\n\t * better be handled here, than in more critical paths. While we are\n\t * checking for loops we also determine the list of files reachable\n\t * and hang them on the tfile_check_list, so we can check that we\n\t * haven't created too many possible wakeup paths.\n\t *\n\t * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when\n\t * the epoll file descriptor is attaching directly to a wakeup source,\n\t * unless the epoll file descriptor is nested. The purpose of taking the\n\t * 'epmutex' on add is to prevent complex toplogies such as loops and\n\t * deep wakeup paths from forming in parallel through multiple\n\t * EPOLL_CTL_ADD operations.\n\t */\n\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\tif (error)\n\t\tgoto error_tgt_fput;\n\tif (op == EPOLL_CTL_ADD) {\n\t\tif (!list_empty(&f.file->f_ep_links) ||\n\t\t\t\t\t\tis_file_epoll(tf.file)) {\n\t\t\tmutex_unlock(&ep->mtx);\n\t\t\terror = epoll_mutex_lock(&epmutex, 0, nonblock);\n\t\t\tif (error)\n\t\t\t\tgoto error_tgt_fput;\n\t\t\tfull_check = 1;\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\terror = -ELOOP;\n\t\t\t\tif (ep_loop_check(ep, tf.file) != 0) {\n\t\t\t\t\tclear_tfile_check_list();\n\t\t\t\t\tgoto error_tgt_fput;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tget_file(tf.file);\n\t\t\t\tlist_add(&tf.file->f_tfile_llink,\n\t\t\t\t\t\t\t&tfile_check_list);\n\t\t\t}\n\t\t\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\t\t\tif (error) {\nout_del:\n\t\t\t\tlist_del(&tf.file->f_tfile_llink);\n\t\t\t\tif (!is_file_epoll(tf.file))\n\t\t\t\t\tfput(tf.file);\n\t\t\t\tgoto error_tgt_fput;\n\t\t\t}\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\ttep = tf.file->private_data;\n\t\t\t\terror = epoll_mutex_lock(&tep->mtx, 1, nonblock);\n\t\t\t\tif (error) {\n\t\t\t\t\tmutex_unlock(&ep->mtx);\n\t\t\t\t\tgoto out_del;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Try to lookup the file inside our RB tree, Since we grabbed \"mtx\"\n\t * above, we can be sure to be able to use the item looked up by\n\t * ep_find() till we release the mutex.\n\t */\n\tepi = ep_find(ep, tf.file, fd);\n\n\terror = -EINVAL;\n\tswitch (op) {\n\tcase EPOLL_CTL_ADD:\n\t\tif (!epi) {\n\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\terror = ep_insert(ep, epds, tf.file, fd, full_check);\n\t\t} else\n\t\t\terror = -EEXIST;\n\t\tif (full_check)\n\t\t\tclear_tfile_check_list();\n\t\tbreak;\n\tcase EPOLL_CTL_DEL:\n\t\tif (epi)\n\t\t\terror = ep_remove(ep, epi);\n\t\telse\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\tcase EPOLL_CTL_MOD:\n\t\tif (epi) {\n\t\t\tif (!(epi->event.events & EPOLLEXCLUSIVE)) {\n\t\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\t\terror = ep_modify(ep, epi, epds);\n\t\t\t}\n\t\t} else\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\t}\n\tif (tep != NULL)\n\t\tmutex_unlock(&tep->mtx);\n\tmutex_unlock(&ep->mtx);\n\nerror_tgt_fput:\n\tif (full_check)\n\t\tmutex_unlock(&epmutex);\n\n\tfdput(tf);\nerror_fput:\n\tfdput(f);\nerror_return:\n\n\treturn error;\n}", "func_hash": 262544806716092063434657830535515753358, "file_name": "eventpoll.c", "file_hash": 23733303808216168189329022110449235571, "cwe": ["CWE-416"], "cve": "CVE-2020-0466", "cve_desc": "In do_epoll_ctl and ep_loop_check_proc of eventpoll.c, there is a possible use after free due to a logic error. This could lead to local escalation of privilege with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android kernelAndroid ID: A-147802478References: Upstream kernel", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0466"} {"idx": 336269, "project": "linux", "commit_id": "52c479697c9b73f628140dcdfcd39ea302d05482", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=52c479697c9b73f628140dcdfcd39ea302d05482", "commit_message": "do_epoll_ctl(): clean the failure exits up a bit\n\nSigned-off-by: Al Viro ", "target": 0, "func": "int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,\n\t\t bool nonblock)\n{\n\tint error;\n\tint full_check = 0;\n\tstruct fd f, tf;\n\tstruct eventpoll *ep;\n\tstruct epitem *epi;\n\tstruct eventpoll *tep = NULL;\n\n\terror = -EBADF;\n\tf = fdget(epfd);\n\tif (!f.file)\n\t\tgoto error_return;\n\n\t/* Get the \"struct file *\" for the target file */\n\ttf = fdget(fd);\n\tif (!tf.file)\n\t\tgoto error_fput;\n\n\t/* The target file descriptor must support poll */\n\terror = -EPERM;\n\tif (!file_can_poll(tf.file))\n\t\tgoto error_tgt_fput;\n\n\t/* Check if EPOLLWAKEUP is allowed */\n\tif (ep_op_has_event(op))\n\t\tep_take_care_of_epollwakeup(epds);\n\n\t/*\n\t * We have to check that the file structure underneath the file descriptor\n\t * the user passed to us _is_ an eventpoll file. And also we do not permit\n\t * adding an epoll file descriptor inside itself.\n\t */\n\terror = -EINVAL;\n\tif (f.file == tf.file || !is_file_epoll(f.file))\n\t\tgoto error_tgt_fput;\n\n\t/*\n\t * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,\n\t * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.\n\t * Also, we do not currently supported nested exclusive wakeups.\n\t */\n\tif (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) {\n\t\tif (op == EPOLL_CTL_MOD)\n\t\t\tgoto error_tgt_fput;\n\t\tif (op == EPOLL_CTL_ADD && (is_file_epoll(tf.file) ||\n\t\t\t\t(epds->events & ~EPOLLEXCLUSIVE_OK_BITS)))\n\t\t\tgoto error_tgt_fput;\n\t}\n\n\t/*\n\t * At this point it is safe to assume that the \"private_data\" contains\n\t * our own data structure.\n\t */\n\tep = f.file->private_data;\n\n\t/*\n\t * When we insert an epoll file descriptor, inside another epoll file\n\t * descriptor, there is the change of creating closed loops, which are\n\t * better be handled here, than in more critical paths. While we are\n\t * checking for loops we also determine the list of files reachable\n\t * and hang them on the tfile_check_list, so we can check that we\n\t * haven't created too many possible wakeup paths.\n\t *\n\t * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when\n\t * the epoll file descriptor is attaching directly to a wakeup source,\n\t * unless the epoll file descriptor is nested. The purpose of taking the\n\t * 'epmutex' on add is to prevent complex toplogies such as loops and\n\t * deep wakeup paths from forming in parallel through multiple\n\t * EPOLL_CTL_ADD operations.\n\t */\n\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\tif (error)\n\t\tgoto error_tgt_fput;\n\tif (op == EPOLL_CTL_ADD) {\n\t\tif (!list_empty(&f.file->f_ep_links) ||\n\t\t\t\t\t\tis_file_epoll(tf.file)) {\n\t\t\tmutex_unlock(&ep->mtx);\n\t\t\terror = epoll_mutex_lock(&epmutex, 0, nonblock);\n\t\t\tif (error)\n\t\t\t\tgoto error_tgt_fput;\n\t\t\tfull_check = 1;\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\terror = -ELOOP;\n\t\t\t\tif (ep_loop_check(ep, tf.file) != 0)\n\t\t\t\t\tgoto error_tgt_fput;\n\t\t\t} else {\n\t\t\t\tget_file(tf.file);\n\t\t\t\tlist_add(&tf.file->f_tfile_llink,\n\t\t\t\t\t\t\t&tfile_check_list);\n\t\t\t}\n\t\t\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\t\t\tif (error)\n\t\t\t\tgoto error_tgt_fput;\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\ttep = tf.file->private_data;\n\t\t\t\terror = epoll_mutex_lock(&tep->mtx, 1, nonblock);\n\t\t\t\tif (error) {\n\t\t\t\t\tmutex_unlock(&ep->mtx);\n\t\t\t\t\tgoto error_tgt_fput;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Try to lookup the file inside our RB tree, Since we grabbed \"mtx\"\n\t * above, we can be sure to be able to use the item looked up by\n\t * ep_find() till we release the mutex.\n\t */\n\tepi = ep_find(ep, tf.file, fd);\n\n\terror = -EINVAL;\n\tswitch (op) {\n\tcase EPOLL_CTL_ADD:\n\t\tif (!epi) {\n\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\terror = ep_insert(ep, epds, tf.file, fd, full_check);\n\t\t} else\n\t\t\terror = -EEXIST;\n\t\tbreak;\n\tcase EPOLL_CTL_DEL:\n\t\tif (epi)\n\t\t\terror = ep_remove(ep, epi);\n\t\telse\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\tcase EPOLL_CTL_MOD:\n\t\tif (epi) {\n\t\t\tif (!(epi->event.events & EPOLLEXCLUSIVE)) {\n\t\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\t\terror = ep_modify(ep, epi, epds);\n\t\t\t}\n\t\t} else\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\t}\n\tif (tep != NULL)\n\t\tmutex_unlock(&tep->mtx);\n\tmutex_unlock(&ep->mtx);\n\nerror_tgt_fput:\n\tif (full_check) {\n\t\tclear_tfile_check_list();\n\t\tmutex_unlock(&epmutex);\n\t}\n\n\tfdput(tf);\nerror_fput:\n\tfdput(f);\nerror_return:\n\n\treturn error;\n}", "func_hash": 204587501599965192886151219706057039285, "file_name": "eventpoll.c", "file_hash": 116824817354272945663148562078242733653, "cwe": ["CWE-416"], "cve": "CVE-2020-0466", "cve_desc": "In do_epoll_ctl and ep_loop_check_proc of eventpoll.c, there is a possible use after free due to a logic error. This could lead to local escalation of privilege with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android kernelAndroid ID: A-147802478References: Upstream kernel", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0466"} {"idx": 202689, "project": "ruby", "commit_id": "1c2ef610358af33f9ded3086aa2d70aac03dcac5", "project_url": "https://github.com/ruby/ruby", "commit_url": "https://github.com/ruby/ruby/commit/1c2ef610358af33f9ded3086aa2d70aac03dcac5", "commit_message": "* string.c (rb_str_justify): CVE-2009-4124.\n Fixes a bug reported by \n Emmanouel Kellinis , KPMG London;\n Patch by nobu.\n\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@26038 b2dd03c8-39d4-4d8f-98ff-823fe69b080e", "target": 1, "func": "rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag)\n{\n rb_encoding *enc;\n VALUE w;\n long width, len, flen = 1, fclen = 1;\n VALUE res;\n char *p;\n const char *f = \" \";\n long n, llen, rlen;\n volatile VALUE pad;\n int singlebyte = 1, cr;\n\n rb_scan_args(argc, argv, \"11\", &w, &pad);\n enc = STR_ENC_GET(str);\n width = NUM2LONG(w);\n if (argc == 2) {\n\tStringValue(pad);\n\tenc = rb_enc_check(str, pad);\n\tf = RSTRING_PTR(pad);\n\tflen = RSTRING_LEN(pad);\n\tfclen = str_strlen(pad, enc);\n\tsinglebyte = single_byte_optimizable(pad);\n\tif (flen == 0 || fclen == 0) {\n\t rb_raise(rb_eArgError, \"zero width padding\");\n\t}\n }\n len = str_strlen(str, enc);\n if (width < 0 || len >= width) return rb_str_dup(str);\n n = width - len;\n llen = (jflag == 'l') ? 0 : ((jflag == 'r') ? n : n/2);\n rlen = n - llen;\n cr = ENC_CODERANGE(str);\n res = rb_str_new5(str, 0, RSTRING_LEN(str)+n*flen/fclen+2);\n p = RSTRING_PTR(res);\n while (llen) {\n\tif (flen <= 1) {\n\t *p++ = *f;\n\t llen--;\n\t}\n\telse if (llen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t llen -= fclen;\n\t}\n\telse {\n\t char *fp = str_nth(f, f+flen, llen, enc, singlebyte);\n\t n = fp - f;\n\t memcpy(p,f,n);\n\t p+=n;\n\t break;\n\t}\n }\n memcpy(p, RSTRING_PTR(str), RSTRING_LEN(str));\n p+=RSTRING_LEN(str);\n while (rlen) {\n\tif (flen <= 1) {\n\t *p++ = *f;\n\t rlen--;\n\t}\n\telse if (rlen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t rlen -= fclen;\n\t}\n\telse {\n\t char *fp = str_nth(f, f+flen, rlen, enc, singlebyte);\n\t n = fp - f;\n\t memcpy(p,f,n);\n\t p+=n;\n\t break;\n\t}\n }\n *p = '\\0';\n STR_SET_LEN(res, p-RSTRING_PTR(res));\n OBJ_INFECT(res, str);\n if (!NIL_P(pad)) OBJ_INFECT(res, pad);\n rb_enc_associate(res, enc);\n if (argc == 2)\n\tcr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad));\n if (cr != ENC_CODERANGE_BROKEN)\n\tENC_CODERANGE_SET(res, cr);\n return res;\n}", "func_hash": 96535770875198543353927532580683488949, "file_name": "string.c", "file_hash": 83781261524574653534903673209195830268, "cwe": ["CWE-119"], "cve": "CVE-2009-4124", "cve_desc": "Heap-based buffer overflow in the rb_str_justify function in string.c in Ruby 1.9.1 before 1.9.1-p376 allows context-dependent attackers to execute arbitrary code via unspecified vectors involving (1) String#ljust, (2) String#center, or (3) String#rjust. NOTE: some of these details are obtained from third party information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2009-4124"} {"idx": 337027, "project": "ruby", "commit_id": "1c2ef610358af33f9ded3086aa2d70aac03dcac5", "project_url": "https://github.com/ruby/ruby", "commit_url": "https://github.com/ruby/ruby/commit/1c2ef610358af33f9ded3086aa2d70aac03dcac5", "commit_message": "* string.c (rb_str_justify): CVE-2009-4124.\n Fixes a bug reported by \n Emmanouel Kellinis , KPMG London;\n Patch by nobu.\n\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@26038 b2dd03c8-39d4-4d8f-98ff-823fe69b080e", "target": 0, "func": "rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag)\n{\n rb_encoding *enc;\n VALUE w;\n long width, len, flen = 1, fclen = 1;\n VALUE res;\n char *p;\n const char *f = \" \";\n long n, size, llen, rlen, llen2 = 0, rlen2 = 0;\n volatile VALUE pad;\n int singlebyte = 1, cr;\n\n rb_scan_args(argc, argv, \"11\", &w, &pad);\n enc = STR_ENC_GET(str);\n width = NUM2LONG(w);\n if (argc == 2) {\n\tStringValue(pad);\n\tenc = rb_enc_check(str, pad);\n\tf = RSTRING_PTR(pad);\n\tflen = RSTRING_LEN(pad);\n\tfclen = str_strlen(pad, enc);\n\tsinglebyte = single_byte_optimizable(pad);\n\tif (flen == 0 || fclen == 0) {\n\t rb_raise(rb_eArgError, \"zero width padding\");\n\t}\n }\n len = str_strlen(str, enc);\n if (width < 0 || len >= width) return rb_str_dup(str);\n n = width - len;\n llen = (jflag == 'l') ? 0 : ((jflag == 'r') ? n : n/2);\n rlen = n - llen;\n cr = ENC_CODERANGE(str);\n if (flen > 1) {\n llen2 = str_offset(f, f + flen, llen % fclen, enc, singlebyte);\n rlen2 = str_offset(f, f + flen, rlen % fclen, enc, singlebyte);\n }\n size = RSTRING_LEN(str);\n if ((len = llen / fclen + rlen / fclen) >= LONG_MAX / flen ||\n (len *= flen) >= LONG_MAX - llen2 - rlen2 ||\n (len += llen2 + rlen2) >= LONG_MAX - size) {\n rb_raise(rb_eArgError, \"argument too big\");\n }\n len += size;\n res = rb_str_new5(str, 0, len);\n p = RSTRING_PTR(res);\n if (flen <= 1) {\n memset(p, *f, llen);\n p += llen;\n }\n else {\n while (llen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t llen -= fclen;\n\t}\n if (llen > 0) {\n memcpy(p, f, llen2);\n p += llen2;\n\t}\n }\n memcpy(p, RSTRING_PTR(str), size);\n p += size;\n if (flen <= 1) {\n memset(p, *f, rlen);\n p += rlen;\n }\n else {\n while (rlen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t rlen -= fclen;\n\t}\n if (rlen > 0) {\n memcpy(p, f, rlen2);\n p += rlen2;\n\t}\n }\n *p = '\\0';\n STR_SET_LEN(res, p-RSTRING_PTR(res));\n OBJ_INFECT(res, str);\n if (!NIL_P(pad)) OBJ_INFECT(res, pad);\n rb_enc_associate(res, enc);\n if (argc == 2)\n\tcr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad));\n if (cr != ENC_CODERANGE_BROKEN)\n\tENC_CODERANGE_SET(res, cr);\n return res;\n}", "func_hash": 150678874008212840218011097873195264393, "file_name": "string.c", "file_hash": 67890317483163917769043655586705006581, "cwe": ["CWE-119"], "cve": "CVE-2009-4124", "cve_desc": "Heap-based buffer overflow in the rb_str_justify function in string.c in Ruby 1.9.1 before 1.9.1-p376 allows context-dependent attackers to execute arbitrary code via unspecified vectors involving (1) String#ljust, (2) String#center, or (3) String#rjust. NOTE: some of these details are obtained from third party information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2009-4124"} {"idx": 202733, "project": "mutt", "commit_id": "9347b5c01dc52682cb6be11539d9b7ebceae4416", "project_url": "https://github.com/muttmua/mutt", "commit_url": "https://gitlab.com/muttmua/mutt/commit/9347b5c01dc52682cb6be11539d9b7ebceae4416", "commit_message": "Handle NO response without message properly", "target": 1, "func": "static int cmd_handle_untagged (IMAP_DATA* idata)\n{\n char* s;\n char* pn;\n unsigned int count;\n\n s = imap_next_word (idata->buf);\n pn = imap_next_word (s);\n\n if ((idata->state >= IMAP_SELECTED) && isdigit ((unsigned char) *s))\n {\n pn = s;\n s = imap_next_word (s);\n\n /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the\n * connection, so update that one.\n */\n if (ascii_strncasecmp (\"EXISTS\", s, 6) == 0)\n {\n dprint (2, (debugfile, \"Handling EXISTS\\n\"));\n\n /* new mail arrived */\n mutt_atoui (pn, &count);\n\n if ( !(idata->reopen & IMAP_EXPUNGE_PENDING) &&\n\t count < idata->max_msn)\n {\n /* Notes 6.0.3 has a tendency to report fewer messages exist than\n * it should. */\n\tdprint (1, (debugfile, \"Message count is out of sync\"));\n\treturn 0;\n }\n /* at least the InterChange server sends EXISTS messages freely,\n * even when there is no new mail */\n else if (count == idata->max_msn)\n\tdprint (3, (debugfile,\n \"cmd_handle_untagged: superfluous EXISTS message.\\n\"));\n else\n {\n\tif (!(idata->reopen & IMAP_EXPUNGE_PENDING))\n {\n dprint (2, (debugfile,\n \"cmd_handle_untagged: New mail in %s - %d messages total.\\n\",\n idata->mailbox, count));\n\t idata->reopen |= IMAP_NEWMAIL_PENDING;\n }\n\tidata->newMailCount = count;\n }\n }\n /* pn vs. s: need initial seqno */\n else if (ascii_strncasecmp (\"EXPUNGE\", s, 7) == 0)\n cmd_parse_expunge (idata, pn);\n else if (ascii_strncasecmp (\"FETCH\", s, 5) == 0)\n cmd_parse_fetch (idata, pn);\n }\n else if (ascii_strncasecmp (\"CAPABILITY\", s, 10) == 0)\n cmd_parse_capability (idata, s);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", s, 14))\n cmd_parse_capability (idata, pn);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", pn, 14))\n cmd_parse_capability (idata, imap_next_word (pn));\n else if (ascii_strncasecmp (\"LIST\", s, 4) == 0)\n cmd_parse_list (idata, s);\n else if (ascii_strncasecmp (\"LSUB\", s, 4) == 0)\n cmd_parse_lsub (idata, s);\n else if (ascii_strncasecmp (\"MYRIGHTS\", s, 8) == 0)\n cmd_parse_myrights (idata, s);\n else if (ascii_strncasecmp (\"SEARCH\", s, 6) == 0)\n cmd_parse_search (idata, s);\n else if (ascii_strncasecmp (\"STATUS\", s, 6) == 0)\n cmd_parse_status (idata, s);\n else if (ascii_strncasecmp (\"ENABLED\", s, 7) == 0)\n cmd_parse_enabled (idata, s);\n else if (ascii_strncasecmp (\"BYE\", s, 3) == 0)\n {\n dprint (2, (debugfile, \"Handling BYE\\n\"));\n\n /* check if we're logging out */\n if (idata->status == IMAP_BYE)\n return 0;\n\n /* server shut down our connection */\n s += 3;\n SKIPWS (s);\n mutt_error (\"%s\", s);\n mutt_sleep (2);\n cmd_handle_fatal (idata);\n\n return -1;\n }\n else if (option (OPTIMAPSERVERNOISE) && (ascii_strncasecmp (\"NO\", s, 2) == 0))\n {\n dprint (2, (debugfile, \"Handling untagged NO\\n\"));\n\n /* Display the warning message from the server */\n mutt_error (\"%s\", s+3);\n mutt_sleep (2);\n }\n\n return 0;\n}", "func_hash": 231364707770859653033899083886202835248, "file_name": "command.c", "file_hash": 105167514454387493156849327959718351487, "cwe": ["CWE-20"], "cve": "CVE-2018-14349", "cve_desc": "An issue was discovered in Mutt before 1.10.1 and NeoMutt before 2018-07-16. imap/command.c mishandles a NO response without a message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14349"} {"idx": 338014, "project": "mutt", "commit_id": "9347b5c01dc52682cb6be11539d9b7ebceae4416", "project_url": "https://github.com/muttmua/mutt", "commit_url": "https://gitlab.com/muttmua/mutt/commit/9347b5c01dc52682cb6be11539d9b7ebceae4416", "commit_message": "Handle NO response without message properly", "target": 0, "func": "static int cmd_handle_untagged (IMAP_DATA* idata)\n{\n char* s;\n char* pn;\n unsigned int count;\n\n s = imap_next_word (idata->buf);\n pn = imap_next_word (s);\n\n if ((idata->state >= IMAP_SELECTED) && isdigit ((unsigned char) *s))\n {\n pn = s;\n s = imap_next_word (s);\n\n /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the\n * connection, so update that one.\n */\n if (ascii_strncasecmp (\"EXISTS\", s, 6) == 0)\n {\n dprint (2, (debugfile, \"Handling EXISTS\\n\"));\n\n /* new mail arrived */\n mutt_atoui (pn, &count);\n\n if ( !(idata->reopen & IMAP_EXPUNGE_PENDING) &&\n\t count < idata->max_msn)\n {\n /* Notes 6.0.3 has a tendency to report fewer messages exist than\n * it should. */\n\tdprint (1, (debugfile, \"Message count is out of sync\"));\n\treturn 0;\n }\n /* at least the InterChange server sends EXISTS messages freely,\n * even when there is no new mail */\n else if (count == idata->max_msn)\n\tdprint (3, (debugfile,\n \"cmd_handle_untagged: superfluous EXISTS message.\\n\"));\n else\n {\n\tif (!(idata->reopen & IMAP_EXPUNGE_PENDING))\n {\n dprint (2, (debugfile,\n \"cmd_handle_untagged: New mail in %s - %d messages total.\\n\",\n idata->mailbox, count));\n\t idata->reopen |= IMAP_NEWMAIL_PENDING;\n }\n\tidata->newMailCount = count;\n }\n }\n /* pn vs. s: need initial seqno */\n else if (ascii_strncasecmp (\"EXPUNGE\", s, 7) == 0)\n cmd_parse_expunge (idata, pn);\n else if (ascii_strncasecmp (\"FETCH\", s, 5) == 0)\n cmd_parse_fetch (idata, pn);\n }\n else if (ascii_strncasecmp (\"CAPABILITY\", s, 10) == 0)\n cmd_parse_capability (idata, s);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", s, 14))\n cmd_parse_capability (idata, pn);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", pn, 14))\n cmd_parse_capability (idata, imap_next_word (pn));\n else if (ascii_strncasecmp (\"LIST\", s, 4) == 0)\n cmd_parse_list (idata, s);\n else if (ascii_strncasecmp (\"LSUB\", s, 4) == 0)\n cmd_parse_lsub (idata, s);\n else if (ascii_strncasecmp (\"MYRIGHTS\", s, 8) == 0)\n cmd_parse_myrights (idata, s);\n else if (ascii_strncasecmp (\"SEARCH\", s, 6) == 0)\n cmd_parse_search (idata, s);\n else if (ascii_strncasecmp (\"STATUS\", s, 6) == 0)\n cmd_parse_status (idata, s);\n else if (ascii_strncasecmp (\"ENABLED\", s, 7) == 0)\n cmd_parse_enabled (idata, s);\n else if (ascii_strncasecmp (\"BYE\", s, 3) == 0)\n {\n dprint (2, (debugfile, \"Handling BYE\\n\"));\n\n /* check if we're logging out */\n if (idata->status == IMAP_BYE)\n return 0;\n\n /* server shut down our connection */\n s += 3;\n SKIPWS (s);\n mutt_error (\"%s\", s);\n mutt_sleep (2);\n cmd_handle_fatal (idata);\n\n return -1;\n }\n else if (option (OPTIMAPSERVERNOISE) && (ascii_strncasecmp (\"NO\", s, 2) == 0))\n {\n dprint (2, (debugfile, \"Handling untagged NO\\n\"));\n\n /* Display the warning message from the server */\n mutt_error (\"%s\", s+2);\n mutt_sleep (2);\n }\n\n return 0;\n}", "func_hash": 237756261686663930223683075145539895870, "file_name": "command.c", "file_hash": 274263564788760634547511533833777629466, "cwe": ["CWE-20"], "cve": "CVE-2018-14349", "cve_desc": "An issue was discovered in Mutt before 1.10.1 and NeoMutt before 2018-07-16. imap/command.c mishandles a NO response without a message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14349"} {"idx": 202739, "project": "ImageMagick", "commit_id": "ef59bd764f88d893f1219fee8ba696a5d3f8c1c4", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/ef59bd764f88d893f1219fee8ba696a5d3f8c1c4", "commit_message": "There is a Division by Zero in function OptimizeLayerFrames (#2743)\n\nin file MagickCore/layer.c. cur->ticks_per_seconds can be zero\nwith a crafted input argument *image. This is similar to\nCVE-2019-13454.", "target": 1, "func": "static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method,\n ExceptionInfo *exception)\n{\n ExceptionInfo\n *sans_exception;\n\n Image\n *prev_image,\n *dup_image,\n *bgnd_image,\n *optimized_image;\n\n RectangleInfo\n try_bounds,\n bgnd_bounds,\n dup_bounds,\n *bounds;\n\n MagickBooleanType\n add_frames,\n try_cleared,\n cleared;\n\n DisposeType\n *disposals;\n\n register const Image\n *curr;\n\n register ssize_t\n i;\n\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n assert(method == OptimizeLayer ||\n method == OptimizeImageLayer ||\n method == OptimizePlusLayer);\n /*\n Are we allowed to add/remove frames from animation?\n */\n add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse;\n /*\n Ensure all the images are the same size.\n */\n curr=GetFirstImageInList(image);\n for (; curr != (Image *) NULL; curr=GetNextImageInList(curr))\n {\n if ((curr->columns != image->columns) || (curr->rows != image->rows))\n ThrowImageException(OptionError,\"ImagesAreNotTheSameSize\");\n\n if ((curr->page.x != 0) || (curr->page.y != 0) ||\n (curr->page.width != image->page.width) ||\n (curr->page.height != image->page.height))\n ThrowImageException(OptionError,\"ImagePagesAreNotCoalesced\");\n }\n /*\n Allocate memory (times 2 if we allow the use of frame duplications)\n */\n curr=GetFirstImageInList(image);\n bounds=(RectangleInfo *) AcquireQuantumMemory((size_t)\n GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*bounds));\n if (bounds == (RectangleInfo *) NULL)\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n disposals=(DisposeType *) AcquireQuantumMemory((size_t)\n GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*disposals));\n if (disposals == (DisposeType *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Initialise Previous Image as fully transparent\n */\n prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */\n prev_image->page.x=0;\n prev_image->page.y=0;\n prev_image->dispose=NoneDispose;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n prev_image->background_color.alpha=(MagickRealType) TransparentAlpha;\n (void) SetImageBackgroundColor(prev_image,exception);\n /*\n Figure out the area of overlay of the first frame\n No pixel could be cleared as all pixels are already cleared.\n */\n#if DEBUG_OPT_FRAME\n i=0;\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n disposals[0]=NoneDispose;\n bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g\\n\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n#endif\n /*\n Compute the bounding box of changes for each pair of images.\n */\n i=1;\n bgnd_image=(Image *) NULL;\n dup_image=(Image *) NULL;\n dup_bounds.width=0;\n dup_bounds.height=0;\n dup_bounds.x=0;\n dup_bounds.y=0;\n curr=GetNextImageInList(curr);\n for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr))\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n /*\n Assume none disposal is the best\n */\n bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception);\n cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception);\n disposals[i-1]=NoneDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g%s%s\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y,\n bounds[i].x < 0?\" (unchanged)\":\"\",\n cleared?\" (pixels cleared)\":\"\");\n#endif\n if ( bounds[i].x < 0 ) {\n /*\n Image frame is exactly the same as the previous frame!\n If not adding frames leave it to be cropped down to a null image.\n Otherwise mark previous image for deleted, transfering its crop bounds\n to the current image.\n */\n if ( add_frames && i>=2 ) {\n disposals[i-1]=DelDispose;\n disposals[i]=NoneDispose;\n bounds[i]=bounds[i-1];\n i++;\n continue;\n }\n }\n else\n {\n /*\n Compare a none disposal against a previous disposal\n */\n try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"test_prev: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels were cleared)\":\"\");\n#endif\n if ( (!try_cleared && cleared ) ||\n try_bounds.width * try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=try_cleared;\n bounds[i]=try_bounds;\n disposals[i-1]=PreviousDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"previous: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"previous: rejected\\n\");\n#endif\n }\n\n /*\n If we are allowed lets try a complex frame duplication.\n It is useless if the previous image already clears pixels correctly.\n This method will always clear all the pixels that need to be cleared.\n */\n dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */\n if ( add_frames )\n {\n dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (dup_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n return((Image *) NULL);\n }\n dup_image->background_color.alpha_trait=BlendPixelTrait;\n dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception);\n ClearBounds(dup_image,&dup_bounds,exception);\n try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception);\n if ( cleared ||\n dup_bounds.width*dup_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i]=try_bounds;\n disposals[i-1]=DupDispose;\n /* to be finalised later, if found to be optimial */\n }\n else\n dup_bounds.width=dup_bounds.height=0;\n }\n /*\n Now compare against a simple background disposal\n */\n bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (bgnd_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n return((Image *) NULL);\n }\n bgnd_image->background_color.alpha_trait=BlendPixelTrait;\n bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"background: %s\\n\",\n try_cleared?\"(pixels cleared)\":\"\");\n#endif\n if ( try_cleared )\n {\n /*\n Straight background disposal failed to clear pixels needed!\n Lets try expanding the disposal area of the previous frame, to\n include the pixels that are cleared. This guaranteed\n to work, though may not be the most optimized solution.\n */\n try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_clear: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_bounds.x<0?\" (no expand nessary)\":\"\");\n#endif\n if ( bgnd_bounds.x < 0 )\n bgnd_bounds = try_bounds;\n else\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_bgnd: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n if ( try_bounds.x < bgnd_bounds.x )\n {\n bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n bgnd_bounds.x = try_bounds.x;\n }\n else\n {\n try_bounds.width += try_bounds.x - bgnd_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n }\n if ( try_bounds.y < bgnd_bounds.y )\n {\n bgnd_bounds.height += bgnd_bounds.y - try_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n bgnd_bounds.y = try_bounds.y;\n }\n else\n {\n try_bounds.height += try_bounds.y - bgnd_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n }\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \" to : %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n }\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n#if DEBUG_OPT_FRAME\n/* Something strange is happening with a specific animation\n * CompareAnyLayers (normal method) and CompareClearLayers returns the whole\n * image, which is not posibly correct! As verified by previous tests.\n * Something changed beyond the bgnd_bounds clearing. But without being able\n * to see, or writet he image at this point it is hard to tell what is wrong!\n * Only CompareOverlay seemed to return something sensible.\n */\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception);\n (void) FormatLocaleFile(stderr, \"expand_ctst: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y );\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_any : %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception);\n#if DEBUG_OPT_FRAME\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_test: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n }\n /*\n Test if this background dispose is smaller than any of the\n other methods we tryed before this (including duplicated frame)\n */\n if ( cleared ||\n bgnd_bounds.width*bgnd_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i-1].width*bounds[i-1].height\n +dup_bounds.width*dup_bounds.height\n +bounds[i].width*bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i-1]=bgnd_bounds;\n bounds[i]=try_bounds;\n if ( disposals[i-1] == DupDispose )\n dup_image=DestroyImage(dup_image);\n disposals[i-1]=BackgroundDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"expand_bgnd: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"expand_bgnd: reject\\n\");\n#endif\n }\n }\n /*\n Finalise choice of dispose, set new prev_image,\n and junk any extra images as appropriate,\n */\n if ( disposals[i-1] == DupDispose )\n {\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n prev_image=DestroyImage(prev_image);\n prev_image=dup_image, dup_image=(Image *) NULL;\n bounds[i+1]=bounds[i];\n bounds[i]=dup_bounds;\n disposals[i-1]=DupDispose;\n disposals[i]=BackgroundDispose;\n i++;\n }\n else\n {\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n if ( disposals[i-1] != PreviousDispose )\n prev_image=DestroyImage(prev_image);\n if ( disposals[i-1] == BackgroundDispose )\n prev_image=bgnd_image, bgnd_image=(Image *) NULL;\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n if ( disposals[i-1] == NoneDispose )\n {\n prev_image=ReferenceImage(curr->previous);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n }\n\n }\n assert(prev_image != (Image *) NULL);\n disposals[i]=disposals[i-1];\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"final %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i-1,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]),\n (double) bounds[i-1].width,(double) bounds[i-1].height,\n (double) bounds[i-1].x,(double) bounds[i-1].y );\n#endif\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"interum %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]),\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n (void) FormatLocaleFile(stderr,\"\\n\");\n#endif\n i++;\n }\n prev_image=DestroyImage(prev_image);\n /*\n Optimize all images in sequence.\n */\n sans_exception=AcquireExceptionInfo();\n i=0;\n curr=GetFirstImageInList(image);\n optimized_image=NewImageList();\n while ( curr != (const Image *) NULL )\n {\n prev_image=CloneImage(curr,0,0,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n break;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n if ( disposals[i] == DelDispose ) {\n size_t time = 0;\n while ( disposals[i] == DelDispose ) {\n time += curr->delay*1000/curr->ticks_per_second;\n curr=GetNextImageInList(curr);\n i++;\n }\n time += curr->delay*1000/curr->ticks_per_second;\n prev_image->ticks_per_second = 100L;\n prev_image->delay = time*prev_image->ticks_per_second/1000;\n }\n bgnd_image=CropImage(prev_image,&bounds[i],sans_exception);\n prev_image=DestroyImage(prev_image);\n if (bgnd_image == (Image *) NULL)\n break;\n bgnd_image->dispose=disposals[i];\n if ( disposals[i] == DupDispose ) {\n bgnd_image->delay=0;\n bgnd_image->dispose=NoneDispose;\n }\n else\n curr=GetNextImageInList(curr);\n AppendImageToList(&optimized_image,bgnd_image);\n i++;\n }\n sans_exception=DestroyExceptionInfo(sans_exception);\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n if (curr != (Image *) NULL)\n {\n optimized_image=DestroyImageList(optimized_image);\n return((Image *) NULL);\n }\n return(GetFirstImageInList(optimized_image));\n}", "func_hash": 202873389027395428716287075636405798973, "file_name": "layer.c", "file_hash": 292469542477439640201471858939436777728, "cwe": ["CWE-399"], "cve": "CVE-2020-27560", "cve_desc": "ImageMagick 7.0.10-34 allows Division by Zero in OptimizeLayerFrames in MagickCore/layer.c, which may cause a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27560"} {"idx": 338501, "project": "ImageMagick", "commit_id": "ef59bd764f88d893f1219fee8ba696a5d3f8c1c4", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/ef59bd764f88d893f1219fee8ba696a5d3f8c1c4", "commit_message": "There is a Division by Zero in function OptimizeLayerFrames (#2743)\n\nin file MagickCore/layer.c. cur->ticks_per_seconds can be zero\nwith a crafted input argument *image. This is similar to\nCVE-2019-13454.", "target": 0, "func": "static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method,\n ExceptionInfo *exception)\n{\n ExceptionInfo\n *sans_exception;\n\n Image\n *prev_image,\n *dup_image,\n *bgnd_image,\n *optimized_image;\n\n RectangleInfo\n try_bounds,\n bgnd_bounds,\n dup_bounds,\n *bounds;\n\n MagickBooleanType\n add_frames,\n try_cleared,\n cleared;\n\n DisposeType\n *disposals;\n\n register const Image\n *curr;\n\n register ssize_t\n i;\n\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n assert(method == OptimizeLayer ||\n method == OptimizeImageLayer ||\n method == OptimizePlusLayer);\n /*\n Are we allowed to add/remove frames from animation?\n */\n add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse;\n /*\n Ensure all the images are the same size.\n */\n curr=GetFirstImageInList(image);\n for (; curr != (Image *) NULL; curr=GetNextImageInList(curr))\n {\n if ((curr->columns != image->columns) || (curr->rows != image->rows))\n ThrowImageException(OptionError,\"ImagesAreNotTheSameSize\");\n\n if ((curr->page.x != 0) || (curr->page.y != 0) ||\n (curr->page.width != image->page.width) ||\n (curr->page.height != image->page.height))\n ThrowImageException(OptionError,\"ImagePagesAreNotCoalesced\");\n }\n /*\n Allocate memory (times 2 if we allow the use of frame duplications)\n */\n curr=GetFirstImageInList(image);\n bounds=(RectangleInfo *) AcquireQuantumMemory((size_t)\n GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*bounds));\n if (bounds == (RectangleInfo *) NULL)\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n disposals=(DisposeType *) AcquireQuantumMemory((size_t)\n GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*disposals));\n if (disposals == (DisposeType *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Initialise Previous Image as fully transparent\n */\n prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */\n prev_image->page.x=0;\n prev_image->page.y=0;\n prev_image->dispose=NoneDispose;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n prev_image->background_color.alpha=(MagickRealType) TransparentAlpha;\n (void) SetImageBackgroundColor(prev_image,exception);\n /*\n Figure out the area of overlay of the first frame\n No pixel could be cleared as all pixels are already cleared.\n */\n#if DEBUG_OPT_FRAME\n i=0;\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n disposals[0]=NoneDispose;\n bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g\\n\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n#endif\n /*\n Compute the bounding box of changes for each pair of images.\n */\n i=1;\n bgnd_image=(Image *) NULL;\n dup_image=(Image *) NULL;\n dup_bounds.width=0;\n dup_bounds.height=0;\n dup_bounds.x=0;\n dup_bounds.y=0;\n curr=GetNextImageInList(curr);\n for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr))\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n /*\n Assume none disposal is the best\n */\n bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception);\n cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception);\n disposals[i-1]=NoneDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g%s%s\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y,\n bounds[i].x < 0?\" (unchanged)\":\"\",\n cleared?\" (pixels cleared)\":\"\");\n#endif\n if ( bounds[i].x < 0 ) {\n /*\n Image frame is exactly the same as the previous frame!\n If not adding frames leave it to be cropped down to a null image.\n Otherwise mark previous image for deleted, transfering its crop bounds\n to the current image.\n */\n if ( add_frames && i>=2 ) {\n disposals[i-1]=DelDispose;\n disposals[i]=NoneDispose;\n bounds[i]=bounds[i-1];\n i++;\n continue;\n }\n }\n else\n {\n /*\n Compare a none disposal against a previous disposal\n */\n try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"test_prev: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels were cleared)\":\"\");\n#endif\n if ( (!try_cleared && cleared ) ||\n try_bounds.width * try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=try_cleared;\n bounds[i]=try_bounds;\n disposals[i-1]=PreviousDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"previous: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"previous: rejected\\n\");\n#endif\n }\n\n /*\n If we are allowed lets try a complex frame duplication.\n It is useless if the previous image already clears pixels correctly.\n This method will always clear all the pixels that need to be cleared.\n */\n dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */\n if ( add_frames )\n {\n dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (dup_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n return((Image *) NULL);\n }\n dup_image->background_color.alpha_trait=BlendPixelTrait;\n dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception);\n ClearBounds(dup_image,&dup_bounds,exception);\n try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception);\n if ( cleared ||\n dup_bounds.width*dup_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i]=try_bounds;\n disposals[i-1]=DupDispose;\n /* to be finalised later, if found to be optimial */\n }\n else\n dup_bounds.width=dup_bounds.height=0;\n }\n /*\n Now compare against a simple background disposal\n */\n bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (bgnd_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n return((Image *) NULL);\n }\n bgnd_image->background_color.alpha_trait=BlendPixelTrait;\n bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"background: %s\\n\",\n try_cleared?\"(pixels cleared)\":\"\");\n#endif\n if ( try_cleared )\n {\n /*\n Straight background disposal failed to clear pixels needed!\n Lets try expanding the disposal area of the previous frame, to\n include the pixels that are cleared. This guaranteed\n to work, though may not be the most optimized solution.\n */\n try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_clear: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_bounds.x<0?\" (no expand nessary)\":\"\");\n#endif\n if ( bgnd_bounds.x < 0 )\n bgnd_bounds = try_bounds;\n else\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_bgnd: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n if ( try_bounds.x < bgnd_bounds.x )\n {\n bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n bgnd_bounds.x = try_bounds.x;\n }\n else\n {\n try_bounds.width += try_bounds.x - bgnd_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n }\n if ( try_bounds.y < bgnd_bounds.y )\n {\n bgnd_bounds.height += bgnd_bounds.y - try_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n bgnd_bounds.y = try_bounds.y;\n }\n else\n {\n try_bounds.height += try_bounds.y - bgnd_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n }\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \" to : %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n }\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n#if DEBUG_OPT_FRAME\n/* Something strange is happening with a specific animation\n * CompareAnyLayers (normal method) and CompareClearLayers returns the whole\n * image, which is not posibly correct! As verified by previous tests.\n * Something changed beyond the bgnd_bounds clearing. But without being able\n * to see, or writet he image at this point it is hard to tell what is wrong!\n * Only CompareOverlay seemed to return something sensible.\n */\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception);\n (void) FormatLocaleFile(stderr, \"expand_ctst: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y );\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_any : %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception);\n#if DEBUG_OPT_FRAME\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_test: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n }\n /*\n Test if this background dispose is smaller than any of the\n other methods we tryed before this (including duplicated frame)\n */\n if ( cleared ||\n bgnd_bounds.width*bgnd_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i-1].width*bounds[i-1].height\n +dup_bounds.width*dup_bounds.height\n +bounds[i].width*bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i-1]=bgnd_bounds;\n bounds[i]=try_bounds;\n if ( disposals[i-1] == DupDispose )\n dup_image=DestroyImage(dup_image);\n disposals[i-1]=BackgroundDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"expand_bgnd: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"expand_bgnd: reject\\n\");\n#endif\n }\n }\n /*\n Finalise choice of dispose, set new prev_image,\n and junk any extra images as appropriate,\n */\n if ( disposals[i-1] == DupDispose )\n {\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n prev_image=DestroyImage(prev_image);\n prev_image=dup_image, dup_image=(Image *) NULL;\n bounds[i+1]=bounds[i];\n bounds[i]=dup_bounds;\n disposals[i-1]=DupDispose;\n disposals[i]=BackgroundDispose;\n i++;\n }\n else\n {\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n if ( disposals[i-1] != PreviousDispose )\n prev_image=DestroyImage(prev_image);\n if ( disposals[i-1] == BackgroundDispose )\n prev_image=bgnd_image, bgnd_image=(Image *) NULL;\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n if ( disposals[i-1] == NoneDispose )\n {\n prev_image=ReferenceImage(curr->previous);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n }\n\n }\n assert(prev_image != (Image *) NULL);\n disposals[i]=disposals[i-1];\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"final %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i-1,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]),\n (double) bounds[i-1].width,(double) bounds[i-1].height,\n (double) bounds[i-1].x,(double) bounds[i-1].y );\n#endif\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"interum %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]),\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n (void) FormatLocaleFile(stderr,\"\\n\");\n#endif\n i++;\n }\n prev_image=DestroyImage(prev_image);\n /*\n Optimize all images in sequence.\n */\n sans_exception=AcquireExceptionInfo();\n i=0;\n curr=GetFirstImageInList(image);\n optimized_image=NewImageList();\n while ( curr != (const Image *) NULL )\n {\n prev_image=CloneImage(curr,0,0,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n break;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n if ( disposals[i] == DelDispose ) {\n size_t time = 0;\n while ( disposals[i] == DelDispose ) {\n time +=(size_t) (curr->delay*1000*\n PerceptibleReciprocal((double) curr->ticks_per_second));\n curr=GetNextImageInList(curr);\n i++;\n }\n time += (size_t)(curr->delay*1000*\n PerceptibleReciprocal((double) curr->ticks_per_second));\n prev_image->ticks_per_second = 100L;\n prev_image->delay = time*prev_image->ticks_per_second/1000;\n }\n bgnd_image=CropImage(prev_image,&bounds[i],sans_exception);\n prev_image=DestroyImage(prev_image);\n if (bgnd_image == (Image *) NULL)\n break;\n bgnd_image->dispose=disposals[i];\n if ( disposals[i] == DupDispose ) {\n bgnd_image->delay=0;\n bgnd_image->dispose=NoneDispose;\n }\n else\n curr=GetNextImageInList(curr);\n AppendImageToList(&optimized_image,bgnd_image);\n i++;\n }\n sans_exception=DestroyExceptionInfo(sans_exception);\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n if (curr != (Image *) NULL)\n {\n optimized_image=DestroyImageList(optimized_image);\n return((Image *) NULL);\n }\n return(GetFirstImageInList(optimized_image));\n}", "func_hash": 19530939790924698730019509509431862455, "file_name": "layer.c", "file_hash": 97740820797759815991722412757481041551, "cwe": ["CWE-399"], "cve": "CVE-2020-27560", "cve_desc": "ImageMagick 7.0.10-34 allows Division by Zero in OptimizeLayerFrames in MagickCore/layer.c, which may cause a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27560"} {"idx": 202741, "project": "linux", "commit_id": "d1f82808877bb10d3deee7cf3374a4eb3fb582db", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d1f82808877bb10d3deee7cf3374a4eb3fb582db", "commit_message": "io_uring: truncate lengths larger than MAX_RW_COUNT on provide buffers\n\nRead and write operations are capped to MAX_RW_COUNT. Some read ops rely on\nthat limit, and that is not guaranteed by the IORING_OP_PROVIDE_BUFFERS.\n\nTruncate those lengths when doing io_add_buffers, so buffer addresses still\nuse the uncapped length.\n\nAlso, take the chance and change struct io_buffer len member to __u32, so\nit matches struct io_provide_buffer len member.\n\nThis fixes CVE-2021-3491, also reported as ZDI-CAN-13546.\n\nFixes: ddf0322db79c (\"io_uring: add IORING_OP_PROVIDE_BUFFERS\")\nReported-by: Billy Jheng Bing-Jhong (@st424204)\nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: Jens Axboe ", "target": 1, "func": "static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)\n{\n\tstruct io_buffer *buf;\n\tu64 addr = pbuf->addr;\n\tint i, bid = pbuf->bid;\n\n\tfor (i = 0; i < pbuf->nbufs; i++) {\n\t\tbuf = kmalloc(sizeof(*buf), GFP_KERNEL);\n\t\tif (!buf)\n\t\t\tbreak;\n\n\t\tbuf->addr = addr;\n\t\tbuf->len = pbuf->len;\n\t\tbuf->bid = bid;\n\t\taddr += pbuf->len;\n\t\tbid++;\n\t\tif (!*head) {\n\t\t\tINIT_LIST_HEAD(&buf->list);\n\t\t\t*head = buf;\n\t\t} else {\n\t\t\tlist_add_tail(&buf->list, &(*head)->list);\n\t\t}\n\t}\n\n\treturn i ? i : -ENOMEM;\n}", "func_hash": 235088268107377507878150408482760106492, "file_name": "io_uring.c", "file_hash": 61197944568979656540627164461985314945, "cwe": ["CWE-787"], "cve": "CVE-2021-3491", "cve_desc": "The io_uring subsystem in the Linux kernel allowed the MAX_RW_COUNT limit to be bypassed in the PROVIDE_BUFFERS operation, which led to negative values being usedin mem_rw when reading /proc//mem. This could be used to create a heap overflow leading to arbitrary code execution in the kernel. It was addressed via commit d1f82808877b (\"io_uring: truncate lengths larger than MAX_RW_COUNT on provide buffers\") (v5.13-rc1) and backported to the stable kernels in v5.12.4, v5.11.21, and v5.10.37. It was introduced in ddf0322db79c (\"io_uring: add IORING_OP_PROVIDE_BUFFERS\") (v5.7-rc1).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3491"} {"idx": 338639, "project": "linux", "commit_id": "d1f82808877bb10d3deee7cf3374a4eb3fb582db", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d1f82808877bb10d3deee7cf3374a4eb3fb582db", "commit_message": "io_uring: truncate lengths larger than MAX_RW_COUNT on provide buffers\n\nRead and write operations are capped to MAX_RW_COUNT. Some read ops rely on\nthat limit, and that is not guaranteed by the IORING_OP_PROVIDE_BUFFERS.\n\nTruncate those lengths when doing io_add_buffers, so buffer addresses still\nuse the uncapped length.\n\nAlso, take the chance and change struct io_buffer len member to __u32, so\nit matches struct io_provide_buffer len member.\n\nThis fixes CVE-2021-3491, also reported as ZDI-CAN-13546.\n\nFixes: ddf0322db79c (\"io_uring: add IORING_OP_PROVIDE_BUFFERS\")\nReported-by: Billy Jheng Bing-Jhong (@st424204)\nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: Jens Axboe ", "target": 0, "func": "static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)\n{\n\tstruct io_buffer *buf;\n\tu64 addr = pbuf->addr;\n\tint i, bid = pbuf->bid;\n\n\tfor (i = 0; i < pbuf->nbufs; i++) {\n\t\tbuf = kmalloc(sizeof(*buf), GFP_KERNEL);\n\t\tif (!buf)\n\t\t\tbreak;\n\n\t\tbuf->addr = addr;\n\t\tbuf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);\n\t\tbuf->bid = bid;\n\t\taddr += pbuf->len;\n\t\tbid++;\n\t\tif (!*head) {\n\t\t\tINIT_LIST_HEAD(&buf->list);\n\t\t\t*head = buf;\n\t\t} else {\n\t\t\tlist_add_tail(&buf->list, &(*head)->list);\n\t\t}\n\t}\n\n\treturn i ? i : -ENOMEM;\n}", "func_hash": 118344393878354847807482962780979983951, "file_name": "io_uring.c", "file_hash": 29368837531971764003549686425861293292, "cwe": ["CWE-787"], "cve": "CVE-2021-3491", "cve_desc": "The io_uring subsystem in the Linux kernel allowed the MAX_RW_COUNT limit to be bypassed in the PROVIDE_BUFFERS operation, which led to negative values being usedin mem_rw when reading /proc//mem. This could be used to create a heap overflow leading to arbitrary code execution in the kernel. It was addressed via commit d1f82808877b (\"io_uring: truncate lengths larger than MAX_RW_COUNT on provide buffers\") (v5.13-rc1) and backported to the stable kernels in v5.12.4, v5.11.21, and v5.10.37. It was introduced in ddf0322db79c (\"io_uring: add IORING_OP_PROVIDE_BUFFERS\") (v5.7-rc1).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3491"} {"idx": 202842, "project": "linux", "commit_id": "5d069dbe8aaf2a197142558b6fb2978189ba3454", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5d069dbe8aaf2a197142558b6fb2978189ba3454", "commit_message": "fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: ", "target": 1, "func": "static int fuse_do_getattr(struct inode *inode, struct kstat *stat,\n\t\t\t struct file *file)\n{\n\tint err;\n\tstruct fuse_getattr_in inarg;\n\tstruct fuse_attr_out outarg;\n\tstruct fuse_mount *fm = get_fuse_mount(inode);\n\tFUSE_ARGS(args);\n\tu64 attr_version;\n\n\tattr_version = fuse_get_attr_version(fm->fc);\n\n\tmemset(&inarg, 0, sizeof(inarg));\n\tmemset(&outarg, 0, sizeof(outarg));\n\t/* Directories have separate file-handle space */\n\tif (file && S_ISREG(inode->i_mode)) {\n\t\tstruct fuse_file *ff = file->private_data;\n\n\t\tinarg.getattr_flags |= FUSE_GETATTR_FH;\n\t\tinarg.fh = ff->fh;\n\t}\n\targs.opcode = FUSE_GETATTR;\n\targs.nodeid = get_node_id(inode);\n\targs.in_numargs = 1;\n\targs.in_args[0].size = sizeof(inarg);\n\targs.in_args[0].value = &inarg;\n\targs.out_numargs = 1;\n\targs.out_args[0].size = sizeof(outarg);\n\targs.out_args[0].value = &outarg;\n\terr = fuse_simple_request(fm, &args);\n\tif (!err) {\n\t\tif (fuse_invalid_attr(&outarg.attr) ||\n\t\t (inode->i_mode ^ outarg.attr.mode) & S_IFMT) {\n\t\t\tmake_bad_inode(inode);\n\t\t\terr = -EIO;\n\t\t} else {\n\t\t\tfuse_change_attributes(inode, &outarg.attr,\n\t\t\t\t\t attr_timeout(&outarg),\n\t\t\t\t\t attr_version);\n\t\t\tif (stat)\n\t\t\t\tfuse_fillattr(inode, &outarg.attr, stat);\n\t\t}\n\t}\n\treturn err;\n}", "func_hash": 287058390429495805183065367870864783452, "file_name": "dir.c", "file_hash": 249642739263407289477313030143114384319, "cwe": ["CWE-459"], "cve": "CVE-2020-36322", "cve_desc": "An issue was discovered in the FUSE filesystem implementation in the Linux kernel before 5.10.6, aka CID-5d069dbe8aaf. fuse_do_getattr() calls make_bad_inode() in inappropriate situations, causing a system crash. NOTE: the original fix for this vulnerability was incomplete, and its incompleteness is tracked as CVE-2021-28950.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36322"} {"idx": 342120, "project": "linux", "commit_id": "5d069dbe8aaf2a197142558b6fb2978189ba3454", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5d069dbe8aaf2a197142558b6fb2978189ba3454", "commit_message": "fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: ", "target": 0, "func": "static int fuse_do_getattr(struct inode *inode, struct kstat *stat,\n\t\t\t struct file *file)\n{\n\tint err;\n\tstruct fuse_getattr_in inarg;\n\tstruct fuse_attr_out outarg;\n\tstruct fuse_mount *fm = get_fuse_mount(inode);\n\tFUSE_ARGS(args);\n\tu64 attr_version;\n\n\tattr_version = fuse_get_attr_version(fm->fc);\n\n\tmemset(&inarg, 0, sizeof(inarg));\n\tmemset(&outarg, 0, sizeof(outarg));\n\t/* Directories have separate file-handle space */\n\tif (file && S_ISREG(inode->i_mode)) {\n\t\tstruct fuse_file *ff = file->private_data;\n\n\t\tinarg.getattr_flags |= FUSE_GETATTR_FH;\n\t\tinarg.fh = ff->fh;\n\t}\n\targs.opcode = FUSE_GETATTR;\n\targs.nodeid = get_node_id(inode);\n\targs.in_numargs = 1;\n\targs.in_args[0].size = sizeof(inarg);\n\targs.in_args[0].value = &inarg;\n\targs.out_numargs = 1;\n\targs.out_args[0].size = sizeof(outarg);\n\targs.out_args[0].value = &outarg;\n\terr = fuse_simple_request(fm, &args);\n\tif (!err) {\n\t\tif (fuse_invalid_attr(&outarg.attr) ||\n\t\t (inode->i_mode ^ outarg.attr.mode) & S_IFMT) {\n\t\t\tfuse_make_bad(inode);\n\t\t\terr = -EIO;\n\t\t} else {\n\t\t\tfuse_change_attributes(inode, &outarg.attr,\n\t\t\t\t\t attr_timeout(&outarg),\n\t\t\t\t\t attr_version);\n\t\t\tif (stat)\n\t\t\t\tfuse_fillattr(inode, &outarg.attr, stat);\n\t\t}\n\t}\n\treturn err;\n}", "func_hash": 135082996437979771576693838863366259059, "file_name": "dir.c", "file_hash": 110737495401188274740990043185842649540, "cwe": ["CWE-459"], "cve": "CVE-2020-36322", "cve_desc": "An issue was discovered in the FUSE filesystem implementation in the Linux kernel before 5.10.6, aka CID-5d069dbe8aaf. fuse_do_getattr() calls make_bad_inode() in inappropriate situations, causing a system crash. NOTE: the original fix for this vulnerability was incomplete, and its incompleteness is tracked as CVE-2021-28950.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36322"} {"idx": 202898, "project": "linux", "commit_id": "919f4ebc598701670e80e31573a58f1f2d2bf918", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=919f4ebc598701670e80e31573a58f1f2d2bf918", "commit_message": "KVM: x86: hyper-v: Fix Hyper-V context null-ptr-deref\n\nReported by syzkaller:\n\n KASAN: null-ptr-deref in range [0x0000000000000140-0x0000000000000147]\n CPU: 1 PID: 8370 Comm: syz-executor859 Not tainted 5.11.0-syzkaller #0\n RIP: 0010:synic_get arch/x86/kvm/hyperv.c:165 [inline]\n RIP: 0010:kvm_hv_set_sint_gsi arch/x86/kvm/hyperv.c:475 [inline]\n RIP: 0010:kvm_hv_irq_routing_update+0x230/0x460 arch/x86/kvm/hyperv.c:498\n Call Trace:\n kvm_set_irq_routing+0x69b/0x940 arch/x86/kvm/../../../virt/kvm/irqchip.c:223\n kvm_vm_ioctl+0x12d0/0x2800 arch/x86/kvm/../../../virt/kvm/kvm_main.c:3959\n vfs_ioctl fs/ioctl.c:48 [inline]\n __do_sys_ioctl fs/ioctl.c:753 [inline]\n __se_sys_ioctl fs/ioctl.c:739 [inline]\n __x64_sys_ioctl+0x193/0x200 fs/ioctl.c:739\n do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nHyper-V context is lazily allocated until Hyper-V specific MSRs are accessed\nor SynIC is enabled. However, the syzkaller testcase sets irq routing table\ndirectly w/o enabling SynIC. This results in null-ptr-deref when accessing\nSynIC Hyper-V context. This patch fixes it.\n\nsyzkaller source: https://syzkaller.appspot.com/x/repro.c?x=163342ccd00000\n\nReported-by: syzbot+6987f3b2dbd9eda95f12@syzkaller.appspotmail.com\nFixes: 8f014550dfb1 (\"KVM: x86: hyper-v: Make Hyper-V emulation enablement conditional\")\nSigned-off-by: Wanpeng Li \nMessage-Id: <1614326399-5762-1-git-send-email-wanpengli@tencent.com>\nSigned-off-by: Paolo Bonzini ", "target": 1, "func": "static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx)\n{\n\tstruct kvm_vcpu *vcpu;\n\tstruct kvm_vcpu_hv_synic *synic;\n\n\tvcpu = get_vcpu_by_vpidx(kvm, vpidx);\n\tif (!vcpu)\n\t\treturn NULL;\n\tsynic = to_hv_synic(vcpu);\n\treturn (synic->active) ? synic : NULL;\n}", "func_hash": 317020325351550856667241325316720950028, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-30178", "cve_desc": "An issue was discovered in the Linux kernel through 5.11.11. synic_get in arch/x86/kvm/hyperv.c has a NULL pointer dereference for certain accesses to the SynIC Hyper-V context, aka CID-919f4ebc5987.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30178"} {"idx": 343525, "project": "linux", "commit_id": "919f4ebc598701670e80e31573a58f1f2d2bf918", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=919f4ebc598701670e80e31573a58f1f2d2bf918", "commit_message": "KVM: x86: hyper-v: Fix Hyper-V context null-ptr-deref\n\nReported by syzkaller:\n\n KASAN: null-ptr-deref in range [0x0000000000000140-0x0000000000000147]\n CPU: 1 PID: 8370 Comm: syz-executor859 Not tainted 5.11.0-syzkaller #0\n RIP: 0010:synic_get arch/x86/kvm/hyperv.c:165 [inline]\n RIP: 0010:kvm_hv_set_sint_gsi arch/x86/kvm/hyperv.c:475 [inline]\n RIP: 0010:kvm_hv_irq_routing_update+0x230/0x460 arch/x86/kvm/hyperv.c:498\n Call Trace:\n kvm_set_irq_routing+0x69b/0x940 arch/x86/kvm/../../../virt/kvm/irqchip.c:223\n kvm_vm_ioctl+0x12d0/0x2800 arch/x86/kvm/../../../virt/kvm/kvm_main.c:3959\n vfs_ioctl fs/ioctl.c:48 [inline]\n __do_sys_ioctl fs/ioctl.c:753 [inline]\n __se_sys_ioctl fs/ioctl.c:739 [inline]\n __x64_sys_ioctl+0x193/0x200 fs/ioctl.c:739\n do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nHyper-V context is lazily allocated until Hyper-V specific MSRs are accessed\nor SynIC is enabled. However, the syzkaller testcase sets irq routing table\ndirectly w/o enabling SynIC. This results in null-ptr-deref when accessing\nSynIC Hyper-V context. This patch fixes it.\n\nsyzkaller source: https://syzkaller.appspot.com/x/repro.c?x=163342ccd00000\n\nReported-by: syzbot+6987f3b2dbd9eda95f12@syzkaller.appspotmail.com\nFixes: 8f014550dfb1 (\"KVM: x86: hyper-v: Make Hyper-V emulation enablement conditional\")\nSigned-off-by: Wanpeng Li \nMessage-Id: <1614326399-5762-1-git-send-email-wanpengli@tencent.com>\nSigned-off-by: Paolo Bonzini ", "target": 0, "func": "static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx)\n{\n\tstruct kvm_vcpu *vcpu;\n\tstruct kvm_vcpu_hv_synic *synic;\n\n\tvcpu = get_vcpu_by_vpidx(kvm, vpidx);\n\tif (!vcpu || !to_hv_vcpu(vcpu))\n\t\treturn NULL;\n\tsynic = to_hv_synic(vcpu);\n\treturn (synic->active) ? synic : NULL;\n}", "func_hash": 328923225120147409125787363706675003605, "file_name": "hyperv.c", "file_hash": 337086461031312798158060474345990122568, "cwe": ["CWE-476"], "cve": "CVE-2021-30178", "cve_desc": "An issue was discovered in the Linux kernel through 5.11.11. synic_get in arch/x86/kvm/hyperv.c has a NULL pointer dereference for certain accesses to the SynIC Hyper-V context, aka CID-919f4ebc5987.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30178"} {"idx": 203616, "project": "libssh-mirror", "commit_id": "10b3ebbe61a7031a3dae97f05834442220447181", "project_url": "https://gitlab.com/libssh/libssh-mirror", "commit_url": "https://gitlab.com/libssh/libssh-mirror/-/commit/10b3ebbe61a7031a3dae97f05834442220447181", "commit_message": "buffer: Reformat ssh_buffer_add_data()\n\nSigned-off-by: Andreas Schneider \nReviewed-by: Anderson Toshiyuki Sasaki \nReviewed-by: Jakub Jelen ", "target": 1, "func": "int ssh_buffer_add_data(struct ssh_buffer_struct *buffer, const void *data, uint32_t len)\n{\n buffer_verify(buffer);\n\n if (data == NULL) {\n return -1;\n }\n\n if (buffer->used + len < len) {\n return -1;\n }\n\n if (buffer->allocated < (buffer->used + len)) {\n if(buffer->pos > 0)\n buffer_shift(buffer);\n if (realloc_buffer(buffer, buffer->used + len) < 0) {\n return -1;\n }\n }\n\n memcpy(buffer->data+buffer->used, data, len);\n buffer->used+=len;\n buffer_verify(buffer);\n return 0;\n}", "func_hash": 275519893357241612262747139929791979443, "file_name": "buffer.c", "file_hash": 335242773451315151542811456025566793195, "cwe": ["CWE-476"], "cve": "CVE-2020-16135", "cve_desc": "libssh 0.9.4 has a NULL pointer dereference in tftpserver.c if ssh_buffer_new returns NULL.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16135"} {"idx": 345161, "project": "libssh-mirror", "commit_id": "10b3ebbe61a7031a3dae97f05834442220447181", "project_url": "https://gitlab.com/libssh/libssh-mirror", "commit_url": "https://gitlab.com/libssh/libssh-mirror/-/commit/10b3ebbe61a7031a3dae97f05834442220447181", "commit_message": "buffer: Reformat ssh_buffer_add_data()\n\nSigned-off-by: Andreas Schneider \nReviewed-by: Anderson Toshiyuki Sasaki \nReviewed-by: Jakub Jelen ", "target": 0, "func": "void *ssh_buffer_allocate(struct ssh_buffer_struct *buffer, uint32_t len)\n{\n void *ptr;\n buffer_verify(buffer);\n\n if (buffer->used + len < len) {\n return NULL;\n }\n\n if (buffer->allocated < (buffer->used + len)) {\n if (buffer->pos > 0) {\n buffer_shift(buffer);\n }\n\n if (realloc_buffer(buffer, buffer->used + len) < 0) {\n return NULL;\n }\n }\n\n ptr = buffer->data + buffer->used;\n buffer->used+=len;\n buffer_verify(buffer);\n\n return ptr;\n}", "func_hash": 282661601547706809770077453953120843062, "file_name": "buffer.c", "file_hash": 281754696881245544059364173580209455772, "cwe": ["CWE-476"], "cve": "CVE-2020-16135", "cve_desc": "libssh 0.9.4 has a NULL pointer dereference in tftpserver.c if ssh_buffer_new returns NULL.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16135"} {"idx": 203887, "project": "qemu", "commit_id": "babd03fde68093482528010a5435c14ce9128e3f", "project_url": "https://github.com/bonzini/qemu", "commit_url": "http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=babd03fde68093482528010a5435c14ce9128e3f", "commit_message": "usb-linux.c: fix buffer overflow\n\nIn usb-linux.c:usb_host_handle_control, we pass a 1024-byte buffer and\nlength to the kernel. However, the length was provided by the caller\nof dev->handle_packet, and is not checked, so the kernel might provide\ntoo much data and overflow our buffer.\n\nFor example, hw/usb-uhci.c could set the length to 2047.\nhw/usb-ohci.c looks like it might go up to 4096 or 8192.\n\nThis causes a qemu crash, as reported here:\n http://www.mail-archive.com/kvm@vger.kernel.org/msg18447.html\n\nThis patch increases the usb-linux.c buffer size to 2048 to fix the\nspecific device reported, and adds a check to avoid the overflow in\nany case.\n\nSigned-off-by: Jim Paris \nSigned-off-by: Anthony Liguori ", "target": 1, "func": "static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)\n{\n struct usbdevfs_urb *urb;\n AsyncURB *aurb;\n int ret, value, index;\n\n /* \n * Process certain standard device requests.\n * These are infrequent and are processed synchronously.\n */\n value = le16_to_cpu(s->ctrl.req.wValue);\n index = le16_to_cpu(s->ctrl.req.wIndex);\n\n dprintf(\"husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\\n\",\n s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, \n s->ctrl.len);\n\n if (s->ctrl.req.bRequestType == 0) {\n switch (s->ctrl.req.bRequest) {\n case USB_REQ_SET_ADDRESS:\n return usb_host_set_address(s, value);\n\n case USB_REQ_SET_CONFIGURATION:\n return usb_host_set_config(s, value & 0xff);\n }\n }\n\n if (s->ctrl.req.bRequestType == 1 &&\n s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)\n return usb_host_set_interface(s, index, value);\n\n /* The rest are asynchronous */\n\n aurb = async_alloc();\n aurb->hdev = s;\n aurb->packet = p;\n\n /* \n * Setup ctrl transfer.\n *\n * s->ctrl is layed out such that data buffer immediately follows\n * 'req' struct which is exactly what usbdevfs expects.\n */ \n urb = &aurb->urb;\n\n urb->type = USBDEVFS_URB_TYPE_CONTROL;\n urb->endpoint = p->devep;\n\n urb->buffer = &s->ctrl.req;\n urb->buffer_length = 8 + s->ctrl.len;\n\n urb->usercontext = s;\n\n ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);\n\n dprintf(\"husb: submit ctrl. len %u aurb %p\\n\", urb->buffer_length, aurb);\n\n if (ret < 0) {\n dprintf(\"husb: submit failed. errno %d\\n\", errno);\n async_free(aurb);\n\n switch(errno) {\n case ETIMEDOUT:\n return USB_RET_NAK;\n case EPIPE:\n default:\n return USB_RET_STALL;\n }\n }\n\n usb_defer_packet(p, async_cancel, aurb);\n return USB_RET_ASYNC;\n}", "func_hash": 111506142078956030755598122317914761720, "file_name": "usb-linux.c", "file_hash": 152773906347195177664553230815404641046, "cwe": ["CWE-119"], "cve": "CVE-2010-0297", "cve_desc": "Buffer overflow in the usb_host_handle_control function in the USB passthrough handling implementation in usb-linux.c in QEMU before 0.11.1 allows guest OS users to cause a denial of service (guest OS crash or hang) or possibly execute arbitrary code on the host OS via a crafted USB packet.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0297"} {"idx": 346299, "project": "qemu", "commit_id": "babd03fde68093482528010a5435c14ce9128e3f", "project_url": "https://github.com/bonzini/qemu", "commit_url": "http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=babd03fde68093482528010a5435c14ce9128e3f", "commit_message": "usb-linux.c: fix buffer overflow\n\nIn usb-linux.c:usb_host_handle_control, we pass a 1024-byte buffer and\nlength to the kernel. However, the length was provided by the caller\nof dev->handle_packet, and is not checked, so the kernel might provide\ntoo much data and overflow our buffer.\n\nFor example, hw/usb-uhci.c could set the length to 2047.\nhw/usb-ohci.c looks like it might go up to 4096 or 8192.\n\nThis causes a qemu crash, as reported here:\n http://www.mail-archive.com/kvm@vger.kernel.org/msg18447.html\n\nThis patch increases the usb-linux.c buffer size to 2048 to fix the\nspecific device reported, and adds a check to avoid the overflow in\nany case.\n\nSigned-off-by: Jim Paris \nSigned-off-by: Anthony Liguori ", "target": 0, "func": "static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)\n{\n struct usbdevfs_urb *urb;\n AsyncURB *aurb;\n int ret, value, index;\n int buffer_len;\n\n /* \n * Process certain standard device requests.\n * These are infrequent and are processed synchronously.\n */\n value = le16_to_cpu(s->ctrl.req.wValue);\n index = le16_to_cpu(s->ctrl.req.wIndex);\n\n dprintf(\"husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\\n\",\n s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, \n s->ctrl.len);\n\n if (s->ctrl.req.bRequestType == 0) {\n switch (s->ctrl.req.bRequest) {\n case USB_REQ_SET_ADDRESS:\n return usb_host_set_address(s, value);\n\n case USB_REQ_SET_CONFIGURATION:\n return usb_host_set_config(s, value & 0xff);\n }\n }\n\n if (s->ctrl.req.bRequestType == 1 &&\n s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)\n return usb_host_set_interface(s, index, value);\n\n /* The rest are asynchronous */\n\n buffer_len = 8 + s->ctrl.len;\n if (buffer_len > sizeof(s->ctrl.buffer)) {\n\t fprintf(stderr, \"husb: ctrl buffer too small (%u > %lu)\\n\",\n\t\t buffer_len, sizeof(s->ctrl.buffer));\n\t return USB_RET_STALL;\n }\n\n aurb = async_alloc();\n aurb->hdev = s;\n aurb->packet = p;\n\n /* \n * Setup ctrl transfer.\n *\n * s->ctrl is layed out such that data buffer immediately follows\n * 'req' struct which is exactly what usbdevfs expects.\n */ \n urb = &aurb->urb;\n\n urb->type = USBDEVFS_URB_TYPE_CONTROL;\n urb->endpoint = p->devep;\n\n urb->buffer = &s->ctrl.req;\n urb->buffer_length = buffer_len;\n\n urb->usercontext = s;\n\n ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);\n\n dprintf(\"husb: submit ctrl. len %u aurb %p\\n\", urb->buffer_length, aurb);\n\n if (ret < 0) {\n dprintf(\"husb: submit failed. errno %d\\n\", errno);\n async_free(aurb);\n\n switch(errno) {\n case ETIMEDOUT:\n return USB_RET_NAK;\n case EPIPE:\n default:\n return USB_RET_STALL;\n }\n }\n\n usb_defer_packet(p, async_cancel, aurb);\n return USB_RET_ASYNC;\n}", "func_hash": 126381043260370035413870768060891425783, "file_name": "usb-linux.c", "file_hash": 136557488548851062485135735438534992532, "cwe": ["CWE-119"], "cve": "CVE-2010-0297", "cve_desc": "Buffer overflow in the usb_host_handle_control function in the USB passthrough handling implementation in usb-linux.c in QEMU before 0.11.1 allows guest OS users to cause a denial of service (guest OS crash or hang) or possibly execute arbitrary code on the host OS via a crafted USB packet.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0297"} {"idx": 203893, "project": "libevent", "commit_id": "20d6d4458bee5d88bda1511c225c25b2d3198d6c", "project_url": "https://github.com/libevent/libevent", "commit_url": "https://github.com/libevent/libevent/commit/20d6d4458bee5d88bda1511c225c25b2d3198d6c", "commit_message": "Fix CVE-2014-6272 in Libevent 2.0\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.", "target": 1, "func": "evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)\n{\n\tstruct evbuffer_chain *chain, *tmp;\n\tconst unsigned char *data = data_in;\n\tsize_t remain, to_alloc;\n\tint result = -1;\n\n\tEVBUFFER_LOCK(buf);\n\n\tif (buf->freeze_end) {\n\t\tgoto done;\n\t}\n\n\tchain = buf->last;\n\n\t/* If there are no chains allocated for this buffer, allocate one\n\t * big enough to hold all the data. */\n\tif (chain == NULL) {\n\t\tchain = evbuffer_chain_new(datlen);\n\t\tif (!chain)\n\t\t\tgoto done;\n\t\tevbuffer_chain_insert(buf, chain);\n\t}\n\n\tif ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {\n\t\tremain = (size_t)(chain->buffer_len - chain->misalign - chain->off);\n\t\tif (remain >= datlen) {\n\t\t\t/* there's enough space to hold all the data in the\n\t\t\t * current last chain */\n\t\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t\t data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t} else if (!CHAIN_PINNED(chain) &&\n\t\t evbuffer_chain_should_realign(chain, datlen)) {\n\t\t\t/* we can fit the data into the misalignment */\n\t\t\tevbuffer_chain_align(chain);\n\n\t\t\tmemcpy(chain->buffer + chain->off, data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\t/* we cannot write any data to the last chain */\n\t\tremain = 0;\n\t}\n\n\t/* we need to add another chain */\n\tto_alloc = chain->buffer_len;\n\tif (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)\n\t\tto_alloc <<= 1;\n\tif (datlen > to_alloc)\n\t\tto_alloc = datlen;\n\ttmp = evbuffer_chain_new(to_alloc);\n\tif (tmp == NULL)\n\t\tgoto done;\n\n\tif (remain) {\n\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t data, remain);\n\t\tchain->off += remain;\n\t\tbuf->total_len += remain;\n\t\tbuf->n_add_for_cb += remain;\n\t}\n\n\tdata += remain;\n\tdatlen -= remain;\n\n\tmemcpy(tmp->buffer, data, datlen);\n\ttmp->off = datlen;\n\tevbuffer_chain_insert(buf, tmp);\n\tbuf->n_add_for_cb += datlen;\n\nout:\n\tevbuffer_invoke_callbacks(buf);\n\tresult = 0;\ndone:\n\tEVBUFFER_UNLOCK(buf);\n\treturn result;\n}", "func_hash": 235268206269696302871058803798758898060, "file_name": "buffer.c", "file_hash": 198309574084700790660592572809901758078, "cwe": ["CWE-189"], "cve": "CVE-2014-6272", "cve_desc": "Multiple integer overflows in the evbuffer API in Libevent 1.4.x before 1.4.15, 2.0.x before 2.0.22, and 2.1.x before 2.1.5-beta allow context-dependent attackers to cause a denial of service or possibly have other unspecified impact via \"insanely large inputs\" to the (1) evbuffer_add, (2) evbuffer_expand, or (3) bufferevent_write function, which triggers a heap-based buffer overflow or an infinite loop. NOTE: this identifier has been SPLIT per ADT3 due to different affected versions. See CVE-2015-6525 for the functions that are only affected in 2.0 and later.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-6272"} {"idx": 346340, "project": "libevent", "commit_id": "20d6d4458bee5d88bda1511c225c25b2d3198d6c", "project_url": "https://github.com/libevent/libevent", "commit_url": "https://github.com/libevent/libevent/commit/20d6d4458bee5d88bda1511c225c25b2d3198d6c", "commit_message": "Fix CVE-2014-6272 in Libevent 2.0\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.", "target": 0, "func": "evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)\n{\n\tstruct evbuffer_chain *chain, *tmp;\n\tconst unsigned char *data = data_in;\n\tsize_t remain, to_alloc;\n\tint result = -1;\n\n\tEVBUFFER_LOCK(buf);\n\n\tif (buf->freeze_end) {\n\t\tgoto done;\n\t}\n\t/* Prevent buf->total_len overflow */\n\tif (datlen > EV_SIZE_MAX - buf->total_len) {\n\t\tgoto done;\n\t}\n\n\tchain = buf->last;\n\n\t/* If there are no chains allocated for this buffer, allocate one\n\t * big enough to hold all the data. */\n\tif (chain == NULL) {\n\t\tchain = evbuffer_chain_new(datlen);\n\t\tif (!chain)\n\t\t\tgoto done;\n\t\tevbuffer_chain_insert(buf, chain);\n\t}\n\n\tif ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {\n\t\t/* Always true for mutable buffers */\n\t\tEVUTIL_ASSERT(chain->misalign >= 0 &&\n\t\t (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);\n\t\tremain = chain->buffer_len - (size_t)chain->misalign - chain->off;\n\t\tif (remain >= datlen) {\n\t\t\t/* there's enough space to hold all the data in the\n\t\t\t * current last chain */\n\t\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t\t data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t} else if (!CHAIN_PINNED(chain) &&\n\t\t evbuffer_chain_should_realign(chain, datlen)) {\n\t\t\t/* we can fit the data into the misalignment */\n\t\t\tevbuffer_chain_align(chain);\n\n\t\t\tmemcpy(chain->buffer + chain->off, data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\t/* we cannot write any data to the last chain */\n\t\tremain = 0;\n\t}\n\n\t/* we need to add another chain */\n\tto_alloc = chain->buffer_len;\n\tif (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)\n\t\tto_alloc <<= 1;\n\tif (datlen > to_alloc)\n\t\tto_alloc = datlen;\n\ttmp = evbuffer_chain_new(to_alloc);\n\tif (tmp == NULL)\n\t\tgoto done;\n\n\tif (remain) {\n\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t data, remain);\n\t\tchain->off += remain;\n\t\tbuf->total_len += remain;\n\t\tbuf->n_add_for_cb += remain;\n\t}\n\n\tdata += remain;\n\tdatlen -= remain;\n\n\tmemcpy(tmp->buffer, data, datlen);\n\ttmp->off = datlen;\n\tevbuffer_chain_insert(buf, tmp);\n\tbuf->n_add_for_cb += datlen;\n\nout:\n\tevbuffer_invoke_callbacks(buf);\n\tresult = 0;\ndone:\n\tEVBUFFER_UNLOCK(buf);\n\treturn result;\n}", "func_hash": 254277473596800240289874509618169928560, "file_name": "buffer.c", "file_hash": 60763147300788492626298407117311819637, "cwe": ["CWE-189"], "cve": "CVE-2014-6272", "cve_desc": "Multiple integer overflows in the evbuffer API in Libevent 1.4.x before 1.4.15, 2.0.x before 2.0.22, and 2.1.x before 2.1.5-beta allow context-dependent attackers to cause a denial of service or possibly have other unspecified impact via \"insanely large inputs\" to the (1) evbuffer_add, (2) evbuffer_expand, or (3) bufferevent_write function, which triggers a heap-based buffer overflow or an infinite loop. NOTE: this identifier has been SPLIT per ADT3 due to different affected versions. See CVE-2015-6525 for the functions that are only affected in 2.0 and later.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-6272"} {"idx": 204031, "project": "p11-kit", "commit_id": "69d751ca9df9ac101adfb1e5aa7e83e3358106ba", "project_url": "https://github.com/p11-glue/p11-kit", "commit_url": "https://github.com/p11-glue/p11-kit/commit/69d751ca9df9ac101adfb1e5aa7e83e3358106ba#diff-f91391f1b8084605c5e76b328deabc6dffc1c869408dd62703474e6a75636e67", "commit_message": "Fix bounds check in p11_rpc_buffer_get_byte_array\n\nThis bounds check should be using off, not *offset, because it has been\nadvanced four bytes from reading a uint32 earlier in the function.\nAdditionally, the pointer that is returned is computed using off, not\n*offset.", "target": 1, "func": "p11_rpc_buffer_get_byte_array (p11_buffer *buf,\n size_t *offset,\n const unsigned char **data,\n size_t *length)\n{\n\tsize_t off = *offset;\n\tuint32_t len;\n\tif (!p11_rpc_buffer_get_uint32 (buf, &off, &len))\n\t\treturn false;\n\tif (len == 0xffffffff) {\n\t\t*offset = off;\n\t\tif (data)\n\t\t\t*data = NULL;\n\t\tif (length)\n\t\t\t*length = 0;\n\t\treturn true;\n\t} else if (len >= 0x7fffffff) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (buf->len < len || *offset > buf->len - len) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (data)\n\t\t*data = (unsigned char *)buf->data + off;\n\tif (length)\n\t\t*length = len;\n\t*offset = off + len;\n\n\treturn true;\n}", "func_hash": 69591878142004212733645099974045801999, "file_name": "rpc-message.c", "file_hash": 239379770851171301998106948250778262201, "cwe": ["CWE-125"], "cve": "CVE-2020-29362", "cve_desc": "An issue was discovered in p11-kit 0.21.1 through 0.23.21. A heap-based buffer over-read has been discovered in the RPC protocol used by thep11-kit server/remote commands and the client library. When the remote entity supplies a byte array through a serialized PKCS#11 function call, the receiving entity may allow the reading of up to 4 bytes of memory past the heap allocation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29362"} {"idx": 349479, "project": "p11-kit", "commit_id": "69d751ca9df9ac101adfb1e5aa7e83e3358106ba", "project_url": "https://github.com/p11-glue/p11-kit", "commit_url": "https://github.com/p11-glue/p11-kit/commit/69d751ca9df9ac101adfb1e5aa7e83e3358106ba#diff-f91391f1b8084605c5e76b328deabc6dffc1c869408dd62703474e6a75636e67", "commit_message": "Fix bounds check in p11_rpc_buffer_get_byte_array\n\nThis bounds check should be using off, not *offset, because it has been\nadvanced four bytes from reading a uint32 earlier in the function.\nAdditionally, the pointer that is returned is computed using off, not\n*offset.", "target": 0, "func": "p11_rpc_buffer_get_byte_array (p11_buffer *buf,\n size_t *offset,\n const unsigned char **data,\n size_t *length)\n{\n\tsize_t off = *offset;\n\tuint32_t len;\n\tif (!p11_rpc_buffer_get_uint32 (buf, &off, &len))\n\t\treturn false;\n\tif (len == 0xffffffff) {\n\t\t*offset = off;\n\t\tif (data)\n\t\t\t*data = NULL;\n\t\tif (length)\n\t\t\t*length = 0;\n\t\treturn true;\n\t} else if (len >= 0x7fffffff) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (buf->len < len || off > buf->len - len) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (data)\n\t\t*data = (unsigned char *)buf->data + off;\n\tif (length)\n\t\t*length = len;\n\t*offset = off + len;\n\n\treturn true;\n}", "func_hash": 320328075282752053598271733890822856712, "file_name": "rpc-message.c", "file_hash": 305078838636873668676733828148939508794, "cwe": ["CWE-125"], "cve": "CVE-2020-29362", "cve_desc": "An issue was discovered in p11-kit 0.21.1 through 0.23.21. A heap-based buffer over-read has been discovered in the RPC protocol used by thep11-kit server/remote commands and the client library. When the remote entity supplies a byte array through a serialized PKCS#11 function call, the receiving entity may allow the reading of up to 4 bytes of memory past the heap allocation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29362"} {"idx": 204059, "project": "leptonica", "commit_id": "5ba34b1fe741d69d43a6c8cf767756997eadd87c", "project_url": "https://github.com/DanBloomberg/leptonica", "commit_url": "https://github.com/DanBloomberg/leptonica/commit/5ba34b1fe741d69d43a6c8cf767756997eadd87c", "commit_message": "Issue 23654 in oss-fuzz: Heap-buffer-overflow in pixReadFromTiffStream\n * Increase scanline buffer for reading gray+alpha and converting to RGBA", "target": 1, "func": "pixReadFromTiffStream(TIFF *tif)\n{\nchar *text;\nl_uint8 *linebuf, *data, *rowptr;\nl_uint16 spp, bps, photometry, tiffcomp, orientation, sample_fmt;\nl_uint16 *redmap, *greenmap, *bluemap;\nl_int32 d, wpl, bpl, comptype, i, j, k, ncolors, rval, gval, bval, aval;\nl_int32 xres, yres, tiffbpl, packedbpl, halfsize;\nl_uint32 w, h, tiffword, read_oriented;\nl_uint32 *line, *ppixel, *tiffdata, *pixdata;\nPIX *pix, *pix1;\nPIXCMAP *cmap;\n\n PROCNAME(\"pixReadFromTiffStream\");\n\n if (!tif)\n return (PIX *)ERROR_PTR(\"tif not defined\", procName, NULL);\n\n read_oriented = 0;\n\n /* Only accept uint image data:\n * SAMPLEFORMAT_UINT = 1;\n * SAMPLEFORMAT_INT = 2;\n * SAMPLEFORMAT_IEEEFP = 3;\n * SAMPLEFORMAT_VOID = 4; */\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sample_fmt);\n if (sample_fmt != SAMPLEFORMAT_UINT) {\n L_ERROR(\"sample format = %d is not uint\\n\", procName, sample_fmt);\n return NULL;\n }\n\n /* Can't read tiff in tiled format. For what is involved, see, e.g:\n * https://www.cs.rochester.edu/~nelson/courses/vision/\\\n * resources/tiff/libtiff.html#Tiles\n * A tiled tiff can be converted to a normal (strip) tif:\n * tiffcp -s */\n if (TIFFIsTiled(tif)) {\n L_ERROR(\"tiled format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Old style jpeg is not supported. We tried supporting 8 bpp.\n * TIFFReadScanline() fails on this format, so we used RGBA\n * reading, which generates a 4 spp image, and pulled out the\n * red component. However, there were problems with double-frees\n * in cleanup. For RGB, tiffbpl is exactly half the size that\n * you would expect for the raster data in a scanline, which\n * is 3 * w. */\n TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);\n if (tiffcomp == COMPRESSION_OJPEG) {\n L_ERROR(\"old style jpeg format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Use default fields for bps and spp */\n TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);\n if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16) {\n L_ERROR(\"invalid bps = %d\\n\", procName, bps);\n return NULL;\n }\n if (spp == 2 && bps != 8) {\n L_WARNING(\"for 2 spp, only handle 8 bps\\n\", procName);\n return NULL;\n }\n if (spp == 1)\n d = bps;\n else if (spp == 2) /* gray plus alpha */\n d = 32; /* will convert to RGBA */\n else if (spp == 3 || spp == 4)\n d = 32;\n else\n return (PIX *)ERROR_PTR(\"spp not in set {1,2,3,4}\", procName, NULL);\n\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);\n if (w > MaxTiffWidth) {\n L_ERROR(\"width = %d pixels; too large\\n\", procName, w);\n return NULL;\n }\n if (h > MaxTiffHeight) {\n L_ERROR(\"height = %d pixels; too large\\n\", procName, h);\n return NULL;\n }\n\n /* The relation between the size of a byte buffer required to hold\n a raster of image pixels (packedbpl) and the size of the tiff\n buffer (tiffbuf) is either 1:1 or approximately 2:1, depending\n on how the data is stored and subsampled. Allow some slop\n when validating the relation between buffer size and the image\n parameters w, spp and bps. */\n tiffbpl = TIFFScanlineSize(tif);\n packedbpl = (bps * spp * w + 7) / 8;\n halfsize = L_ABS(2 * tiffbpl - packedbpl) <= 8;\n#if 0\n if (halfsize)\n L_INFO(\"packedbpl = %d is approx. twice tiffbpl = %d\\n\", procName,\n packedbpl, tiffbpl);\n#endif\n if (tiffbpl != packedbpl && !halfsize) {\n L_ERROR(\"invalid tiffbpl: tiffbpl = %d, packedbpl = %d, \"\n \"bps = %d, spp = %d, w = %d\\n\",\n procName, tiffbpl, packedbpl, bps, spp, w);\n return NULL;\n }\n\n if ((pix = pixCreate(w, h, d)) == NULL)\n return (PIX *)ERROR_PTR(\"pix not made\", procName, NULL);\n pixSetInputFormat(pix, IFF_TIFF);\n data = (l_uint8 *)pixGetData(pix);\n wpl = pixGetWpl(pix);\n bpl = 4 * wpl;\n\n if (spp == 1) {\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n memcpy(data, linebuf, tiffbpl);\n data += bpl;\n }\n if (bps <= 8)\n pixEndianByteSwap(pix);\n else /* bps == 16 */\n pixEndianTwoByteSwap(pix);\n LEPT_FREE(linebuf);\n } else if (spp == 2 && bps == 8) { /* gray plus alpha */\n L_INFO(\"gray+alpha is not supported; converting to RGBA\\n\", procName);\n pixSetSpp(pix, 4);\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n pixdata = pixGetData(pix);\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n rowptr = linebuf;\n ppixel = pixdata + i * wpl;\n for (j = k = 0; j < w; j++) {\n /* Copy gray value into r, g and b */\n SET_DATA_BYTE(ppixel, COLOR_RED, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_GREEN, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_BLUE, rowptr[k++]);\n SET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL, rowptr[k++]);\n ppixel++;\n }\n }\n LEPT_FREE(linebuf);\n } else { /* rgb and rgba */\n if ((tiffdata = (l_uint32 *)LEPT_CALLOC((size_t)w * h,\n sizeof(l_uint32))) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"calloc fail for tiffdata\", procName, NULL);\n }\n /* TIFFReadRGBAImageOriented() converts to 8 bps */\n if (!TIFFReadRGBAImageOriented(tif, w, h, tiffdata,\n ORIENTATION_TOPLEFT, 0)) {\n LEPT_FREE(tiffdata);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"failed to read tiffdata\", procName, NULL);\n } else {\n read_oriented = 1;\n }\n\n if (spp == 4) pixSetSpp(pix, 4);\n line = pixGetData(pix);\n for (i = 0; i < h; i++, line += wpl) {\n for (j = 0, ppixel = line; j < w; j++) {\n /* TIFFGet* are macros */\n tiffword = tiffdata[i * w + j];\n rval = TIFFGetR(tiffword);\n gval = TIFFGetG(tiffword);\n bval = TIFFGetB(tiffword);\n if (spp == 3) {\n composeRGBPixel(rval, gval, bval, ppixel);\n } else { /* spp == 4 */\n aval = TIFFGetA(tiffword);\n composeRGBAPixel(rval, gval, bval, aval, ppixel);\n }\n ppixel++;\n }\n }\n LEPT_FREE(tiffdata);\n }\n\n if (getTiffStreamResolution(tif, &xres, &yres) == 0) {\n pixSetXRes(pix, xres);\n pixSetYRes(pix, yres);\n }\n\n /* Find and save the compression type */\n comptype = getTiffCompressedFormat(tiffcomp);\n pixSetInputFormat(pix, comptype);\n\n if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) {\n /* Save the colormap as a pix cmap. Because the\n * tiff colormap components are 16 bit unsigned,\n * and go from black (0) to white (0xffff), the\n * the pix cmap takes the most significant byte. */\n if (bps > 8) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap size > 256\", procName, NULL);\n }\n if ((cmap = pixcmapCreate(bps)) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap not made\", procName, NULL);\n }\n ncolors = 1 << bps;\n for (i = 0; i < ncolors; i++)\n pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8,\n bluemap[i] >> 8);\n if (pixSetColormap(pix, cmap)) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"invalid colormap\", procName, NULL);\n }\n\n /* Remove the colormap for 1 bpp. */\n if (bps == 1) {\n pix1 = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC);\n pixDestroy(&pix);\n pix = pix1;\n }\n } else { /* No colormap: check photometry and invert if necessary */\n if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) {\n /* Guess default photometry setting. Assume min_is_white\n * if compressed 1 bpp; min_is_black otherwise. */\n if (tiffcomp == COMPRESSION_CCITTFAX3 ||\n tiffcomp == COMPRESSION_CCITTFAX4 ||\n tiffcomp == COMPRESSION_CCITTRLE ||\n tiffcomp == COMPRESSION_CCITTRLEW) {\n photometry = PHOTOMETRIC_MINISWHITE;\n } else {\n photometry = PHOTOMETRIC_MINISBLACK;\n }\n }\n if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) ||\n (d == 8 && photometry == PHOTOMETRIC_MINISWHITE))\n pixInvert(pix, pix);\n }\n\n if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) {\n if (orientation >= 1 && orientation <= 8) {\n struct tiff_transform *transform = (read_oriented) ?\n &tiff_partial_orientation_transforms[orientation - 1] :\n &tiff_orientation_transforms[orientation - 1];\n if (transform->vflip) pixFlipTB(pix, pix);\n if (transform->hflip) pixFlipLR(pix, pix);\n if (transform->rotate) {\n PIX *oldpix = pix;\n pix = pixRotate90(oldpix, transform->rotate);\n pixDestroy(&oldpix);\n }\n }\n }\n\n text = NULL;\n TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &text);\n if (text) pixSetText(pix, text);\n return pix;\n}", "func_hash": 92760914110904026171508479259933914226, "file_name": "tiffio.c", "file_hash": 83017061318286327052200451724387486655, "cwe": ["CWE-125"], "cve": "CVE-2020-36280", "cve_desc": "Leptonica before 1.80.0 allows a heap-based buffer over-read in pixReadFromTiffStream, related to tiffio.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36280"} {"idx": 350367, "project": "leptonica", "commit_id": "5ba34b1fe741d69d43a6c8cf767756997eadd87c", "project_url": "https://github.com/DanBloomberg/leptonica", "commit_url": "https://github.com/DanBloomberg/leptonica/commit/5ba34b1fe741d69d43a6c8cf767756997eadd87c", "commit_message": "Issue 23654 in oss-fuzz: Heap-buffer-overflow in pixReadFromTiffStream\n * Increase scanline buffer for reading gray+alpha and converting to RGBA", "target": 0, "func": "pixReadFromTiffStream(TIFF *tif)\n{\nchar *text;\nl_uint8 *linebuf, *data, *rowptr;\nl_uint16 spp, bps, photometry, tiffcomp, orientation, sample_fmt;\nl_uint16 *redmap, *greenmap, *bluemap;\nl_int32 d, wpl, bpl, comptype, i, j, k, ncolors, rval, gval, bval, aval;\nl_int32 xres, yres, tiffbpl, packedbpl, halfsize;\nl_uint32 w, h, tiffword, read_oriented;\nl_uint32 *line, *ppixel, *tiffdata, *pixdata;\nPIX *pix, *pix1;\nPIXCMAP *cmap;\n\n PROCNAME(\"pixReadFromTiffStream\");\n\n if (!tif)\n return (PIX *)ERROR_PTR(\"tif not defined\", procName, NULL);\n\n read_oriented = 0;\n\n /* Only accept uint image data:\n * SAMPLEFORMAT_UINT = 1;\n * SAMPLEFORMAT_INT = 2;\n * SAMPLEFORMAT_IEEEFP = 3;\n * SAMPLEFORMAT_VOID = 4; */\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sample_fmt);\n if (sample_fmt != SAMPLEFORMAT_UINT) {\n L_ERROR(\"sample format = %d is not uint\\n\", procName, sample_fmt);\n return NULL;\n }\n\n /* Can't read tiff in tiled format. For what is involved, see, e.g:\n * https://www.cs.rochester.edu/~nelson/courses/vision/\\\n * resources/tiff/libtiff.html#Tiles\n * A tiled tiff can be converted to a normal (strip) tif:\n * tiffcp -s */\n if (TIFFIsTiled(tif)) {\n L_ERROR(\"tiled format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Old style jpeg is not supported. We tried supporting 8 bpp.\n * TIFFReadScanline() fails on this format, so we used RGBA\n * reading, which generates a 4 spp image, and pulled out the\n * red component. However, there were problems with double-frees\n * in cleanup. For RGB, tiffbpl is exactly half the size that\n * you would expect for the raster data in a scanline, which\n * is 3 * w. */\n TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);\n if (tiffcomp == COMPRESSION_OJPEG) {\n L_ERROR(\"old style jpeg format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Use default fields for bps and spp */\n TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);\n if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16) {\n L_ERROR(\"invalid bps = %d\\n\", procName, bps);\n return NULL;\n }\n if (spp == 2 && bps != 8) {\n L_WARNING(\"for 2 spp, only handle 8 bps\\n\", procName);\n return NULL;\n }\n if (spp == 1)\n d = bps;\n else if (spp == 2) /* gray plus alpha */\n d = 32; /* will convert to RGBA */\n else if (spp == 3 || spp == 4)\n d = 32;\n else\n return (PIX *)ERROR_PTR(\"spp not in set {1,2,3,4}\", procName, NULL);\n\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);\n if (w > MaxTiffWidth) {\n L_ERROR(\"width = %d pixels; too large\\n\", procName, w);\n return NULL;\n }\n if (h > MaxTiffHeight) {\n L_ERROR(\"height = %d pixels; too large\\n\", procName, h);\n return NULL;\n }\n\n /* The relation between the size of a byte buffer required to hold\n a raster of image pixels (packedbpl) and the size of the tiff\n buffer (tiffbuf) is either 1:1 or approximately 2:1, depending\n on how the data is stored and subsampled. Allow some slop\n when validating the relation between buffer size and the image\n parameters w, spp and bps. */\n tiffbpl = TIFFScanlineSize(tif);\n packedbpl = (bps * spp * w + 7) / 8;\n halfsize = L_ABS(2 * tiffbpl - packedbpl) <= 8;\n#if 0\n if (halfsize)\n L_INFO(\"packedbpl = %d is approx. twice tiffbpl = %d\\n\", procName,\n packedbpl, tiffbpl);\n#endif\n if (tiffbpl != packedbpl && !halfsize) {\n L_ERROR(\"invalid tiffbpl: tiffbpl = %d, packedbpl = %d, \"\n \"bps = %d, spp = %d, w = %d\\n\",\n procName, tiffbpl, packedbpl, bps, spp, w);\n return NULL;\n }\n\n if ((pix = pixCreate(w, h, d)) == NULL)\n return (PIX *)ERROR_PTR(\"pix not made\", procName, NULL);\n pixSetInputFormat(pix, IFF_TIFF);\n data = (l_uint8 *)pixGetData(pix);\n wpl = pixGetWpl(pix);\n bpl = 4 * wpl;\n\n if (spp == 1) {\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n memcpy(data, linebuf, tiffbpl);\n data += bpl;\n }\n if (bps <= 8)\n pixEndianByteSwap(pix);\n else /* bps == 16 */\n pixEndianTwoByteSwap(pix);\n LEPT_FREE(linebuf);\n } else if (spp == 2 && bps == 8) { /* gray plus alpha */\n L_INFO(\"gray+alpha is not supported; converting to RGBA\\n\", procName);\n pixSetSpp(pix, 4);\n linebuf = (l_uint8 *)LEPT_CALLOC(2 * tiffbpl + 1, sizeof(l_uint8));\n pixdata = pixGetData(pix);\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n rowptr = linebuf;\n ppixel = pixdata + i * wpl;\n for (j = k = 0; j < w; j++) {\n /* Copy gray value into r, g and b */\n SET_DATA_BYTE(ppixel, COLOR_RED, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_GREEN, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_BLUE, rowptr[k++]);\n SET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL, rowptr[k++]);\n ppixel++;\n }\n }\n LEPT_FREE(linebuf);\n } else { /* rgb and rgba */\n if ((tiffdata = (l_uint32 *)LEPT_CALLOC((size_t)w * h,\n sizeof(l_uint32))) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"calloc fail for tiffdata\", procName, NULL);\n }\n /* TIFFReadRGBAImageOriented() converts to 8 bps */\n if (!TIFFReadRGBAImageOriented(tif, w, h, tiffdata,\n ORIENTATION_TOPLEFT, 0)) {\n LEPT_FREE(tiffdata);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"failed to read tiffdata\", procName, NULL);\n } else {\n read_oriented = 1;\n }\n\n if (spp == 4) pixSetSpp(pix, 4);\n line = pixGetData(pix);\n for (i = 0; i < h; i++, line += wpl) {\n for (j = 0, ppixel = line; j < w; j++) {\n /* TIFFGet* are macros */\n tiffword = tiffdata[i * w + j];\n rval = TIFFGetR(tiffword);\n gval = TIFFGetG(tiffword);\n bval = TIFFGetB(tiffword);\n if (spp == 3) {\n composeRGBPixel(rval, gval, bval, ppixel);\n } else { /* spp == 4 */\n aval = TIFFGetA(tiffword);\n composeRGBAPixel(rval, gval, bval, aval, ppixel);\n }\n ppixel++;\n }\n }\n LEPT_FREE(tiffdata);\n }\n\n if (getTiffStreamResolution(tif, &xres, &yres) == 0) {\n pixSetXRes(pix, xres);\n pixSetYRes(pix, yres);\n }\n\n /* Find and save the compression type */\n comptype = getTiffCompressedFormat(tiffcomp);\n pixSetInputFormat(pix, comptype);\n\n if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) {\n /* Save the colormap as a pix cmap. Because the\n * tiff colormap components are 16 bit unsigned,\n * and go from black (0) to white (0xffff), the\n * the pix cmap takes the most significant byte. */\n if (bps > 8) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap size > 256\", procName, NULL);\n }\n if ((cmap = pixcmapCreate(bps)) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap not made\", procName, NULL);\n }\n ncolors = 1 << bps;\n for (i = 0; i < ncolors; i++)\n pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8,\n bluemap[i] >> 8);\n if (pixSetColormap(pix, cmap)) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"invalid colormap\", procName, NULL);\n }\n\n /* Remove the colormap for 1 bpp. */\n if (bps == 1) {\n pix1 = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC);\n pixDestroy(&pix);\n pix = pix1;\n }\n } else { /* No colormap: check photometry and invert if necessary */\n if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) {\n /* Guess default photometry setting. Assume min_is_white\n * if compressed 1 bpp; min_is_black otherwise. */\n if (tiffcomp == COMPRESSION_CCITTFAX3 ||\n tiffcomp == COMPRESSION_CCITTFAX4 ||\n tiffcomp == COMPRESSION_CCITTRLE ||\n tiffcomp == COMPRESSION_CCITTRLEW) {\n photometry = PHOTOMETRIC_MINISWHITE;\n } else {\n photometry = PHOTOMETRIC_MINISBLACK;\n }\n }\n if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) ||\n (d == 8 && photometry == PHOTOMETRIC_MINISWHITE))\n pixInvert(pix, pix);\n }\n\n if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) {\n if (orientation >= 1 && orientation <= 8) {\n struct tiff_transform *transform = (read_oriented) ?\n &tiff_partial_orientation_transforms[orientation - 1] :\n &tiff_orientation_transforms[orientation - 1];\n if (transform->vflip) pixFlipTB(pix, pix);\n if (transform->hflip) pixFlipLR(pix, pix);\n if (transform->rotate) {\n PIX *oldpix = pix;\n pix = pixRotate90(oldpix, transform->rotate);\n pixDestroy(&oldpix);\n }\n }\n }\n\n text = NULL;\n TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &text);\n if (text) pixSetText(pix, text);\n return pix;\n}", "func_hash": 230107247668638228748517086369896339381, "file_name": "tiffio.c", "file_hash": 154258430817453431857791044149734148809, "cwe": ["CWE-125"], "cve": "CVE-2020-36280", "cve_desc": "Leptonica before 1.80.0 allows a heap-based buffer over-read in pixReadFromTiffStream, related to tiffio.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36280"} {"idx": 204147, "project": "linux", "commit_id": "cb222aed03d798fc074be55e59d9a112338ee784", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/cb222aed03d798fc074be55e59d9a112338ee784", "commit_message": "Input: add safety guards to input_set_keycode()\n\nIf we happen to have a garbage in input device's keycode table with values\ntoo big we'll end up doing clear_bit() with offset way outside of our\nbitmaps, damaging other objects within an input device or even outside of\nit. Let's add sanity checks to the returned old keycodes.\n\nReported-by: syzbot+c769968809f9359b07aa@syzkaller.appspotmail.com\nReported-by: syzbot+76f3a30e88d256644c78@syzkaller.appspotmail.com\nLink: https://lore.kernel.org/r/20191207212757.GA245964@dtor-ws\nSigned-off-by: Dmitry Torokhov ", "target": 1, "func": "int input_set_keycode(struct input_dev *dev,\n\t\t const struct input_keymap_entry *ke)\n{\n\tunsigned long flags;\n\tunsigned int old_keycode;\n\tint retval;\n\n\tif (ke->keycode > KEY_MAX)\n\t\treturn -EINVAL;\n\n\tspin_lock_irqsave(&dev->event_lock, flags);\n\n\tretval = dev->setkeycode(dev, ke, &old_keycode);\n\tif (retval)\n\t\tgoto out;\n\n\t/* Make sure KEY_RESERVED did not get enabled. */\n\t__clear_bit(KEY_RESERVED, dev->keybit);\n\n\t/*\n\t * Simulate keyup event if keycode is not present\n\t * in the keymap anymore\n\t */\n\tif (test_bit(EV_KEY, dev->evbit) &&\n\t !is_event_supported(old_keycode, dev->keybit, KEY_MAX) &&\n\t __test_and_clear_bit(old_keycode, dev->key)) {\n\t\tstruct input_value vals[] = {\n\t\t\t{ EV_KEY, old_keycode, 0 },\n\t\t\tinput_value_sync\n\t\t};\n\n\t\tinput_pass_values(dev, vals, ARRAY_SIZE(vals));\n\t}\n\n out:\n\tspin_unlock_irqrestore(&dev->event_lock, flags);\n\n\treturn retval;\n}", "func_hash": 91024855980652304402428037587277765279, "file_name": "input.c", "file_hash": 225127408911810491553095208704712324623, "cwe": ["CWE-703"], "cve": "CVE-2019-20636", "cve_desc": "In the Linux kernel before 5.4.12, drivers/input/input.c has out-of-bounds writes via a crafted keycode table, as demonstrated by input_set_keycode, aka CID-cb222aed03d7.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20636"} {"idx": 353362, "project": "linux", "commit_id": "cb222aed03d798fc074be55e59d9a112338ee784", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/cb222aed03d798fc074be55e59d9a112338ee784", "commit_message": "Input: add safety guards to input_set_keycode()\n\nIf we happen to have a garbage in input device's keycode table with values\ntoo big we'll end up doing clear_bit() with offset way outside of our\nbitmaps, damaging other objects within an input device or even outside of\nit. Let's add sanity checks to the returned old keycodes.\n\nReported-by: syzbot+c769968809f9359b07aa@syzkaller.appspotmail.com\nReported-by: syzbot+76f3a30e88d256644c78@syzkaller.appspotmail.com\nLink: https://lore.kernel.org/r/20191207212757.GA245964@dtor-ws\nSigned-off-by: Dmitry Torokhov ", "target": 0, "func": "int input_set_keycode(struct input_dev *dev,\n\t\t const struct input_keymap_entry *ke)\n{\n\tunsigned long flags;\n\tunsigned int old_keycode;\n\tint retval;\n\n\tif (ke->keycode > KEY_MAX)\n\t\treturn -EINVAL;\n\n\tspin_lock_irqsave(&dev->event_lock, flags);\n\n\tretval = dev->setkeycode(dev, ke, &old_keycode);\n\tif (retval)\n\t\tgoto out;\n\n\t/* Make sure KEY_RESERVED did not get enabled. */\n\t__clear_bit(KEY_RESERVED, dev->keybit);\n\n\t/*\n\t * Simulate keyup event if keycode is not present\n\t * in the keymap anymore\n\t */\n\tif (old_keycode > KEY_MAX) {\n\t\tdev_warn(dev->dev.parent ?: &dev->dev,\n\t\t\t \"%s: got too big old keycode %#x\\n\",\n\t\t\t __func__, old_keycode);\n\t} else if (test_bit(EV_KEY, dev->evbit) &&\n\t\t !is_event_supported(old_keycode, dev->keybit, KEY_MAX) &&\n\t\t __test_and_clear_bit(old_keycode, dev->key)) {\n\t\tstruct input_value vals[] = {\n\t\t\t{ EV_KEY, old_keycode, 0 },\n\t\t\tinput_value_sync\n\t\t};\n\n\t\tinput_pass_values(dev, vals, ARRAY_SIZE(vals));\n\t}\n\n out:\n\tspin_unlock_irqrestore(&dev->event_lock, flags);\n\n\treturn retval;\n}", "func_hash": 158267801833710173885734518885383698523, "file_name": "input.c", "file_hash": 25533660993263468568832235927135315256, "cwe": ["CWE-703"], "cve": "CVE-2019-20636", "cve_desc": "In the Linux kernel before 5.4.12, drivers/input/input.c has out-of-bounds writes via a crafted keycode table, as demonstrated by input_set_keycode, aka CID-cb222aed03d7.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20636"} {"idx": 204189, "project": "linux", "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0774a964ef561b7170d8d1b1bfe6f88002b6d219", "commit_message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 1, "func": "static int kvm_s390_get_cmma(struct kvm *kvm, struct kvm_s390_cmma_log *args,\n\t\t\t u8 *res, unsigned long bufsize)\n{\n\tunsigned long mem_end, cur_gfn, next_gfn, hva, pgstev;\n\tstruct kvm_memslots *slots = kvm_memslots(kvm);\n\tstruct kvm_memory_slot *ms;\n\n\tcur_gfn = kvm_s390_next_dirty_cmma(slots, args->start_gfn);\n\tms = gfn_to_memslot(kvm, cur_gfn);\n\targs->count = 0;\n\targs->start_gfn = cur_gfn;\n\tif (!ms)\n\t\treturn 0;\n\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\tmem_end = slots->memslots[0].base_gfn + slots->memslots[0].npages;\n\n\twhile (args->count < bufsize) {\n\t\thva = gfn_to_hva(kvm, cur_gfn);\n\t\tif (kvm_is_error_hva(hva))\n\t\t\treturn 0;\n\t\t/* Decrement only if we actually flipped the bit to 0 */\n\t\tif (test_and_clear_bit(cur_gfn - ms->base_gfn, kvm_second_dirty_bitmap(ms)))\n\t\t\tatomic64_dec(&kvm->arch.cmma_dirty_pages);\n\t\tif (get_pgste(kvm->mm, hva, &pgstev) < 0)\n\t\t\tpgstev = 0;\n\t\t/* Save the value */\n\t\tres[args->count++] = (pgstev >> 24) & 0x43;\n\t\t/* If the next bit is too far away, stop. */\n\t\tif (next_gfn > cur_gfn + KVM_S390_MAX_BIT_DISTANCE)\n\t\t\treturn 0;\n\t\t/* If we reached the previous \"next\", find the next one */\n\t\tif (cur_gfn == next_gfn)\n\t\t\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\t\t/* Reached the end of memory or of the buffer, stop */\n\t\tif ((next_gfn >= mem_end) ||\n\t\t (next_gfn - args->start_gfn >= bufsize))\n\t\t\treturn 0;\n\t\tcur_gfn++;\n\t\t/* Reached the end of the current memslot, take the next one. */\n\t\tif (cur_gfn - ms->base_gfn >= ms->npages) {\n\t\t\tms = gfn_to_memslot(kvm, cur_gfn);\n\t\t\tif (!ms)\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}", "func_hash": 44826651134105184008838870911558629571, "file_name": "kvm-s390.c", "file_hash": 27454589135521123532587932199910957919, "cwe": ["CWE-416"], "cve": "CVE-2020-36313", "cve_desc": "An issue was discovered in the Linux kernel before 5.7. The KVM subsystem allows out-of-range access to memslots after a deletion, aka CID-0774a964ef56. This affects arch/s390/kvm/kvm-s390.c, include/linux/kvm_host.h, and virt/kvm/kvm_main.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36313"} {"idx": 354690, "project": "linux", "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0774a964ef561b7170d8d1b1bfe6f88002b6d219", "commit_message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 0, "func": "static int kvm_s390_get_cmma(struct kvm *kvm, struct kvm_s390_cmma_log *args,\n\t\t\t u8 *res, unsigned long bufsize)\n{\n\tunsigned long mem_end, cur_gfn, next_gfn, hva, pgstev;\n\tstruct kvm_memslots *slots = kvm_memslots(kvm);\n\tstruct kvm_memory_slot *ms;\n\n\tif (unlikely(!slots->used_slots))\n\t\treturn 0;\n\n\tcur_gfn = kvm_s390_next_dirty_cmma(slots, args->start_gfn);\n\tms = gfn_to_memslot(kvm, cur_gfn);\n\targs->count = 0;\n\targs->start_gfn = cur_gfn;\n\tif (!ms)\n\t\treturn 0;\n\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\tmem_end = slots->memslots[0].base_gfn + slots->memslots[0].npages;\n\n\twhile (args->count < bufsize) {\n\t\thva = gfn_to_hva(kvm, cur_gfn);\n\t\tif (kvm_is_error_hva(hva))\n\t\t\treturn 0;\n\t\t/* Decrement only if we actually flipped the bit to 0 */\n\t\tif (test_and_clear_bit(cur_gfn - ms->base_gfn, kvm_second_dirty_bitmap(ms)))\n\t\t\tatomic64_dec(&kvm->arch.cmma_dirty_pages);\n\t\tif (get_pgste(kvm->mm, hva, &pgstev) < 0)\n\t\t\tpgstev = 0;\n\t\t/* Save the value */\n\t\tres[args->count++] = (pgstev >> 24) & 0x43;\n\t\t/* If the next bit is too far away, stop. */\n\t\tif (next_gfn > cur_gfn + KVM_S390_MAX_BIT_DISTANCE)\n\t\t\treturn 0;\n\t\t/* If we reached the previous \"next\", find the next one */\n\t\tif (cur_gfn == next_gfn)\n\t\t\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\t\t/* Reached the end of memory or of the buffer, stop */\n\t\tif ((next_gfn >= mem_end) ||\n\t\t (next_gfn - args->start_gfn >= bufsize))\n\t\t\treturn 0;\n\t\tcur_gfn++;\n\t\t/* Reached the end of the current memslot, take the next one. */\n\t\tif (cur_gfn - ms->base_gfn >= ms->npages) {\n\t\t\tms = gfn_to_memslot(kvm, cur_gfn);\n\t\t\tif (!ms)\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}", "func_hash": 67871706334924386479221442732996654591, "file_name": "kvm-s390.c", "file_hash": 274908678656843506920587415247714571063, "cwe": ["CWE-416"], "cve": "CVE-2020-36313", "cve_desc": "An issue was discovered in the Linux kernel before 5.7. The KVM subsystem allows out-of-range access to memslots after a deletion, aka CID-0774a964ef56. This affects arch/s390/kvm/kvm-s390.c, include/linux/kvm_host.h, and virt/kvm/kvm_main.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36313"} {"idx": 204190, "project": "linux", "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0774a964ef561b7170d8d1b1bfe6f88002b6d219", "commit_message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 1, "func": "static inline void kvm_memslot_delete(struct kvm_memslots *slots,\n\t\t\t\t struct kvm_memory_slot *memslot)\n{\n\tstruct kvm_memory_slot *mslots = slots->memslots;\n\tint i;\n\n\tif (WARN_ON(slots->id_to_index[memslot->id] == -1))\n\t\treturn;\n\n\tslots->used_slots--;\n\n\tfor (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {\n\t\tmslots[i] = mslots[i + 1];\n\t\tslots->id_to_index[mslots[i].id] = i;\n\t}\n\tmslots[i] = *memslot;\n\tslots->id_to_index[memslot->id] = -1;\n}", "func_hash": 85517350581815341586256942650801879575, "file_name": "kvm_main.c", "file_hash": 148756822660729870289743004390888300524, "cwe": ["CWE-416"], "cve": "CVE-2020-36313", "cve_desc": "An issue was discovered in the Linux kernel before 5.7. The KVM subsystem allows out-of-range access to memslots after a deletion, aka CID-0774a964ef56. This affects arch/s390/kvm/kvm-s390.c, include/linux/kvm_host.h, and virt/kvm/kvm_main.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36313"} {"idx": 354527, "project": "linux", "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0774a964ef561b7170d8d1b1bfe6f88002b6d219", "commit_message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 0, "func": "static inline void kvm_memslot_delete(struct kvm_memslots *slots,\n\t\t\t\t struct kvm_memory_slot *memslot)\n{\n\tstruct kvm_memory_slot *mslots = slots->memslots;\n\tint i;\n\n\tif (WARN_ON(slots->id_to_index[memslot->id] == -1))\n\t\treturn;\n\n\tslots->used_slots--;\n\n\tif (atomic_read(&slots->lru_slot) >= slots->used_slots)\n\t\tatomic_set(&slots->lru_slot, 0);\n\n\tfor (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {\n\t\tmslots[i] = mslots[i + 1];\n\t\tslots->id_to_index[mslots[i].id] = i;\n\t}\n\tmslots[i] = *memslot;\n\tslots->id_to_index[memslot->id] = -1;\n}", "func_hash": 138452985850951254794639053427061151091, "file_name": "kvm_main.c", "file_hash": 103948528607694430587327221155945049934, "cwe": ["CWE-416"], "cve": "CVE-2020-36313", "cve_desc": "An issue was discovered in the Linux kernel before 5.7. The KVM subsystem allows out-of-range access to memslots after a deletion, aka CID-0774a964ef56. This affects arch/s390/kvm/kvm-s390.c, include/linux/kvm_host.h, and virt/kvm/kvm_main.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36313"} {"idx": 204191, "project": "linux", "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0774a964ef561b7170d8d1b1bfe6f88002b6d219", "commit_message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 1, "func": "search_memslots(struct kvm_memslots *slots, gfn_t gfn)\n{\n\tint start = 0, end = slots->used_slots;\n\tint slot = atomic_read(&slots->lru_slot);\n\tstruct kvm_memory_slot *memslots = slots->memslots;\n\n\tif (gfn >= memslots[slot].base_gfn &&\n\t gfn < memslots[slot].base_gfn + memslots[slot].npages)\n\t\treturn &memslots[slot];\n\n\twhile (start < end) {\n\t\tslot = start + (end - start) / 2;\n\n\t\tif (gfn >= memslots[slot].base_gfn)\n\t\t\tend = slot;\n\t\telse\n\t\t\tstart = slot + 1;\n\t}\n\n\tif (gfn >= memslots[start].base_gfn &&\n\t gfn < memslots[start].base_gfn + memslots[start].npages) {\n\t\tatomic_set(&slots->lru_slot, start);\n\t\treturn &memslots[start];\n\t}\n\n\treturn NULL;\n}", "func_hash": 30438556611494884449840011200874365385, "file_name": "kvm_host.h", "file_hash": 106379722539628835681382557954112403194, "cwe": ["CWE-416"], "cve": "CVE-2020-36313", "cve_desc": "An issue was discovered in the Linux kernel before 5.7. The KVM subsystem allows out-of-range access to memslots after a deletion, aka CID-0774a964ef56. This affects arch/s390/kvm/kvm-s390.c, include/linux/kvm_host.h, and virt/kvm/kvm_main.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36313"} {"idx": 354422, "project": "linux", "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0774a964ef561b7170d8d1b1bfe6f88002b6d219", "commit_message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 0, "func": "search_memslots(struct kvm_memslots *slots, gfn_t gfn)\n{\n\tint start = 0, end = slots->used_slots;\n\tint slot = atomic_read(&slots->lru_slot);\n\tstruct kvm_memory_slot *memslots = slots->memslots;\n\n\tif (unlikely(!slots->used_slots))\n\t\treturn NULL;\n\n\tif (gfn >= memslots[slot].base_gfn &&\n\t gfn < memslots[slot].base_gfn + memslots[slot].npages)\n\t\treturn &memslots[slot];\n\n\twhile (start < end) {\n\t\tslot = start + (end - start) / 2;\n\n\t\tif (gfn >= memslots[slot].base_gfn)\n\t\t\tend = slot;\n\t\telse\n\t\t\tstart = slot + 1;\n\t}\n\n\tif (gfn >= memslots[start].base_gfn &&\n\t gfn < memslots[start].base_gfn + memslots[start].npages) {\n\t\tatomic_set(&slots->lru_slot, start);\n\t\treturn &memslots[start];\n\t}\n\n\treturn NULL;\n}", "func_hash": 53399243438294283478019164927157028421, "file_name": "kvm_host.h", "file_hash": 318479034002452728449371899455627196005, "cwe": ["CWE-416"], "cve": "CVE-2020-36313", "cve_desc": "An issue was discovered in the Linux kernel before 5.7. The KVM subsystem allows out-of-range access to memslots after a deletion, aka CID-0774a964ef56. This affects arch/s390/kvm/kvm-s390.c, include/linux/kvm_host.h, and virt/kvm/kvm_main.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36313"} {"idx": 204216, "project": "libfuse", "commit_id": "5018a0c016495155ee598b7e0167b43d5d902414", "project_url": "https://github.com/libfuse/libfuse", "commit_url": "https://github.com/libfuse/libfuse/commit/5018a0c016495155ee598b7e0167b43d5d902414", "commit_message": "fusermount: refuse unknown options\n\nBlacklists are notoriously fragile; especially if the kernel wishes to add\nsome security-critical mount option at a later date, all existing systems\nwith older versions of fusermount installed will suddenly have a security\nproblem.\nAdditionally, if the kernel's option parsing became a tiny bit laxer, the\nblacklist could probably be bypassed.\n\nWhitelist known-harmless flags instead, even if it's slightly more\ninconvenient.", "target": 1, "func": "static int do_mount(const char *mnt, char **typep, mode_t rootmode,\n\t\t int fd, const char *opts, const char *dev, char **sourcep,\n\t\t char **mnt_optsp)\n{\n\tint res;\n\tint flags = MS_NOSUID | MS_NODEV;\n\tchar *optbuf;\n\tchar *mnt_opts = NULL;\n\tconst char *s;\n\tchar *d;\n\tchar *fsname = NULL;\n\tchar *subtype = NULL;\n\tchar *source = NULL;\n\tchar *type = NULL;\n\tint blkdev = 0;\n\n\toptbuf = (char *) malloc(strlen(opts) + 128);\n\tif (!optbuf) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\treturn -1;\n\t}\n\n\tfor (s = opts, d = optbuf; *s;) {\n\t\tunsigned len;\n\t\tconst char *fsname_str = \"fsname=\";\n\t\tconst char *subtype_str = \"subtype=\";\n\t\tbool escape_ok = begins_with(s, fsname_str) ||\n\t\t\t\t begins_with(s, subtype_str);\n\t\tfor (len = 0; s[len]; len++) {\n\t\t\tif (escape_ok && s[len] == '\\\\' && s[len + 1])\n\t\t\t\tlen++;\n\t\t\telse if (s[len] == ',')\n\t\t\t\tbreak;\n\t\t}\n\t\tif (begins_with(s, fsname_str)) {\n\t\t\tif (!get_string_opt(s, len, fsname_str, &fsname))\n\t\t\t\tgoto err;\n\t\t} else if (begins_with(s, subtype_str)) {\n\t\t\tif (!get_string_opt(s, len, subtype_str, &subtype))\n\t\t\t\tgoto err;\n\t\t} else if (opt_eq(s, len, \"blkdev\")) {\n\t\t\tif (getuid() != 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"%s: option blkdev is privileged\\n\",\n\t\t\t\t\tprogname);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tblkdev = 1;\n\t\t} else if (opt_eq(s, len, \"auto_unmount\")) {\n\t\t\tauto_unmount = 1;\n\t\t} else if (!begins_with(s, \"fd=\") &&\n\t\t\t !begins_with(s, \"rootmode=\") &&\n\t\t\t !begins_with(s, \"user_id=\") &&\n\t\t\t !begins_with(s, \"group_id=\")) {\n\t\t\tint on;\n\t\t\tint flag;\n\t\t\tint skip_option = 0;\n\t\t\tif (opt_eq(s, len, \"large_read\")) {\n\t\t\t\tstruct utsname utsname;\n\t\t\t\tunsigned kmaj, kmin;\n\t\t\t\tres = uname(&utsname);\n\t\t\t\tif (res == 0 &&\n\t\t\t\t sscanf(utsname.release, \"%u.%u\",\n\t\t\t\t\t &kmaj, &kmin) == 2 &&\n\t\t\t\t (kmaj > 2 || (kmaj == 2 && kmin > 4))) {\n\t\t\t\t\tfprintf(stderr, \"%s: note: 'large_read' mount option is deprecated for %i.%i kernels\\n\", progname, kmaj, kmin);\n\t\t\t\t\tskip_option = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (getuid() != 0 && !user_allow_other &&\n\t\t\t (opt_eq(s, len, \"allow_other\") ||\n\t\t\t opt_eq(s, len, \"allow_root\"))) {\n\t\t\t\tfprintf(stderr, \"%s: option %.*s only allowed if 'user_allow_other' is set in %s\\n\", progname, len, s, FUSE_CONF);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif (!skip_option) {\n\t\t\t\tif (find_mount_flag(s, len, &on, &flag)) {\n\t\t\t\t\tif (on)\n\t\t\t\t\t\tflags |= flag;\n\t\t\t\t\telse\n\t\t\t\t\t\tflags &= ~flag;\n\t\t\t\t} else {\n\t\t\t\t\tmemcpy(d, s, len);\n\t\t\t\t\td += len;\n\t\t\t\t\t*d++ = ',';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ts += len;\n\t\tif (*s)\n\t\t\ts++;\n\t}\n\t*d = '\\0';\n\tres = get_mnt_opts(flags, optbuf, &mnt_opts);\n\tif (res == -1)\n\t\tgoto err;\n\n\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u,group_id=%u\",\n\t\tfd, rootmode, getuid(), getgid());\n\n\tsource = malloc((fsname ? strlen(fsname) : 0) +\n\t\t\t(subtype ? strlen(subtype) : 0) + strlen(dev) + 32);\n\n\ttype = malloc((subtype ? strlen(subtype) : 0) + 32);\n\tif (!type || !source) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\tgoto err;\n\t}\n\n\tif (subtype)\n\t\tsprintf(type, \"%s.%s\", blkdev ? \"fuseblk\" : \"fuse\", subtype);\n\telse\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\n\tif (fsname)\n\t\tstrcpy(source, fsname);\n\telse\n\t\tstrcpy(source, subtype ? subtype : dev);\n\n\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\tif (res == -1 && errno == ENODEV && subtype) {\n\t\t/* Probably missing subtype support */\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\t\tif (fsname) {\n\t\t\tif (!blkdev)\n\t\t\t\tsprintf(source, \"%s#%s\", subtype, fsname);\n\t\t} else {\n\t\t\tstrcpy(source, type);\n\t\t}\n\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1 && errno == EINVAL) {\n\t\t/* It could be an old version not supporting group_id */\n\t\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u\",\n\t\t\tfd, rootmode, getuid());\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1) {\n\t\tint errno_save = errno;\n\t\tif (blkdev && errno == ENODEV && !fuse_mnt_check_fuseblk())\n\t\t\tfprintf(stderr, \"%s: 'fuseblk' support missing\\n\",\n\t\t\t\tprogname);\n\t\telse\n\t\t\tfprintf(stderr, \"%s: mount failed: %s\\n\", progname,\n\t\t\t\tstrerror(errno_save));\n\t\tgoto err;\n\t}\n\t*sourcep = source;\n\t*typep = type;\n\t*mnt_optsp = mnt_opts;\n\tfree(fsname);\n\tfree(optbuf);\n\n\treturn 0;\n\nerr:\n\tfree(fsname);\n\tfree(subtype);\n\tfree(source);\n\tfree(type);\n\tfree(mnt_opts);\n\tfree(optbuf);\n\treturn -1;\n}", "func_hash": 110205972093822928720874404143078303739, "file_name": "None", "file_hash": null, "cwe": ["CWE-269"], "cve": "CVE-2018-10906", "cve_desc": "In fuse before versions 2.9.8 and 3.x before 3.2.5, fusermount is vulnerable to a restriction bypass when SELinux is active. This allows non-root users to mount a FUSE file system with the 'allow_other' mount option regardless of whether 'user_allow_other' is set in the fuse configuration. An attacker may use this flaw to mount a FUSE file system, accessible by other users, and trick them into accessing files on that file system, possibly causing Denial of Service or other unspecified effects.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-10906"} {"idx": 355497, "project": "libfuse", "commit_id": "5018a0c016495155ee598b7e0167b43d5d902414", "project_url": "https://github.com/libfuse/libfuse", "commit_url": "https://github.com/libfuse/libfuse/commit/5018a0c016495155ee598b7e0167b43d5d902414", "commit_message": "fusermount: refuse unknown options\n\nBlacklists are notoriously fragile; especially if the kernel wishes to add\nsome security-critical mount option at a later date, all existing systems\nwith older versions of fusermount installed will suddenly have a security\nproblem.\nAdditionally, if the kernel's option parsing became a tiny bit laxer, the\nblacklist could probably be bypassed.\n\nWhitelist known-harmless flags instead, even if it's slightly more\ninconvenient.", "target": 0, "func": "static int do_mount(const char *mnt, char **typep, mode_t rootmode,\n\t\t int fd, const char *opts, const char *dev, char **sourcep,\n\t\t char **mnt_optsp)\n{\n\tint res;\n\tint flags = MS_NOSUID | MS_NODEV;\n\tchar *optbuf;\n\tchar *mnt_opts = NULL;\n\tconst char *s;\n\tchar *d;\n\tchar *fsname = NULL;\n\tchar *subtype = NULL;\n\tchar *source = NULL;\n\tchar *type = NULL;\n\tint blkdev = 0;\n\n\toptbuf = (char *) malloc(strlen(opts) + 128);\n\tif (!optbuf) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\treturn -1;\n\t}\n\n\tfor (s = opts, d = optbuf; *s;) {\n\t\tunsigned len;\n\t\tconst char *fsname_str = \"fsname=\";\n\t\tconst char *subtype_str = \"subtype=\";\n\t\tbool escape_ok = begins_with(s, fsname_str) ||\n\t\t\t\t begins_with(s, subtype_str);\n\t\tfor (len = 0; s[len]; len++) {\n\t\t\tif (escape_ok && s[len] == '\\\\' && s[len + 1])\n\t\t\t\tlen++;\n\t\t\telse if (s[len] == ',')\n\t\t\t\tbreak;\n\t\t}\n\t\tif (begins_with(s, fsname_str)) {\n\t\t\tif (!get_string_opt(s, len, fsname_str, &fsname))\n\t\t\t\tgoto err;\n\t\t} else if (begins_with(s, subtype_str)) {\n\t\t\tif (!get_string_opt(s, len, subtype_str, &subtype))\n\t\t\t\tgoto err;\n\t\t} else if (opt_eq(s, len, \"blkdev\")) {\n\t\t\tif (getuid() != 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"%s: option blkdev is privileged\\n\",\n\t\t\t\t\tprogname);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tblkdev = 1;\n\t\t} else if (opt_eq(s, len, \"auto_unmount\")) {\n\t\t\tauto_unmount = 1;\n\t\t} else if (!begins_with(s, \"fd=\") &&\n\t\t\t !begins_with(s, \"rootmode=\") &&\n\t\t\t !begins_with(s, \"user_id=\") &&\n\t\t\t !begins_with(s, \"group_id=\")) {\n\t\t\tint on;\n\t\t\tint flag;\n\t\t\tint skip_option = 0;\n\t\t\tif (opt_eq(s, len, \"large_read\")) {\n\t\t\t\tstruct utsname utsname;\n\t\t\t\tunsigned kmaj, kmin;\n\t\t\t\tres = uname(&utsname);\n\t\t\t\tif (res == 0 &&\n\t\t\t\t sscanf(utsname.release, \"%u.%u\",\n\t\t\t\t\t &kmaj, &kmin) == 2 &&\n\t\t\t\t (kmaj > 2 || (kmaj == 2 && kmin > 4))) {\n\t\t\t\t\tfprintf(stderr, \"%s: note: 'large_read' mount option is deprecated for %i.%i kernels\\n\", progname, kmaj, kmin);\n\t\t\t\t\tskip_option = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (getuid() != 0 && !user_allow_other &&\n\t\t\t (opt_eq(s, len, \"allow_other\") ||\n\t\t\t opt_eq(s, len, \"allow_root\"))) {\n\t\t\t\tfprintf(stderr, \"%s: option %.*s only allowed if 'user_allow_other' is set in %s\\n\", progname, len, s, FUSE_CONF);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif (!skip_option) {\n\t\t\t\tif (find_mount_flag(s, len, &on, &flag)) {\n\t\t\t\t\tif (on)\n\t\t\t\t\t\tflags |= flag;\n\t\t\t\t\telse\n\t\t\t\t\t\tflags &= ~flag;\n\t\t\t\t} else if (opt_eq(s, len, \"default_permissions\") ||\n\t\t\t\t\t opt_eq(s, len, \"allow_other\") ||\n\t\t\t\t\t begins_with(s, \"max_read=\") ||\n\t\t\t\t\t begins_with(s, \"blksize=\")) {\n\t\t\t\t\tmemcpy(d, s, len);\n\t\t\t\t\td += len;\n\t\t\t\t\t*d++ = ',';\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"%s: unknown option '%.*s'\\n\", progname, len, s);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ts += len;\n\t\tif (*s)\n\t\t\ts++;\n\t}\n\t*d = '\\0';\n\tres = get_mnt_opts(flags, optbuf, &mnt_opts);\n\tif (res == -1)\n\t\tgoto err;\n\n\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u,group_id=%u\",\n\t\tfd, rootmode, getuid(), getgid());\n\n\tsource = malloc((fsname ? strlen(fsname) : 0) +\n\t\t\t(subtype ? strlen(subtype) : 0) + strlen(dev) + 32);\n\n\ttype = malloc((subtype ? strlen(subtype) : 0) + 32);\n\tif (!type || !source) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\tgoto err;\n\t}\n\n\tif (subtype)\n\t\tsprintf(type, \"%s.%s\", blkdev ? \"fuseblk\" : \"fuse\", subtype);\n\telse\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\n\tif (fsname)\n\t\tstrcpy(source, fsname);\n\telse\n\t\tstrcpy(source, subtype ? subtype : dev);\n\n\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\tif (res == -1 && errno == ENODEV && subtype) {\n\t\t/* Probably missing subtype support */\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\t\tif (fsname) {\n\t\t\tif (!blkdev)\n\t\t\t\tsprintf(source, \"%s#%s\", subtype, fsname);\n\t\t} else {\n\t\t\tstrcpy(source, type);\n\t\t}\n\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1 && errno == EINVAL) {\n\t\t/* It could be an old version not supporting group_id */\n\t\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u\",\n\t\t\tfd, rootmode, getuid());\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1) {\n\t\tint errno_save = errno;\n\t\tif (blkdev && errno == ENODEV && !fuse_mnt_check_fuseblk())\n\t\t\tfprintf(stderr, \"%s: 'fuseblk' support missing\\n\",\n\t\t\t\tprogname);\n\t\telse\n\t\t\tfprintf(stderr, \"%s: mount failed: %s\\n\", progname,\n\t\t\t\tstrerror(errno_save));\n\t\tgoto err;\n\t}\n\t*sourcep = source;\n\t*typep = type;\n\t*mnt_optsp = mnt_opts;\n\tfree(fsname);\n\tfree(optbuf);\n\n\treturn 0;\n\nerr:\n\tfree(fsname);\n\tfree(subtype);\n\tfree(source);\n\tfree(type);\n\tfree(mnt_opts);\n\tfree(optbuf);\n\treturn -1;\n}", "func_hash": 320075556680199479400562750268242493669, "file_name": "None", "file_hash": null, "cwe": ["CWE-269"], "cve": "CVE-2018-10906", "cve_desc": "In fuse before versions 2.9.8 and 3.x before 3.2.5, fusermount is vulnerable to a restriction bypass when SELinux is active. This allows non-root users to mount a FUSE file system with the 'allow_other' mount option regardless of whether 'user_allow_other' is set in the fuse configuration. An attacker may use this flaw to mount a FUSE file system, accessible by other users, and trick them into accessing files on that file system, possibly causing Denial of Service or other unspecified effects.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-10906"} {"idx": 204281, "project": "libxml2", "commit_id": "f0709e3ca8f8947f2d91ed34e92e38a4c23eae63", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://git.gnome.org/browse/libxml2/commit/?id=f0709e3ca8f8947f2d91ed34e92e38a4c23eae63", "commit_message": "CVE-2015-8035 Fix XZ compression support loop\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=757466\nDoS when parsing specially crafted XML document if XZ support\nis compiled in (which wasn't the case for 2.9.2 and master since\nNov 2013, fixed in next commit !)", "target": 1, "func": "xz_decomp(xz_statep state)\n{\n int ret;\n unsigned had;\n unsigned long crc, len;\n lzma_stream *strm = &(state->strm);\n\n lzma_action action = LZMA_RUN;\n\n /* fill output buffer up to end of deflate stream */\n had = strm->avail_out;\n do {\n /* get more input for inflate() */\n if (strm->avail_in == 0 && xz_avail(state) == -1)\n return -1;\n if (strm->avail_in == 0) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (state->eof)\n action = LZMA_FINISH;\n\n /* decompress and handle errors */\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n state->zstrm.avail_in = (uInt) state->strm.avail_in;\n state->zstrm.next_in = (Bytef *) state->strm.next_in;\n state->zstrm.avail_out = (uInt) state->strm.avail_out;\n state->zstrm.next_out = (Bytef *) state->strm.next_out;\n ret = inflate(&state->zstrm, Z_NO_FLUSH);\n if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {\n xz_error(state, Z_STREAM_ERROR,\n \"internal error: inflate stream corrupt\");\n return -1;\n }\n if (ret == Z_MEM_ERROR)\n ret = LZMA_MEM_ERROR;\n if (ret == Z_DATA_ERROR)\n ret = LZMA_DATA_ERROR;\n if (ret == Z_STREAM_END)\n ret = LZMA_STREAM_END;\n state->strm.avail_in = state->zstrm.avail_in;\n state->strm.next_in = state->zstrm.next_in;\n state->strm.avail_out = state->zstrm.avail_out;\n state->strm.next_out = state->zstrm.next_out;\n } else /* state->how == LZMA */\n#endif\n ret = lzma_code(strm, action);\n if (ret == LZMA_MEM_ERROR) {\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n if (ret == LZMA_DATA_ERROR) {\n xz_error(state, LZMA_DATA_ERROR, \"compressed data error\");\n return -1;\n }\n } while (strm->avail_out && ret != LZMA_STREAM_END);\n\n /* update available output and crc check value */\n state->have = had - strm->avail_out;\n state->next = strm->next_out - state->have;\n#ifdef HAVE_ZLIB_H\n state->zstrm.adler =\n crc32(state->zstrm.adler, state->next, state->have);\n#endif\n\n if (ret == LZMA_STREAM_END) {\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (crc != state->zstrm.adler) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect data check\");\n return -1;\n }\n if (len != (state->zstrm.total_out & 0xffffffffL)) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect length check\");\n return -1;\n }\n state->strm.avail_in = 0;\n state->strm.next_in = NULL;\n state->strm.avail_out = 0;\n state->strm.next_out = NULL;\n } else\n#endif\n if (strm->avail_in != 0 || !state->eof) {\n xz_error(state, LZMA_DATA_ERROR, \"trailing garbage\");\n return -1;\n }\n state->how = LOOK; /* ready for next stream, once have is 0 (leave\n * state->direct unchanged to remember how) */\n }\n\n /* good decompression */\n return 0;\n}", "func_hash": 98949320946826255611420079215457140035, "file_name": "xzlib.c", "file_hash": 186131441682702860311049346756703601700, "cwe": ["CWE-399"], "cve": "CVE-2015-8035", "cve_desc": "The xz_decomp function in xzlib.c in libxml2 2.9.1 does not properly detect compression errors, which allows context-dependent attackers to cause a denial of service (process hang) via crafted XML data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-8035"} {"idx": 356273, "project": "libxml2", "commit_id": "f0709e3ca8f8947f2d91ed34e92e38a4c23eae63", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://git.gnome.org/browse/libxml2/commit/?id=f0709e3ca8f8947f2d91ed34e92e38a4c23eae63", "commit_message": "CVE-2015-8035 Fix XZ compression support loop\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=757466\nDoS when parsing specially crafted XML document if XZ support\nis compiled in (which wasn't the case for 2.9.2 and master since\nNov 2013, fixed in next commit !)", "target": 0, "func": "xz_decomp(xz_statep state)\n{\n int ret;\n unsigned had;\n unsigned long crc, len;\n lzma_stream *strm = &(state->strm);\n\n lzma_action action = LZMA_RUN;\n\n /* fill output buffer up to end of deflate stream */\n had = strm->avail_out;\n do {\n /* get more input for inflate() */\n if (strm->avail_in == 0 && xz_avail(state) == -1)\n return -1;\n if (strm->avail_in == 0) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (state->eof)\n action = LZMA_FINISH;\n\n /* decompress and handle errors */\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n state->zstrm.avail_in = (uInt) state->strm.avail_in;\n state->zstrm.next_in = (Bytef *) state->strm.next_in;\n state->zstrm.avail_out = (uInt) state->strm.avail_out;\n state->zstrm.next_out = (Bytef *) state->strm.next_out;\n ret = inflate(&state->zstrm, Z_NO_FLUSH);\n if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {\n xz_error(state, Z_STREAM_ERROR,\n \"internal error: inflate stream corrupt\");\n return -1;\n }\n if (ret == Z_MEM_ERROR)\n ret = LZMA_MEM_ERROR;\n if (ret == Z_DATA_ERROR)\n ret = LZMA_DATA_ERROR;\n if (ret == Z_STREAM_END)\n ret = LZMA_STREAM_END;\n state->strm.avail_in = state->zstrm.avail_in;\n state->strm.next_in = state->zstrm.next_in;\n state->strm.avail_out = state->zstrm.avail_out;\n state->strm.next_out = state->zstrm.next_out;\n } else /* state->how == LZMA */\n#endif\n ret = lzma_code(strm, action);\n if (ret == LZMA_MEM_ERROR) {\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n if (ret == LZMA_DATA_ERROR) {\n xz_error(state, LZMA_DATA_ERROR, \"compressed data error\");\n return -1;\n }\n if (ret == LZMA_PROG_ERROR) {\n xz_error(state, LZMA_PROG_ERROR, \"compression error\");\n return -1;\n }\n } while (strm->avail_out && ret != LZMA_STREAM_END);\n\n /* update available output and crc check value */\n state->have = had - strm->avail_out;\n state->next = strm->next_out - state->have;\n#ifdef HAVE_ZLIB_H\n state->zstrm.adler =\n crc32(state->zstrm.adler, state->next, state->have);\n#endif\n\n if (ret == LZMA_STREAM_END) {\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (crc != state->zstrm.adler) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect data check\");\n return -1;\n }\n if (len != (state->zstrm.total_out & 0xffffffffL)) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect length check\");\n return -1;\n }\n state->strm.avail_in = 0;\n state->strm.next_in = NULL;\n state->strm.avail_out = 0;\n state->strm.next_out = NULL;\n } else\n#endif\n if (strm->avail_in != 0 || !state->eof) {\n xz_error(state, LZMA_DATA_ERROR, \"trailing garbage\");\n return -1;\n }\n state->how = LOOK; /* ready for next stream, once have is 0 (leave\n * state->direct unchanged to remember how) */\n }\n\n /* good decompression */\n return 0;\n}", "func_hash": 278327953608983845969384208205318316008, "file_name": "xzlib.c", "file_hash": 214417675830901242458165382615962643666, "cwe": ["CWE-399"], "cve": "CVE-2015-8035", "cve_desc": "The xz_decomp function in xzlib.c in libxml2 2.9.1 does not properly detect compression errors, which allows context-dependent attackers to cause a denial of service (process hang) via crafted XML data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-8035"} {"idx": 204285, "project": "sqlite", "commit_id": "a6c1a71cde082e09750465d5675699062922e387", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/a6c1a71cde082e09750465d5675699062922e387", "commit_message": "Do not attempt to unwind the WITH stack in the Parse object following an error. This fixes a separate case to [de6e6d68].\n\nFossilOrigin-Name: d29edef93451cc67a5d69c1cce1b1832d9ca8fff1f600afdd51338b74d077b92", "target": 1, "func": "static int selectExpander(Walker *pWalker, Select *p){\n Parse *pParse = pWalker->pParse;\n int i, j, k;\n SrcList *pTabList;\n ExprList *pEList;\n struct SrcList_item *pFrom;\n sqlite3 *db = pParse->db;\n Expr *pE, *pRight, *pExpr;\n u16 selFlags = p->selFlags;\n u32 elistFlags = 0;\n\n p->selFlags |= SF_Expanded;\n if( db->mallocFailed ){\n return WRC_Abort;\n }\n assert( p->pSrc!=0 );\n if( (selFlags & SF_Expanded)!=0 ){\n return WRC_Prune;\n }\n if( pWalker->eCode ){\n /* Renumber selId because it has been copied from a view */\n p->selId = ++pParse->nSelect;\n }\n pTabList = p->pSrc;\n pEList = p->pEList;\n sqlite3WithPush(pParse, p->pWith, 0);\n\n /* Make sure cursor numbers have been assigned to all entries in\n ** the FROM clause of the SELECT statement.\n */\n sqlite3SrcListAssignCursors(pParse, pTabList);\n\n /* Look up every table named in the FROM clause of the select. If\n ** an entry of the FROM clause is a subquery instead of a table or view,\n ** then create a transient table structure to describe the subquery.\n */\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab;\n assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );\n if( pFrom->fg.isRecursive ) continue;\n assert( pFrom->pTab==0 );\n#ifndef SQLITE_OMIT_CTE\n if( withExpand(pWalker, pFrom) ) return WRC_Abort;\n if( pFrom->pTab ) {} else\n#endif\n if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n Select *pSel = pFrom->pSelect;\n /* A sub-query in the FROM clause of a SELECT */\n assert( pSel!=0 );\n assert( pFrom->pTab==0 );\n if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;\n if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;\n#endif\n }else{\n /* An ordinary table or view name in the FROM clause */\n assert( pFrom->pTab==0 );\n pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);\n if( pTab==0 ) return WRC_Abort;\n if( pTab->nTabRef>=0xffff ){\n sqlite3ErrorMsg(pParse, \"too many references to \\\"%s\\\": max 65535\",\n pTab->zName);\n pFrom->pTab = 0;\n return WRC_Abort;\n }\n pTab->nTabRef++;\n if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){\n return WRC_Abort;\n }\n#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)\n if( IsVirtual(pTab) || pTab->pSelect ){\n i16 nCol;\n u8 eCodeOrig = pWalker->eCode;\n if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n assert( pFrom->pSelect==0 );\n if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){\n sqlite3ErrorMsg(pParse, \"access to view \\\"%s\\\" prohibited\",\n pTab->zName);\n }\n pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n nCol = pTab->nCol;\n pTab->nCol = -1;\n pWalker->eCode = 1; /* Turn on Select.selId renumbering */\n sqlite3WalkSelect(pWalker, pFrom->pSelect);\n pWalker->eCode = eCodeOrig;\n pTab->nCol = nCol;\n }\n#endif\n }\n\n /* Locate the index named by the INDEXED BY clause, if any. */\n if( sqlite3IndexedByLookup(pParse, pFrom) ){\n return WRC_Abort;\n }\n }\n\n /* Process NATURAL keywords, and ON and USING clauses of joins.\n */\n if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n return WRC_Abort;\n }\n\n /* For every \"*\" that occurs in the column list, insert the names of\n ** all columns in all tables. And for every TABLE.* insert the names\n ** of all columns in TABLE. The parser inserted a special expression\n ** with the TK_ASTERISK operator for each \"*\" that it found in the column\n ** list. The following code just has to locate the TK_ASTERISK\n ** expressions and expand each one to the list of all columns in\n ** all tables.\n **\n ** The first loop just checks to see if there are any \"*\" operators\n ** that need expanding.\n */\n for(k=0; knExpr; k++){\n pE = pEList->a[k].pExpr;\n if( pE->op==TK_ASTERISK ) break;\n assert( pE->op!=TK_DOT || pE->pRight!=0 );\n assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;\n elistFlags |= pE->flags;\n }\n if( knExpr ){\n /*\n ** If we get here it means the result set contains one or more \"*\"\n ** operators that need to be expanded. Loop through each expression\n ** in the result set and expand them one by one.\n */\n struct ExprList_item *a = pEList->a;\n ExprList *pNew = 0;\n int flags = pParse->db->flags;\n int longNames = (flags & SQLITE_FullColNames)!=0\n && (flags & SQLITE_ShortColNames)==0;\n\n for(k=0; knExpr; k++){\n pE = a[k].pExpr;\n elistFlags |= pE->flags;\n pRight = pE->pRight;\n assert( pE->op!=TK_DOT || pRight!=0 );\n if( pE->op!=TK_ASTERISK\n && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)\n ){\n /* This particular expression does not need to be expanded.\n */\n pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n if( pNew ){\n pNew->a[pNew->nExpr-1].zName = a[k].zName;\n pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;\n a[k].zName = 0;\n a[k].zSpan = 0;\n }\n a[k].pExpr = 0;\n }else{\n /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n ** expanded. */\n int tableSeen = 0; /* Set to 1 when TABLE matches */\n char *zTName = 0; /* text of name of TABLE */\n if( pE->op==TK_DOT ){\n assert( pE->pLeft!=0 );\n assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n zTName = pE->pLeft->u.zToken;\n }\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab = pFrom->pTab;\n Select *pSub = pFrom->pSelect;\n char *zTabName = pFrom->zAlias;\n const char *zSchemaName = 0;\n int iDb;\n if( zTabName==0 ){\n zTabName = pTab->zName;\n }\n if( db->mallocFailed ) break;\n if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){\n pSub = 0;\n if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n continue;\n }\n iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : \"*\";\n }\n for(j=0; jnCol; j++){\n char *zName = pTab->aCol[j].zName;\n char *zColname; /* The computed column name */\n char *zToFree; /* Malloced string that needs to be freed */\n Token sColname; /* Computed column name as a token */\n\n assert( zName );\n if( zTName && pSub\n && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0\n ){\n continue;\n }\n\n /* If a column is marked as 'hidden', omit it from the expanded\n ** result-set list unless the SELECT has the SF_IncludeHidden\n ** bit set.\n */\n if( (p->selFlags & SF_IncludeHidden)==0\n && IsHiddenColumn(&pTab->aCol[j]) \n ){\n continue;\n }\n tableSeen = 1;\n\n if( i>0 && zTName==0 ){\n if( (pFrom->fg.jointype & JT_NATURAL)!=0\n && tableAndColumnIndex(pTabList, i, zName, 0, 0)\n ){\n /* In a NATURAL join, omit the join columns from the \n ** table to the right of the join */\n continue;\n }\n if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n /* In a join with a USING clause, omit columns in the\n ** using clause from the table on the right. */\n continue;\n }\n }\n pRight = sqlite3Expr(db, TK_ID, zName);\n zColname = zName;\n zToFree = 0;\n if( longNames || pTabList->nSrc>1 ){\n Expr *pLeft;\n pLeft = sqlite3Expr(db, TK_ID, zTabName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n if( zSchemaName ){\n pLeft = sqlite3Expr(db, TK_ID, zSchemaName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);\n }\n if( longNames ){\n zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n zToFree = zColname;\n }\n }else{\n pExpr = pRight;\n }\n pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n sqlite3TokenInit(&sColname, zColname);\n sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){\n struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];\n if( pSub ){\n pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);\n testcase( pX->zSpan==0 );\n }else{\n pX->zSpan = sqlite3MPrintf(db, \"%s.%s.%s\",\n zSchemaName, zTabName, zColname);\n testcase( pX->zSpan==0 );\n }\n pX->bSpanIsTab = 1;\n }\n sqlite3DbFree(db, zToFree);\n }\n }\n if( !tableSeen ){\n if( zTName ){\n sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n }else{\n sqlite3ErrorMsg(pParse, \"no tables specified\");\n }\n }\n }\n }\n sqlite3ExprListDelete(db, pEList);\n p->pEList = pNew;\n }\n if( p->pEList ){\n if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n return WRC_Abort;\n }\n if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){\n p->selFlags |= SF_ComplexResult;\n }\n }\n return WRC_Continue;\n}", "func_hash": 332547868173561651486607854690851812987, "file_name": "select.c", "file_hash": 58598362314587806073473930834009300780, "cwe": ["CWE-755"], "cve": "CVE-2019-20218", "cve_desc": "selectExpander in select.c in SQLite 3.30.1 proceeds with WITH stack unwinding even after a parsing error.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20218"} {"idx": 356309, "project": "sqlite", "commit_id": "a6c1a71cde082e09750465d5675699062922e387", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/a6c1a71cde082e09750465d5675699062922e387", "commit_message": "Do not attempt to unwind the WITH stack in the Parse object following an error. This fixes a separate case to [de6e6d68].\n\nFossilOrigin-Name: d29edef93451cc67a5d69c1cce1b1832d9ca8fff1f600afdd51338b74d077b92", "target": 0, "func": "static int selectExpander(Walker *pWalker, Select *p){\n Parse *pParse = pWalker->pParse;\n int i, j, k;\n SrcList *pTabList;\n ExprList *pEList;\n struct SrcList_item *pFrom;\n sqlite3 *db = pParse->db;\n Expr *pE, *pRight, *pExpr;\n u16 selFlags = p->selFlags;\n u32 elistFlags = 0;\n\n p->selFlags |= SF_Expanded;\n if( db->mallocFailed ){\n return WRC_Abort;\n }\n assert( p->pSrc!=0 );\n if( (selFlags & SF_Expanded)!=0 ){\n return WRC_Prune;\n }\n if( pWalker->eCode ){\n /* Renumber selId because it has been copied from a view */\n p->selId = ++pParse->nSelect;\n }\n pTabList = p->pSrc;\n pEList = p->pEList;\n sqlite3WithPush(pParse, p->pWith, 0);\n\n /* Make sure cursor numbers have been assigned to all entries in\n ** the FROM clause of the SELECT statement.\n */\n sqlite3SrcListAssignCursors(pParse, pTabList);\n\n /* Look up every table named in the FROM clause of the select. If\n ** an entry of the FROM clause is a subquery instead of a table or view,\n ** then create a transient table structure to describe the subquery.\n */\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab;\n assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );\n if( pFrom->fg.isRecursive ) continue;\n assert( pFrom->pTab==0 );\n#ifndef SQLITE_OMIT_CTE\n if( withExpand(pWalker, pFrom) ) return WRC_Abort;\n if( pFrom->pTab ) {} else\n#endif\n if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n Select *pSel = pFrom->pSelect;\n /* A sub-query in the FROM clause of a SELECT */\n assert( pSel!=0 );\n assert( pFrom->pTab==0 );\n if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;\n if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;\n#endif\n }else{\n /* An ordinary table or view name in the FROM clause */\n assert( pFrom->pTab==0 );\n pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);\n if( pTab==0 ) return WRC_Abort;\n if( pTab->nTabRef>=0xffff ){\n sqlite3ErrorMsg(pParse, \"too many references to \\\"%s\\\": max 65535\",\n pTab->zName);\n pFrom->pTab = 0;\n return WRC_Abort;\n }\n pTab->nTabRef++;\n if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){\n return WRC_Abort;\n }\n#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)\n if( IsVirtual(pTab) || pTab->pSelect ){\n i16 nCol;\n u8 eCodeOrig = pWalker->eCode;\n if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n assert( pFrom->pSelect==0 );\n if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){\n sqlite3ErrorMsg(pParse, \"access to view \\\"%s\\\" prohibited\",\n pTab->zName);\n }\n pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n nCol = pTab->nCol;\n pTab->nCol = -1;\n pWalker->eCode = 1; /* Turn on Select.selId renumbering */\n sqlite3WalkSelect(pWalker, pFrom->pSelect);\n pWalker->eCode = eCodeOrig;\n pTab->nCol = nCol;\n }\n#endif\n }\n\n /* Locate the index named by the INDEXED BY clause, if any. */\n if( sqlite3IndexedByLookup(pParse, pFrom) ){\n return WRC_Abort;\n }\n }\n\n /* Process NATURAL keywords, and ON and USING clauses of joins.\n */\n if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n return WRC_Abort;\n }\n\n /* For every \"*\" that occurs in the column list, insert the names of\n ** all columns in all tables. And for every TABLE.* insert the names\n ** of all columns in TABLE. The parser inserted a special expression\n ** with the TK_ASTERISK operator for each \"*\" that it found in the column\n ** list. The following code just has to locate the TK_ASTERISK\n ** expressions and expand each one to the list of all columns in\n ** all tables.\n **\n ** The first loop just checks to see if there are any \"*\" operators\n ** that need expanding.\n */\n for(k=0; knExpr; k++){\n pE = pEList->a[k].pExpr;\n if( pE->op==TK_ASTERISK ) break;\n assert( pE->op!=TK_DOT || pE->pRight!=0 );\n assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;\n elistFlags |= pE->flags;\n }\n if( knExpr ){\n /*\n ** If we get here it means the result set contains one or more \"*\"\n ** operators that need to be expanded. Loop through each expression\n ** in the result set and expand them one by one.\n */\n struct ExprList_item *a = pEList->a;\n ExprList *pNew = 0;\n int flags = pParse->db->flags;\n int longNames = (flags & SQLITE_FullColNames)!=0\n && (flags & SQLITE_ShortColNames)==0;\n\n for(k=0; knExpr; k++){\n pE = a[k].pExpr;\n elistFlags |= pE->flags;\n pRight = pE->pRight;\n assert( pE->op!=TK_DOT || pRight!=0 );\n if( pE->op!=TK_ASTERISK\n && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)\n ){\n /* This particular expression does not need to be expanded.\n */\n pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n if( pNew ){\n pNew->a[pNew->nExpr-1].zName = a[k].zName;\n pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;\n a[k].zName = 0;\n a[k].zSpan = 0;\n }\n a[k].pExpr = 0;\n }else{\n /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n ** expanded. */\n int tableSeen = 0; /* Set to 1 when TABLE matches */\n char *zTName = 0; /* text of name of TABLE */\n if( pE->op==TK_DOT ){\n assert( pE->pLeft!=0 );\n assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n zTName = pE->pLeft->u.zToken;\n }\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab = pFrom->pTab;\n Select *pSub = pFrom->pSelect;\n char *zTabName = pFrom->zAlias;\n const char *zSchemaName = 0;\n int iDb;\n if( zTabName==0 ){\n zTabName = pTab->zName;\n }\n if( db->mallocFailed ) break;\n if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){\n pSub = 0;\n if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n continue;\n }\n iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : \"*\";\n }\n for(j=0; jnCol; j++){\n char *zName = pTab->aCol[j].zName;\n char *zColname; /* The computed column name */\n char *zToFree; /* Malloced string that needs to be freed */\n Token sColname; /* Computed column name as a token */\n\n assert( zName );\n if( zTName && pSub\n && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0\n ){\n continue;\n }\n\n /* If a column is marked as 'hidden', omit it from the expanded\n ** result-set list unless the SELECT has the SF_IncludeHidden\n ** bit set.\n */\n if( (p->selFlags & SF_IncludeHidden)==0\n && IsHiddenColumn(&pTab->aCol[j]) \n ){\n continue;\n }\n tableSeen = 1;\n\n if( i>0 && zTName==0 ){\n if( (pFrom->fg.jointype & JT_NATURAL)!=0\n && tableAndColumnIndex(pTabList, i, zName, 0, 0)\n ){\n /* In a NATURAL join, omit the join columns from the \n ** table to the right of the join */\n continue;\n }\n if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n /* In a join with a USING clause, omit columns in the\n ** using clause from the table on the right. */\n continue;\n }\n }\n pRight = sqlite3Expr(db, TK_ID, zName);\n zColname = zName;\n zToFree = 0;\n if( longNames || pTabList->nSrc>1 ){\n Expr *pLeft;\n pLeft = sqlite3Expr(db, TK_ID, zTabName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n if( zSchemaName ){\n pLeft = sqlite3Expr(db, TK_ID, zSchemaName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);\n }\n if( longNames ){\n zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n zToFree = zColname;\n }\n }else{\n pExpr = pRight;\n }\n pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n sqlite3TokenInit(&sColname, zColname);\n sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){\n struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];\n if( pSub ){\n pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);\n testcase( pX->zSpan==0 );\n }else{\n pX->zSpan = sqlite3MPrintf(db, \"%s.%s.%s\",\n zSchemaName, zTabName, zColname);\n testcase( pX->zSpan==0 );\n }\n pX->bSpanIsTab = 1;\n }\n sqlite3DbFree(db, zToFree);\n }\n }\n if( !tableSeen ){\n if( zTName ){\n sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n }else{\n sqlite3ErrorMsg(pParse, \"no tables specified\");\n }\n }\n }\n }\n sqlite3ExprListDelete(db, pEList);\n p->pEList = pNew;\n }\n if( p->pEList ){\n if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n return WRC_Abort;\n }\n if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){\n p->selFlags |= SF_ComplexResult;\n }\n }\n return WRC_Continue;\n}", "func_hash": 227702455008184199587562576280160755305, "file_name": "select.c", "file_hash": 22011899472848775616825833189035278966, "cwe": ["CWE-755"], "cve": "CVE-2019-20218", "cve_desc": "selectExpander in select.c in SQLite 3.30.1 proceeds with WITH stack unwinding even after a parsing error.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-20218"} {"idx": 204323, "project": "sudo", "commit_id": "c4d384082fdbc8406cf19e08d05db4cded920a55", "project_url": "https://github.com/sudo-project/sudo", "commit_url": "https://github.com/sudo-project/sudo/commit/c4d384082fdbc8406cf19e08d05db4cded920a55", "commit_message": "Add sudoedit flag checks in plugin that are consistent with front-end.\nDon't assume the sudo front-end is sending reasonable mode flags.\nThese checks need to be kept consistent between the sudo front-end\nand the sudoers plugin.", "target": 1, "func": "sudoers_policy_deserialize_info(void *v)\n{\n struct sudoers_open_info *info = v;\n char * const *cur;\n const char *p, *errstr, *groups = NULL;\n const char *remhost = NULL;\n int flags = 0;\n debug_decl(sudoers_policy_deserialize_info, SUDOERS_DEBUG_PLUGIN);\n\n#define MATCHES(s, v)\t\\\n (strncmp((s), (v), sizeof(v) - 1) == 0)\n\n#define INVALID(v) do {\t\\\n sudo_warn(U_(\"invalid %.*s set by sudo front-end\"), \\\n\t(int)(sizeof(v) - 2), (v)); \\\n} while (0)\n\n#define CHECK(s, v) do {\t\\\n if ((s)[sizeof(v) - 1] == '\\0') { \\\n\tINVALID(v); \\\n\tgoto bad; \\\n } \\\n} while (0)\n\n if (sudo_gettime_real(&sudo_user.submit_time) == -1) {\n\tsudo_warn(\"%s\", U_(\"unable to get time of day\"));\n\tgoto bad;\n }\n\n /* Parse sudo.conf plugin args. */\n if (info->plugin_args != NULL) {\n\tfor (cur = info->plugin_args; *cur != NULL; cur++) {\n\t if (MATCHES(*cur, \"error_recovery=\")) {\n\t\tint val = sudo_strtobool(*cur + sizeof(\"error_recovery=\") - 1);\n\t\tif (val == -1) {\n\t\t INVALID(\"error_recovery=\");\t/* Not a fatal error. */\n\t\t} else {\n\t\t sudoers_recovery = val;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_file=\")) {\n\t\tCHECK(*cur, \"sudoers_file=\");\n\t\tsudoers_file = *cur + sizeof(\"sudoers_file=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_uid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_uid=\") - 1;\n\t\tsudoers_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_gid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_gid=\") - 1;\n\t\tsudoers_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_mode=\")) {\n\t\tp = *cur + sizeof(\"sudoers_mode=\") - 1;\n\t\tsudoers_mode = sudo_strtomode(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_conf=\")) {\n\t\tCHECK(*cur, \"ldap_conf=\");\n\t\tpath_ldap_conf = *cur + sizeof(\"ldap_conf=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_secret=\")) {\n\t\tCHECK(*cur, \"ldap_secret=\");\n\t\tpath_ldap_secret = *cur + sizeof(\"ldap_secret=\") - 1;\n\t\tcontinue;\n\t }\n\t}\n }\n\n /* Parse command line settings. */\n user_closefrom = -1;\n for (cur = info->settings; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"closefrom=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"closefrom=\") - 1;\n\t user_closefrom = sudo_strtonum(p, 3, INT_MAX, &errstr);\n\t if (user_closefrom == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_chroot=\")) {\n\t CHECK(*cur, \"cmnd_chroot=\");\n\t user_runchroot = *cur + sizeof(\"cmnd_chroot=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_cwd=\")) {\n\t CHECK(*cur, \"cmnd_cwd=\");\n\t user_runcwd = *cur + sizeof(\"cmnd_cwd=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_user=\")) {\n\t CHECK(*cur, \"runas_user=\");\n\t sudo_user.runas_user = *cur + sizeof(\"runas_user=\") - 1;\n\t SET(sudo_user.flags, RUNAS_USER_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_group=\")) {\n\t CHECK(*cur, \"runas_group=\");\n\t sudo_user.runas_group = *cur + sizeof(\"runas_group=\") - 1;\n\t SET(sudo_user.flags, RUNAS_GROUP_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"prompt=\")) {\n\t /* Allow epmpty prompt. */\n\t user_prompt = *cur + sizeof(\"prompt=\") - 1;\n\t def_passprompt_override = true;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"set_home=\")) {\n\t if (parse_bool(*cur, sizeof(\"set_home\") - 1, &flags,\n\t\tMODE_RESET_HOME) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_environment=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_environment\") - 1, &flags,\n\t\tMODE_PRESERVE_ENV) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"run_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"run_shell\") -1, &flags,\n\t\tMODE_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"login_shell\") - 1, &flags,\n\t\tMODE_LOGIN_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"implied_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"implied_shell\") - 1, &flags,\n\t\tMODE_IMPLIED_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_groups=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_groups\") - 1, &flags,\n\t\tMODE_PRESERVE_GROUPS) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"ignore_ticket=\")) {\n\t if (parse_bool(*cur, sizeof(\"ignore_ticket\") -1, &flags,\n\t\tMODE_IGNORE_TICKET) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"noninteractive=\")) {\n\t if (parse_bool(*cur, sizeof(\"noninteractive\") - 1, &flags,\n\t\tMODE_NONINTERACTIVE) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sudoedit=\")) {\n\t if (parse_bool(*cur, sizeof(\"sudoedit\") - 1, &flags,\n\t\tMODE_EDIT) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_class=\")) {\n\t CHECK(*cur, \"login_class=\");\n\t login_class = *cur + sizeof(\"login_class=\") - 1;\n\t def_use_loginclass = true;\n\t continue;\n\t}\n#ifdef HAVE_PRIV_SET\n\tif (MATCHES(*cur, \"runas_privs=\")) {\n\t CHECK(*cur, \"runas_privs=\");\n\t def_privs = *cur + sizeof(\"runas_privs=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_limitprivs=\")) {\n\t CHECK(*cur, \"runas_limitprivs=\");\n\t def_limitprivs = *cur + sizeof(\"runas_limitprivs=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_PRIV_SET */\n#ifdef HAVE_SELINUX\n\tif (MATCHES(*cur, \"selinux_role=\")) {\n\t CHECK(*cur, \"selinux_role=\");\n\t user_role = *cur + sizeof(\"selinux_role=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"selinux_type=\")) {\n\t CHECK(*cur, \"selinux_type=\");\n\t user_type = *cur + sizeof(\"selinux_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_SELINUX */\n#ifdef HAVE_BSD_AUTH_H\n\tif (MATCHES(*cur, \"bsdauth_type=\")) {\n\t CHECK(*cur, \"login_style=\");\n\t login_style = *cur + sizeof(\"bsdauth_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_BSD_AUTH_H */\n\tif (MATCHES(*cur, \"network_addrs=\")) {\n\t interfaces_string = *cur + sizeof(\"network_addrs=\") - 1;\n\t if (!set_interfaces(interfaces_string)) {\n\t\tsudo_warn(\"%s\", U_(\"unable to parse network address list\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"max_groups=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"max_groups=\") - 1;\n\t sudo_user.max_groups = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.max_groups == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"remote_host=\")) {\n\t CHECK(*cur, \"remote_host=\");\n\t remhost = *cur + sizeof(\"remote_host=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"timeout=\")) {\n\t p = *cur + sizeof(\"timeout=\") - 1;\n\t user_timeout = parse_timeout(p);\n\t if (user_timeout == -1) {\n\t\tif (errno == ERANGE)\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"timeout value too large\"));\n\t\telse\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"invalid timeout value\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n#ifdef ENABLE_SUDO_PLUGIN_API\n\tif (MATCHES(*cur, \"plugin_dir=\")) {\n\t CHECK(*cur, \"plugin_dir=\");\n\t path_plugin_dir = *cur + sizeof(\"plugin_dir=\") - 1;\n\t continue;\n\t}\n#endif\n }\n\n user_gid = (gid_t)-1;\n user_sid = (pid_t)-1;\n user_uid = (gid_t)-1;\n user_umask = (mode_t)-1;\n for (cur = info->user_info; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"user=\")) {\n\t CHECK(*cur, \"user=\");\n\t if ((user_name = strdup(*cur + sizeof(\"user=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"uid=\")) {\n\t p = *cur + sizeof(\"uid=\") - 1;\n\t user_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"gid=\")) {\n\t p = *cur + sizeof(\"gid=\") - 1;\n\t user_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"groups=\")) {\n\t CHECK(*cur, \"groups=\");\n\t groups = *cur + sizeof(\"groups=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cwd=\")) {\n\t CHECK(*cur, \"cwd=\");\n\t if ((user_cwd = strdup(*cur + sizeof(\"cwd=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"tty=\")) {\n\t CHECK(*cur, \"tty=\");\n\t if ((user_ttypath = strdup(*cur + sizeof(\"tty=\") - 1)) == NULL)\n\t\tgoto oom;\n\t user_tty = user_ttypath;\n\t if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)\n\t\tuser_tty += sizeof(_PATH_DEV) - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"host=\")) {\n\t CHECK(*cur, \"host=\");\n\t if ((user_host = strdup(*cur + sizeof(\"host=\") - 1)) == NULL)\n\t\tgoto oom;\n\t if ((p = strchr(user_host, '.')) != NULL) {\n\t\tuser_shost = strndup(user_host, (size_t)(p - user_host));\n\t\tif (user_shost == NULL)\n\t\t goto oom;\n\t } else {\n\t\tuser_shost = user_host;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"lines=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"lines=\") - 1;\n\t sudo_user.lines = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.lines == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cols=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"cols=\") - 1;\n\t sudo_user.cols = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.cols == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sid=\")) {\n\t p = *cur + sizeof(\"sid=\") - 1;\n\t user_sid = (pid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"umask=\")) {\n\t p = *cur + sizeof(\"umask=\") - 1;\n\t sudo_user.umask = sudo_strtomode(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n }\n\n /* User name, user-ID, group-ID and host name must be specified. */\n if (user_name == NULL) {\n\tsudo_warnx(\"%s\", U_(\"user name not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_uid == (uid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"user-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_gid == (gid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"group-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_host == NULL) {\n\tsudo_warnx(\"%s\", U_(\"host name not set by sudo front-end\"));\n\tgoto bad;\n }\n\n if ((user_runhost = strdup(remhost ? remhost : user_host)) == NULL)\n\tgoto oom;\n if ((p = strchr(user_runhost, '.')) != NULL) {\n\tuser_srunhost = strndup(user_runhost, (size_t)(p - user_runhost));\n\tif (user_srunhost == NULL)\n\t goto oom;\n } else {\n\tuser_srunhost = user_runhost;\n }\n if (user_cwd == NULL) {\n\tif ((user_cwd = strdup(\"unknown\")) == NULL)\n\t goto oom;\n }\n if (user_runcwd == NULL) {\n\tif ((user_runcwd = strdup(user_cwd)) == NULL)\n\t goto oom;\n }\n if (user_tty == NULL) {\n\tif ((user_tty = strdup(\"unknown\")) == NULL)\n\t goto oom;\n\t/* user_ttypath remains NULL */\n }\n\n if (groups != NULL) {\n\t/* sudo_parse_gids() will print a warning on error. */\n\tuser_ngids = sudo_parse_gids(groups, &user_gid, &user_gids);\n\tif (user_ngids == -1)\n\t goto bad;\n }\n\n /* umask is only set in user_info[] for API 1.10 and above. */\n if (user_umask == (mode_t)-1) {\n\tuser_umask = umask(0);\n\tumask(user_umask);\n }\n\n /* Always reset the environment for a login shell. */\n if (ISSET(flags, MODE_LOGIN_SHELL))\n\tdef_env_reset = true;\n\n /* Some systems support fexecve() which we use for digest matches. */\n cmnd_fd = -1;\n\n /* Dump settings and user info (XXX - plugin args) */\n for (cur = info->settings; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"settings: %s\", *cur);\n for (cur = info->user_info; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"user_info: %s\", *cur);\n\n#undef MATCHES\n#undef INVALID\n#undef CHECK\n debug_return_int(flags);\n\noom:\n sudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\nbad:\n debug_return_int(MODE_ERROR);\n}", "func_hash": 243132594910049975735814289957782249756, "file_name": "policy.c", "file_hash": 250725641189734152105750508366545429681, "cwe": ["CWE-193"], "cve": "CVE-2021-3156", "cve_desc": "Sudo before 1.9.5p2 contains an off-by-one error that can result in a heap-based buffer overflow, which allows privilege escalation to root via \"sudoedit -s\" and a command-line argument that ends with a single backslash character.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3156"} {"idx": 356720, "project": "sudo", "commit_id": "c4d384082fdbc8406cf19e08d05db4cded920a55", "project_url": "https://github.com/sudo-project/sudo", "commit_url": "https://github.com/sudo-project/sudo/commit/c4d384082fdbc8406cf19e08d05db4cded920a55", "commit_message": "Add sudoedit flag checks in plugin that are consistent with front-end.\nDon't assume the sudo front-end is sending reasonable mode flags.\nThese checks need to be kept consistent between the sudo front-end\nand the sudoers plugin.", "target": 0, "func": "sudoers_policy_deserialize_info(void *v)\n{\n const int edit_mask = MODE_EDIT|MODE_IGNORE_TICKET|MODE_NONINTERACTIVE;\n struct sudoers_open_info *info = v;\n const char *p, *errstr, *groups = NULL;\n const char *remhost = NULL;\n char * const *cur;\n int flags = 0;\n debug_decl(sudoers_policy_deserialize_info, SUDOERS_DEBUG_PLUGIN);\n\n#define MATCHES(s, v)\t\\\n (strncmp((s), (v), sizeof(v) - 1) == 0)\n\n#define INVALID(v) do {\t\\\n sudo_warn(U_(\"invalid %.*s set by sudo front-end\"), \\\n\t(int)(sizeof(v) - 2), (v)); \\\n} while (0)\n\n#define CHECK(s, v) do {\t\\\n if ((s)[sizeof(v) - 1] == '\\0') { \\\n\tINVALID(v); \\\n\tgoto bad; \\\n } \\\n} while (0)\n\n if (sudo_gettime_real(&sudo_user.submit_time) == -1) {\n\tsudo_warn(\"%s\", U_(\"unable to get time of day\"));\n\tgoto bad;\n }\n\n /* Parse sudo.conf plugin args. */\n if (info->plugin_args != NULL) {\n\tfor (cur = info->plugin_args; *cur != NULL; cur++) {\n\t if (MATCHES(*cur, \"error_recovery=\")) {\n\t\tint val = sudo_strtobool(*cur + sizeof(\"error_recovery=\") - 1);\n\t\tif (val == -1) {\n\t\t INVALID(\"error_recovery=\");\t/* Not a fatal error. */\n\t\t} else {\n\t\t sudoers_recovery = val;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_file=\")) {\n\t\tCHECK(*cur, \"sudoers_file=\");\n\t\tsudoers_file = *cur + sizeof(\"sudoers_file=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_uid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_uid=\") - 1;\n\t\tsudoers_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_gid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_gid=\") - 1;\n\t\tsudoers_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_mode=\")) {\n\t\tp = *cur + sizeof(\"sudoers_mode=\") - 1;\n\t\tsudoers_mode = sudo_strtomode(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_conf=\")) {\n\t\tCHECK(*cur, \"ldap_conf=\");\n\t\tpath_ldap_conf = *cur + sizeof(\"ldap_conf=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_secret=\")) {\n\t\tCHECK(*cur, \"ldap_secret=\");\n\t\tpath_ldap_secret = *cur + sizeof(\"ldap_secret=\") - 1;\n\t\tcontinue;\n\t }\n\t}\n }\n\n /* Parse command line settings. */\n user_closefrom = -1;\n for (cur = info->settings; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"closefrom=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"closefrom=\") - 1;\n\t user_closefrom = sudo_strtonum(p, 3, INT_MAX, &errstr);\n\t if (user_closefrom == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_chroot=\")) {\n\t CHECK(*cur, \"cmnd_chroot=\");\n\t user_runchroot = *cur + sizeof(\"cmnd_chroot=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_cwd=\")) {\n\t CHECK(*cur, \"cmnd_cwd=\");\n\t user_runcwd = *cur + sizeof(\"cmnd_cwd=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_user=\")) {\n\t CHECK(*cur, \"runas_user=\");\n\t sudo_user.runas_user = *cur + sizeof(\"runas_user=\") - 1;\n\t SET(sudo_user.flags, RUNAS_USER_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_group=\")) {\n\t CHECK(*cur, \"runas_group=\");\n\t sudo_user.runas_group = *cur + sizeof(\"runas_group=\") - 1;\n\t SET(sudo_user.flags, RUNAS_GROUP_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"prompt=\")) {\n\t /* Allow epmpty prompt. */\n\t user_prompt = *cur + sizeof(\"prompt=\") - 1;\n\t def_passprompt_override = true;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"set_home=\")) {\n\t if (parse_bool(*cur, sizeof(\"set_home\") - 1, &flags,\n\t\tMODE_RESET_HOME) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_environment=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_environment\") - 1, &flags,\n\t\tMODE_PRESERVE_ENV) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"run_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"run_shell\") -1, &flags,\n\t\tMODE_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"login_shell\") - 1, &flags,\n\t\tMODE_LOGIN_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"implied_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"implied_shell\") - 1, &flags,\n\t\tMODE_IMPLIED_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_groups=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_groups\") - 1, &flags,\n\t\tMODE_PRESERVE_GROUPS) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"ignore_ticket=\")) {\n\t if (parse_bool(*cur, sizeof(\"ignore_ticket\") -1, &flags,\n\t\tMODE_IGNORE_TICKET) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"noninteractive=\")) {\n\t if (parse_bool(*cur, sizeof(\"noninteractive\") - 1, &flags,\n\t\tMODE_NONINTERACTIVE) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sudoedit=\")) {\n\t if (parse_bool(*cur, sizeof(\"sudoedit\") - 1, &flags,\n\t\tMODE_EDIT) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_class=\")) {\n\t CHECK(*cur, \"login_class=\");\n\t login_class = *cur + sizeof(\"login_class=\") - 1;\n\t def_use_loginclass = true;\n\t continue;\n\t}\n#ifdef HAVE_PRIV_SET\n\tif (MATCHES(*cur, \"runas_privs=\")) {\n\t CHECK(*cur, \"runas_privs=\");\n\t def_privs = *cur + sizeof(\"runas_privs=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_limitprivs=\")) {\n\t CHECK(*cur, \"runas_limitprivs=\");\n\t def_limitprivs = *cur + sizeof(\"runas_limitprivs=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_PRIV_SET */\n#ifdef HAVE_SELINUX\n\tif (MATCHES(*cur, \"selinux_role=\")) {\n\t CHECK(*cur, \"selinux_role=\");\n\t user_role = *cur + sizeof(\"selinux_role=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"selinux_type=\")) {\n\t CHECK(*cur, \"selinux_type=\");\n\t user_type = *cur + sizeof(\"selinux_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_SELINUX */\n#ifdef HAVE_BSD_AUTH_H\n\tif (MATCHES(*cur, \"bsdauth_type=\")) {\n\t CHECK(*cur, \"login_style=\");\n\t login_style = *cur + sizeof(\"bsdauth_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_BSD_AUTH_H */\n\tif (MATCHES(*cur, \"network_addrs=\")) {\n\t interfaces_string = *cur + sizeof(\"network_addrs=\") - 1;\n\t if (!set_interfaces(interfaces_string)) {\n\t\tsudo_warn(\"%s\", U_(\"unable to parse network address list\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"max_groups=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"max_groups=\") - 1;\n\t sudo_user.max_groups = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.max_groups == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"remote_host=\")) {\n\t CHECK(*cur, \"remote_host=\");\n\t remhost = *cur + sizeof(\"remote_host=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"timeout=\")) {\n\t p = *cur + sizeof(\"timeout=\") - 1;\n\t user_timeout = parse_timeout(p);\n\t if (user_timeout == -1) {\n\t\tif (errno == ERANGE)\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"timeout value too large\"));\n\t\telse\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"invalid timeout value\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n#ifdef ENABLE_SUDO_PLUGIN_API\n\tif (MATCHES(*cur, \"plugin_dir=\")) {\n\t CHECK(*cur, \"plugin_dir=\");\n\t path_plugin_dir = *cur + sizeof(\"plugin_dir=\") - 1;\n\t continue;\n\t}\n#endif\n }\n\n /* Sudo front-end should restrict mode flags for sudoedit. */\n if (ISSET(flags, MODE_EDIT) && (flags & edit_mask) != flags) {\n\tsudo_warnx(U_(\"invalid mode flags from sudo front end: 0x%x\"), flags);\n\tgoto bad;\n }\n\n user_gid = (gid_t)-1;\n user_sid = (pid_t)-1;\n user_uid = (gid_t)-1;\n user_umask = (mode_t)-1;\n for (cur = info->user_info; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"user=\")) {\n\t CHECK(*cur, \"user=\");\n\t if ((user_name = strdup(*cur + sizeof(\"user=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"uid=\")) {\n\t p = *cur + sizeof(\"uid=\") - 1;\n\t user_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"gid=\")) {\n\t p = *cur + sizeof(\"gid=\") - 1;\n\t user_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"groups=\")) {\n\t CHECK(*cur, \"groups=\");\n\t groups = *cur + sizeof(\"groups=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cwd=\")) {\n\t CHECK(*cur, \"cwd=\");\n\t if ((user_cwd = strdup(*cur + sizeof(\"cwd=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"tty=\")) {\n\t CHECK(*cur, \"tty=\");\n\t if ((user_ttypath = strdup(*cur + sizeof(\"tty=\") - 1)) == NULL)\n\t\tgoto oom;\n\t user_tty = user_ttypath;\n\t if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)\n\t\tuser_tty += sizeof(_PATH_DEV) - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"host=\")) {\n\t CHECK(*cur, \"host=\");\n\t if ((user_host = strdup(*cur + sizeof(\"host=\") - 1)) == NULL)\n\t\tgoto oom;\n\t if ((p = strchr(user_host, '.')) != NULL) {\n\t\tuser_shost = strndup(user_host, (size_t)(p - user_host));\n\t\tif (user_shost == NULL)\n\t\t goto oom;\n\t } else {\n\t\tuser_shost = user_host;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"lines=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"lines=\") - 1;\n\t sudo_user.lines = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.lines == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cols=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"cols=\") - 1;\n\t sudo_user.cols = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.cols == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sid=\")) {\n\t p = *cur + sizeof(\"sid=\") - 1;\n\t user_sid = (pid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"umask=\")) {\n\t p = *cur + sizeof(\"umask=\") - 1;\n\t sudo_user.umask = sudo_strtomode(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n }\n\n /* User name, user-ID, group-ID and host name must be specified. */\n if (user_name == NULL) {\n\tsudo_warnx(\"%s\", U_(\"user name not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_uid == (uid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"user-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_gid == (gid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"group-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_host == NULL) {\n\tsudo_warnx(\"%s\", U_(\"host name not set by sudo front-end\"));\n\tgoto bad;\n }\n\n if ((user_runhost = strdup(remhost ? remhost : user_host)) == NULL)\n\tgoto oom;\n if ((p = strchr(user_runhost, '.')) != NULL) {\n\tuser_srunhost = strndup(user_runhost, (size_t)(p - user_runhost));\n\tif (user_srunhost == NULL)\n\t goto oom;\n } else {\n\tuser_srunhost = user_runhost;\n }\n if (user_cwd == NULL) {\n\tif ((user_cwd = strdup(\"unknown\")) == NULL)\n\t goto oom;\n }\n if (user_runcwd == NULL) {\n\tif ((user_runcwd = strdup(user_cwd)) == NULL)\n\t goto oom;\n }\n if (user_tty == NULL) {\n\tif ((user_tty = strdup(\"unknown\")) == NULL)\n\t goto oom;\n\t/* user_ttypath remains NULL */\n }\n\n if (groups != NULL) {\n\t/* sudo_parse_gids() will print a warning on error. */\n\tuser_ngids = sudo_parse_gids(groups, &user_gid, &user_gids);\n\tif (user_ngids == -1)\n\t goto bad;\n }\n\n /* umask is only set in user_info[] for API 1.10 and above. */\n if (user_umask == (mode_t)-1) {\n\tuser_umask = umask(0);\n\tumask(user_umask);\n }\n\n /* Always reset the environment for a login shell. */\n if (ISSET(flags, MODE_LOGIN_SHELL))\n\tdef_env_reset = true;\n\n /* Some systems support fexecve() which we use for digest matches. */\n cmnd_fd = -1;\n\n /* Dump settings and user info (XXX - plugin args) */\n for (cur = info->settings; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"settings: %s\", *cur);\n for (cur = info->user_info; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"user_info: %s\", *cur);\n\n#undef MATCHES\n#undef INVALID\n#undef CHECK\n debug_return_int(flags);\n\noom:\n sudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\nbad:\n debug_return_int(MODE_ERROR);\n}", "func_hash": 220700186458620971493558850287592547118, "file_name": "policy.c", "file_hash": 179005217035119130324823970264281645304, "cwe": ["CWE-193"], "cve": "CVE-2021-3156", "cve_desc": "Sudo before 1.9.5p2 contains an off-by-one error that can result in a heap-based buffer overflow, which allows privilege escalation to root via \"sudoedit -s\" and a command-line argument that ends with a single backslash character.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3156"} {"idx": 204337, "project": "neomutt", "commit_id": "9c36717a3e2af1f2c1b7242035455ec8112b4b06", "project_url": "https://github.com/neomutt/neomutt", "commit_url": "https://github.com/neomutt/neomutt/commit/9c36717a3e2af1f2c1b7242035455ec8112b4b06", "commit_message": "imap: close connection on all failures\n\nThanks to Gabriel Salles-Loustau for spotting the problem.\n\nCo-authored-by: Kevin McCarthy ", "target": 1, "func": "int imap_open_connection(struct ImapAccountData *adata)\n{\n if (mutt_socket_open(adata->conn) < 0)\n return -1;\n\n adata->state = IMAP_CONNECTED;\n\n if (imap_cmd_step(adata) != IMAP_RES_OK)\n {\n imap_close_connection(adata);\n return -1;\n }\n\n if (mutt_istr_startswith(adata->buf, \"* OK\"))\n {\n if (!mutt_istr_startswith(adata->buf, \"* OK [CAPABILITY\") && check_capabilities(adata))\n {\n goto bail;\n }\n#ifdef USE_SSL\n /* Attempt STARTTLS if available and desired. */\n if ((adata->conn->ssf == 0) && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS)))\n {\n enum QuadOption ans;\n\n if (C_SslForceTls)\n ans = MUTT_YES;\n else if ((ans = query_quadoption(C_SslStarttls,\n _(\"Secure connection with TLS?\"))) == MUTT_ABORT)\n {\n goto err_close_conn;\n }\n if (ans == MUTT_YES)\n {\n enum ImapExecResult rc = imap_exec(adata, \"STARTTLS\", IMAP_CMD_SINGLE);\n // Clear any data after the STARTTLS acknowledgement\n mutt_socket_empty(adata->conn);\n\n if (rc == IMAP_EXEC_FATAL)\n goto bail;\n if (rc != IMAP_EXEC_ERROR)\n {\n if (mutt_ssl_starttls(adata->conn))\n {\n mutt_error(_(\"Could not negotiate TLS connection\"));\n goto err_close_conn;\n }\n else\n {\n /* RFC2595 demands we recheck CAPABILITY after TLS completes. */\n if (imap_exec(adata, \"CAPABILITY\", IMAP_CMD_NO_FLAGS))\n goto bail;\n }\n }\n }\n }\n\n if (C_SslForceTls && (adata->conn->ssf == 0))\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto err_close_conn;\n }\n#endif\n }\n else if (mutt_istr_startswith(adata->buf, \"* PREAUTH\"))\n {\n#ifdef USE_SSL\n /* Unless using a secure $tunnel, an unencrypted PREAUTH response may be a\n * MITM attack. The only way to stop \"STARTTLS\" MITM attacks is via\n * $ssl_force_tls: an attacker can easily spoof \"* OK\" and strip the\n * STARTTLS capability. So consult $ssl_force_tls, not $ssl_starttls, to\n * decide whether to abort. Note that if using $tunnel and\n * $tunnel_is_secure, adata->conn->ssf will be set to 1. */\n if ((adata->conn->ssf == 0) && C_SslForceTls)\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto err_close_conn;\n }\n#endif\n\n adata->state = IMAP_AUTHENTICATED;\n if (check_capabilities(adata) != 0)\n goto bail;\n FREE(&adata->capstr);\n }\n else\n {\n imap_error(\"imap_open_connection()\", adata->buf);\n goto bail;\n }\n\n return 0;\n\n#ifdef USE_SSL\nerr_close_conn:\n imap_close_connection(adata);\n#endif\nbail:\n FREE(&adata->capstr);\n return -1;\n}", "func_hash": 93784481573427322112392051774990244975, "file_name": "imap.c", "file_hash": 112359935362005334749284802567448911812, "cwe": ["CWE-522"], "cve": "CVE-2020-28896", "cve_desc": "Mutt before 2.0.2 and NeoMutt before 2020-11-20 did not ensure that $ssl_force_tls was processed if an IMAP server's initial server response was invalid. The connection was not properly closed, and the code could continue attempting to authenticate. This could result in authentication credentials being exposed on an unencrypted connection, or to a machine-in-the-middle.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-28896"} {"idx": 357032, "project": "neomutt", "commit_id": "9c36717a3e2af1f2c1b7242035455ec8112b4b06", "project_url": "https://github.com/neomutt/neomutt", "commit_url": "https://github.com/neomutt/neomutt/commit/9c36717a3e2af1f2c1b7242035455ec8112b4b06", "commit_message": "imap: close connection on all failures\n\nThanks to Gabriel Salles-Loustau for spotting the problem.\n\nCo-authored-by: Kevin McCarthy ", "target": 0, "func": "int imap_open_connection(struct ImapAccountData *adata)\n{\n if (mutt_socket_open(adata->conn) < 0)\n return -1;\n\n adata->state = IMAP_CONNECTED;\n\n if (imap_cmd_step(adata) != IMAP_RES_OK)\n {\n imap_close_connection(adata);\n return -1;\n }\n\n if (mutt_istr_startswith(adata->buf, \"* OK\"))\n {\n if (!mutt_istr_startswith(adata->buf, \"* OK [CAPABILITY\") && check_capabilities(adata))\n {\n goto bail;\n }\n#ifdef USE_SSL\n /* Attempt STARTTLS if available and desired. */\n if ((adata->conn->ssf == 0) && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS)))\n {\n enum QuadOption ans;\n\n if (C_SslForceTls)\n ans = MUTT_YES;\n else if ((ans = query_quadoption(C_SslStarttls,\n _(\"Secure connection with TLS?\"))) == MUTT_ABORT)\n {\n goto bail;\n }\n if (ans == MUTT_YES)\n {\n enum ImapExecResult rc = imap_exec(adata, \"STARTTLS\", IMAP_CMD_SINGLE);\n // Clear any data after the STARTTLS acknowledgement\n mutt_socket_empty(adata->conn);\n\n if (rc == IMAP_EXEC_FATAL)\n goto bail;\n if (rc != IMAP_EXEC_ERROR)\n {\n if (mutt_ssl_starttls(adata->conn))\n {\n mutt_error(_(\"Could not negotiate TLS connection\"));\n goto bail;\n }\n else\n {\n /* RFC2595 demands we recheck CAPABILITY after TLS completes. */\n if (imap_exec(adata, \"CAPABILITY\", IMAP_CMD_NO_FLAGS))\n goto bail;\n }\n }\n }\n }\n\n if (C_SslForceTls && (adata->conn->ssf == 0))\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto bail;\n }\n#endif\n }\n else if (mutt_istr_startswith(adata->buf, \"* PREAUTH\"))\n {\n#ifdef USE_SSL\n /* Unless using a secure $tunnel, an unencrypted PREAUTH response may be a\n * MITM attack. The only way to stop \"STARTTLS\" MITM attacks is via\n * $ssl_force_tls: an attacker can easily spoof \"* OK\" and strip the\n * STARTTLS capability. So consult $ssl_force_tls, not $ssl_starttls, to\n * decide whether to abort. Note that if using $tunnel and\n * $tunnel_is_secure, adata->conn->ssf will be set to 1. */\n if ((adata->conn->ssf == 0) && C_SslForceTls)\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto bail;\n }\n#endif\n\n adata->state = IMAP_AUTHENTICATED;\n if (check_capabilities(adata) != 0)\n goto bail;\n FREE(&adata->capstr);\n }\n else\n {\n imap_error(\"imap_open_connection()\", adata->buf);\n goto bail;\n }\n\n return 0;\n\nbail:\n imap_close_connection(adata);\n FREE(&adata->capstr);\n return -1;\n}", "func_hash": 309933549090178399390442634015165106779, "file_name": "imap.c", "file_hash": 12750382870724217531930778784353883505, "cwe": ["CWE-522"], "cve": "CVE-2020-28896", "cve_desc": "Mutt before 2.0.2 and NeoMutt before 2020-11-20 did not ensure that $ssl_force_tls was processed if an IMAP server's initial server response was invalid. The connection was not properly closed, and the code could continue attempting to authenticate. This could result in authentication credentials being exposed on an unencrypted connection, or to a machine-in-the-middle.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-28896"} {"idx": 204345, "project": "openjpeg", "commit_id": "73fdf28342e4594019af26eb6a347a34eceb6296", "project_url": "https://github.com/uclouvain/openjpeg", "commit_url": "https://github.com/uclouvain/openjpeg/commit/73fdf28342e4594019af26eb6a347a34eceb6296", "commit_message": "opj_j2k_write_sod(): avoid potential heap buffer overflow (fixes #1299) (probably master only)", "target": 1, "func": "static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,\n opj_tcd_t * p_tile_coder,\n OPJ_BYTE * p_data,\n OPJ_UINT32 * p_data_written,\n OPJ_UINT32 total_data_size,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager\n )\n{\n opj_codestream_info_t *l_cstr_info = 00;\n OPJ_UINT32 l_remaining_data;\n opj_tcd_marker_info_t* marker_info = NULL;\n\n /* preconditions */\n assert(p_j2k != 00);\n assert(p_manager != 00);\n assert(p_stream != 00);\n\n OPJ_UNUSED(p_stream);\n\n if (total_data_size < 4) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Not enough bytes in output buffer to write SOD marker\\n\");\n return OPJ_FALSE;\n }\n\n opj_write_bytes(p_data, J2K_MS_SOD,\n 2); /* SOD */\n\n /* make room for the EOF marker */\n l_remaining_data = total_data_size - 4;\n\n /* update tile coder */\n p_tile_coder->tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;\n p_tile_coder->cur_tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n\n /* INDEX >> */\n /* TODO mergeV2: check this part which use cstr_info */\n /*l_cstr_info = p_j2k->cstr_info;\n if (l_cstr_info) {\n if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {\n //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;\n l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;\n }\n else {*/\n /*\n TODO\n if\n (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))\n {\n cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);\n }*/\n /*}*/\n /* UniPG>> */\n#ifdef USE_JPWL\n /* update markers struct */\n /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);\n */\n assert(0 && \"TODO\");\n#endif /* USE_JPWL */\n /* <m_specific_param.m_encoder.m_current_tile_part_number == 0) {\n p_tile_coder->tcd_image->tiles->packno = 0;\n#ifdef deadcode\n if (l_cstr_info) {\n l_cstr_info->packno = 0;\n }\n#endif\n }\n\n *p_data_written = 0;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n marker_info = opj_tcd_marker_info_create(\n p_j2k->m_specific_param.m_encoder.m_PLT);\n if (marker_info == NULL) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Cannot encode tile: opj_tcd_marker_info_create() failed\\n\");\n return OPJ_FALSE;\n }\n }\n\n assert(l_remaining_data >\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n l_remaining_data -= p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT;\n\n if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number,\n p_data + 2,\n p_data_written, l_remaining_data, l_cstr_info,\n marker_info,\n p_manager)) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot encode tile\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n\n /* For SOD */\n *p_data_written += 2;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n OPJ_UINT32 l_data_written_PLT = 0;\n OPJ_BYTE* p_PLT_buffer = (OPJ_BYTE*)opj_malloc(\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n if (!p_PLT_buffer) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot allocate memory\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n if (!opj_j2k_write_plt_in_memory(p_j2k,\n marker_info,\n p_PLT_buffer,\n &l_data_written_PLT,\n p_manager)) {\n opj_tcd_marker_info_destroy(marker_info);\n opj_free(p_PLT_buffer);\n return OPJ_FALSE;\n }\n\n assert(l_data_written_PLT <=\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n\n /* Move PLT marker(s) before SOD */\n memmove(p_data + l_data_written_PLT, p_data, *p_data_written);\n memcpy(p_data, p_PLT_buffer, l_data_written_PLT);\n opj_free(p_PLT_buffer);\n *p_data_written += l_data_written_PLT;\n }\n\n opj_tcd_marker_info_destroy(marker_info);\n\n return OPJ_TRUE;\n}", "func_hash": 34546354339261632456619948510424675060, "file_name": "j2k.c", "file_hash": 259008115029151894695758063160634365803, "cwe": ["CWE-20"], "cve": "CVE-2020-27844", "cve_desc": "A flaw was found in openjpeg's src/lib/openjp2/t2.c in versions prior to 2.4.0. This flaw allows an attacker to provide crafted input to openjpeg during conversion and encoding, causing an out-of-bounds write. The highest threat from this vulnerability is to confidentiality, integrity, as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27844"} {"idx": 357326, "project": "openjpeg", "commit_id": "73fdf28342e4594019af26eb6a347a34eceb6296", "project_url": "https://github.com/uclouvain/openjpeg", "commit_url": "https://github.com/uclouvain/openjpeg/commit/73fdf28342e4594019af26eb6a347a34eceb6296", "commit_message": "opj_j2k_write_sod(): avoid potential heap buffer overflow (fixes #1299) (probably master only)", "target": 0, "func": "static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,\n opj_tcd_t * p_tile_coder,\n OPJ_BYTE * p_data,\n OPJ_UINT32 * p_data_written,\n OPJ_UINT32 total_data_size,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager\n )\n{\n opj_codestream_info_t *l_cstr_info = 00;\n OPJ_UINT32 l_remaining_data;\n opj_tcd_marker_info_t* marker_info = NULL;\n\n /* preconditions */\n assert(p_j2k != 00);\n assert(p_manager != 00);\n assert(p_stream != 00);\n\n OPJ_UNUSED(p_stream);\n\n if (total_data_size < 4) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Not enough bytes in output buffer to write SOD marker\\n\");\n return OPJ_FALSE;\n }\n\n opj_write_bytes(p_data, J2K_MS_SOD,\n 2); /* SOD */\n\n /* make room for the EOF marker */\n l_remaining_data = total_data_size - 4;\n\n /* update tile coder */\n p_tile_coder->tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;\n p_tile_coder->cur_tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n\n /* INDEX >> */\n /* TODO mergeV2: check this part which use cstr_info */\n /*l_cstr_info = p_j2k->cstr_info;\n if (l_cstr_info) {\n if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {\n //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;\n l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;\n }\n else {*/\n /*\n TODO\n if\n (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))\n {\n cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);\n }*/\n /*}*/\n /* UniPG>> */\n#ifdef USE_JPWL\n /* update markers struct */\n /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);\n */\n assert(0 && \"TODO\");\n#endif /* USE_JPWL */\n /* <m_specific_param.m_encoder.m_current_tile_part_number == 0) {\n p_tile_coder->tcd_image->tiles->packno = 0;\n#ifdef deadcode\n if (l_cstr_info) {\n l_cstr_info->packno = 0;\n }\n#endif\n }\n\n *p_data_written = 0;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n marker_info = opj_tcd_marker_info_create(\n p_j2k->m_specific_param.m_encoder.m_PLT);\n if (marker_info == NULL) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Cannot encode tile: opj_tcd_marker_info_create() failed\\n\");\n return OPJ_FALSE;\n }\n }\n\n if (l_remaining_data <\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Not enough bytes in output buffer to write SOD marker\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n l_remaining_data -= p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT;\n\n if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number,\n p_data + 2,\n p_data_written, l_remaining_data, l_cstr_info,\n marker_info,\n p_manager)) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot encode tile\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n\n /* For SOD */\n *p_data_written += 2;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n OPJ_UINT32 l_data_written_PLT = 0;\n OPJ_BYTE* p_PLT_buffer = (OPJ_BYTE*)opj_malloc(\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n if (!p_PLT_buffer) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot allocate memory\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n if (!opj_j2k_write_plt_in_memory(p_j2k,\n marker_info,\n p_PLT_buffer,\n &l_data_written_PLT,\n p_manager)) {\n opj_tcd_marker_info_destroy(marker_info);\n opj_free(p_PLT_buffer);\n return OPJ_FALSE;\n }\n\n assert(l_data_written_PLT <=\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n\n /* Move PLT marker(s) before SOD */\n memmove(p_data + l_data_written_PLT, p_data, *p_data_written);\n memcpy(p_data, p_PLT_buffer, l_data_written_PLT);\n opj_free(p_PLT_buffer);\n *p_data_written += l_data_written_PLT;\n }\n\n opj_tcd_marker_info_destroy(marker_info);\n\n return OPJ_TRUE;\n}", "func_hash": 6905568543353010466362332534230544208, "file_name": "j2k.c", "file_hash": 130406106314953887257782839529645170894, "cwe": ["CWE-20"], "cve": "CVE-2020-27844", "cve_desc": "A flaw was found in openjpeg's src/lib/openjp2/t2.c in versions prior to 2.4.0. This flaw allows an attacker to provide crafted input to openjpeg during conversion and encoding, causing an out-of-bounds write. The highest threat from this vulnerability is to confidentiality, integrity, as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27844"} {"idx": 204380, "project": "p11-kit", "commit_id": "2617f3ef888e103324a28811886b99ed0a56346d", "project_url": "https://github.com/p11-glue/p11-kit", "commit_url": "https://github.com/p11-glue/p11-kit/commit/2617f3ef888e103324a28811886b99ed0a56346d", "commit_message": "Check attribute length against buffer size\n\nIf an attribute's length does not match the length of the byte array\ninside it, one length was used for allocation, and the other was used\nfor memcpy. This additional check will instead return an error on\nmalformed messages.", "target": 1, "func": "p11_rpc_buffer_get_attribute (p11_buffer *buffer,\n\t\t\t size_t *offset,\n\t\t\t CK_ATTRIBUTE *attr)\n{\n\tuint32_t type, length;\n\tunsigned char validity;\n\tp11_rpc_attribute_serializer *serializer;\n\tp11_rpc_value_type value_type;\n\n\t/* The attribute type */\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &type))\n\t\treturn false;\n\n\t/* Attribute validity */\n\tif (!p11_rpc_buffer_get_byte (buffer, offset, &validity))\n\t\treturn false;\n\n\t/* Not a valid attribute */\n\tif (!validity) {\n\t\tattr->ulValueLen = ((CK_ULONG)-1);\n\t\tattr->type = type;\n\t\treturn true;\n\t}\n\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &length))\n\t\treturn false;\n\n\t/* Decode the attribute value */\n\tvalue_type = map_attribute_to_value_type (type);\n\tassert (value_type < ELEMS (p11_rpc_attribute_serializers));\n\tserializer = &p11_rpc_attribute_serializers[value_type];\n\tassert (serializer != NULL);\n\tif (!serializer->decode (buffer, offset, attr->pValue, &attr->ulValueLen))\n\t\treturn false;\n\tif (!attr->pValue)\n\t\tattr->ulValueLen = length;\n\tattr->type = type;\n\treturn true;\n}", "func_hash": 84951473144972188856086810662960675896, "file_name": "rpc-message.c", "file_hash": 218775460487908262432373384827836061043, "cwe": ["CWE-787"], "cve": "CVE-2020-29363", "cve_desc": "An issue was discovered in p11-kit 0.23.6 through 0.23.21. A heap-based buffer overflow has been discovered in the RPC protocol used by p11-kit server/remote commands and the client library. When the remote entity supplies a serialized byte array in a CK_ATTRIBUTE, the receiving entity may not allocate sufficient length for the buffer to store the deserialized value.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29363"} {"idx": 358130, "project": "p11-kit", "commit_id": "2617f3ef888e103324a28811886b99ed0a56346d", "project_url": "https://github.com/p11-glue/p11-kit", "commit_url": "https://github.com/p11-glue/p11-kit/commit/2617f3ef888e103324a28811886b99ed0a56346d", "commit_message": "Check attribute length against buffer size\n\nIf an attribute's length does not match the length of the byte array\ninside it, one length was used for allocation, and the other was used\nfor memcpy. This additional check will instead return an error on\nmalformed messages.", "target": 0, "func": "p11_rpc_buffer_get_attribute (p11_buffer *buffer,\n\t\t\t size_t *offset,\n\t\t\t CK_ATTRIBUTE *attr)\n{\n\tuint32_t type, length, decode_length;\n\tunsigned char validity;\n\tp11_rpc_attribute_serializer *serializer;\n\tp11_rpc_value_type value_type;\n\n\t/* The attribute type */\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &type))\n\t\treturn false;\n\n\t/* Attribute validity */\n\tif (!p11_rpc_buffer_get_byte (buffer, offset, &validity))\n\t\treturn false;\n\n\t/* Not a valid attribute */\n\tif (!validity) {\n\t\tattr->ulValueLen = ((CK_ULONG)-1);\n\t\tattr->type = type;\n\t\treturn true;\n\t}\n\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &length))\n\t\treturn false;\n\n\t/* Decode the attribute value */\n\tvalue_type = map_attribute_to_value_type (type);\n\tassert (value_type < ELEMS (p11_rpc_attribute_serializers));\n\tserializer = &p11_rpc_attribute_serializers[value_type];\n\tassert (serializer != NULL);\n\tif (!serializer->decode (buffer, offset, attr->pValue, &attr->ulValueLen))\n\t\treturn false;\n\tif (!attr->pValue) {\n\t\tdecode_length = attr->ulValueLen;\n\t\tattr->ulValueLen = length;\n\t\tif (decode_length > length) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tattr->type = type;\n\treturn true;\n}", "func_hash": 208075421498069336026999228714755505760, "file_name": "rpc-message.c", "file_hash": 305078838636873668676733828148939508794, "cwe": ["CWE-787"], "cve": "CVE-2020-29363", "cve_desc": "An issue was discovered in p11-kit 0.23.6 through 0.23.21. A heap-based buffer overflow has been discovered in the RPC protocol used by p11-kit server/remote commands and the client library. When the remote entity supplies a serialized byte array in a CK_ATTRIBUTE, the receiving entity may not allocate sufficient length for the buffer to store the deserialized value.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29363"} {"idx": 204411, "project": "openjpeg", "commit_id": "15cf3d95814dc931ca0ecb132f81cb152e051bae", "project_url": "https://github.com/uclouvain/openjpeg", "commit_url": "https://github.com/uclouvain/openjpeg/commit/15cf3d95814dc931ca0ecb132f81cb152e051bae", "commit_message": "Encoder: grow again buffer size in opj_tcd_code_block_enc_allocate_data() (fixes #1283)", "target": 1, "func": "static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *\n p_code_block)\n{\n OPJ_UINT32 l_data_size;\n\n /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */\n /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */\n /* and +7 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 3) */\n /* and +26 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 7) */\n /* TODO: is there a theoretical upper-bound for the compressed code */\n /* block size ? */\n l_data_size = 26 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *\n (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));\n\n if (l_data_size > p_code_block->data_size) {\n if (p_code_block->data) {\n /* We refer to data - 1 since below we incremented it */\n opj_free(p_code_block->data - 1);\n }\n p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);\n if (! p_code_block->data) {\n p_code_block->data_size = 0U;\n return OPJ_FALSE;\n }\n p_code_block->data_size = l_data_size;\n\n /* We reserve the initial byte as a fake byte to a non-FF value */\n /* and increment the data pointer, so that opj_mqc_init_enc() */\n /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */\n /* it. */\n p_code_block->data[0] = 0;\n p_code_block->data += 1; /*why +1 ?*/\n }\n return OPJ_TRUE;\n}", "func_hash": 77446808125543815045226261374735164207, "file_name": "tcd.c", "file_hash": 228264055130794049372695262967126714227, "cwe": ["CWE-122"], "cve": "CVE-2020-27814", "cve_desc": "A heap-buffer overflow was found in the way openjpeg2 handled certain PNG format files. An attacker could use this flaw to cause an application crash or in some cases execute arbitrary code with the permission of the user running such an application.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27814"} {"idx": 359168, "project": "openjpeg", "commit_id": "15cf3d95814dc931ca0ecb132f81cb152e051bae", "project_url": "https://github.com/uclouvain/openjpeg", "commit_url": "https://github.com/uclouvain/openjpeg/commit/15cf3d95814dc931ca0ecb132f81cb152e051bae", "commit_message": "Encoder: grow again buffer size in opj_tcd_code_block_enc_allocate_data() (fixes #1283)", "target": 0, "func": "static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *\n p_code_block)\n{\n OPJ_UINT32 l_data_size;\n\n /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */\n /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */\n /* and +7 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 3) */\n /* and +26 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 7) */\n /* and +28 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 44) */\n /* TODO: is there a theoretical upper-bound for the compressed code */\n /* block size ? */\n l_data_size = 28 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *\n (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));\n\n if (l_data_size > p_code_block->data_size) {\n if (p_code_block->data) {\n /* We refer to data - 1 since below we incremented it */\n opj_free(p_code_block->data - 1);\n }\n p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);\n if (! p_code_block->data) {\n p_code_block->data_size = 0U;\n return OPJ_FALSE;\n }\n p_code_block->data_size = l_data_size;\n\n /* We reserve the initial byte as a fake byte to a non-FF value */\n /* and increment the data pointer, so that opj_mqc_init_enc() */\n /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */\n /* it. */\n p_code_block->data[0] = 0;\n p_code_block->data += 1; /*why +1 ?*/\n }\n return OPJ_TRUE;\n}", "func_hash": 28637146395998447199250289614239361744, "file_name": "tcd.c", "file_hash": 240020116084600996942290856885366127372, "cwe": ["CWE-122"], "cve": "CVE-2020-27814", "cve_desc": "A heap-buffer overflow was found in the way openjpeg2 handled certain PNG format files. An attacker could use this flaw to cause an application crash or in some cases execute arbitrary code with the permission of the user running such an application.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27814"} {"idx": 204491, "project": "x11vnc", "commit_id": "69eeb9f7baa14ca03b16c9de821f9876def7a36a", "project_url": "https://github.com/LibVNC/x11vnc", "commit_url": "https://github.com/LibVNC/x11vnc/commit/69eeb9f7baa14ca03b16c9de821f9876def7a36a", "commit_message": "scan: limit access to shared memory segments to current user", "target": 1, "func": "static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h,\n char *name) {\n\n\tXImage *xim;\n\tstatic int reported_flip = 0;\n\tint db = 0;\n\n\tshm->shmid = -1;\n\tshm->shmaddr = (char *) -1;\n\t*ximg_ptr = NULL;\n\n\tif (nofb) {\n\t\treturn 1;\n\t}\n\n\tX_LOCK;\n\n\tif (! using_shm || xform24to32 || raw_fb) {\n\t\t/* we only need the XImage created */\n\t\txim = XCreateImage_wr(dpy, default_visual, depth, ZPixmap,\n\t\t 0, NULL, w, h, raw_fb ? 32 : BitmapPad(dpy), 0);\n\n\t\tX_UNLOCK;\n\n\t\tif (xim == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) failed.\\n\",\n\t\t\t\t name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (db) fprintf(stderr, \"shm_create simple %d %d\\t%p %s\\n\", w, h, (void *)xim, name);\n\t\txim->data = (char *) malloc(xim->bytes_per_line * xim->height);\n\t\tif (xim->data == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) data malloc failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) data malloc\"\n\t\t\t\t \" failed.\\n\", name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (flip_byte_order) {\n\t\t\tchar *order = flip_ximage_byte_order(xim);\n\t\t\tif (! reported_flip && ! quiet) {\n\t\t\t\trfbLog(\"Changing XImage byte order\"\n\t\t\t\t \" to %s\\n\", order);\n\t\t\t\treported_flip = 1;\n\t\t\t}\n\t\t}\n\n\t\t*ximg_ptr = xim;\n\t\treturn 1;\n\t}\n\n\tif (! dpy) {\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\txim = XShmCreateImage_wr(dpy, default_visual, depth, ZPixmap, NULL,\n\t shm, w, h);\n\n\tif (xim == NULL) {\n\t\trfbErr(\"XShmCreateImage(%s) failed.\\n\", name);\n\t\tif (quiet) {\n\t\t\tfprintf(stderr, \"XShmCreateImage(%s) failed.\\n\", name);\n\t\t}\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\t*ximg_ptr = xim;\n\n#if HAVE_XSHM\n\tshm->shmid = shmget(IPC_PRIVATE,\n\t xim->bytes_per_line * xim->height, IPC_CREAT | 0777);\n\n\tif (shm->shmid == -1) {\n\t\trfbErr(\"shmget(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmget\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->shmaddr = xim->data = (char *) shmat(shm->shmid, 0, 0);\n\n\tif (shm->shmaddr == (char *)-1) {\n\t\trfbErr(\"shmat(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmat\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->readOnly = False;\n\n\tif (! XShmAttach_wr(dpy, shm)) {\n\t\trfbErr(\"XShmAttach(%s) failed.\\n\", name);\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmdt(shm->shmaddr);\n\t\tshm->shmaddr = (char *) -1;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n#endif\n\n\tX_UNLOCK;\n\treturn 1;\n}", "func_hash": 160674915493190426550761849186987896054, "file_name": "scan.c", "file_hash": 215815604001033938936434534992335895925, "cwe": ["CWE-284"], "cve": "CVE-2020-29074", "cve_desc": "scan.c in x11vnc 0.9.16 uses IPC_CREAT|0777 in shmget calls, which allows access by actors other than the current user.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29074"} {"idx": 360762, "project": "x11vnc", "commit_id": "69eeb9f7baa14ca03b16c9de821f9876def7a36a", "project_url": "https://github.com/LibVNC/x11vnc", "commit_url": "https://github.com/LibVNC/x11vnc/commit/69eeb9f7baa14ca03b16c9de821f9876def7a36a", "commit_message": "scan: limit access to shared memory segments to current user", "target": 0, "func": "static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h,\n char *name) {\n\n\tXImage *xim;\n\tstatic int reported_flip = 0;\n\tint db = 0;\n\n\tshm->shmid = -1;\n\tshm->shmaddr = (char *) -1;\n\t*ximg_ptr = NULL;\n\n\tif (nofb) {\n\t\treturn 1;\n\t}\n\n\tX_LOCK;\n\n\tif (! using_shm || xform24to32 || raw_fb) {\n\t\t/* we only need the XImage created */\n\t\txim = XCreateImage_wr(dpy, default_visual, depth, ZPixmap,\n\t\t 0, NULL, w, h, raw_fb ? 32 : BitmapPad(dpy), 0);\n\n\t\tX_UNLOCK;\n\n\t\tif (xim == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) failed.\\n\",\n\t\t\t\t name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (db) fprintf(stderr, \"shm_create simple %d %d\\t%p %s\\n\", w, h, (void *)xim, name);\n\t\txim->data = (char *) malloc(xim->bytes_per_line * xim->height);\n\t\tif (xim->data == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) data malloc failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) data malloc\"\n\t\t\t\t \" failed.\\n\", name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (flip_byte_order) {\n\t\t\tchar *order = flip_ximage_byte_order(xim);\n\t\t\tif (! reported_flip && ! quiet) {\n\t\t\t\trfbLog(\"Changing XImage byte order\"\n\t\t\t\t \" to %s\\n\", order);\n\t\t\t\treported_flip = 1;\n\t\t\t}\n\t\t}\n\n\t\t*ximg_ptr = xim;\n\t\treturn 1;\n\t}\n\n\tif (! dpy) {\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\txim = XShmCreateImage_wr(dpy, default_visual, depth, ZPixmap, NULL,\n\t shm, w, h);\n\n\tif (xim == NULL) {\n\t\trfbErr(\"XShmCreateImage(%s) failed.\\n\", name);\n\t\tif (quiet) {\n\t\t\tfprintf(stderr, \"XShmCreateImage(%s) failed.\\n\", name);\n\t\t}\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\t*ximg_ptr = xim;\n\n#if HAVE_XSHM\n\tshm->shmid = shmget(IPC_PRIVATE,\n\t xim->bytes_per_line * xim->height, IPC_CREAT | 0600);\n\n\tif (shm->shmid == -1) {\n\t\trfbErr(\"shmget(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmget\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->shmaddr = xim->data = (char *) shmat(shm->shmid, 0, 0);\n\n\tif (shm->shmaddr == (char *)-1) {\n\t\trfbErr(\"shmat(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmat\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->readOnly = False;\n\n\tif (! XShmAttach_wr(dpy, shm)) {\n\t\trfbErr(\"XShmAttach(%s) failed.\\n\", name);\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmdt(shm->shmaddr);\n\t\tshm->shmaddr = (char *) -1;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n#endif\n\n\tX_UNLOCK;\n\treturn 1;\n}", "func_hash": 131458532570037914024580191951431826486, "file_name": "scan.c", "file_hash": 336958043898065117217964953114003835789, "cwe": ["CWE-284"], "cve": "CVE-2020-29074", "cve_desc": "scan.c in x11vnc 0.9.16 uses IPC_CREAT|0777 in shmget calls, which allows access by actors other than the current user.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29074"} {"idx": 204533, "project": "redis", "commit_id": "394614a5f91d88380f480c4610926a865b5b0f16", "project_url": "https://github.com/antirez/redis", "commit_url": "https://github.com/redis/redis/commit/394614a5f91d88380f480c4610926a865b5b0f16", "commit_message": "Fix integer overflow in STRALGO LCS (CVE-2021-29477)\n\nAn integer overflow bug in Redis version 6.0 or newer could be exploited using\nthe STRALGO LCS command to corrupt the heap and potentially result with remote\ncode execution.\n\n(cherry picked from commit f0c5f920d0f88bd8aa376a2c05af4902789d1ef9)", "target": 1, "func": "void stralgoLCS(client *c) {\n uint32_t i, j;\n long long minmatchlen = 0;\n sds a = NULL, b = NULL;\n int getlen = 0, getidx = 0, withmatchlen = 0;\n robj *obja = NULL, *objb = NULL;\n\n for (j = 2; j < (uint32_t)c->argc; j++) {\n char *opt = c->argv[j]->ptr;\n int moreargs = (c->argc-1) - j;\n\n if (!strcasecmp(opt,\"IDX\")) {\n getidx = 1;\n } else if (!strcasecmp(opt,\"LEN\")) {\n getlen = 1;\n } else if (!strcasecmp(opt,\"WITHMATCHLEN\")) {\n withmatchlen = 1;\n } else if (!strcasecmp(opt,\"MINMATCHLEN\") && moreargs) {\n if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL)\n != C_OK) goto cleanup;\n if (minmatchlen < 0) minmatchlen = 0;\n j++;\n } else if (!strcasecmp(opt,\"STRINGS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n a = c->argv[j+1]->ptr;\n b = c->argv[j+2]->ptr;\n j += 2;\n } else if (!strcasecmp(opt,\"KEYS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n obja = lookupKeyRead(c->db,c->argv[j+1]);\n objb = lookupKeyRead(c->db,c->argv[j+2]);\n if ((obja && obja->type != OBJ_STRING) ||\n (objb && objb->type != OBJ_STRING))\n {\n addReplyError(c,\n \"The specified keys must contain string values\");\n /* Don't cleanup the objects, we need to do that\n * only after callign getDecodedObject(). */\n obja = NULL;\n objb = NULL;\n goto cleanup;\n }\n obja = obja ? getDecodedObject(obja) : createStringObject(\"\",0);\n objb = objb ? getDecodedObject(objb) : createStringObject(\"\",0);\n a = obja->ptr;\n b = objb->ptr;\n j += 2;\n } else {\n addReply(c,shared.syntaxerr);\n goto cleanup;\n }\n }\n\n /* Complain if the user passed ambiguous parameters. */\n if (a == NULL) {\n addReplyError(c,\"Please specify two strings: \"\n \"STRINGS or KEYS options are mandatory\");\n goto cleanup;\n } else if (getlen && getidx) {\n addReplyError(c,\n \"If you want both the length and indexes, please \"\n \"just use IDX.\");\n goto cleanup;\n }\n\n /* Compute the LCS using the vanilla dynamic programming technique of\n * building a table of LCS(x,y) substrings. */\n uint32_t alen = sdslen(a);\n uint32_t blen = sdslen(b);\n\n /* Setup an uint32_t array to store at LCS[i,j] the length of the\n * LCS A0..i-1, B0..j-1. Note that we have a linear array here, so\n * we index it as LCS[j+(blen+1)*j] */\n uint32_t *lcs = zmalloc((alen+1)*(blen+1)*sizeof(uint32_t));\n #define LCS(A,B) lcs[(B)+((A)*(blen+1))]\n\n /* Start building the LCS table. */\n for (uint32_t i = 0; i <= alen; i++) {\n for (uint32_t j = 0; j <= blen; j++) {\n if (i == 0 || j == 0) {\n /* If one substring has length of zero, the\n * LCS length is zero. */\n LCS(i,j) = 0;\n } else if (a[i-1] == b[j-1]) {\n /* The len LCS (and the LCS itself) of two\n * sequences with the same final character, is the\n * LCS of the two sequences without the last char\n * plus that last char. */\n LCS(i,j) = LCS(i-1,j-1)+1;\n } else {\n /* If the last character is different, take the longest\n * between the LCS of the first string and the second\n * minus the last char, and the reverse. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n LCS(i,j) = lcs1 > lcs2 ? lcs1 : lcs2;\n }\n }\n }\n\n /* Store the actual LCS string in \"result\" if needed. We create\n * it backward, but the length is already known, we store it into idx. */\n uint32_t idx = LCS(alen,blen);\n sds result = NULL; /* Resulting LCS string. */\n void *arraylenptr = NULL; /* Deffered length of the array for IDX. */\n uint32_t arange_start = alen, /* alen signals that values are not set. */\n arange_end = 0,\n brange_start = 0,\n brange_end = 0;\n\n /* Do we need to compute the actual LCS string? Allocate it in that case. */\n int computelcs = getidx || !getlen;\n if (computelcs) result = sdsnewlen(SDS_NOINIT,idx);\n\n /* Start with a deferred array if we have to emit the ranges. */\n uint32_t arraylen = 0; /* Number of ranges emitted in the array. */\n if (getidx) {\n addReplyMapLen(c,2);\n addReplyBulkCString(c,\"matches\");\n arraylenptr = addReplyDeferredLen(c);\n }\n\n i = alen, j = blen;\n while (computelcs && i > 0 && j > 0) {\n int emit_range = 0;\n if (a[i-1] == b[j-1]) {\n /* If there is a match, store the character and reduce\n * the indexes to look for a new match. */\n result[idx-1] = a[i-1];\n\n /* Track the current range. */\n if (arange_start == alen) {\n arange_start = i-1;\n arange_end = i-1;\n brange_start = j-1;\n brange_end = j-1;\n } else {\n /* Let's see if we can extend the range backward since\n * it is contiguous. */\n if (arange_start == i && brange_start == j) {\n arange_start--;\n brange_start--;\n } else {\n emit_range = 1;\n }\n }\n /* Emit the range if we matched with the first byte of\n * one of the two strings. We'll exit the loop ASAP. */\n if (arange_start == 0 || brange_start == 0) emit_range = 1;\n idx--; i--; j--;\n } else {\n /* Otherwise reduce i and j depending on the largest\n * LCS between, to understand what direction we need to go. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n if (lcs1 > lcs2)\n i--;\n else\n j--;\n if (arange_start != alen) emit_range = 1;\n }\n\n /* Emit the current range if needed. */\n uint32_t match_len = arange_end - arange_start + 1;\n if (emit_range) {\n if (minmatchlen == 0 || match_len >= minmatchlen) {\n if (arraylenptr) {\n addReplyArrayLen(c,2+withmatchlen);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,arange_start);\n addReplyLongLong(c,arange_end);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,brange_start);\n addReplyLongLong(c,brange_end);\n if (withmatchlen) addReplyLongLong(c,match_len);\n arraylen++;\n }\n }\n arange_start = alen; /* Restart at the next match. */\n }\n }\n\n /* Signal modified key, increment dirty, ... */\n\n /* Reply depending on the given options. */\n if (arraylenptr) {\n addReplyBulkCString(c,\"len\");\n addReplyLongLong(c,LCS(alen,blen));\n setDeferredArrayLen(c,arraylenptr,arraylen);\n } else if (getlen) {\n addReplyLongLong(c,LCS(alen,blen));\n } else {\n addReplyBulkSds(c,result);\n result = NULL;\n }\n\n /* Cleanup. */\n sdsfree(result);\n zfree(lcs);\n\ncleanup:\n if (obja) decrRefCount(obja);\n if (objb) decrRefCount(objb);\n return;\n}", "func_hash": 332626774353740168750649144666525377879, "file_name": "t_string.c", "file_hash": 80148431573971948655025802281854616072, "cwe": ["CWE-190"], "cve": "CVE-2021-29477", "cve_desc": "Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. An integer overflow bug in Redis version 6.0 or newer could be exploited using the `STRALGO LCS` command to corrupt the heap and potentially result with remote code execution. The problem is fixed in version 6.2.3 and 6.0.13. An additional workaround to mitigate the problem without patching the redis-server executable is to use ACL configuration to prevent clients from using the `STRALGO LCS` command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29477"} {"idx": 361275, "project": "redis", "commit_id": "394614a5f91d88380f480c4610926a865b5b0f16", "project_url": "https://github.com/antirez/redis", "commit_url": "https://github.com/redis/redis/commit/394614a5f91d88380f480c4610926a865b5b0f16", "commit_message": "Fix integer overflow in STRALGO LCS (CVE-2021-29477)\n\nAn integer overflow bug in Redis version 6.0 or newer could be exploited using\nthe STRALGO LCS command to corrupt the heap and potentially result with remote\ncode execution.\n\n(cherry picked from commit f0c5f920d0f88bd8aa376a2c05af4902789d1ef9)", "target": 0, "func": "void stralgoLCS(client *c) {\n uint32_t i, j;\n long long minmatchlen = 0;\n sds a = NULL, b = NULL;\n int getlen = 0, getidx = 0, withmatchlen = 0;\n robj *obja = NULL, *objb = NULL;\n\n for (j = 2; j < (uint32_t)c->argc; j++) {\n char *opt = c->argv[j]->ptr;\n int moreargs = (c->argc-1) - j;\n\n if (!strcasecmp(opt,\"IDX\")) {\n getidx = 1;\n } else if (!strcasecmp(opt,\"LEN\")) {\n getlen = 1;\n } else if (!strcasecmp(opt,\"WITHMATCHLEN\")) {\n withmatchlen = 1;\n } else if (!strcasecmp(opt,\"MINMATCHLEN\") && moreargs) {\n if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL)\n != C_OK) goto cleanup;\n if (minmatchlen < 0) minmatchlen = 0;\n j++;\n } else if (!strcasecmp(opt,\"STRINGS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n a = c->argv[j+1]->ptr;\n b = c->argv[j+2]->ptr;\n j += 2;\n } else if (!strcasecmp(opt,\"KEYS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n obja = lookupKeyRead(c->db,c->argv[j+1]);\n objb = lookupKeyRead(c->db,c->argv[j+2]);\n if ((obja && obja->type != OBJ_STRING) ||\n (objb && objb->type != OBJ_STRING))\n {\n addReplyError(c,\n \"The specified keys must contain string values\");\n /* Don't cleanup the objects, we need to do that\n * only after callign getDecodedObject(). */\n obja = NULL;\n objb = NULL;\n goto cleanup;\n }\n obja = obja ? getDecodedObject(obja) : createStringObject(\"\",0);\n objb = objb ? getDecodedObject(objb) : createStringObject(\"\",0);\n a = obja->ptr;\n b = objb->ptr;\n j += 2;\n } else {\n addReply(c,shared.syntaxerr);\n goto cleanup;\n }\n }\n\n /* Complain if the user passed ambiguous parameters. */\n if (a == NULL) {\n addReplyError(c,\"Please specify two strings: \"\n \"STRINGS or KEYS options are mandatory\");\n goto cleanup;\n } else if (getlen && getidx) {\n addReplyError(c,\n \"If you want both the length and indexes, please \"\n \"just use IDX.\");\n goto cleanup;\n }\n\n /* Compute the LCS using the vanilla dynamic programming technique of\n * building a table of LCS(x,y) substrings. */\n uint32_t alen = sdslen(a);\n uint32_t blen = sdslen(b);\n\n /* Setup an uint32_t array to store at LCS[i,j] the length of the\n * LCS A0..i-1, B0..j-1. Note that we have a linear array here, so\n * we index it as LCS[j+(blen+1)*j] */\n uint32_t *lcs = zmalloc((size_t)(alen+1)*(blen+1)*sizeof(uint32_t));\n #define LCS(A,B) lcs[(B)+((A)*(blen+1))]\n\n /* Start building the LCS table. */\n for (uint32_t i = 0; i <= alen; i++) {\n for (uint32_t j = 0; j <= blen; j++) {\n if (i == 0 || j == 0) {\n /* If one substring has length of zero, the\n * LCS length is zero. */\n LCS(i,j) = 0;\n } else if (a[i-1] == b[j-1]) {\n /* The len LCS (and the LCS itself) of two\n * sequences with the same final character, is the\n * LCS of the two sequences without the last char\n * plus that last char. */\n LCS(i,j) = LCS(i-1,j-1)+1;\n } else {\n /* If the last character is different, take the longest\n * between the LCS of the first string and the second\n * minus the last char, and the reverse. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n LCS(i,j) = lcs1 > lcs2 ? lcs1 : lcs2;\n }\n }\n }\n\n /* Store the actual LCS string in \"result\" if needed. We create\n * it backward, but the length is already known, we store it into idx. */\n uint32_t idx = LCS(alen,blen);\n sds result = NULL; /* Resulting LCS string. */\n void *arraylenptr = NULL; /* Deffered length of the array for IDX. */\n uint32_t arange_start = alen, /* alen signals that values are not set. */\n arange_end = 0,\n brange_start = 0,\n brange_end = 0;\n\n /* Do we need to compute the actual LCS string? Allocate it in that case. */\n int computelcs = getidx || !getlen;\n if (computelcs) result = sdsnewlen(SDS_NOINIT,idx);\n\n /* Start with a deferred array if we have to emit the ranges. */\n uint32_t arraylen = 0; /* Number of ranges emitted in the array. */\n if (getidx) {\n addReplyMapLen(c,2);\n addReplyBulkCString(c,\"matches\");\n arraylenptr = addReplyDeferredLen(c);\n }\n\n i = alen, j = blen;\n while (computelcs && i > 0 && j > 0) {\n int emit_range = 0;\n if (a[i-1] == b[j-1]) {\n /* If there is a match, store the character and reduce\n * the indexes to look for a new match. */\n result[idx-1] = a[i-1];\n\n /* Track the current range. */\n if (arange_start == alen) {\n arange_start = i-1;\n arange_end = i-1;\n brange_start = j-1;\n brange_end = j-1;\n } else {\n /* Let's see if we can extend the range backward since\n * it is contiguous. */\n if (arange_start == i && brange_start == j) {\n arange_start--;\n brange_start--;\n } else {\n emit_range = 1;\n }\n }\n /* Emit the range if we matched with the first byte of\n * one of the two strings. We'll exit the loop ASAP. */\n if (arange_start == 0 || brange_start == 0) emit_range = 1;\n idx--; i--; j--;\n } else {\n /* Otherwise reduce i and j depending on the largest\n * LCS between, to understand what direction we need to go. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n if (lcs1 > lcs2)\n i--;\n else\n j--;\n if (arange_start != alen) emit_range = 1;\n }\n\n /* Emit the current range if needed. */\n uint32_t match_len = arange_end - arange_start + 1;\n if (emit_range) {\n if (minmatchlen == 0 || match_len >= minmatchlen) {\n if (arraylenptr) {\n addReplyArrayLen(c,2+withmatchlen);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,arange_start);\n addReplyLongLong(c,arange_end);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,brange_start);\n addReplyLongLong(c,brange_end);\n if (withmatchlen) addReplyLongLong(c,match_len);\n arraylen++;\n }\n }\n arange_start = alen; /* Restart at the next match. */\n }\n }\n\n /* Signal modified key, increment dirty, ... */\n\n /* Reply depending on the given options. */\n if (arraylenptr) {\n addReplyBulkCString(c,\"len\");\n addReplyLongLong(c,LCS(alen,blen));\n setDeferredArrayLen(c,arraylenptr,arraylen);\n } else if (getlen) {\n addReplyLongLong(c,LCS(alen,blen));\n } else {\n addReplyBulkSds(c,result);\n result = NULL;\n }\n\n /* Cleanup. */\n sdsfree(result);\n zfree(lcs);\n\ncleanup:\n if (obja) decrRefCount(obja);\n if (objb) decrRefCount(objb);\n return;\n}", "func_hash": 287836847179025856325729282475760004434, "file_name": "t_string.c", "file_hash": 203124188209700042085800083662764441846, "cwe": ["CWE-190"], "cve": "CVE-2021-29477", "cve_desc": "Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. An integer overflow bug in Redis version 6.0 or newer could be exploited using the `STRALGO LCS` command to corrupt the heap and potentially result with remote code execution. The problem is fixed in version 6.2.3 and 6.0.13. An additional workaround to mitigate the problem without patching the redis-server executable is to use ACL configuration to prevent clients from using the `STRALGO LCS` command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29477"} {"idx": 204639, "project": "openexr", "commit_id": "25259a84827234a283f6f9db72978198c7a3f268", "project_url": "https://github.com/AcademySoftwareFoundation/openexr", "commit_url": "https://github.com/AcademySoftwareFoundation/openexr/commit/25259a84827234a283f6f9db72978198c7a3f268", "commit_message": "detect buffer overflows in RleUncompress (#1036)\n\nSigned-off-by: Peter Hillman ", "target": 1, "func": "rleUncompress (int inLength, int maxLength, const signed char in[], char out[])\n{\n char *outStart = out;\n\n while (inLength > 0)\n {\n\tif (*in < 0)\n\t{\n\t int count = -((int)*in++);\n\t inLength -= count + 1;\n\n\t if (0 > (maxLength -= count))\n\t\treturn 0;\n\n // check the input buffer is big enough to contain\n // 'count' bytes of remaining data\n if (inLength < 0)\n return 0;\n\n memcpy(out, in, count);\n out += count;\n in += count;\n\t}\n\telse\n\t{\n\t int count = *in++;\n\t inLength -= 2;\n\n\t if (0 > (maxLength -= count + 1))\n\t\treturn 0;\n\n memset(out, *(char*)in, count+1);\n out += count+1;\n\n\t in++;\n\t}\n }\n\n return out - outStart;\n}", "func_hash": 231017890802196578109341157285993576532, "file_name": "ImfRle.cpp", "file_hash": 92102696201282194055983698133624995030, "cwe": ["CWE-119"], "cve": "CVE-2021-3605", "cve_desc": "There's a flaw in OpenEXR's rleUncompress functionality in versions prior to 3.0.5. An attacker who is able to submit a crafted file to an application linked with OpenEXR could cause an out-of-bounds read. The greatest risk from this flaw is to application availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3605"} {"idx": 362854, "project": "openexr", "commit_id": "25259a84827234a283f6f9db72978198c7a3f268", "project_url": "https://github.com/AcademySoftwareFoundation/openexr", "commit_url": "https://github.com/AcademySoftwareFoundation/openexr/commit/25259a84827234a283f6f9db72978198c7a3f268", "commit_message": "detect buffer overflows in RleUncompress (#1036)\n\nSigned-off-by: Peter Hillman ", "target": 0, "func": "rleUncompress (int inLength, int maxLength, const signed char in[], char out[])\n{\n char *outStart = out;\n\n while (inLength > 0)\n {\n\tif (*in < 0)\n\t{\n\t int count = -((int)*in++);\n\t inLength -= count + 1;\n\n\t if (0 > (maxLength -= count))\n\t\treturn 0;\n\n // check the input buffer is big enough to contain\n // 'count' bytes of remaining data\n if (inLength < 0)\n return 0;\n\n memcpy(out, in, count);\n out += count;\n in += count;\n\t}\n\telse\n\t{\n\t int count = *in++;\n\t inLength -= 2;\n\n\t if (0 > (maxLength -= count + 1))\n\t\treturn 0;\n\n // check the input buffer is big enough to contain\n // byte to be duplicated\n if (inLength < 0)\n return 0;\n\n memset(out, *(char*)in, count+1);\n out += count+1;\n\n\t in++;\n\t}\n }\n\n return out - outStart;\n}", "func_hash": 85194498445233380776395557051941305034, "file_name": "ImfRle.cpp", "file_hash": 217905819488035336106349997550934705797, "cwe": ["CWE-119"], "cve": "CVE-2021-3605", "cve_desc": "There's a flaw in OpenEXR's rleUncompress functionality in versions prior to 3.0.5. An attacker who is able to submit a crafted file to an application linked with OpenEXR could cause an out-of-bounds read. The greatest risk from this flaw is to application availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3605"} {"idx": 204723, "project": "linux", "commit_id": "99e3a236dd43d06c65af0a2ef9cb44306aef6e02", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/99e3a236dd43d06c65af0a2ef9cb44306aef6e02", "commit_message": "xsk: Add missing check on user supplied headroom size\n\nAdd a check that the headroom cannot be larger than the available\nspace in the chunk. In the current code, a malicious user can set the\nheadroom to a value larger than the chunk size minus the fixed XDP\nheadroom. That way packets with a length larger than the supported\nsize in the umem could get accepted and result in an out-of-bounds\nwrite.\n\nFixes: c0c77d8fb787 (\"xsk: add user memory registration support sockopt\")\nReported-by: Bui Quang Minh \nSigned-off-by: Magnus Karlsson \nSigned-off-by: Daniel Borkmann \nLink: https://bugzilla.kernel.org/show_bug.cgi?id=207225\nLink: https://lore.kernel.org/bpf/1586849715-23490-1-git-send-email-magnus.karlsson@intel.com", "target": 1, "func": "static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n{\n\tbool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;\n\tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n\tunsigned int chunks, chunks_per_page;\n\tu64 addr = mr->addr, size = mr->len;\n\tint size_chk, err;\n\n\tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n\t\t/* Strictly speaking we could support this, if:\n\t\t * - huge pages, or*\n\t\t * - using an IOMMU, or\n\t\t * - making sure the memory area is consecutive\n\t\t * but for now, we simply say \"computer says no\".\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |\n\t\t\tXDP_UMEM_USES_NEED_WAKEUP))\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks && !is_power_of_2(chunk_size))\n\t\treturn -EINVAL;\n\n\tif (!PAGE_ALIGNED(addr)) {\n\t\t/* Memory area has to be page size aligned. For\n\t\t * simplicity, this might change.\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((addr + size) < addr)\n\t\treturn -EINVAL;\n\n\tchunks = (unsigned int)div_u64(size, chunk_size);\n\tif (chunks == 0)\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks) {\n\t\tchunks_per_page = PAGE_SIZE / chunk_size;\n\t\tif (chunks < chunks_per_page || chunks % chunks_per_page)\n\t\t\treturn -EINVAL;\n\t}\n\n\tsize_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;\n\tif (size_chk < 0)\n\t\treturn -EINVAL;\n\n\tumem->address = (unsigned long)addr;\n\tumem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK\n\t\t\t\t\t : ~((u64)chunk_size - 1);\n\tumem->size = size;\n\tumem->headroom = headroom;\n\tumem->chunk_size_nohr = chunk_size - headroom;\n\tumem->npgs = size / PAGE_SIZE;\n\tumem->pgs = NULL;\n\tumem->user = NULL;\n\tumem->flags = mr->flags;\n\tINIT_LIST_HEAD(&umem->xsk_list);\n\tspin_lock_init(&umem->xsk_list_lock);\n\n\trefcount_set(&umem->users, 1);\n\n\terr = xdp_umem_account_pages(umem);\n\tif (err)\n\t\treturn err;\n\n\terr = xdp_umem_pin_pages(umem);\n\tif (err)\n\t\tgoto out_account;\n\n\tumem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),\n\t\t\t GFP_KERNEL_ACCOUNT);\n\tif (!umem->pages) {\n\t\terr = -ENOMEM;\n\t\tgoto out_pin;\n\t}\n\n\terr = xdp_umem_map_pages(umem);\n\tif (!err)\n\t\treturn 0;\n\n\tkvfree(umem->pages);\n\nout_pin:\n\txdp_umem_unpin_pages(umem);\nout_account:\n\txdp_umem_unaccount_pages(umem);\n\treturn err;\n}", "func_hash": 195570399432205421707161576441282593598, "file_name": "xdp_umem.c", "file_hash": 246887528956685624500104034416106480125, "cwe": ["CWE-416"], "cve": "CVE-2020-12659", "cve_desc": "An issue was discovered in the Linux kernel before 5.6.7. xdp_umem_reg in net/xdp/xdp_umem.c has an out-of-bounds write (by a user with the CAP_NET_ADMIN capability) because of a lack of headroom validation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12659"} {"idx": 364107, "project": "linux", "commit_id": "99e3a236dd43d06c65af0a2ef9cb44306aef6e02", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/99e3a236dd43d06c65af0a2ef9cb44306aef6e02", "commit_message": "xsk: Add missing check on user supplied headroom size\n\nAdd a check that the headroom cannot be larger than the available\nspace in the chunk. In the current code, a malicious user can set the\nheadroom to a value larger than the chunk size minus the fixed XDP\nheadroom. That way packets with a length larger than the supported\nsize in the umem could get accepted and result in an out-of-bounds\nwrite.\n\nFixes: c0c77d8fb787 (\"xsk: add user memory registration support sockopt\")\nReported-by: Bui Quang Minh \nSigned-off-by: Magnus Karlsson \nSigned-off-by: Daniel Borkmann \nLink: https://bugzilla.kernel.org/show_bug.cgi?id=207225\nLink: https://lore.kernel.org/bpf/1586849715-23490-1-git-send-email-magnus.karlsson@intel.com", "target": 0, "func": "static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n{\n\tbool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;\n\tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n\tunsigned int chunks, chunks_per_page;\n\tu64 addr = mr->addr, size = mr->len;\n\tint err;\n\n\tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n\t\t/* Strictly speaking we could support this, if:\n\t\t * - huge pages, or*\n\t\t * - using an IOMMU, or\n\t\t * - making sure the memory area is consecutive\n\t\t * but for now, we simply say \"computer says no\".\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |\n\t\t\tXDP_UMEM_USES_NEED_WAKEUP))\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks && !is_power_of_2(chunk_size))\n\t\treturn -EINVAL;\n\n\tif (!PAGE_ALIGNED(addr)) {\n\t\t/* Memory area has to be page size aligned. For\n\t\t * simplicity, this might change.\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((addr + size) < addr)\n\t\treturn -EINVAL;\n\n\tchunks = (unsigned int)div_u64(size, chunk_size);\n\tif (chunks == 0)\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks) {\n\t\tchunks_per_page = PAGE_SIZE / chunk_size;\n\t\tif (chunks < chunks_per_page || chunks % chunks_per_page)\n\t\t\treturn -EINVAL;\n\t}\n\n\tif (headroom >= chunk_size - XDP_PACKET_HEADROOM)\n\t\treturn -EINVAL;\n\n\tumem->address = (unsigned long)addr;\n\tumem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK\n\t\t\t\t\t : ~((u64)chunk_size - 1);\n\tumem->size = size;\n\tumem->headroom = headroom;\n\tumem->chunk_size_nohr = chunk_size - headroom;\n\tumem->npgs = size / PAGE_SIZE;\n\tumem->pgs = NULL;\n\tumem->user = NULL;\n\tumem->flags = mr->flags;\n\tINIT_LIST_HEAD(&umem->xsk_list);\n\tspin_lock_init(&umem->xsk_list_lock);\n\n\trefcount_set(&umem->users, 1);\n\n\terr = xdp_umem_account_pages(umem);\n\tif (err)\n\t\treturn err;\n\n\terr = xdp_umem_pin_pages(umem);\n\tif (err)\n\t\tgoto out_account;\n\n\tumem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),\n\t\t\t GFP_KERNEL_ACCOUNT);\n\tif (!umem->pages) {\n\t\terr = -ENOMEM;\n\t\tgoto out_pin;\n\t}\n\n\terr = xdp_umem_map_pages(umem);\n\tif (!err)\n\t\treturn 0;\n\n\tkvfree(umem->pages);\n\nout_pin:\n\txdp_umem_unpin_pages(umem);\nout_account:\n\txdp_umem_unaccount_pages(umem);\n\treturn err;\n}", "func_hash": 100730009397692201208247887759368551148, "file_name": "xdp_umem.c", "file_hash": 256623347227727309003561909025607490713, "cwe": ["CWE-416"], "cve": "CVE-2020-12659", "cve_desc": "An issue was discovered in the Linux kernel before 5.6.7. xdp_umem_reg in net/xdp/xdp_umem.c has an out-of-bounds write (by a user with the CAP_NET_ADMIN capability) because of a lack of headroom validation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12659"} {"idx": 204725, "project": "linux", "commit_id": "c444eb564fb16645c172d550359cb3d75fe8a040", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c444eb564fb16645c172d550359cb3d75fe8a040", "commit_message": "mm: thp: make the THP mapcount atomic against __split_huge_pmd_locked()\n\nWrite protect anon page faults require an accurate mapcount to decide\nif to break the COW or not. This is implemented in the THP path with\nreuse_swap_page() ->\npage_trans_huge_map_swapcount()/page_trans_huge_mapcount().\n\nIf the COW triggers while the other processes sharing the page are\nunder a huge pmd split, to do an accurate reading, we must ensure the\nmapcount isn't computed while it's being transferred from the head\npage to the tail pages.\n\nreuse_swap_cache() already runs serialized by the page lock, so it's\nenough to add the page lock around __split_huge_pmd_locked too, in\norder to add the missing serialization.\n\nNote: the commit in \"Fixes\" is just to facilitate the backporting,\nbecause the code before such commit didn't try to do an accurate THP\nmapcount calculation and it instead used the page_count() to decide if\nto COW or not. Both the page_count and the pin_count are THP-wide\nrefcounts, so they're inaccurate if used in\nreuse_swap_page(). Reverting such commit (besides the unrelated fix to\nthe local anon_vma assignment) would have also opened the window for\nmemory corruption side effects to certain workloads as documented in\nsuch commit header.\n\nSigned-off-by: Andrea Arcangeli \nSuggested-by: Jann Horn \nReported-by: Jann Horn \nAcked-by: Kirill A. Shutemov \nFixes: 6d0a07edd17c (\"mm: thp: calculate the mapcount correctly for THP pages during WP faults\")\nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds ", "target": 1, "func": "void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,\n\t\tunsigned long address, bool freeze, struct page *page)\n{\n\tspinlock_t *ptl;\n\tstruct mmu_notifier_range range;\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,\n\t\t\t\taddress & HPAGE_PMD_MASK,\n\t\t\t\t(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);\n\tmmu_notifier_invalidate_range_start(&range);\n\tptl = pmd_lock(vma->vm_mm, pmd);\n\n\t/*\n\t * If caller asks to setup a migration entries, we need a page to check\n\t * pmd against. Otherwise we can end up replacing wrong page.\n\t */\n\tVM_BUG_ON(freeze && !page);\n\tif (page && page != pmd_page(*pmd))\n\t goto out;\n\n\tif (pmd_trans_huge(*pmd)) {\n\t\tpage = pmd_page(*pmd);\n\t\tif (PageMlocked(page))\n\t\t\tclear_page_mlock(page);\n\t} else if (!(pmd_devmap(*pmd) || is_pmd_migration_entry(*pmd)))\n\t\tgoto out;\n\t__split_huge_pmd_locked(vma, pmd, range.start, freeze);\nout:\n\tspin_unlock(ptl);\n\t/*\n\t * No need to double call mmu_notifier->invalidate_range() callback.\n\t * They are 3 cases to consider inside __split_huge_pmd_locked():\n\t * 1) pmdp_huge_clear_flush_notify() call invalidate_range() obvious\n\t * 2) __split_huge_zero_page_pmd() read only zero page and any write\n\t * fault will trigger a flush_notify before pointing to a new page\n\t * (it is fine if the secondary mmu keeps pointing to the old zero\n\t * page in the meantime)\n\t * 3) Split a huge pmd into pte pointing to the same page. No need\n\t * to invalidate secondary tlb entry they are all still valid.\n\t * any further changes to individual pte will notify. So no need\n\t * to call mmu_notifier->invalidate_range()\n\t */\n\tmmu_notifier_invalidate_range_only_end(&range);\n}", "func_hash": 243940681934408838517049958554207444689, "file_name": "huge_memory.c", "file_hash": 27234768011367588418306716723035144723, "cwe": ["CWE-362"], "cve": "CVE-2020-29368", "cve_desc": "An issue was discovered in __split_huge_pmd in mm/huge_memory.c in the Linux kernel before 5.7.5. The copy-on-write implementation can grant unintended write access because of a race condition in a THP mapcount check, aka CID-c444eb564fb1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29368"} {"idx": 364123, "project": "linux", "commit_id": "c444eb564fb16645c172d550359cb3d75fe8a040", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c444eb564fb16645c172d550359cb3d75fe8a040", "commit_message": "mm: thp: make the THP mapcount atomic against __split_huge_pmd_locked()\n\nWrite protect anon page faults require an accurate mapcount to decide\nif to break the COW or not. This is implemented in the THP path with\nreuse_swap_page() ->\npage_trans_huge_map_swapcount()/page_trans_huge_mapcount().\n\nIf the COW triggers while the other processes sharing the page are\nunder a huge pmd split, to do an accurate reading, we must ensure the\nmapcount isn't computed while it's being transferred from the head\npage to the tail pages.\n\nreuse_swap_cache() already runs serialized by the page lock, so it's\nenough to add the page lock around __split_huge_pmd_locked too, in\norder to add the missing serialization.\n\nNote: the commit in \"Fixes\" is just to facilitate the backporting,\nbecause the code before such commit didn't try to do an accurate THP\nmapcount calculation and it instead used the page_count() to decide if\nto COW or not. Both the page_count and the pin_count are THP-wide\nrefcounts, so they're inaccurate if used in\nreuse_swap_page(). Reverting such commit (besides the unrelated fix to\nthe local anon_vma assignment) would have also opened the window for\nmemory corruption side effects to certain workloads as documented in\nsuch commit header.\n\nSigned-off-by: Andrea Arcangeli \nSuggested-by: Jann Horn \nReported-by: Jann Horn \nAcked-by: Kirill A. Shutemov \nFixes: 6d0a07edd17c (\"mm: thp: calculate the mapcount correctly for THP pages during WP faults\")\nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds ", "target": 0, "func": "void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,\n\t\tunsigned long address, bool freeze, struct page *page)\n{\n\tspinlock_t *ptl;\n\tstruct mmu_notifier_range range;\n\tbool was_locked = false;\n\tpmd_t _pmd;\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,\n\t\t\t\taddress & HPAGE_PMD_MASK,\n\t\t\t\t(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);\n\tmmu_notifier_invalidate_range_start(&range);\n\tptl = pmd_lock(vma->vm_mm, pmd);\n\n\t/*\n\t * If caller asks to setup a migration entries, we need a page to check\n\t * pmd against. Otherwise we can end up replacing wrong page.\n\t */\n\tVM_BUG_ON(freeze && !page);\n\tif (page) {\n\t\tVM_WARN_ON_ONCE(!PageLocked(page));\n\t\twas_locked = true;\n\t\tif (page != pmd_page(*pmd))\n\t\t\tgoto out;\n\t}\n\nrepeat:\n\tif (pmd_trans_huge(*pmd)) {\n\t\tif (!page) {\n\t\t\tpage = pmd_page(*pmd);\n\t\t\tif (unlikely(!trylock_page(page))) {\n\t\t\t\tget_page(page);\n\t\t\t\t_pmd = *pmd;\n\t\t\t\tspin_unlock(ptl);\n\t\t\t\tlock_page(page);\n\t\t\t\tspin_lock(ptl);\n\t\t\t\tif (unlikely(!pmd_same(*pmd, _pmd))) {\n\t\t\t\t\tunlock_page(page);\n\t\t\t\t\tput_page(page);\n\t\t\t\t\tpage = NULL;\n\t\t\t\t\tgoto repeat;\n\t\t\t\t}\n\t\t\t\tput_page(page);\n\t\t\t}\n\t\t}\n\t\tif (PageMlocked(page))\n\t\t\tclear_page_mlock(page);\n\t} else if (!(pmd_devmap(*pmd) || is_pmd_migration_entry(*pmd)))\n\t\tgoto out;\n\t__split_huge_pmd_locked(vma, pmd, range.start, freeze);\nout:\n\tspin_unlock(ptl);\n\tif (!was_locked && page)\n\t\tunlock_page(page);\n\t/*\n\t * No need to double call mmu_notifier->invalidate_range() callback.\n\t * They are 3 cases to consider inside __split_huge_pmd_locked():\n\t * 1) pmdp_huge_clear_flush_notify() call invalidate_range() obvious\n\t * 2) __split_huge_zero_page_pmd() read only zero page and any write\n\t * fault will trigger a flush_notify before pointing to a new page\n\t * (it is fine if the secondary mmu keeps pointing to the old zero\n\t * page in the meantime)\n\t * 3) Split a huge pmd into pte pointing to the same page. No need\n\t * to invalidate secondary tlb entry they are all still valid.\n\t * any further changes to individual pte will notify. So no need\n\t * to call mmu_notifier->invalidate_range()\n\t */\n\tmmu_notifier_invalidate_range_only_end(&range);\n}", "func_hash": 167849063947042314060600654532118187799, "file_name": "huge_memory.c", "file_hash": 140534657853866355654658621817803088847, "cwe": ["CWE-362"], "cve": "CVE-2020-29368", "cve_desc": "An issue was discovered in __split_huge_pmd in mm/huge_memory.c in the Linux kernel before 5.7.5. The copy-on-write implementation can grant unintended write access because of a race condition in a THP mapcount check, aka CID-c444eb564fb1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29368"} {"idx": 204825, "project": "libyang", "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "project_url": "https://github.com/CESNET/libyang", "commit_url": "https://github.com/CESNET/libyang/commit/298b30ea4ebee137226acf9bb38678bd82704582", "commit_message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 1, "func": "lyxml_parse_elem(struct ly_ctx *ctx, const char *data, unsigned int *len, struct lyxml_elem *parent, int options)\n{\n const char *c = data, *start, *e;\n const char *lws; /* leading white space for handling mixed content */\n int uc;\n char *str;\n char *prefix = NULL;\n unsigned int prefix_len = 0;\n struct lyxml_elem *elem = NULL, *child;\n struct lyxml_attr *attr;\n unsigned int size;\n int nons_flag = 0, closed_flag = 0;\n\n *len = 0;\n\n if (*c != '<') {\n return NULL;\n }\n\n /* locate element name */\n c++;\n e = c;\n\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"NameStartChar of the element\");\n return NULL;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n if (prefix_len) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"element name, multiple colons found\");\n goto error;\n }\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n prefix_len = e - c;\n LY_CHECK_ERR_GOTO(prefix, LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, e), error);\n prefix = malloc((prefix_len + 1) * sizeof *prefix);\n LY_CHECK_ERR_GOTO(!prefix, LOGMEM(ctx), error);\n memcpy(prefix, c, prefix_len);\n prefix[prefix_len] = '\\0';\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n free(prefix);\n return NULL;\n }\n\n /* allocate element structure */\n elem = calloc(1, sizeof *elem);\n LY_CHECK_ERR_RETURN(!elem, free(prefix); LOGMEM(ctx), NULL);\n\n elem->next = NULL;\n elem->prev = elem;\n if (parent) {\n lyxml_add_child(ctx, parent, elem);\n }\n\n /* store the name into the element structure */\n elem->name = lydict_insert(ctx, c, e - c);\n c = e;\n\nprocess:\n ign_xmlws(c);\n if (!strncmp(\"/>\", c, 2)) {\n /* we are done, it was EmptyElemTag */\n c += 2;\n elem->content = lydict_insert(ctx, \"\", 0);\n closed_flag = 1;\n } else if (*c == '>') {\n /* process element content */\n c++;\n lws = NULL;\n\n while (*c) {\n if (!strncmp(c, \"child) {\n /* leading white spaces were actually content */\n goto store_content;\n }\n\n /* Etag */\n c += 2;\n /* get name and check it */\n e = c;\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"NameStartChar of the element\");\n goto error;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n if (!prefix || memcmp(prefix, c, e - c)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (different namespaces) opening (%s) and closing element tags.\", elem->name);\n goto error;\n }\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n goto error;\n }\n\n /* check that it corresponds to opening tag */\n size = e - c;\n str = malloc((size + 1) * sizeof *str);\n LY_CHECK_ERR_GOTO(!str, LOGMEM(ctx), error);\n memcpy(str, c, e - c);\n str[e - c] = '\\0';\n if (size != strlen(elem->name) || memcmp(str, elem->name, size)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (mixed names) opening (%s) and closing (%s) element tags.\", elem->name, str);\n free(str);\n goto error;\n }\n free(str);\n c = e;\n\n ign_xmlws(c);\n if (*c != '>') {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem, \"Data after closing element tag \\\"%s\\\".\", elem->name);\n goto error;\n }\n c++;\n if (!(elem->flags & LYXML_ELEM_MIXED) && !elem->content) {\n /* there was no content, but we don't want NULL (only if mixed content) */\n elem->content = lydict_insert(ctx, \"\", 0);\n }\n closed_flag = 1;\n break;\n\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"flags & LYXML_ELEM_MIXED) {\n /* we have a mixed content */\n goto store_content;\n } else {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n }\n if (elem->content) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n child = lyxml_parse_elem(ctx, c, &size, elem, options);\n if (!child) {\n goto error;\n }\n c += size; /* move after processed child element */\n } else if (is_xmlws(*c)) {\n lws = c;\n ign_xmlws(c);\n } else {\nstore_content:\n /* store text content */\n if (lws) {\n /* process content including the leading white spaces */\n c = lws;\n lws = NULL;\n }\n str = parse_text(ctx, c, '<', &size);\n if (!str && !size) {\n goto error;\n }\n elem->content = lydict_insert_zc(ctx, str);\n c += size; /* move after processed text content */\n\n if (elem->child) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n }\n }\n } else {\n /* process attribute */\n attr = parse_attr(ctx, c, &size, elem);\n if (!attr) {\n goto error;\n }\n c += size; /* move after processed attribute */\n\n /* check namespace */\n if (attr->type == LYXML_ATTR_NS) {\n if ((!prefix || !prefix[0]) && !attr->name) {\n if (attr->value) {\n /* default prefix */\n elem->ns = (struct lyxml_ns *)attr;\n } else {\n /* xmlns=\"\" -> no namespace */\n nons_flag = 1;\n }\n } else if (prefix && prefix[0] && attr->name && !strncmp(attr->name, prefix, prefix_len + 1)) {\n /* matching namespace with prefix */\n elem->ns = (struct lyxml_ns *)attr;\n }\n }\n\n /* go back to finish element processing */\n goto process;\n }\n\n *len = c - data;\n\n if (!closed_flag) {\n LOGVAL(ctx, LYE_XML_MISS, LY_VLOG_XML, elem, \"closing element tag\", elem->name);\n goto error;\n }\n\n /* resolve all attribute prefixes */\n LY_TREE_FOR(elem->attr, attr) {\n if (attr->type == LYXML_ATTR_STD_UNRES) {\n str = (char *)attr->ns;\n attr->ns = lyxml_get_ns(elem, str);\n free(str);\n attr->type = LYXML_ATTR_STD;\n }\n }\n\n if (!elem->ns && !nons_flag && parent) {\n elem->ns = lyxml_get_ns(parent, prefix_len ? prefix : NULL);\n }\n free(prefix);\n return elem;\n\nerror:\n lyxml_free(ctx, elem);\n free(prefix);\n return NULL;\n}", "func_hash": 137341441302693733535233017899971598842, "file_name": "xml.c", "file_hash": 243377256222146355519954749014560243024, "cwe": ["CWE-674"], "cve": "CVE-2021-28903", "cve_desc": "A stack overflow in libyang <= v1.0.225 can cause a denial of service through function lyxml_parse_mem(). lyxml_parse_elem() function will be called recursively, which will consume stack space and lead to crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28903"} {"idx": 366009, "project": "libyang", "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "project_url": "https://github.com/CESNET/libyang", "commit_url": "https://github.com/CESNET/libyang/commit/298b30ea4ebee137226acf9bb38678bd82704582", "commit_message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 0, "func": "lyxml_parse_elem(struct ly_ctx *ctx, const char *data, unsigned int *len, struct lyxml_elem *parent, int options,\n int bt_count)\n{\n const char *c = data, *start, *e;\n const char *lws; /* leading white space for handling mixed content */\n int uc;\n char *str;\n char *prefix = NULL;\n unsigned int prefix_len = 0;\n struct lyxml_elem *elem = NULL, *child;\n struct lyxml_attr *attr;\n unsigned int size;\n int nons_flag = 0, closed_flag = 0;\n\n *len = 0;\n\n if (bt_count > LY_RECURSION_LIMIT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"Recursion limit %d reached\", LY_RECURSION_LIMIT);\n return NULL;\n }\n\n if (*c != '<') {\n return NULL;\n }\n\n /* locate element name */\n c++;\n e = c;\n\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"NameStartChar of the element\");\n return NULL;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n if (prefix_len) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"element name, multiple colons found\");\n goto error;\n }\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n prefix_len = e - c;\n LY_CHECK_ERR_GOTO(prefix, LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, e), error);\n prefix = malloc((prefix_len + 1) * sizeof *prefix);\n LY_CHECK_ERR_GOTO(!prefix, LOGMEM(ctx), error);\n memcpy(prefix, c, prefix_len);\n prefix[prefix_len] = '\\0';\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n free(prefix);\n return NULL;\n }\n\n /* allocate element structure */\n elem = calloc(1, sizeof *elem);\n LY_CHECK_ERR_RETURN(!elem, free(prefix); LOGMEM(ctx), NULL);\n\n elem->next = NULL;\n elem->prev = elem;\n if (parent) {\n lyxml_add_child(ctx, parent, elem);\n }\n\n /* store the name into the element structure */\n elem->name = lydict_insert(ctx, c, e - c);\n c = e;\n\nprocess:\n ign_xmlws(c);\n if (!strncmp(\"/>\", c, 2)) {\n /* we are done, it was EmptyElemTag */\n c += 2;\n elem->content = lydict_insert(ctx, \"\", 0);\n closed_flag = 1;\n } else if (*c == '>') {\n /* process element content */\n c++;\n lws = NULL;\n\n while (*c) {\n if (!strncmp(c, \"child) {\n /* leading white spaces were actually content */\n goto store_content;\n }\n\n /* Etag */\n c += 2;\n /* get name and check it */\n e = c;\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"NameStartChar of the element\");\n goto error;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n if (!prefix || memcmp(prefix, c, e - c)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (different namespaces) opening (%s) and closing element tags.\", elem->name);\n goto error;\n }\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n goto error;\n }\n\n /* check that it corresponds to opening tag */\n size = e - c;\n str = malloc((size + 1) * sizeof *str);\n LY_CHECK_ERR_GOTO(!str, LOGMEM(ctx), error);\n memcpy(str, c, e - c);\n str[e - c] = '\\0';\n if (size != strlen(elem->name) || memcmp(str, elem->name, size)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (mixed names) opening (%s) and closing (%s) element tags.\", elem->name, str);\n free(str);\n goto error;\n }\n free(str);\n c = e;\n\n ign_xmlws(c);\n if (*c != '>') {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem, \"Data after closing element tag \\\"%s\\\".\", elem->name);\n goto error;\n }\n c++;\n if (!(elem->flags & LYXML_ELEM_MIXED) && !elem->content) {\n /* there was no content, but we don't want NULL (only if mixed content) */\n elem->content = lydict_insert(ctx, \"\", 0);\n }\n closed_flag = 1;\n break;\n\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"flags & LYXML_ELEM_MIXED) {\n /* we have a mixed content */\n goto store_content;\n } else {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n }\n if (elem->content) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n child = lyxml_parse_elem(ctx, c, &size, elem, options, bt_count + 1);\n if (!child) {\n goto error;\n }\n c += size; /* move after processed child element */\n } else if (is_xmlws(*c)) {\n lws = c;\n ign_xmlws(c);\n } else {\nstore_content:\n /* store text content */\n if (lws) {\n /* process content including the leading white spaces */\n c = lws;\n lws = NULL;\n }\n str = parse_text(ctx, c, '<', &size);\n if (!str && !size) {\n goto error;\n }\n elem->content = lydict_insert_zc(ctx, str);\n c += size; /* move after processed text content */\n\n if (elem->child) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n }\n }\n } else {\n /* process attribute */\n attr = parse_attr(ctx, c, &size, elem);\n if (!attr) {\n goto error;\n }\n c += size; /* move after processed attribute */\n\n /* check namespace */\n if (attr->type == LYXML_ATTR_NS) {\n if ((!prefix || !prefix[0]) && !attr->name) {\n if (attr->value) {\n /* default prefix */\n elem->ns = (struct lyxml_ns *)attr;\n } else {\n /* xmlns=\"\" -> no namespace */\n nons_flag = 1;\n }\n } else if (prefix && prefix[0] && attr->name && !strncmp(attr->name, prefix, prefix_len + 1)) {\n /* matching namespace with prefix */\n elem->ns = (struct lyxml_ns *)attr;\n }\n }\n\n /* go back to finish element processing */\n goto process;\n }\n\n *len = c - data;\n\n if (!closed_flag) {\n LOGVAL(ctx, LYE_XML_MISS, LY_VLOG_XML, elem, \"closing element tag\", elem->name);\n goto error;\n }\n\n /* resolve all attribute prefixes */\n LY_TREE_FOR(elem->attr, attr) {\n if (attr->type == LYXML_ATTR_STD_UNRES) {\n str = (char *)attr->ns;\n attr->ns = lyxml_get_ns(elem, str);\n free(str);\n attr->type = LYXML_ATTR_STD;\n }\n }\n\n if (!elem->ns && !nons_flag && parent) {\n elem->ns = lyxml_get_ns(parent, prefix_len ? prefix : NULL);\n }\n free(prefix);\n return elem;\n\nerror:\n lyxml_free(ctx, elem);\n free(prefix);\n return NULL;\n}", "func_hash": 120303615925561054469092998021840288743, "file_name": "xml.c", "file_hash": 65687228735889027579503738444437386081, "cwe": ["CWE-674"], "cve": "CVE-2021-28903", "cve_desc": "A stack overflow in libyang <= v1.0.225 can cause a denial of service through function lyxml_parse_mem(). lyxml_parse_elem() function will be called recursively, which will consume stack space and lead to crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28903"} {"idx": 204826, "project": "libyang", "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "project_url": "https://github.com/CESNET/libyang", "commit_url": "https://github.com/CESNET/libyang/commit/298b30ea4ebee137226acf9bb38678bd82704582", "commit_message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 1, "func": "lyxml_parse_mem(struct ly_ctx *ctx, const char *data, int options)\n{\n FUN_IN;\n\n const char *c = data;\n unsigned int len;\n struct lyxml_elem *root, *first = NULL, *next;\n\n if (!ctx) {\n LOGARG;\n return NULL;\n }\n\n if (!data) {\n /* nothing to parse */\n return NULL;\n }\n\nrepeat:\n /* process document */\n while (1) {\n if (!*c) {\n /* eof */\n return first;\n } else if (is_xmlws(*c)) {\n /* skip whitespaces */\n ign_xmlws(c);\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \" */\n LOGERR(ctx, LY_EINVAL, \"DOCTYPE not supported in XML documents.\");\n goto error;\n } else if (*c == '<') {\n /* element - process it in next loop to strictly follow XML\n * format\n */\n break;\n } else {\n LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, c);\n goto error;\n }\n }\n\n root = lyxml_parse_elem(ctx, c, &len, NULL, options);\n if (!root) {\n goto error;\n } else if (!first) {\n first = root;\n } else {\n first->prev->next = root;\n root->prev = first->prev;\n first->prev = root;\n }\n c += len;\n\n /* ignore the rest of document where can be comments, PIs and whitespaces,\n * note that we are not detecting syntax errors in these parts\n */\n ign_xmlws(c);\n if (*c) {\n if (options & LYXML_PARSE_MULTIROOT) {\n goto repeat;\n } else {\n LOGWRN(ctx, \"There are some not parsed data:\\n%s\", c);\n }\n }\n\n return first;\n\nerror:\n LY_TREE_FOR_SAFE(first, next, root) {\n lyxml_free(ctx, root);\n }\n return NULL;\n}", "func_hash": 101541079794207541098601304899112621658, "file_name": "xml.c", "file_hash": 243377256222146355519954749014560243024, "cwe": ["CWE-674"], "cve": "CVE-2021-28903", "cve_desc": "A stack overflow in libyang <= v1.0.225 can cause a denial of service through function lyxml_parse_mem(). lyxml_parse_elem() function will be called recursively, which will consume stack space and lead to crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28903"} {"idx": 366026, "project": "libyang", "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "project_url": "https://github.com/CESNET/libyang", "commit_url": "https://github.com/CESNET/libyang/commit/298b30ea4ebee137226acf9bb38678bd82704582", "commit_message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 0, "func": "lyxml_parse_mem(struct ly_ctx *ctx, const char *data, int options)\n{\n FUN_IN;\n\n const char *c = data;\n unsigned int len;\n struct lyxml_elem *root, *first = NULL, *next;\n\n if (!ctx) {\n LOGARG;\n return NULL;\n }\n\n if (!data) {\n /* nothing to parse */\n return NULL;\n }\n\nrepeat:\n /* process document */\n while (1) {\n if (!*c) {\n /* eof */\n return first;\n } else if (is_xmlws(*c)) {\n /* skip whitespaces */\n ign_xmlws(c);\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \" */\n LOGERR(ctx, LY_EINVAL, \"DOCTYPE not supported in XML documents.\");\n goto error;\n } else if (*c == '<') {\n /* element - process it in next loop to strictly follow XML\n * format\n */\n break;\n } else {\n LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, c);\n goto error;\n }\n }\n\n root = lyxml_parse_elem(ctx, c, &len, NULL, options, 0);\n if (!root) {\n goto error;\n } else if (!first) {\n first = root;\n } else {\n first->prev->next = root;\n root->prev = first->prev;\n first->prev = root;\n }\n c += len;\n\n /* ignore the rest of document where can be comments, PIs and whitespaces,\n * note that we are not detecting syntax errors in these parts\n */\n ign_xmlws(c);\n if (*c) {\n if (options & LYXML_PARSE_MULTIROOT) {\n goto repeat;\n } else {\n LOGWRN(ctx, \"There are some not parsed data:\\n%s\", c);\n }\n }\n\n return first;\n\nerror:\n LY_TREE_FOR_SAFE(first, next, root) {\n lyxml_free(ctx, root);\n }\n return NULL;\n}", "func_hash": 255299558757831402836903840192646636553, "file_name": "xml.c", "file_hash": 65687228735889027579503738444437386081, "cwe": ["CWE-674"], "cve": "CVE-2021-28903", "cve_desc": "A stack overflow in libyang <= v1.0.225 can cause a denial of service through function lyxml_parse_mem(). lyxml_parse_elem() function will be called recursively, which will consume stack space and lead to crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28903"} {"idx": 204856, "project": "linux", "commit_id": "aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd", "commit_message": "mm: mempolicy: require at least one nodeid for MPOL_PREFERRED\n\nUsing an empty (malformed) nodelist that is not caught during mount option\nparsing leads to a stack-out-of-bounds access.\n\nThe option string that was used was: \"mpol=prefer:,\". However,\nMPOL_PREFERRED requires a single node number, which is not being provided\nhere.\n\nAdd a check that 'nodes' is not empty after parsing for MPOL_PREFERRED's\nnodeid.\n\nFixes: 095f1fc4ebf3 (\"mempolicy: rework shmem mpol parsing and display\")\nReported-by: Entropy Moe <3ntr0py1337@gmail.com>\nReported-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nSigned-off-by: Randy Dunlap \nSigned-off-by: Andrew Morton \nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn \nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org\nSigned-off-by: Linus Torvalds ", "target": 1, "func": "int mpol_parse_str(char *str, struct mempolicy **mpol)\n{\n\tstruct mempolicy *new = NULL;\n\tunsigned short mode_flags;\n\tnodemask_t nodes;\n\tchar *nodelist = strchr(str, ':');\n\tchar *flags = strchr(str, '=');\n\tint err = 1, mode;\n\n\tif (flags)\n\t\t*flags++ = '\\0';\t/* terminate mode string */\n\n\tif (nodelist) {\n\t\t/* NUL-terminate mode or flags string */\n\t\t*nodelist++ = '\\0';\n\t\tif (nodelist_parse(nodelist, nodes))\n\t\t\tgoto out;\n\t\tif (!nodes_subset(nodes, node_states[N_MEMORY]))\n\t\t\tgoto out;\n\t} else\n\t\tnodes_clear(nodes);\n\n\tmode = match_string(policy_modes, MPOL_MAX, str);\n\tif (mode < 0)\n\t\tgoto out;\n\n\tswitch (mode) {\n\tcase MPOL_PREFERRED:\n\t\t/*\n\t\t * Insist on a nodelist of one node only\n\t\t */\n\t\tif (nodelist) {\n\t\t\tchar *rest = nodelist;\n\t\t\twhile (isdigit(*rest))\n\t\t\t\trest++;\n\t\t\tif (*rest)\n\t\t\t\tgoto out;\n\t\t}\n\t\tbreak;\n\tcase MPOL_INTERLEAVE:\n\t\t/*\n\t\t * Default to online nodes with memory if no nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tnodes = node_states[N_MEMORY];\n\t\tbreak;\n\tcase MPOL_LOCAL:\n\t\t/*\n\t\t * Don't allow a nodelist; mpol_new() checks flags\n\t\t */\n\t\tif (nodelist)\n\t\t\tgoto out;\n\t\tmode = MPOL_PREFERRED;\n\t\tbreak;\n\tcase MPOL_DEFAULT:\n\t\t/*\n\t\t * Insist on a empty nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\terr = 0;\n\t\tgoto out;\n\tcase MPOL_BIND:\n\t\t/*\n\t\t * Insist on a nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tgoto out;\n\t}\n\n\tmode_flags = 0;\n\tif (flags) {\n\t\t/*\n\t\t * Currently, we only support two mutually exclusive\n\t\t * mode flags.\n\t\t */\n\t\tif (!strcmp(flags, \"static\"))\n\t\t\tmode_flags |= MPOL_F_STATIC_NODES;\n\t\telse if (!strcmp(flags, \"relative\"))\n\t\t\tmode_flags |= MPOL_F_RELATIVE_NODES;\n\t\telse\n\t\t\tgoto out;\n\t}\n\n\tnew = mpol_new(mode, mode_flags, &nodes);\n\tif (IS_ERR(new))\n\t\tgoto out;\n\n\t/*\n\t * Save nodes for mpol_to_str() to show the tmpfs mount options\n\t * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.\n\t */\n\tif (mode != MPOL_PREFERRED)\n\t\tnew->v.nodes = nodes;\n\telse if (nodelist)\n\t\tnew->v.preferred_node = first_node(nodes);\n\telse\n\t\tnew->flags |= MPOL_F_LOCAL;\n\n\t/*\n\t * Save nodes for contextualization: this will be used to \"clone\"\n\t * the mempolicy in a specific context [cpuset] at a later time.\n\t */\n\tnew->w.user_nodemask = nodes;\n\n\terr = 0;\n\nout:\n\t/* Restore string for error message */\n\tif (nodelist)\n\t\t*--nodelist = ':';\n\tif (flags)\n\t\t*--flags = '=';\n\tif (!err)\n\t\t*mpol = new;\n\treturn err;\n}", "func_hash": 246524800916613685346098332675277582251, "file_name": "mempolicy.c", "file_hash": 320565603122670908660235565056388226926, "cwe": ["CWE-787"], "cve": "CVE-2020-11565", "cve_desc": "An issue was discovered in the Linux kernel through 5.6.2. mpol_parse_str in mm/mempolicy.c has a stack-based out-of-bounds write because an empty nodelist is mishandled during mount option parsing, aka CID-aa9f7d5172fa. NOTE: Someone in the security community disagrees that this is a vulnerability because the issue \u201cis a bug in parsing mount options which can only be specified by a privileged user, so triggering the bug does not grant any powers not already held.\u201d", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11565"} {"idx": 366756, "project": "linux", "commit_id": "aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd", "commit_message": "mm: mempolicy: require at least one nodeid for MPOL_PREFERRED\n\nUsing an empty (malformed) nodelist that is not caught during mount option\nparsing leads to a stack-out-of-bounds access.\n\nThe option string that was used was: \"mpol=prefer:,\". However,\nMPOL_PREFERRED requires a single node number, which is not being provided\nhere.\n\nAdd a check that 'nodes' is not empty after parsing for MPOL_PREFERRED's\nnodeid.\n\nFixes: 095f1fc4ebf3 (\"mempolicy: rework shmem mpol parsing and display\")\nReported-by: Entropy Moe <3ntr0py1337@gmail.com>\nReported-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nSigned-off-by: Randy Dunlap \nSigned-off-by: Andrew Morton \nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn \nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org\nSigned-off-by: Linus Torvalds ", "target": 0, "func": "int mpol_parse_str(char *str, struct mempolicy **mpol)\n{\n\tstruct mempolicy *new = NULL;\n\tunsigned short mode_flags;\n\tnodemask_t nodes;\n\tchar *nodelist = strchr(str, ':');\n\tchar *flags = strchr(str, '=');\n\tint err = 1, mode;\n\n\tif (flags)\n\t\t*flags++ = '\\0';\t/* terminate mode string */\n\n\tif (nodelist) {\n\t\t/* NUL-terminate mode or flags string */\n\t\t*nodelist++ = '\\0';\n\t\tif (nodelist_parse(nodelist, nodes))\n\t\t\tgoto out;\n\t\tif (!nodes_subset(nodes, node_states[N_MEMORY]))\n\t\t\tgoto out;\n\t} else\n\t\tnodes_clear(nodes);\n\n\tmode = match_string(policy_modes, MPOL_MAX, str);\n\tif (mode < 0)\n\t\tgoto out;\n\n\tswitch (mode) {\n\tcase MPOL_PREFERRED:\n\t\t/*\n\t\t * Insist on a nodelist of one node only, although later\n\t\t * we use first_node(nodes) to grab a single node, so here\n\t\t * nodelist (or nodes) cannot be empty.\n\t\t */\n\t\tif (nodelist) {\n\t\t\tchar *rest = nodelist;\n\t\t\twhile (isdigit(*rest))\n\t\t\t\trest++;\n\t\t\tif (*rest)\n\t\t\t\tgoto out;\n\t\t\tif (nodes_empty(nodes))\n\t\t\t\tgoto out;\n\t\t}\n\t\tbreak;\n\tcase MPOL_INTERLEAVE:\n\t\t/*\n\t\t * Default to online nodes with memory if no nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tnodes = node_states[N_MEMORY];\n\t\tbreak;\n\tcase MPOL_LOCAL:\n\t\t/*\n\t\t * Don't allow a nodelist; mpol_new() checks flags\n\t\t */\n\t\tif (nodelist)\n\t\t\tgoto out;\n\t\tmode = MPOL_PREFERRED;\n\t\tbreak;\n\tcase MPOL_DEFAULT:\n\t\t/*\n\t\t * Insist on a empty nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\terr = 0;\n\t\tgoto out;\n\tcase MPOL_BIND:\n\t\t/*\n\t\t * Insist on a nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tgoto out;\n\t}\n\n\tmode_flags = 0;\n\tif (flags) {\n\t\t/*\n\t\t * Currently, we only support two mutually exclusive\n\t\t * mode flags.\n\t\t */\n\t\tif (!strcmp(flags, \"static\"))\n\t\t\tmode_flags |= MPOL_F_STATIC_NODES;\n\t\telse if (!strcmp(flags, \"relative\"))\n\t\t\tmode_flags |= MPOL_F_RELATIVE_NODES;\n\t\telse\n\t\t\tgoto out;\n\t}\n\n\tnew = mpol_new(mode, mode_flags, &nodes);\n\tif (IS_ERR(new))\n\t\tgoto out;\n\n\t/*\n\t * Save nodes for mpol_to_str() to show the tmpfs mount options\n\t * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.\n\t */\n\tif (mode != MPOL_PREFERRED)\n\t\tnew->v.nodes = nodes;\n\telse if (nodelist)\n\t\tnew->v.preferred_node = first_node(nodes);\n\telse\n\t\tnew->flags |= MPOL_F_LOCAL;\n\n\t/*\n\t * Save nodes for contextualization: this will be used to \"clone\"\n\t * the mempolicy in a specific context [cpuset] at a later time.\n\t */\n\tnew->w.user_nodemask = nodes;\n\n\terr = 0;\n\nout:\n\t/* Restore string for error message */\n\tif (nodelist)\n\t\t*--nodelist = ':';\n\tif (flags)\n\t\t*--flags = '=';\n\tif (!err)\n\t\t*mpol = new;\n\treturn err;\n}", "func_hash": 66303911981091017372615100823767409778, "file_name": "mempolicy.c", "file_hash": 209924796117806767450097870559126973053, "cwe": ["CWE-787"], "cve": "CVE-2020-11565", "cve_desc": "An issue was discovered in the Linux kernel through 5.6.2. mpol_parse_str in mm/mempolicy.c has a stack-based out-of-bounds write because an empty nodelist is mishandled during mount option parsing, aka CID-aa9f7d5172fa. NOTE: Someone in the security community disagrees that this is a vulnerability because the issue \u201cis a bug in parsing mount options which can only be specified by a privileged user, so triggering the bug does not grant any powers not already held.\u201d", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11565"} {"idx": 204867, "project": "qemu", "commit_id": "b15a22bbcbe6a78dc3d88fe3134985e4cdd87de4", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=b15a22bbcbe6a78dc3d88fe3134985e4cdd87de4", "commit_message": "sm501: Replace hand written implementation with pixman where possible\n\nBesides being faster this should also prevent malicious guests to\nabuse 2D engine to overwrite data or cause a crash.\n\nSigned-off-by: BALATON Zoltan \nMessage-id: 58666389b6cae256e4e972a32c05cf8aa51bffc0.1590089984.git.balaton@eik.bme.hu\nSigned-off-by: Gerd Hoffmann ", "target": 1, "func": "static void sm501_2d_operation(SM501State *s)\n{\n int cmd = (s->twoD_control >> 16) & 0x1F;\n int rtl = s->twoD_control & BIT(27);\n int format = (s->twoD_stretch >> 20) & 0x3;\n int rop_mode = (s->twoD_control >> 15) & 0x1; /* 1 for rop2, else rop3 */\n /* 1 if rop2 source is the pattern, otherwise the source is the bitmap */\n int rop2_source_is_pattern = (s->twoD_control >> 14) & 0x1;\n int rop = s->twoD_control & 0xFF;\n int dst_x = (s->twoD_destination >> 16) & 0x01FFF;\n int dst_y = s->twoD_destination & 0xFFFF;\n int width = (s->twoD_dimension >> 16) & 0x1FFF;\n int height = s->twoD_dimension & 0xFFFF;\n uint32_t dst_base = s->twoD_destination_base & 0x03FFFFFF;\n uint8_t *dst = s->local_mem + dst_base;\n int dst_pitch = (s->twoD_pitch >> 16) & 0x1FFF;\n int crt = (s->dc_crt_control & SM501_DC_CRT_CONTROL_SEL) ? 1 : 0;\n int fb_len = get_width(s, crt) * get_height(s, crt) * get_bpp(s, crt);\n\n if ((s->twoD_stretch >> 16) & 0xF) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only XY addressing is supported.\\n\");\n return;\n }\n\n if (rop_mode == 0) {\n if (rop != 0xcc) {\n /* Anything other than plain copies are not supported */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop3 mode with rop %x is not \"\n \"supported.\\n\", rop);\n }\n } else {\n if (rop2_source_is_pattern && rop != 0x5) {\n /* For pattern source, we support only inverse dest */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop2 source being the pattern and \"\n \"rop %x is not supported.\\n\", rop);\n } else {\n if (rop != 0x5 && rop != 0xc) {\n /* Anything other than plain copies or inverse dest is not\n * supported */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop mode %x is not \"\n \"supported.\\n\", rop);\n }\n }\n }\n\n if (s->twoD_source_base & BIT(27) || s->twoD_destination_base & BIT(27)) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only local memory is supported.\\n\");\n return;\n }\n\n switch (cmd) {\n case 0x00: /* copy area */\n {\n int src_x = (s->twoD_source >> 16) & 0x01FFF;\n int src_y = s->twoD_source & 0xFFFF;\n uint32_t src_base = s->twoD_source_base & 0x03FFFFFF;\n uint8_t *src = s->local_mem + src_base;\n int src_pitch = s->twoD_pitch & 0x1FFF;\n\n#define COPY_AREA(_bpp, _pixel_type, rtl) { \\\n int y, x, index_d, index_s; \\\n for (y = 0; y < height; y++) { \\\n for (x = 0; x < width; x++) { \\\n _pixel_type val; \\\n \\\n if (rtl) { \\\n index_s = ((src_y - y) * src_pitch + src_x - x) * _bpp; \\\n index_d = ((dst_y - y) * dst_pitch + dst_x - x) * _bpp; \\\n } else { \\\n index_s = ((src_y + y) * src_pitch + src_x + x) * _bpp; \\\n index_d = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \\\n } \\\n if (rop_mode == 1 && rop == 5) { \\\n /* Invert dest */ \\\n val = ~*(_pixel_type *)&dst[index_d]; \\\n } else { \\\n val = *(_pixel_type *)&src[index_s]; \\\n } \\\n *(_pixel_type *)&dst[index_d] = val; \\\n } \\\n } \\\n }\n switch (format) {\n case 0:\n COPY_AREA(1, uint8_t, rtl);\n break;\n case 1:\n COPY_AREA(2, uint16_t, rtl);\n break;\n case 2:\n COPY_AREA(4, uint32_t, rtl);\n break;\n }\n break;\n }\n case 0x01: /* fill rectangle */\n {\n uint32_t color = s->twoD_foreground;\n\n#define FILL_RECT(_bpp, _pixel_type) { \\\n int y, x; \\\n for (y = 0; y < height; y++) { \\\n for (x = 0; x < width; x++) { \\\n int index = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \\\n *(_pixel_type *)&dst[index] = (_pixel_type)color; \\\n } \\\n } \\\n }\n\n switch (format) {\n case 0:\n FILL_RECT(1, uint8_t);\n break;\n case 1:\n color = cpu_to_le16(color);\n FILL_RECT(2, uint16_t);\n break;\n case 2:\n color = cpu_to_le32(color);\n FILL_RECT(4, uint32_t);\n break;\n }\n break;\n }\n default:\n qemu_log_mask(LOG_UNIMP, \"sm501: not implemented 2D operation: %d\\n\",\n cmd);\n return;\n }\n\n if (dst_base >= get_fb_addr(s, crt) &&\n dst_base <= get_fb_addr(s, crt) + fb_len) {\n int dst_len = MIN(fb_len, ((dst_y + height - 1) * dst_pitch +\n dst_x + width) * (1 << format));\n if (dst_len) {\n memory_region_set_dirty(&s->local_mem_region, dst_base, dst_len);\n }\n }\n}", "func_hash": 211660814656777819247494130158952066961, "file_name": "sm501.c", "file_hash": 332598706492134995320459198660359754491, "cwe": ["CWE-190"], "cve": "CVE-2020-12829", "cve_desc": "In QEMU through 5.0.0, an integer overflow was found in the SM501 display driver implementation. This flaw occurs in the COPY_AREA macro while handling MMIO write operations through the sm501_2d_engine_write() callback. A local attacker could abuse this flaw to crash the QEMU process in sm501_2d_operation() in hw/display/sm501.c on the host, resulting in a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12829"} {"idx": 367048, "project": "qemu", "commit_id": "b15a22bbcbe6a78dc3d88fe3134985e4cdd87de4", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=b15a22bbcbe6a78dc3d88fe3134985e4cdd87de4", "commit_message": "sm501: Replace hand written implementation with pixman where possible\n\nBesides being faster this should also prevent malicious guests to\nabuse 2D engine to overwrite data or cause a crash.\n\nSigned-off-by: BALATON Zoltan \nMessage-id: 58666389b6cae256e4e972a32c05cf8aa51bffc0.1590089984.git.balaton@eik.bme.hu\nSigned-off-by: Gerd Hoffmann ", "target": 0, "func": "static void sm501_2d_operation(SM501State *s)\n{\n int cmd = (s->twoD_control >> 16) & 0x1F;\n int rtl = s->twoD_control & BIT(27);\n int format = (s->twoD_stretch >> 20) & 0x3;\n int rop_mode = (s->twoD_control >> 15) & 0x1; /* 1 for rop2, else rop3 */\n /* 1 if rop2 source is the pattern, otherwise the source is the bitmap */\n int rop2_source_is_pattern = (s->twoD_control >> 14) & 0x1;\n int rop = s->twoD_control & 0xFF;\n unsigned int dst_x = (s->twoD_destination >> 16) & 0x01FFF;\n unsigned int dst_y = s->twoD_destination & 0xFFFF;\n unsigned int width = (s->twoD_dimension >> 16) & 0x1FFF;\n unsigned int height = s->twoD_dimension & 0xFFFF;\n uint32_t dst_base = s->twoD_destination_base & 0x03FFFFFF;\n unsigned int dst_pitch = (s->twoD_pitch >> 16) & 0x1FFF;\n int crt = (s->dc_crt_control & SM501_DC_CRT_CONTROL_SEL) ? 1 : 0;\n int fb_len = get_width(s, crt) * get_height(s, crt) * get_bpp(s, crt);\n\n if ((s->twoD_stretch >> 16) & 0xF) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only XY addressing is supported.\\n\");\n return;\n }\n\n if (s->twoD_source_base & BIT(27) || s->twoD_destination_base & BIT(27)) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only local memory is supported.\\n\");\n return;\n }\n\n if (!dst_pitch) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: Zero dest pitch.\\n\");\n return;\n }\n\n if (!width || !height) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: Zero size 2D op.\\n\");\n return;\n }\n\n if (rtl) {\n dst_x -= width - 1;\n dst_y -= height - 1;\n }\n\n if (dst_base >= get_local_mem_size(s) || dst_base +\n (dst_x + width + (dst_y + height) * (dst_pitch + width)) *\n (1 << format) >= get_local_mem_size(s)) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: 2D op dest is outside vram.\\n\");\n return;\n }\n\n switch (cmd) {\n case 0: /* BitBlt */\n {\n unsigned int src_x = (s->twoD_source >> 16) & 0x01FFF;\n unsigned int src_y = s->twoD_source & 0xFFFF;\n uint32_t src_base = s->twoD_source_base & 0x03FFFFFF;\n unsigned int src_pitch = s->twoD_pitch & 0x1FFF;\n\n if (!src_pitch) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: Zero src pitch.\\n\");\n return;\n }\n\n if (rtl) {\n src_x -= width - 1;\n src_y -= height - 1;\n }\n\n if (src_base >= get_local_mem_size(s) || src_base +\n (src_x + width + (src_y + height) * (src_pitch + width)) *\n (1 << format) >= get_local_mem_size(s)) {\n qemu_log_mask(LOG_GUEST_ERROR,\n \"sm501: 2D op src is outside vram.\\n\");\n return;\n }\n\n if ((rop_mode && rop == 0x5) || (!rop_mode && rop == 0x55)) {\n /* Invert dest, is there a way to do this with pixman? */\n unsigned int x, y, i;\n uint8_t *d = s->local_mem + dst_base;\n\n for (y = 0; y < height; y++) {\n i = (dst_x + (dst_y + y) * dst_pitch) * (1 << format);\n for (x = 0; x < width; x++, i += (1 << format)) {\n switch (format) {\n case 0:\n d[i] = ~d[i];\n break;\n case 1:\n *(uint16_t *)&d[i] = ~*(uint16_t *)&d[i];\n break;\n case 2:\n *(uint32_t *)&d[i] = ~*(uint32_t *)&d[i];\n break;\n }\n }\n }\n } else {\n /* Do copy src for unimplemented ops, better than unpainted area */\n if ((rop_mode && (rop != 0xc || rop2_source_is_pattern)) ||\n (!rop_mode && rop != 0xcc)) {\n qemu_log_mask(LOG_UNIMP,\n \"sm501: rop%d op %x%s not implemented\\n\",\n (rop_mode ? 2 : 3), rop,\n (rop2_source_is_pattern ?\n \" with pattern source\" : \"\"));\n }\n /* Check for overlaps, this could be made more exact */\n uint32_t sb, se, db, de;\n sb = src_base + src_x + src_y * (width + src_pitch);\n se = sb + width + height * (width + src_pitch);\n db = dst_base + dst_x + dst_y * (width + dst_pitch);\n de = db + width + height * (width + dst_pitch);\n if (rtl && ((db >= sb && db <= se) || (de >= sb && de <= se))) {\n /* regions may overlap: copy via temporary */\n int llb = width * (1 << format);\n int tmp_stride = DIV_ROUND_UP(llb, sizeof(uint32_t));\n uint32_t *tmp = g_malloc(tmp_stride * sizeof(uint32_t) *\n height);\n pixman_blt((uint32_t *)&s->local_mem[src_base], tmp,\n src_pitch * (1 << format) / sizeof(uint32_t),\n tmp_stride, 8 * (1 << format), 8 * (1 << format),\n src_x, src_y, 0, 0, width, height);\n pixman_blt(tmp, (uint32_t *)&s->local_mem[dst_base],\n tmp_stride,\n dst_pitch * (1 << format) / sizeof(uint32_t),\n 8 * (1 << format), 8 * (1 << format),\n 0, 0, dst_x, dst_y, width, height);\n g_free(tmp);\n } else {\n pixman_blt((uint32_t *)&s->local_mem[src_base],\n (uint32_t *)&s->local_mem[dst_base],\n src_pitch * (1 << format) / sizeof(uint32_t),\n dst_pitch * (1 << format) / sizeof(uint32_t),\n 8 * (1 << format), 8 * (1 << format),\n src_x, src_y, dst_x, dst_y, width, height);\n }\n }\n break;\n }\n case 1: /* Rectangle Fill */\n {\n uint32_t color = s->twoD_foreground;\n\n if (format == 2) {\n color = cpu_to_le32(color);\n } else if (format == 1) {\n color = cpu_to_le16(color);\n }\n\n pixman_fill((uint32_t *)&s->local_mem[dst_base],\n dst_pitch * (1 << format) / sizeof(uint32_t),\n 8 * (1 << format), dst_x, dst_y, width, height, color);\n break;\n }\n default:\n qemu_log_mask(LOG_UNIMP, \"sm501: not implemented 2D operation: %d\\n\",\n cmd);\n return;\n }\n\n if (dst_base >= get_fb_addr(s, crt) &&\n dst_base <= get_fb_addr(s, crt) + fb_len) {\n int dst_len = MIN(fb_len, ((dst_y + height - 1) * dst_pitch +\n dst_x + width) * (1 << format));\n if (dst_len) {\n memory_region_set_dirty(&s->local_mem_region, dst_base, dst_len);\n }\n }\n}", "func_hash": 328394315883664122144081856844009832430, "file_name": "sm501.c", "file_hash": 29602277119289772912461795090400748387, "cwe": ["CWE-190"], "cve": "CVE-2020-12829", "cve_desc": "In QEMU through 5.0.0, an integer overflow was found in the SM501 display driver implementation. This flaw occurs in the COPY_AREA macro while handling MMIO write operations through the sm501_2d_engine_write() callback. A local attacker could abuse this flaw to crash the QEMU process in sm501_2d_operation() in hw/display/sm501.c on the host, resulting in a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12829"} {"idx": 204868, "project": "exiv2", "commit_id": "bd0afe0390439b2c424d881c8c6eb0c5624e31d9", "project_url": "https://github.com/Exiv2/exiv2", "commit_url": "https://github.com/Exiv2/exiv2/commit/bd0afe0390439b2c424d881c8c6eb0c5624e31d9", "commit_message": "Add bounds check to MemIo::seek(). (#944)\n\n- Regression test for missing bounds check in MemIo::seek()\n- Add bounds check to MemIo::seek(), this fixes CVE-2019-13504", "target": 1, "func": " int MemIo::seek(int64 offset, Position pos )\n {\n int64 newIdx = 0;\n\n switch (pos) {\n case BasicIo::cur:\n newIdx = p_->idx_ + offset;\n break;\n case BasicIo::beg:\n newIdx = offset;\n break;\n case BasicIo::end:\n newIdx = p_->size_ + offset;\n break;\n }\n\n if (newIdx < 0)\n return 1;\n\n p_->idx_ = static_cast(newIdx); //not very sure about this. need more test!! - note by Shawn fly2xj@gmail.com //TODO\n p_->eof_ = false;\n return 0;\n }", "func_hash": 200396161247820253537751287744131550754, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2019-13504", "cve_desc": "There is an out-of-bounds read in Exiv2::MrwImage::readMetadata in mrwimage.cpp in Exiv2 through 0.27.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-13504"} {"idx": 367064, "project": "exiv2", "commit_id": "bd0afe0390439b2c424d881c8c6eb0c5624e31d9", "project_url": "https://github.com/Exiv2/exiv2", "commit_url": "https://github.com/Exiv2/exiv2/commit/bd0afe0390439b2c424d881c8c6eb0c5624e31d9", "commit_message": "Add bounds check to MemIo::seek(). (#944)\n\n- Regression test for missing bounds check in MemIo::seek()\n- Add bounds check to MemIo::seek(), this fixes CVE-2019-13504", "target": 0, "func": " int MemIo::seek(int64 offset, Position pos )\n {\n int64 newIdx = 0;\n\n switch (pos) {\n case BasicIo::cur:\n newIdx = p_->idx_ + offset;\n break;\n case BasicIo::beg:\n newIdx = offset;\n break;\n case BasicIo::end:\n newIdx = p_->size_ + offset;\n break;\n }\n\n if (newIdx < 0)\n return 1;\n\n if (static_cast(newIdx) > p_->size_) {\n p_->eof_ = true;\n return 1;\n }\n\n p_->idx_ = static_cast(newIdx);\n p_->eof_ = false;\n return 0;\n }", "func_hash": 145872850365992270404465741213448019718, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2019-13504", "cve_desc": "There is an out-of-bounds read in Exiv2::MrwImage::readMetadata in mrwimage.cpp in Exiv2 through 0.27.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-13504"} {"idx": 205562, "project": "soundtouch", "commit_id": "a1c400eb2cff849c0e5f9d6916d69ffea3ad2c85", "project_url": "https://gitlab.com/soundtouch/soundtouch", "commit_url": "https://gitlab.com/soundtouch/soundtouch/commit/a1c400eb2cff849c0e5f9d6916d69ffea3ad2c85", "commit_message": "Fix issue CVE-2018-17096: Replace assert with runtime exception", "target": 1, "func": "BPMDetect::BPMDetect(int numChannels, int aSampleRate) :\r\n beat_lpf(_LPF_coeffs)\r\n{\r\n beats.reserve(250); // initial reservation to prevent frequent reallocation\r\n\r\n this->sampleRate = aSampleRate;\r\n this->channels = numChannels;\r\n\r\n decimateSum = 0;\r\n decimateCount = 0;\r\n\r\n // choose decimation factor so that result is approx. 1000 Hz\r\n decimateBy = sampleRate / TARGET_SRATE;\r\n assert(decimateBy > 0);\r\n assert(INPUT_BLOCK_SIZE < decimateBy * DECIMATED_BLOCK_SIZE);\r\n\r\n // Calculate window length & starting item according to desired min & max bpms\r\n windowLen = (60 * sampleRate) / (decimateBy * MIN_BPM);\r\n windowStart = (60 * sampleRate) / (decimateBy * MAX_BPM_RANGE);\r\n\r\n assert(windowLen > windowStart);\r\n\r\n // allocate new working objects\r\n xcorr = new float[windowLen];\r\n memset(xcorr, 0, windowLen * sizeof(float));\r\n\r\n pos = 0;\r\n peakPos = 0;\r\n peakVal = 0;\r\n init_scaler = 1;\r\n beatcorr_ringbuffpos = 0;\r\n beatcorr_ringbuff = new float[windowLen];\r\n memset(beatcorr_ringbuff, 0, windowLen * sizeof(float));\r\n\r\n // allocate processing buffer\r\n buffer = new FIFOSampleBuffer();\r\n // we do processing in mono mode\r\n buffer->setChannels(1);\r\n buffer->clear();\r\n\r\n // calculate hamming windows\r\n hamw = new float[XCORR_UPDATE_SEQUENCE];\r\n hamming(hamw, XCORR_UPDATE_SEQUENCE);\r\n hamw2 = new float[XCORR_UPDATE_SEQUENCE / 2];\r\n hamming(hamw2, XCORR_UPDATE_SEQUENCE / 2);\r\n}\r", "func_hash": 264313322771785381717618863985113289887, "file_name": "BPMDetect.cpp", "file_hash": 282853650528757723107697266423021591179, "cwe": ["CWE-617"], "cve": "CVE-2018-17096", "cve_desc": "The BPMDetect class in BPMDetect.cpp in libSoundTouch.a in Olli Parviainen SoundTouch 2.0 allows remote attackers to cause a denial of service (assertion failure and application exit), as demonstrated by SoundStretch.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-17096"} {"idx": 368106, "project": "soundtouch", "commit_id": "a1c400eb2cff849c0e5f9d6916d69ffea3ad2c85", "project_url": "https://gitlab.com/soundtouch/soundtouch", "commit_url": "https://gitlab.com/soundtouch/soundtouch/commit/a1c400eb2cff849c0e5f9d6916d69ffea3ad2c85", "commit_message": "Fix issue CVE-2018-17096: Replace assert with runtime exception", "target": 0, "func": "BPMDetect::BPMDetect(int numChannels, int aSampleRate) :\r\n beat_lpf(_LPF_coeffs)\r\n{\r\n beats.reserve(250); // initial reservation to prevent frequent reallocation\r\n\r\n this->sampleRate = aSampleRate;\r\n this->channels = numChannels;\r\n\r\n decimateSum = 0;\r\n decimateCount = 0;\r\n\r\n // choose decimation factor so that result is approx. 1000 Hz\r\n decimateBy = sampleRate / TARGET_SRATE;\r\n if ((decimateBy <= 0) || (decimateBy * DECIMATED_BLOCK_SIZE < INPUT_BLOCK_SIZE))\r\n {\r\n ST_THROW_RT_ERROR(\"Too small samplerate\");\r\n }\r\n\r\n // Calculate window length & starting item according to desired min & max bpms\r\n windowLen = (60 * sampleRate) / (decimateBy * MIN_BPM);\r\n windowStart = (60 * sampleRate) / (decimateBy * MAX_BPM_RANGE);\r\n\r\n assert(windowLen > windowStart);\r\n\r\n // allocate new working objects\r\n xcorr = new float[windowLen];\r\n memset(xcorr, 0, windowLen * sizeof(float));\r\n\r\n pos = 0;\r\n peakPos = 0;\r\n peakVal = 0;\r\n init_scaler = 1;\r\n beatcorr_ringbuffpos = 0;\r\n beatcorr_ringbuff = new float[windowLen];\r\n memset(beatcorr_ringbuff, 0, windowLen * sizeof(float));\r\n\r\n // allocate processing buffer\r\n buffer = new FIFOSampleBuffer();\r\n // we do processing in mono mode\r\n buffer->setChannels(1);\r\n buffer->clear();\r\n\r\n // calculate hamming windows\r\n hamw = new float[XCORR_UPDATE_SEQUENCE];\r\n hamming(hamw, XCORR_UPDATE_SEQUENCE);\r\n hamw2 = new float[XCORR_UPDATE_SEQUENCE / 2];\r\n hamming(hamw2, XCORR_UPDATE_SEQUENCE / 2);\r\n}\r", "func_hash": 92069915114606685309727291807602661420, "file_name": "BPMDetect.cpp", "file_hash": 237475982206128856459642076599546323454, "cwe": ["CWE-617"], "cve": "CVE-2018-17096", "cve_desc": "The BPMDetect class in BPMDetect.cpp in libSoundTouch.a in Olli Parviainen SoundTouch 2.0 allows remote attackers to cause a denial of service (assertion failure and application exit), as demonstrated by SoundStretch.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-17096"} {"idx": 205584, "project": "hivex", "commit_id": "8f1935733b10d974a1a4176d38dd151ed98cf381", "project_url": "https://github.com/libguestfs/hivex", "commit_url": "https://github.com/libguestfs/hivex/commit/8f1935733b10d974a1a4176d38dd151ed98cf381", "commit_message": "lib/handle.c: Bounds check for block exceeding page length (CVE-2021-3504)\n\nHives are encoded as fixed-sized pages containing smaller variable-\nlength blocks:\n\n +-------------------+-------------------+-------------------+--\n | header |[ blk ][blk][ blk ]|[blk][blk][blk] |\n +-------------------+-------------------+-------------------+--\n\nBlocks should not straddle a page boundary. However because blocks\ncontain a 32 bit length field it is possible to construct an invalid\nhive where the last block in a page overlaps either the next page or\nthe end of the file:\n\n +-------------------+-------------------+\n | header |[ blk ][blk][ blk ..... ]\n +-------------------+-------------------+\n\nHivex lacked a bounds check and would process the registry. Because\nthe rest of the code assumes this situation can never happen it was\npossible to have a block containing some field (eg. a registry key\nname) which would extend beyond the end of the file. Hivex mmaps or\nmallocs the file, causing hivex to read memory beyond the end of the\nmapped region, resulting in reading other memory structures or a\ncrash. (Writing beyond the end of the mapped region seems to be\nimpossible because we always allocate a new page before writing.)\n\nThis commit adds a check which rejects the malformed registry on\nhivex_open.\n\nCredit: Jeremy Galindo, Sr Security Engineer, Datto.com\nSigned-off-by: Richard W.M. Jones \nFixes: CVE-2021-3504\nFixes: https://bugzilla.redhat.com/show_bug.cgi?id=1949687", "target": 1, "func": "hivex_open (const char *filename, int flags)\n{\n hive_h *h = NULL;\n\n assert (sizeof (struct ntreg_header) == 0x1000);\n assert (offsetof (struct ntreg_header, csum) == 0x1fc);\n\n h = calloc (1, sizeof *h);\n if (h == NULL)\n goto error;\n\n h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;\n\n const char *debug = getenv (\"HIVEX_DEBUG\");\n if (debug && STREQ (debug, \"1\"))\n h->msglvl = 2;\n\n DEBUG (2, \"created handle %p\", h);\n\n h->writable = !!(flags & HIVEX_OPEN_WRITE);\n h->unsafe = !!(flags & HIVEX_OPEN_UNSAFE);\n h->filename = strdup (filename);\n if (h->filename == NULL)\n goto error;\n\n#ifdef O_CLOEXEC\n h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);\n#else\n h->fd = open (filename, O_RDONLY | O_BINARY);\n#endif\n if (h->fd == -1)\n goto error;\n#ifndef O_CLOEXEC\n fcntl (h->fd, F_SETFD, FD_CLOEXEC);\n#endif\n\n struct stat statbuf;\n if (fstat (h->fd, &statbuf) == -1)\n goto error;\n\n h->size = statbuf.st_size;\n\n if (h->size < 0x2000) {\n SET_ERRNO (EINVAL,\n \"%s: file is too small to be a Windows NT Registry hive file\",\n filename);\n goto error;\n }\n\n if (!h->writable) {\n h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);\n if (h->addr == MAP_FAILED)\n goto error;\n\n DEBUG (2, \"mapped file at %p\", h->addr);\n } else {\n h->addr = malloc (h->size);\n if (h->addr == NULL)\n goto error;\n\n if (full_read (h->fd, h->addr, h->size) < h->size)\n goto error;\n\n /* We don't need the file descriptor along this path, since we\n * have read all the data.\n */\n if (close (h->fd) == -1)\n goto error;\n h->fd = -1;\n }\n\n /* Check header. */\n if (h->hdr->magic[0] != 'r' ||\n h->hdr->magic[1] != 'e' ||\n h->hdr->magic[2] != 'g' ||\n h->hdr->magic[3] != 'f') {\n SET_ERRNO (ENOTSUP,\n \"%s: not a Windows NT Registry hive file\", filename);\n goto error;\n }\n\n /* Check major version. */\n uint32_t major_ver = le32toh (h->hdr->major_ver);\n if (major_ver != 1) {\n SET_ERRNO (ENOTSUP,\n \"%s: hive file major version %\" PRIu32 \" (expected 1)\",\n filename, major_ver);\n goto error;\n }\n\n h->bitmap = calloc (1 + h->size / 32, 1);\n if (h->bitmap == NULL)\n goto error;\n\n /* Header checksum. */\n uint32_t sum = header_checksum (h);\n if (sum != le32toh (h->hdr->csum)) {\n SET_ERRNO (EINVAL, \"%s: bad checksum in hive header\", filename);\n goto error;\n }\n\n for (int t=0; ticonv_cache[t].mutex);\n h->iconv_cache[t].handle = NULL;\n }\n\n /* Last modified time. */\n h->last_modified = le64toh ((int64_t) h->hdr->last_modified);\n\n if (h->msglvl >= 2) {\n char *name = _hivex_recode (h, utf16le_to_utf8,\n h->hdr->name, 64, NULL);\n\n fprintf (stderr,\n \"hivex_open: header fields:\\n\"\n \" file version %\" PRIu32 \".%\" PRIu32 \"\\n\"\n \" sequence nos %\" PRIu32 \" %\" PRIu32 \"\\n\"\n \" (sequences nos should match if hive was synched at shutdown)\\n\"\n \" last modified %\" PRIi64 \"\\n\"\n \" (Windows filetime, x 100 ns since 1601-01-01)\\n\"\n \" original file name %s\\n\"\n \" (only 32 chars are stored, name is probably truncated)\\n\"\n \" root offset 0x%x + 0x1000\\n\"\n \" end of last page 0x%x + 0x1000 (total file size 0x%zx)\\n\"\n \" checksum 0x%x (calculated 0x%x)\\n\",\n major_ver, le32toh (h->hdr->minor_ver),\n le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),\n h->last_modified,\n name ? name : \"(conversion failed)\",\n le32toh (h->hdr->offset),\n le32toh (h->hdr->blocks), h->size,\n le32toh (h->hdr->csum), sum);\n free (name);\n }\n\n h->rootoffs = le32toh (h->hdr->offset) + 0x1000;\n h->endpages = le32toh (h->hdr->blocks) + 0x1000;\n\n DEBUG (2, \"root offset = 0x%zx\", h->rootoffs);\n\n /* We'll set this flag when we see a block with the root offset (ie.\n * the root block).\n */\n int seen_root_block = 0, bad_root_block = 0;\n\n /* Collect some stats. */\n size_t pages = 0; /* Number of hbin pages read. */\n size_t smallest_page = SIZE_MAX, largest_page = 0;\n size_t blocks = 0; /* Total number of blocks found. */\n size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;\n size_t used_blocks = 0; /* Total number of used blocks found. */\n size_t used_size = 0; /* Total size (bytes) of used blocks. */\n\n /* Read the pages and blocks. The aim here is to be robust against\n * corrupt or malicious registries. So we make sure the loops\n * always make forward progress. We add the address of each block\n * we read to a hash table so pointers will only reference the start\n * of valid blocks.\n */\n size_t off;\n struct ntreg_hbin_page *page;\n for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] != 'h' ||\n page->magic[1] != 'b' ||\n page->magic[2] != 'i' ||\n page->magic[3] != 'n') {\n\n if (!h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s: trailing garbage at end of file \"\n \"(at 0x%zx, after %zu pages)\",\n filename, off, pages);\n goto error;\n }\n\n DEBUG (2,\n \"page not found at expected offset 0x%zx, \"\n \"seeking until one is found or EOF is reached\",\n off);\n\n int found = 0;\n while (off < h->size) {\n off += 0x1000;\n\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] == 'h' &&\n page->magic[1] == 'b' &&\n page->magic[2] == 'i' &&\n page->magic[3] == 'n') {\n DEBUG (2, \"found next page by seeking at 0x%zx\", off);\n found = 1;\n break;\n }\n }\n\n if (!found) {\n DEBUG (2, \"page not found and end of pages section reached\");\n break;\n }\n }\n\n size_t page_size = le32toh (page->page_size);\n DEBUG (2, \"page at 0x%zx, size %zu\", off, page_size);\n pages++;\n if (page_size < smallest_page) smallest_page = page_size;\n if (page_size > largest_page) largest_page = page_size;\n\n if (page_size <= sizeof (struct ntreg_hbin_page) ||\n (page_size & 0x0fff) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n if (off + page_size > h->size) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx extends beyond end of file, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n size_t page_offset = le32toh(page->offset_first) + 0x1000;\n\n if (page_offset != off) {\n SET_ERRNO (ENOTSUP,\n \"%s: declared page offset (0x%zx) does not match computed \"\n \"offset (0x%zx), bad registry\",\n filename, page_offset, off);\n goto error;\n }\n\n /* Read the blocks in this page. */\n size_t blkoff;\n struct ntreg_hbin_block *block;\n size_t seg_len;\n for (blkoff = off + 0x20;\n blkoff < off + page_size;\n blkoff += seg_len) {\n blocks++;\n\n int is_root = blkoff == h->rootoffs;\n if (is_root)\n seen_root_block = 1;\n\n block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);\n int used;\n seg_len = block_len (h, blkoff, &used);\n/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78665 */\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wstrict-overflow\"\n if (seg_len <= 4 || (seg_len & 3) != 0) {\n#pragma GCC diagnostic pop\n if (is_root || !h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s, the block at 0x%zx has invalid size %\" PRIu32\n \", bad registry\",\n filename, blkoff, le32toh (block->seg_len));\n goto error;\n } else {\n DEBUG (2,\n \"%s: block at 0x%zx has invalid size %\" PRIu32 \", skipping\",\n filename, blkoff, le32toh (block->seg_len));\n break;\n }\n }\n\n if (h->msglvl >= 2) {\n unsigned char *id = (unsigned char *) block->id;\n int id0 = id[0], id1 = id[1];\n\n fprintf (stderr, \"%s: %s: \"\n \"%s block id %d,%d (%c%c) at 0x%zx size %zu%s\\n\",\n \"hivex\", __func__,\n used ? \"used\" : \"free\",\n id0, id1,\n c_isprint (id0) ? id0 : '.',\n c_isprint (id1) ? id1 : '.',\n blkoff,\n seg_len, is_root ? \" (root)\" : \"\");\n }\n\n blocks_bytes += seg_len;\n if (seg_len < smallest_block) smallest_block = seg_len;\n if (seg_len > largest_block) largest_block = seg_len;\n\n if (is_root && !used)\n bad_root_block = 1;\n\n if (used) {\n used_blocks++;\n used_size += seg_len;\n\n /* Root block must be an nk-block. */\n if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))\n bad_root_block = 1;\n\n /* Note this blkoff is a valid address. */\n BITMAP_SET (h->bitmap, blkoff);\n }\n }\n }\n\n if (!seen_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: no root block found\", filename);\n goto error;\n }\n\n if (bad_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: bad root block (free or not nk)\", filename);\n goto error;\n }\n\n DEBUG (1, \"successfully read Windows Registry hive file:\\n\"\n \" pages: %zu [sml: %zu, lge: %zu]\\n\"\n \" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\\n\"\n \" blocks used: %zu\\n\"\n \" bytes used: %zu\",\n pages, smallest_page, largest_page,\n blocks, smallest_block, blocks_bytes / blocks, largest_block,\n used_blocks, used_size);\n\n return h;\n\n error:;\n int err = errno;\n if (h) {\n free (h->bitmap);\n if (h->addr && h->size && h->addr != MAP_FAILED) {\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n }\n if (h->fd >= 0)\n close (h->fd);\n free (h->filename);\n free (h);\n }\n errno = err;\n return NULL;\n}", "func_hash": 301959441620002037949455962982237591018, "file_name": "handle.c", "file_hash": 168183380756387424984975498642444590309, "cwe": ["CWE-125"], "cve": "CVE-2021-3504", "cve_desc": "A flaw was found in the hivex library in versions before 1.3.20. It is caused due to a lack of bounds check within the hivex_open function. An attacker could input a specially crafted Windows Registry (hive) file which would cause hivex to read memory beyond its normal bounds or cause the program to crash. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3504"} {"idx": 368604, "project": "hivex", "commit_id": "8f1935733b10d974a1a4176d38dd151ed98cf381", "project_url": "https://github.com/libguestfs/hivex", "commit_url": "https://github.com/libguestfs/hivex/commit/8f1935733b10d974a1a4176d38dd151ed98cf381", "commit_message": "lib/handle.c: Bounds check for block exceeding page length (CVE-2021-3504)\n\nHives are encoded as fixed-sized pages containing smaller variable-\nlength blocks:\n\n +-------------------+-------------------+-------------------+--\n | header |[ blk ][blk][ blk ]|[blk][blk][blk] |\n +-------------------+-------------------+-------------------+--\n\nBlocks should not straddle a page boundary. However because blocks\ncontain a 32 bit length field it is possible to construct an invalid\nhive where the last block in a page overlaps either the next page or\nthe end of the file:\n\n +-------------------+-------------------+\n | header |[ blk ][blk][ blk ..... ]\n +-------------------+-------------------+\n\nHivex lacked a bounds check and would process the registry. Because\nthe rest of the code assumes this situation can never happen it was\npossible to have a block containing some field (eg. a registry key\nname) which would extend beyond the end of the file. Hivex mmaps or\nmallocs the file, causing hivex to read memory beyond the end of the\nmapped region, resulting in reading other memory structures or a\ncrash. (Writing beyond the end of the mapped region seems to be\nimpossible because we always allocate a new page before writing.)\n\nThis commit adds a check which rejects the malformed registry on\nhivex_open.\n\nCredit: Jeremy Galindo, Sr Security Engineer, Datto.com\nSigned-off-by: Richard W.M. Jones \nFixes: CVE-2021-3504\nFixes: https://bugzilla.redhat.com/show_bug.cgi?id=1949687", "target": 0, "func": "hivex_open (const char *filename, int flags)\n{\n hive_h *h = NULL;\n\n assert (sizeof (struct ntreg_header) == 0x1000);\n assert (offsetof (struct ntreg_header, csum) == 0x1fc);\n\n h = calloc (1, sizeof *h);\n if (h == NULL)\n goto error;\n\n h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;\n\n const char *debug = getenv (\"HIVEX_DEBUG\");\n if (debug && STREQ (debug, \"1\"))\n h->msglvl = 2;\n\n DEBUG (2, \"created handle %p\", h);\n\n h->writable = !!(flags & HIVEX_OPEN_WRITE);\n h->unsafe = !!(flags & HIVEX_OPEN_UNSAFE);\n h->filename = strdup (filename);\n if (h->filename == NULL)\n goto error;\n\n#ifdef O_CLOEXEC\n h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);\n#else\n h->fd = open (filename, O_RDONLY | O_BINARY);\n#endif\n if (h->fd == -1)\n goto error;\n#ifndef O_CLOEXEC\n fcntl (h->fd, F_SETFD, FD_CLOEXEC);\n#endif\n\n struct stat statbuf;\n if (fstat (h->fd, &statbuf) == -1)\n goto error;\n\n h->size = statbuf.st_size;\n\n if (h->size < 0x2000) {\n SET_ERRNO (EINVAL,\n \"%s: file is too small to be a Windows NT Registry hive file\",\n filename);\n goto error;\n }\n\n if (!h->writable) {\n h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);\n if (h->addr == MAP_FAILED)\n goto error;\n\n DEBUG (2, \"mapped file at %p\", h->addr);\n } else {\n h->addr = malloc (h->size);\n if (h->addr == NULL)\n goto error;\n\n if (full_read (h->fd, h->addr, h->size) < h->size)\n goto error;\n\n /* We don't need the file descriptor along this path, since we\n * have read all the data.\n */\n if (close (h->fd) == -1)\n goto error;\n h->fd = -1;\n }\n\n /* Check header. */\n if (h->hdr->magic[0] != 'r' ||\n h->hdr->magic[1] != 'e' ||\n h->hdr->magic[2] != 'g' ||\n h->hdr->magic[3] != 'f') {\n SET_ERRNO (ENOTSUP,\n \"%s: not a Windows NT Registry hive file\", filename);\n goto error;\n }\n\n /* Check major version. */\n uint32_t major_ver = le32toh (h->hdr->major_ver);\n if (major_ver != 1) {\n SET_ERRNO (ENOTSUP,\n \"%s: hive file major version %\" PRIu32 \" (expected 1)\",\n filename, major_ver);\n goto error;\n }\n\n h->bitmap = calloc (1 + h->size / 32, 1);\n if (h->bitmap == NULL)\n goto error;\n\n /* Header checksum. */\n uint32_t sum = header_checksum (h);\n if (sum != le32toh (h->hdr->csum)) {\n SET_ERRNO (EINVAL, \"%s: bad checksum in hive header\", filename);\n goto error;\n }\n\n for (int t=0; ticonv_cache[t].mutex);\n h->iconv_cache[t].handle = NULL;\n }\n\n /* Last modified time. */\n h->last_modified = le64toh ((int64_t) h->hdr->last_modified);\n\n if (h->msglvl >= 2) {\n char *name = _hivex_recode (h, utf16le_to_utf8,\n h->hdr->name, 64, NULL);\n\n fprintf (stderr,\n \"hivex_open: header fields:\\n\"\n \" file version %\" PRIu32 \".%\" PRIu32 \"\\n\"\n \" sequence nos %\" PRIu32 \" %\" PRIu32 \"\\n\"\n \" (sequences nos should match if hive was synched at shutdown)\\n\"\n \" last modified %\" PRIi64 \"\\n\"\n \" (Windows filetime, x 100 ns since 1601-01-01)\\n\"\n \" original file name %s\\n\"\n \" (only 32 chars are stored, name is probably truncated)\\n\"\n \" root offset 0x%x + 0x1000\\n\"\n \" end of last page 0x%x + 0x1000 (total file size 0x%zx)\\n\"\n \" checksum 0x%x (calculated 0x%x)\\n\",\n major_ver, le32toh (h->hdr->minor_ver),\n le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),\n h->last_modified,\n name ? name : \"(conversion failed)\",\n le32toh (h->hdr->offset),\n le32toh (h->hdr->blocks), h->size,\n le32toh (h->hdr->csum), sum);\n free (name);\n }\n\n h->rootoffs = le32toh (h->hdr->offset) + 0x1000;\n h->endpages = le32toh (h->hdr->blocks) + 0x1000;\n\n DEBUG (2, \"root offset = 0x%zx\", h->rootoffs);\n\n /* We'll set this flag when we see a block with the root offset (ie.\n * the root block).\n */\n int seen_root_block = 0, bad_root_block = 0;\n\n /* Collect some stats. */\n size_t pages = 0; /* Number of hbin pages read. */\n size_t smallest_page = SIZE_MAX, largest_page = 0;\n size_t blocks = 0; /* Total number of blocks found. */\n size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;\n size_t used_blocks = 0; /* Total number of used blocks found. */\n size_t used_size = 0; /* Total size (bytes) of used blocks. */\n\n /* Read the pages and blocks. The aim here is to be robust against\n * corrupt or malicious registries. So we make sure the loops\n * always make forward progress. We add the address of each block\n * we read to a hash table so pointers will only reference the start\n * of valid blocks.\n */\n size_t off;\n struct ntreg_hbin_page *page;\n for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] != 'h' ||\n page->magic[1] != 'b' ||\n page->magic[2] != 'i' ||\n page->magic[3] != 'n') {\n\n if (!h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s: trailing garbage at end of file \"\n \"(at 0x%zx, after %zu pages)\",\n filename, off, pages);\n goto error;\n }\n\n DEBUG (2,\n \"page not found at expected offset 0x%zx, \"\n \"seeking until one is found or EOF is reached\",\n off);\n\n int found = 0;\n while (off < h->size) {\n off += 0x1000;\n\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] == 'h' &&\n page->magic[1] == 'b' &&\n page->magic[2] == 'i' &&\n page->magic[3] == 'n') {\n DEBUG (2, \"found next page by seeking at 0x%zx\", off);\n found = 1;\n break;\n }\n }\n\n if (!found) {\n DEBUG (2, \"page not found and end of pages section reached\");\n break;\n }\n }\n\n size_t page_size = le32toh (page->page_size);\n DEBUG (2, \"page at 0x%zx, size %zu\", off, page_size);\n pages++;\n if (page_size < smallest_page) smallest_page = page_size;\n if (page_size > largest_page) largest_page = page_size;\n\n if (page_size <= sizeof (struct ntreg_hbin_page) ||\n (page_size & 0x0fff) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n if (off + page_size > h->size) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx extends beyond end of file, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n size_t page_offset = le32toh(page->offset_first) + 0x1000;\n\n if (page_offset != off) {\n SET_ERRNO (ENOTSUP,\n \"%s: declared page offset (0x%zx) does not match computed \"\n \"offset (0x%zx), bad registry\",\n filename, page_offset, off);\n goto error;\n }\n\n /* Read the blocks in this page. */\n size_t blkoff;\n struct ntreg_hbin_block *block;\n size_t seg_len;\n for (blkoff = off + 0x20;\n blkoff < off + page_size;\n blkoff += seg_len) {\n blocks++;\n\n int is_root = blkoff == h->rootoffs;\n if (is_root)\n seen_root_block = 1;\n\n block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);\n int used;\n seg_len = block_len (h, blkoff, &used);\n/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78665 */\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wstrict-overflow\"\n if (seg_len <= 4 || (seg_len & 3) != 0) {\n#pragma GCC diagnostic pop\n if (is_root || !h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s, the block at 0x%zx size %\" PRIu32\n \" <= 4 or not a multiple of 4, bad registry\",\n filename, blkoff, le32toh (block->seg_len));\n goto error;\n } else {\n DEBUG (2,\n \"%s: block at 0x%zx has invalid size %\" PRIu32 \", skipping\",\n filename, blkoff, le32toh (block->seg_len));\n break;\n }\n }\n\n if (blkoff + seg_len > off + page_size) {\n SET_ERRNO (ENOTSUP,\n \"%s, the block at 0x%zx size %\" PRIu32\n \" extends beyond the current page, bad registry\",\n filename, blkoff, le32toh (block->seg_len));\n goto error;\n }\n\n if (h->msglvl >= 2) {\n unsigned char *id = (unsigned char *) block->id;\n int id0 = id[0], id1 = id[1];\n\n fprintf (stderr, \"%s: %s: \"\n \"%s block id %d,%d (%c%c) at 0x%zx size %zu%s\\n\",\n \"hivex\", __func__,\n used ? \"used\" : \"free\",\n id0, id1,\n c_isprint (id0) ? id0 : '.',\n c_isprint (id1) ? id1 : '.',\n blkoff,\n seg_len, is_root ? \" (root)\" : \"\");\n }\n\n blocks_bytes += seg_len;\n if (seg_len < smallest_block) smallest_block = seg_len;\n if (seg_len > largest_block) largest_block = seg_len;\n\n if (is_root && !used)\n bad_root_block = 1;\n\n if (used) {\n used_blocks++;\n used_size += seg_len;\n\n /* Root block must be an nk-block. */\n if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))\n bad_root_block = 1;\n\n /* Note this blkoff is a valid address. */\n BITMAP_SET (h->bitmap, blkoff);\n }\n }\n }\n\n if (!seen_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: no root block found\", filename);\n goto error;\n }\n\n if (bad_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: bad root block (free or not nk)\", filename);\n goto error;\n }\n\n DEBUG (1, \"successfully read Windows Registry hive file:\\n\"\n \" pages: %zu [sml: %zu, lge: %zu]\\n\"\n \" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\\n\"\n \" blocks used: %zu\\n\"\n \" bytes used: %zu\",\n pages, smallest_page, largest_page,\n blocks, smallest_block, blocks_bytes / blocks, largest_block,\n used_blocks, used_size);\n\n return h;\n\n error:;\n int err = errno;\n if (h) {\n free (h->bitmap);\n if (h->addr && h->size && h->addr != MAP_FAILED) {\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n }\n if (h->fd >= 0)\n close (h->fd);\n free (h->filename);\n free (h);\n }\n errno = err;\n return NULL;\n}", "func_hash": 247491246850383093323637970136750698397, "file_name": "handle.c", "file_hash": 118224005765273407940556777103596613936, "cwe": ["CWE-125"], "cve": "CVE-2021-3504", "cve_desc": "A flaw was found in the hivex library in versions before 1.3.20. It is caused due to a lack of bounds check within the hivex_open function. An attacker could input a specially crafted Windows Registry (hive) file which would cause hivex to read memory beyond its normal bounds or cause the program to crash. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3504"} {"idx": 205671, "project": "FreeRDP", "commit_id": "9f77fc3dd2394373e1be753952b00dafa1a9b7da", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/9f77fc3dd2394373e1be753952b00dafa1a9b7da", "commit_message": "Fixed int overflow in msusb_mspipes_read\n\nThanks to hac425", "target": 1, "func": "static MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(wStream* s, UINT32 NumberOfPipes)\n{\n\tUINT32 pnum;\n\tMSUSB_PIPE_DESCRIPTOR** MsPipes;\n\n\tif (Stream_GetRemainingCapacity(s) < 12 * NumberOfPipes)\n\t\treturn NULL;\n\n\tMsPipes = (MSUSB_PIPE_DESCRIPTOR**)calloc(NumberOfPipes, sizeof(MSUSB_PIPE_DESCRIPTOR*));\n\n\tif (!MsPipes)\n\t\treturn NULL;\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t{\n\t\tMSUSB_PIPE_DESCRIPTOR* MsPipe = msusb_mspipe_new();\n\n\t\tif (!MsPipe)\n\t\t\tgoto out_error;\n\n\t\tStream_Read_UINT16(s, MsPipe->MaximumPacketSize);\n\t\tStream_Seek(s, 2);\n\t\tStream_Read_UINT32(s, MsPipe->MaximumTransferSize);\n\t\tStream_Read_UINT32(s, MsPipe->PipeFlags);\n\t\t/* Already set to zero by memset\n\t\t MsPipe->PipeHandle\t = 0;\n\t\t MsPipe->bEndpointAddress = 0;\n\t\t MsPipe->bInterval\t\t= 0;\n\t\t MsPipe->PipeType\t\t = 0;\n\t\t MsPipe->InitCompleted\t= 0;\n\t\t*/\n\t\tMsPipes[pnum] = MsPipe;\n\t}\n\n\treturn MsPipes;\nout_error:\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t\tfree(MsPipes[pnum]);\n\n\tfree(MsPipes);\n\treturn NULL;\n}", "func_hash": 98888799377605577596944277010266597262, "file_name": "msusb.c", "file_hash": 224395734470226920826507245479648221079, "cwe": ["CWE-190"], "cve": "CVE-2020-11039", "cve_desc": "In FreeRDP less than or equal to 2.0.0, when using a manipulated server with USB redirection enabled (nearly) arbitrary memory can be read and written due to integer overflows in length checks. This has been patched in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11039"} {"idx": 370198, "project": "FreeRDP", "commit_id": "9f77fc3dd2394373e1be753952b00dafa1a9b7da", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/9f77fc3dd2394373e1be753952b00dafa1a9b7da", "commit_message": "Fixed int overflow in msusb_mspipes_read\n\nThanks to hac425", "target": 0, "func": "static MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(wStream* s, UINT32 NumberOfPipes)\n{\n\tUINT32 pnum;\n\tMSUSB_PIPE_DESCRIPTOR** MsPipes;\n\n\tif (Stream_GetRemainingCapacity(s) / 12 < NumberOfPipes)\n\t\treturn NULL;\n\n\tMsPipes = (MSUSB_PIPE_DESCRIPTOR**)calloc(NumberOfPipes, sizeof(MSUSB_PIPE_DESCRIPTOR*));\n\n\tif (!MsPipes)\n\t\treturn NULL;\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t{\n\t\tMSUSB_PIPE_DESCRIPTOR* MsPipe = msusb_mspipe_new();\n\n\t\tif (!MsPipe)\n\t\t\tgoto out_error;\n\n\t\tStream_Read_UINT16(s, MsPipe->MaximumPacketSize);\n\t\tStream_Seek(s, 2);\n\t\tStream_Read_UINT32(s, MsPipe->MaximumTransferSize);\n\t\tStream_Read_UINT32(s, MsPipe->PipeFlags);\n\t\t/* Already set to zero by memset\n\t\t MsPipe->PipeHandle\t = 0;\n\t\t MsPipe->bEndpointAddress = 0;\n\t\t MsPipe->bInterval\t\t= 0;\n\t\t MsPipe->PipeType\t\t = 0;\n\t\t MsPipe->InitCompleted\t= 0;\n\t\t*/\n\t\tMsPipes[pnum] = MsPipe;\n\t}\n\n\treturn MsPipes;\nout_error:\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t\tfree(MsPipes[pnum]);\n\n\tfree(MsPipes);\n\treturn NULL;\n}", "func_hash": 9070621180805921472718272530999780232, "file_name": "msusb.c", "file_hash": 52079547249991987895905419555177540724, "cwe": ["CWE-190"], "cve": "CVE-2020-11039", "cve_desc": "In FreeRDP less than or equal to 2.0.0, when using a manipulated server with USB redirection enabled (nearly) arbitrary memory can be read and written due to integer overflows in length checks. This has been patched in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11039"} {"idx": 205720, "project": "ImageMagick6", "commit_id": "a78d92dc0f468e79c3d761aae9707042952cdaca", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/a78d92dc0f468e79c3d761aae9707042952cdaca", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3176", "target": 1, "func": "static MagickBooleanType WriteAnimatedWEBPImage(const ImageInfo *image_info,\n Image *image,WebPConfig *configure,WebPMemoryWriter *writer_info,\n ExceptionInfo *exception)\n{\n Image\n *first_image;\n\n PictureMemory\n *current,\n *head;\n\n size_t\n effective_delta = 0,\n frame_timestamp = 0;\n\n WebPAnimEncoder\n *enc;\n\n WebPAnimEncoderOptions\n enc_options;\n\n WebPData\n webp_data;\n\n WebPPicture\n picture;\n\n WebPAnimEncoderOptionsInit(&enc_options);\n if (image_info->verbose)\n enc_options.verbose = 1;\n\n image=CoalesceImages(image, exception);\n first_image=image;\n enc=WebPAnimEncoderNew((int) image->page.width,(int) image->page.height,\n &enc_options);\n\n head=(PictureMemory *) calloc(sizeof(*head),1);\n current=head;\n\n while (image != NULL)\n {\n if (WebPPictureInit(&picture) == 0)\n ThrowWriterException(ResourceLimitError,\"UnableToEncodeImageFile\");\n\n WriteSingleWEBPImage(image_info, image, &picture, current, exception);\n\n effective_delta = image->delay*1000/image->ticks_per_second;\n if (effective_delta < 10)\n effective_delta = 100; /* Consistent with gif2webp */\n frame_timestamp+=effective_delta;\n\n WebPAnimEncoderAdd(enc,&picture,(int) frame_timestamp,configure);\n\n image = GetNextImageInList(image);\n current->next=(PictureMemory *) calloc(sizeof(*head), 1);\n current = current->next;\n }\n webp_data.bytes=writer_info->mem;\n webp_data.size=writer_info->size;\n WebPAnimEncoderAssemble(enc, &webp_data);\n WebPMemoryWriterClear(writer_info);\n writer_info->size=webp_data.size;\n writer_info->mem=(unsigned char *) webp_data.bytes;\n WebPAnimEncoderDelete(enc);\n DestroyImageList(first_image);\n FreePictureMemoryList(head);\n return(MagickTrue);\n}", "func_hash": 96175270459541778664600438251458949084, "file_name": "webp.c", "file_hash": 24011465655789944144141270946969847874, "cwe": ["CWE-369"], "cve": "CVE-2021-20245", "cve_desc": "A flaw was found in ImageMagick in coders/webp.c. An attacker who submits a crafted file that is processed by ImageMagick could trigger undefined behavior in the form of math division by zero. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20245"} {"idx": 370809, "project": "ImageMagick6", "commit_id": "a78d92dc0f468e79c3d761aae9707042952cdaca", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/a78d92dc0f468e79c3d761aae9707042952cdaca", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3176", "target": 0, "func": "static MagickBooleanType WriteAnimatedWEBPImage(const ImageInfo *image_info,\n Image *image,WebPConfig *configure,WebPMemoryWriter *writer_info,\n ExceptionInfo *exception)\n{\n Image\n *first_image;\n\n PictureMemory\n *current,\n *head;\n\n size_t\n effective_delta = 0,\n frame_timestamp = 0;\n\n WebPAnimEncoder\n *enc;\n\n WebPAnimEncoderOptions\n enc_options;\n\n WebPData\n webp_data;\n\n WebPPicture\n picture;\n\n WebPAnimEncoderOptionsInit(&enc_options);\n if (image_info->verbose)\n enc_options.verbose = 1;\n\n image=CoalesceImages(image, exception);\n first_image=image;\n enc=WebPAnimEncoderNew((int) image->page.width,(int) image->page.height,\n &enc_options);\n\n head=(PictureMemory *) calloc(sizeof(*head),1);\n current=head;\n\n while (image != NULL)\n {\n if (WebPPictureInit(&picture) == 0)\n ThrowWriterException(ResourceLimitError,\"UnableToEncodeImageFile\");\n\n WriteSingleWEBPImage(image_info, image, &picture, current, exception);\n\n effective_delta = image->delay*1000*PerceptibleReciprocal(\n image->ticks_per_second);\n if (effective_delta < 10)\n effective_delta = 100; /* Consistent with gif2webp */\n frame_timestamp+=effective_delta;\n\n WebPAnimEncoderAdd(enc,&picture,(int) frame_timestamp,configure);\n\n image = GetNextImageInList(image);\n current->next=(PictureMemory *) calloc(sizeof(*head), 1);\n current = current->next;\n }\n webp_data.bytes=writer_info->mem;\n webp_data.size=writer_info->size;\n WebPAnimEncoderAssemble(enc, &webp_data);\n WebPMemoryWriterClear(writer_info);\n writer_info->size=webp_data.size;\n writer_info->mem=(unsigned char *) webp_data.bytes;\n WebPAnimEncoderDelete(enc);\n DestroyImageList(first_image);\n FreePictureMemoryList(head);\n return(MagickTrue);\n}", "func_hash": 211593539437795267904059739538757509389, "file_name": "webp.c", "file_hash": 282300267507555386778391208190746218277, "cwe": ["CWE-369"], "cve": "CVE-2021-20245", "cve_desc": "A flaw was found in ImageMagick in coders/webp.c. An attacker who submits a crafted file that is processed by ImageMagick could trigger undefined behavior in the form of math division by zero. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20245"} {"idx": 205775, "project": "ImageMagick6", "commit_id": "90255f0834eead08d59f46b0bda7b1580451cc0f", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/90255f0834eead08d59f46b0bda7b1580451cc0f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3077", "target": 1, "func": "MagickExport double GenerateDifferentialNoise(RandomInfo *random_info,\n const Quantum pixel,const NoiseType noise_type,const MagickRealType attenuate)\n{\n#define SigmaUniform (attenuate*0.015625)\n#define SigmaGaussian (attenuate*0.015625)\n#define SigmaImpulse (attenuate*0.1)\n#define SigmaLaplacian (attenuate*0.0390625)\n#define SigmaMultiplicativeGaussian (attenuate*0.5)\n#define SigmaPoisson (attenuate*12.5)\n#define SigmaRandom (attenuate)\n#define TauGaussian (attenuate*0.078125)\n\n double\n alpha,\n beta,\n noise,\n sigma;\n\n alpha=GetPseudoRandomValue(random_info);\n switch (noise_type)\n {\n case UniformNoise:\n default:\n {\n noise=(double) (pixel+QuantumRange*SigmaUniform*(alpha-0.5));\n break;\n }\n case GaussianNoise:\n {\n double\n gamma,\n tau;\n\n if (fabs(alpha) < MagickEpsilon)\n alpha=1.0;\n beta=GetPseudoRandomValue(random_info);\n gamma=sqrt(-2.0*log(alpha));\n sigma=gamma*cos((double) (2.0*MagickPI*beta));\n tau=gamma*sin((double) (2.0*MagickPI*beta));\n noise=(double) (pixel+sqrt((double) pixel)*SigmaGaussian*sigma+\n QuantumRange*TauGaussian*tau);\n break;\n }\n case ImpulseNoise:\n {\n if (alpha < (SigmaImpulse/2.0))\n noise=0.0;\n else\n if (alpha >= (1.0-(SigmaImpulse/2.0)))\n noise=(double) QuantumRange;\n else\n noise=(double) pixel;\n break;\n }\n case LaplacianNoise:\n {\n if (alpha <= 0.5)\n {\n if (alpha <= MagickEpsilon)\n noise=(double) (pixel-QuantumRange);\n else\n noise=(double) (pixel+QuantumRange*SigmaLaplacian*log(2.0*alpha)+\n 0.5);\n break;\n }\n beta=1.0-alpha;\n if (beta <= (0.5*MagickEpsilon))\n noise=(double) (pixel+QuantumRange);\n else\n noise=(double) (pixel-QuantumRange*SigmaLaplacian*log(2.0*beta)+0.5);\n break;\n }\n case MultiplicativeGaussianNoise:\n {\n sigma=1.0;\n if (alpha > MagickEpsilon)\n sigma=sqrt(-2.0*log(alpha));\n beta=GetPseudoRandomValue(random_info);\n noise=(double) (pixel+pixel*SigmaMultiplicativeGaussian*sigma*\n cos((double) (2.0*MagickPI*beta))/2.0);\n break;\n }\n case PoissonNoise:\n {\n double\n poisson;\n\n ssize_t\n i;\n\n poisson=exp(-SigmaPoisson*QuantumScale*pixel);\n for (i=0; alpha > poisson; i++)\n {\n beta=GetPseudoRandomValue(random_info);\n alpha*=beta;\n }\n noise=(double) (QuantumRange*i/SigmaPoisson);\n break;\n }\n case RandomNoise:\n {\n noise=(double) (QuantumRange*SigmaRandom*alpha);\n break;\n }\n }\n return(noise);\n}", "func_hash": 110619127838388056663594760123112207341, "file_name": "gem.c", "file_hash": 114804121573481416344559518219795972373, "cwe": ["CWE-369"], "cve": "CVE-2021-20176", "cve_desc": "A divide-by-zero flaw was found in ImageMagick 6.9.11-57 and 7.0.10-57 in gem.c. This flaw allows an attacker who submits a crafted file that is processed by ImageMagick to trigger undefined behavior through a division by zero. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20176"} {"idx": 371767, "project": "ImageMagick6", "commit_id": "90255f0834eead08d59f46b0bda7b1580451cc0f", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/90255f0834eead08d59f46b0bda7b1580451cc0f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3077", "target": 0, "func": "MagickExport double GenerateDifferentialNoise(RandomInfo *random_info,\n const Quantum pixel,const NoiseType noise_type,const MagickRealType attenuate)\n{\n#define SigmaUniform (attenuate*0.015625)\n#define SigmaGaussian (attenuate*0.015625)\n#define SigmaImpulse (attenuate*0.1)\n#define SigmaLaplacian (attenuate*0.0390625)\n#define SigmaMultiplicativeGaussian (attenuate*0.5)\n#define SigmaPoisson (attenuate*12.5)\n#define SigmaRandom (attenuate)\n#define TauGaussian (attenuate*0.078125)\n\n double\n alpha,\n beta,\n noise,\n sigma;\n\n alpha=GetPseudoRandomValue(random_info);\n switch (noise_type)\n {\n case UniformNoise:\n default:\n {\n noise=(double) (pixel+QuantumRange*SigmaUniform*(alpha-0.5));\n break;\n }\n case GaussianNoise:\n {\n double\n gamma,\n tau;\n\n if (fabs(alpha) < MagickEpsilon)\n alpha=1.0;\n beta=GetPseudoRandomValue(random_info);\n gamma=sqrt(-2.0*log(alpha));\n sigma=gamma*cos((double) (2.0*MagickPI*beta));\n tau=gamma*sin((double) (2.0*MagickPI*beta));\n noise=(double) (pixel+sqrt((double) pixel)*SigmaGaussian*sigma+\n QuantumRange*TauGaussian*tau);\n break;\n }\n case ImpulseNoise:\n {\n if (alpha < (SigmaImpulse/2.0))\n noise=0.0;\n else\n if (alpha >= (1.0-(SigmaImpulse/2.0)))\n noise=(double) QuantumRange;\n else\n noise=(double) pixel;\n break;\n }\n case LaplacianNoise:\n {\n if (alpha <= 0.5)\n {\n if (alpha <= MagickEpsilon)\n noise=(double) (pixel-QuantumRange);\n else\n noise=(double) (pixel+QuantumRange*SigmaLaplacian*log(2.0*alpha)+\n 0.5);\n break;\n }\n beta=1.0-alpha;\n if (beta <= (0.5*MagickEpsilon))\n noise=(double) (pixel+QuantumRange);\n else\n noise=(double) (pixel-QuantumRange*SigmaLaplacian*log(2.0*beta)+0.5);\n break;\n }\n case MultiplicativeGaussianNoise:\n {\n sigma=1.0;\n if (alpha > MagickEpsilon)\n sigma=sqrt(-2.0*log(alpha));\n beta=GetPseudoRandomValue(random_info);\n noise=(double) (pixel+pixel*SigmaMultiplicativeGaussian*sigma*\n cos((double) (2.0*MagickPI*beta))/2.0);\n break;\n }\n case PoissonNoise:\n {\n double\n poisson;\n\n ssize_t\n i;\n\n poisson=exp(-SigmaPoisson*QuantumScale*pixel);\n for (i=0; alpha > poisson; i++)\n {\n beta=GetPseudoRandomValue(random_info);\n alpha*=beta;\n }\n noise=(double) (QuantumRange*i*PerceptibleReciprocal(SigmaPoisson));\n break;\n }\n case RandomNoise:\n {\n noise=(double) (QuantumRange*SigmaRandom*alpha);\n break;\n }\n }\n return(noise);\n}", "func_hash": 280490167859307313583880880744196707953, "file_name": "gem.c", "file_hash": 307990137075722629173304756747671665335, "cwe": ["CWE-369"], "cve": "CVE-2021-20176", "cve_desc": "A divide-by-zero flaw was found in ImageMagick 6.9.11-57 and 7.0.10-57 in gem.c. This flaw allows an attacker who submits a crafted file that is processed by ImageMagick to trigger undefined behavior through a division by zero. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20176"} {"idx": 205810, "project": "postsrsd", "commit_id": "4733fb11f6bec6524bb8518c5e1a699288c26bac", "project_url": "https://github.com/roehling/postsrsd", "commit_url": "https://github.com/roehling/postsrsd/commit/4733fb11f6bec6524bb8518c5e1a699288c26bac", "commit_message": "SECURITY: Fix potential denial of service attack against PostSRSd\n\nI discovered that PostSRSd could be tricked into consuming a lot of CPU\ntime with an SRS address that has an excessively long time stamp tag,\ne.g.\n\nSRS0=HHHH=TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT=0@example.com", "target": 1, "func": "srs_timestamp_check(srs_t *srs, const char *stamp)\n{\n\tconst char\t*sp;\n\tchar\t\t*bp;\n\tint\t\t\t off;\n\ttime_t\t\t now;\n\ttime_t\t\t then;\n\n\t/* We had better go around this loop exactly twice! */\n\tthen = 0;\n\tfor (sp = stamp; *sp; sp++) {\n\t\tbp = strchr(SRS_TIME_BASECHARS, toupper(*sp));\n\t\tif (bp == NULL)\n\t\t\treturn SRS_EBADTIMESTAMPCHAR;\n\t\toff = bp - SRS_TIME_BASECHARS;\n\t\tthen = (then << SRS_TIME_BASEBITS) | off;\n\t}\n\n\ttime(&now);\n\tnow = (now / SRS_TIME_PRECISION) % SRS_TIME_SLOTS;\n\twhile (now < then)\n\t\tnow = now + SRS_TIME_SLOTS;\n\n\tif (now <= then + srs->maxage)\n\t\treturn SRS_SUCCESS;\n\treturn SRS_ETIMESTAMPOUTOFDATE;\n}", "func_hash": 141123991625202689873010895577354854467, "file_name": "srs2.c", "file_hash": 102771571538150464742673514729576036265, "cwe": ["CWE-703"], "cve": "CVE-2020-35573", "cve_desc": "srs2.c in PostSRSd before 1.10 allows remote attackers to cause a denial of service (CPU consumption) via a long timestamp tag in an SRS address.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35573"} {"idx": 372380, "project": "postsrsd", "commit_id": "4733fb11f6bec6524bb8518c5e1a699288c26bac", "project_url": "https://github.com/roehling/postsrsd", "commit_url": "https://github.com/roehling/postsrsd/commit/4733fb11f6bec6524bb8518c5e1a699288c26bac", "commit_message": "SECURITY: Fix potential denial of service attack against PostSRSd\n\nI discovered that PostSRSd could be tricked into consuming a lot of CPU\ntime with an SRS address that has an excessively long time stamp tag,\ne.g.\n\nSRS0=HHHH=TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT=0@example.com", "target": 0, "func": "srs_timestamp_check(srs_t *srs, const char *stamp)\n{\n\tconst char\t*sp;\n\tchar\t\t*bp;\n\tint\t\t\t off;\n\ttime_t\t\t now;\n\ttime_t\t\t then;\n\n\tif (strlen(stamp) != 2) return SRS_ETIMESTAMPOUTOFDATE;\n\t/* We had better go around this loop exactly twice! */\n\tthen = 0;\n\tfor (sp = stamp; *sp; sp++) {\n\t\tbp = strchr(SRS_TIME_BASECHARS, toupper(*sp));\n\t\tif (bp == NULL)\n\t\t\treturn SRS_EBADTIMESTAMPCHAR;\n\t\toff = bp - SRS_TIME_BASECHARS;\n\t\tthen = (then << SRS_TIME_BASEBITS) | off;\n\t}\n\n\ttime(&now);\n\tnow = (now / SRS_TIME_PRECISION) % SRS_TIME_SLOTS;\n\twhile (now < then)\n\t\tnow = now + SRS_TIME_SLOTS;\n\n\tif (now <= then + srs->maxage)\n\t\treturn SRS_SUCCESS;\n\treturn SRS_ETIMESTAMPOUTOFDATE;\n}", "func_hash": 150195214544822376288950533959672389266, "file_name": "srs2.c", "file_hash": 103602974081823594828318008326836235414, "cwe": ["CWE-703"], "cve": "CVE-2020-35573", "cve_desc": "srs2.c in PostSRSd before 1.10 allows remote attackers to cause a denial of service (CPU consumption) via a long timestamp tag in an SRS address.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35573"} {"idx": 205840, "project": "rsyslog", "commit_id": "dfa88369d4ca4290db56b843f9eabdae1bfe0fd5", "project_url": "https://github.com/rsyslog/rsyslog", "commit_url": "http://git.adiscon.com/?p=rsyslog.git;a=commitdiff;h=dfa88369d4ca4290db56b843f9eabdae1bfe0fd5", "commit_message": "bugfix: memory leak when $RepeatedMsgReduction on was used\n\nbug tracker: http://bugzilla.adiscon.com/show_bug.cgi?id=225", "target": 1, "func": "static rsRetVal qAddDirect(qqueue_t *pThis, void* pUsr)\n{\n\tbatch_t singleBatch;\n\tbatch_obj_t batchObj;\n\tDEFiRet;\n\n\t//TODO: init batchObj (states _OK and new fields -- CHECK)\n\tASSERT(pThis != NULL);\n\n\t/* calling the consumer is quite different here than it is from a worker thread */\n\t/* we need to provide the consumer's return value back to the caller because in direct\n\t * mode the consumer probably has a lot to convey (which get's lost in the other modes\n\t * because they are asynchronous. But direct mode is deliberately synchronous.\n\t * rgerhards, 2008-02-12\n\t * We use our knowledge about the batch_t structure below, but without that, we\n\t * pay a too-large performance toll... -- rgerhards, 2009-04-22\n\t */\n\tmemset(&batchObj, 0, sizeof(batch_obj_t));\n\tmemset(&singleBatch, 0, sizeof(batch_t));\n\tbatchObj.state = BATCH_STATE_RDY;\n\tbatchObj.pUsrp = (obj_t*) pUsr;\n\tbatchObj.bFilterOK = 1;\n\tsingleBatch.nElem = 1; /* there always is only one in direct mode */\n\tsingleBatch.pElem = &batchObj;\n\tiRet = pThis->pConsumer(pThis->pUsr, &singleBatch, &pThis->bShutdownImmediate);\n\tobjDestruct(pUsr);\n\n\tRETiRet;\n}", "func_hash": 319001912029649501844387825752512841281, "file_name": "queue.c", "file_hash": 285244138805741677322721124935556040227, "cwe": ["CWE-772"], "cve": "CVE-2011-1488", "cve_desc": "A memory leak in rsyslog before 5.7.6 was found in the way deamon processed log messages are logged when $RepeatedMsgReduction was enabled. A local attacker could use this flaw to cause a denial of the rsyslogd daemon service by crashing the service via a sequence of repeated log messages sent within short periods of time.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2011-1488"} {"idx": 373783, "project": "rsyslog", "commit_id": "dfa88369d4ca4290db56b843f9eabdae1bfe0fd5", "project_url": "https://github.com/rsyslog/rsyslog", "commit_url": "http://git.adiscon.com/?p=rsyslog.git;a=commitdiff;h=dfa88369d4ca4290db56b843f9eabdae1bfe0fd5", "commit_message": "bugfix: memory leak when $RepeatedMsgReduction on was used\n\nbug tracker: http://bugzilla.adiscon.com/show_bug.cgi?id=225", "target": 0, "func": "static rsRetVal qAddDirect(qqueue_t *pThis, void* pUsr)\n{\n\tbatch_t singleBatch;\n\tbatch_obj_t batchObj;\n\tint i;\n\tDEFiRet;\n\n\t//TODO: init batchObj (states _OK and new fields -- CHECK)\n\tASSERT(pThis != NULL);\n\n\t/* calling the consumer is quite different here than it is from a worker thread */\n\t/* we need to provide the consumer's return value back to the caller because in direct\n\t * mode the consumer probably has a lot to convey (which get's lost in the other modes\n\t * because they are asynchronous. But direct mode is deliberately synchronous.\n\t * rgerhards, 2008-02-12\n\t * We use our knowledge about the batch_t structure below, but without that, we\n\t * pay a too-large performance toll... -- rgerhards, 2009-04-22\n\t */\n\tmemset(&batchObj, 0, sizeof(batch_obj_t));\n\tmemset(&singleBatch, 0, sizeof(batch_t));\n\tbatchObj.state = BATCH_STATE_RDY;\n\tbatchObj.pUsrp = (obj_t*) pUsr;\n\tbatchObj.bFilterOK = 1;\n\tsingleBatch.nElem = 1; /* there always is only one in direct mode */\n\tsingleBatch.pElem = &batchObj;\n\tiRet = pThis->pConsumer(pThis->pUsr, &singleBatch, &pThis->bShutdownImmediate);\n\t/* delete the batch string params: TODO: create its own \"class\" for this */\n\tfor(i = 0 ; i < CONF_OMOD_NUMSTRINGS_MAXSIZE ; ++i) {\n\t\tfree(batchObj.staticActStrings[i]);\n\t}\n\tobjDestruct(pUsr);\n\n\tRETiRet;\n}", "func_hash": 222759287895083736150240394595265023355, "file_name": "queue.c", "file_hash": 218612380526620452588573435779641225337, "cwe": ["CWE-772"], "cve": "CVE-2011-1488", "cve_desc": "A memory leak in rsyslog before 5.7.6 was found in the way deamon processed log messages are logged when $RepeatedMsgReduction was enabled. A local attacker could use this flaw to cause a denial of the rsyslogd daemon service by crashing the service via a sequence of repeated log messages sent within short periods of time.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2011-1488"} {"idx": 205872, "project": "bdwgc", "commit_id": "4e1a6f9d8f2a49403bbd00b8c8e5324048fb84d4", "project_url": "https://github.com/ivmai/bdwgc", "commit_url": "https://github.com/ivmai/bdwgc/commit/4e1a6f9d8f2a49403bbd00b8c8e5324048fb84d4", "commit_message": "Fix calloc_explicitly_typed in case of lb*n overflow\n\n* typd_mlc.c: Include limits.h (for SIZE_MAX).\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): New macro (same as in\nmalloc.c).\n* typd_mlc.c (GC_calloc_explicitly_typed): Return NULL if lb * n\noverflows (same algorithm as in calloc defined in malloc.c); eliminate\nlb *= n code duplication.", "target": 1, "func": "GC_API GC_ATTR_MALLOC void * GC_CALL GC_calloc_explicitly_typed(size_t n,\n size_t lb, GC_descr d)\n{\n word *op;\n size_t lg;\n GC_descr simple_descr;\n complex_descriptor *complex_descr;\n int descr_type;\n struct LeafDescriptor leaf;\n\n GC_ASSERT(GC_explicit_typing_initialized);\n descr_type = GC_make_array_descriptor((word)n, (word)lb, d, &simple_descr,\n &complex_descr, &leaf);\n switch(descr_type) {\n case NO_MEM: return(0);\n case SIMPLE: return(GC_malloc_explicitly_typed(n*lb, simple_descr));\n case LEAF:\n lb *= n;\n lb += sizeof(struct LeafDescriptor) + TYPD_EXTRA_BYTES;\n break;\n case COMPLEX:\n lb *= n;\n lb += TYPD_EXTRA_BYTES;\n break;\n }\n op = GC_malloc_kind(lb, GC_array_kind);\n if (EXPECT(NULL == op, FALSE))\n return NULL;\n lg = SMALL_OBJ(lb) ? GC_size_map[lb] : BYTES_TO_GRANULES(GC_size(op));\n if (descr_type == LEAF) {\n /* Set up the descriptor inside the object itself. */\n volatile struct LeafDescriptor * lp =\n (struct LeafDescriptor *)\n (op + GRANULES_TO_WORDS(lg)\n - (BYTES_TO_WORDS(sizeof(struct LeafDescriptor)) + 1));\n\n lp -> ld_tag = LEAF_TAG;\n lp -> ld_size = leaf.ld_size;\n lp -> ld_nelements = leaf.ld_nelements;\n lp -> ld_descriptor = leaf.ld_descriptor;\n ((volatile word *)op)[GRANULES_TO_WORDS(lg) - 1] = (word)lp;\n } else {\n# ifndef GC_NO_FINALIZATION\n size_t lw = GRANULES_TO_WORDS(lg);\n\n op[lw - 1] = (word)complex_descr;\n /* Make sure the descriptor is cleared once there is any danger */\n /* it may have been collected. */\n if (EXPECT(GC_general_register_disappearing_link(\n (void **)(op + lw - 1), op)\n == GC_NO_MEMORY, FALSE))\n# endif\n {\n /* Couldn't register it due to lack of memory. Punt. */\n /* This will probably fail too, but gives the recovery code */\n /* a chance. */\n return GC_malloc(lb);\n }\n }\n return op;\n}", "func_hash": 132292755287902362442364209019022483203, "file_name": "typd_mlc.c", "file_hash": 179453497358114262004936352002106349799, "cwe": ["CWE-119"], "cve": "CVE-2016-9427", "cve_desc": "Integer overflow vulnerability in bdwgc before 2016-09-27 allows attackers to cause client of bdwgc denial of service (heap buffer overflow crash) and possibly execute arbitrary code via huge allocation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-9427"} {"idx": 374064, "project": "bdwgc", "commit_id": "4e1a6f9d8f2a49403bbd00b8c8e5324048fb84d4", "project_url": "https://github.com/ivmai/bdwgc", "commit_url": "https://github.com/ivmai/bdwgc/commit/4e1a6f9d8f2a49403bbd00b8c8e5324048fb84d4", "commit_message": "Fix calloc_explicitly_typed in case of lb*n overflow\n\n* typd_mlc.c: Include limits.h (for SIZE_MAX).\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): New macro (same as in\nmalloc.c).\n* typd_mlc.c (GC_calloc_explicitly_typed): Return NULL if lb * n\noverflows (same algorithm as in calloc defined in malloc.c); eliminate\nlb *= n code duplication.", "target": 0, "func": "GC_API GC_ATTR_MALLOC void * GC_CALL GC_calloc_explicitly_typed(size_t n,\n size_t lb, GC_descr d)\n{\n word *op;\n size_t lg;\n GC_descr simple_descr;\n complex_descriptor *complex_descr;\n int descr_type;\n struct LeafDescriptor leaf;\n\n GC_ASSERT(GC_explicit_typing_initialized);\n descr_type = GC_make_array_descriptor((word)n, (word)lb, d, &simple_descr,\n &complex_descr, &leaf);\n if ((lb | n) > GC_SQRT_SIZE_MAX /* fast initial check */\n && lb > 0 && n > GC_SIZE_MAX / lb)\n return NULL; /* n*lb overflow */\n lb *= n;\n switch(descr_type) {\n case NO_MEM: return(0);\n case SIMPLE:\n return GC_malloc_explicitly_typed(lb, simple_descr);\n case LEAF:\n lb += sizeof(struct LeafDescriptor) + TYPD_EXTRA_BYTES;\n break;\n case COMPLEX:\n lb += TYPD_EXTRA_BYTES;\n break;\n }\n op = GC_malloc_kind(lb, GC_array_kind);\n if (EXPECT(NULL == op, FALSE))\n return NULL;\n lg = SMALL_OBJ(lb) ? GC_size_map[lb] : BYTES_TO_GRANULES(GC_size(op));\n if (descr_type == LEAF) {\n /* Set up the descriptor inside the object itself. */\n volatile struct LeafDescriptor * lp =\n (struct LeafDescriptor *)\n (op + GRANULES_TO_WORDS(lg)\n - (BYTES_TO_WORDS(sizeof(struct LeafDescriptor)) + 1));\n\n lp -> ld_tag = LEAF_TAG;\n lp -> ld_size = leaf.ld_size;\n lp -> ld_nelements = leaf.ld_nelements;\n lp -> ld_descriptor = leaf.ld_descriptor;\n ((volatile word *)op)[GRANULES_TO_WORDS(lg) - 1] = (word)lp;\n } else {\n# ifndef GC_NO_FINALIZATION\n size_t lw = GRANULES_TO_WORDS(lg);\n\n op[lw - 1] = (word)complex_descr;\n /* Make sure the descriptor is cleared once there is any danger */\n /* it may have been collected. */\n if (EXPECT(GC_general_register_disappearing_link(\n (void **)(op + lw - 1), op)\n == GC_NO_MEMORY, FALSE))\n# endif\n {\n /* Couldn't register it due to lack of memory. Punt. */\n /* This will probably fail too, but gives the recovery code */\n /* a chance. */\n return GC_malloc(lb);\n }\n }\n return op;\n}", "func_hash": 155100772399330511892450162300460786645, "file_name": "typd_mlc.c", "file_hash": 290516614470840034377593236377792703253, "cwe": ["CWE-119"], "cve": "CVE-2016-9427", "cve_desc": "Integer overflow vulnerability in bdwgc before 2016-09-27 allows attackers to cause client of bdwgc denial of service (heap buffer overflow crash) and possibly execute arbitrary code via huge allocation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-9427"} {"idx": 205887, "project": "varnish-modules", "commit_id": "2c120e576ebb73bc247790184702ba58dc0afc39", "project_url": "https://github.com/varnish/varnish-modules", "commit_url": "https://github.com/varnish/varnish-modules/commit/2c120e576ebb73bc247790184702ba58dc0afc39", "commit_message": "Check VRT_StrandsWS() return value\n\nFixes: VSV00006", "target": 1, "func": "vmod_append(VRT_CTX, VCL_HEADER hdr, VCL_STRANDS s)\n{\n\tstruct http *hp;\n\tstruct strands st[1];\n\tconst char *p[s->n + 2];\n\tconst char *b;\n\n\tCHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);\n\n\t/* prefix the strand with $hdr_name + space */\n\tp[0] = hdr->what + 1;\n\tp[1] = \" \";\n\tAN(memcpy(p + 2, s->p, s->n * sizeof *s->p));\n\tst->n = s->n + 2;\n\tst->p = p;\n\n\tb = VRT_StrandsWS(ctx->ws, NULL, st);\n\n\thp = VRT_selecthttp(ctx, hdr->where);\n\thttp_SetHeader(hp, b);\n}", "func_hash": 39461599386844728909128837994972830161, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-28543", "cve_desc": "Varnish varnish-modules before 0.17.1 allows remote attackers to cause a denial of service (daemon restart) in some configurations. This does not affect organizations that only install the Varnish Cache product; however, it is common to install both Varnish Cache and varnish-modules. Specifically, an assertion failure or NULL pointer dereference can be triggered in Varnish Cache through the varnish-modules header.append() and header.copy() functions. For some Varnish Configuration Language (VCL) files, this gives remote clients an opportunity to cause a Varnish Cache restart. A restart reduces overall availability and performance due to an increased number of cache misses, and may cause higher load on backend servers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28543"} {"idx": 374508, "project": "varnish-modules", "commit_id": "2c120e576ebb73bc247790184702ba58dc0afc39", "project_url": "https://github.com/varnish/varnish-modules", "commit_url": "https://github.com/varnish/varnish-modules/commit/2c120e576ebb73bc247790184702ba58dc0afc39", "commit_message": "Check VRT_StrandsWS() return value\n\nFixes: VSV00006", "target": 0, "func": "vmod_append(VRT_CTX, VCL_HEADER hdr, VCL_STRANDS s)\n{\n\tstruct http *hp;\n\tstruct strands st[1];\n\tconst char *p[s->n + 2];\n\tconst char *b;\n\n\tCHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);\n\n\t/* prefix the strand with $hdr_name + space */\n\tp[0] = hdr->what + 1;\n\tp[1] = \" \";\n\tAN(memcpy(p + 2, s->p, s->n * sizeof *s->p));\n\tst->n = s->n + 2;\n\tst->p = p;\n\n\tb = VRT_StrandsWS(ctx->ws, NULL, st);\n\tif (b == NULL) {\n\t\tVRT_fail(ctx, \"vmod_header: workspace allocation failure\");\n\t\treturn;\n\t}\n\n\thp = VRT_selecthttp(ctx, hdr->where);\n\thttp_SetHeader(hp, b);\n}", "func_hash": 220302032201731266950465580206551909650, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-28543", "cve_desc": "Varnish varnish-modules before 0.17.1 allows remote attackers to cause a denial of service (daemon restart) in some configurations. This does not affect organizations that only install the Varnish Cache product; however, it is common to install both Varnish Cache and varnish-modules. Specifically, an assertion failure or NULL pointer dereference can be triggered in Varnish Cache through the varnish-modules header.append() and header.copy() functions. For some Varnish Configuration Language (VCL) files, this gives remote clients an opportunity to cause a Varnish Cache restart. A restart reduces overall availability and performance due to an increased number of cache misses, and may cause higher load on backend servers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28543"} {"idx": 205900, "project": "linux", "commit_id": "60b7ed54a41b550d50caf7f2418db4a7e75b5bdc", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/60b7ed54a41b550d50caf7f2418db4a7e75b5bdc", "commit_message": "powerpc/perf: Fix crash in perf_instruction_pointer() when ppmu is not set\n\nOn systems without any specific PMU driver support registered, running\nperf record causes Oops.\n\nThe relevant portion from call trace:\n\n BUG: Kernel NULL pointer dereference on read at 0x00000040\n Faulting instruction address: 0xc0021f0c\n Oops: Kernel access of bad area, sig: 11 [#1]\n BE PAGE_SIZE=4K PREEMPT CMPCPRO\n SAF3000 DIE NOTIFICATION\n CPU: 0 PID: 442 Comm: null_syscall Not tainted 5.13.0-rc6-s3k-dev-01645-g7649ee3d2957 #5164\n NIP: c0021f0c LR: c00e8ad8 CTR: c00d8a5c\n NIP perf_instruction_pointer+0x10/0x60\n LR perf_prepare_sample+0x344/0x674\n Call Trace:\n perf_prepare_sample+0x7c/0x674 (unreliable)\n perf_event_output_forward+0x3c/0x94\n __perf_event_overflow+0x74/0x14c\n perf_swevent_hrtimer+0xf8/0x170\n __hrtimer_run_queues.constprop.0+0x160/0x318\n hrtimer_interrupt+0x148/0x3b0\n timer_interrupt+0xc4/0x22c\n Decrementer_virt+0xb8/0xbc\n\nDuring perf record session, perf_instruction_pointer() is called to\ncapture the sample IP. This function in core-book3s accesses\nppmu->flags. If a platform specific PMU driver is not registered, ppmu\nis set to NULL and accessing its members results in a crash. Fix this\ncrash by checking if ppmu is set.\n\nFixes: 2ca13a4cc56c (\"powerpc/perf: Use regs->nip when SIAR is zero\")\nCc: stable@vger.kernel.org # v5.11+\nReported-by: Christophe Leroy \nSigned-off-by: Athira Rajeev \nTested-by: Christophe Leroy \nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/1623952506-1431-1-git-send-email-atrajeev@linux.vnet.ibm.com", "target": 1, "func": "unsigned long perf_instruction_pointer(struct pt_regs *regs)\n{\n\tbool use_siar = regs_use_siar(regs);\n\tunsigned long siar = mfspr(SPRN_SIAR);\n\n\tif (ppmu->flags & PPMU_P10_DD1) {\n\t\tif (siar)\n\t\t\treturn siar;\n\t\telse\n\t\t\treturn regs->nip;\n\t} else if (use_siar && siar_valid(regs))\n\t\treturn mfspr(SPRN_SIAR) + perf_ip_adjust(regs);\n\telse if (use_siar)\n\t\treturn 0;\t\t// no valid instruction pointer\n\telse\n\t\treturn regs->nip;\n}", "func_hash": 125737970621691329980443663928243210936, "file_name": "core-book3s.c", "file_hash": 35584445543435631723611317311687837654, "cwe": ["CWE-476"], "cve": "CVE-2021-38200", "cve_desc": "arch/powerpc/perf/core-book3s.c in the Linux kernel before 5.12.13, on systems with perf_event_paranoid=-1 and no specific PMU driver support registered, allows local users to cause a denial of service (perf_instruction_pointer NULL pointer dereference and OOPS) via a \"perf record\" command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38200"} {"idx": 374683, "project": "linux", "commit_id": "60b7ed54a41b550d50caf7f2418db4a7e75b5bdc", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/60b7ed54a41b550d50caf7f2418db4a7e75b5bdc", "commit_message": "powerpc/perf: Fix crash in perf_instruction_pointer() when ppmu is not set\n\nOn systems without any specific PMU driver support registered, running\nperf record causes Oops.\n\nThe relevant portion from call trace:\n\n BUG: Kernel NULL pointer dereference on read at 0x00000040\n Faulting instruction address: 0xc0021f0c\n Oops: Kernel access of bad area, sig: 11 [#1]\n BE PAGE_SIZE=4K PREEMPT CMPCPRO\n SAF3000 DIE NOTIFICATION\n CPU: 0 PID: 442 Comm: null_syscall Not tainted 5.13.0-rc6-s3k-dev-01645-g7649ee3d2957 #5164\n NIP: c0021f0c LR: c00e8ad8 CTR: c00d8a5c\n NIP perf_instruction_pointer+0x10/0x60\n LR perf_prepare_sample+0x344/0x674\n Call Trace:\n perf_prepare_sample+0x7c/0x674 (unreliable)\n perf_event_output_forward+0x3c/0x94\n __perf_event_overflow+0x74/0x14c\n perf_swevent_hrtimer+0xf8/0x170\n __hrtimer_run_queues.constprop.0+0x160/0x318\n hrtimer_interrupt+0x148/0x3b0\n timer_interrupt+0xc4/0x22c\n Decrementer_virt+0xb8/0xbc\n\nDuring perf record session, perf_instruction_pointer() is called to\ncapture the sample IP. This function in core-book3s accesses\nppmu->flags. If a platform specific PMU driver is not registered, ppmu\nis set to NULL and accessing its members results in a crash. Fix this\ncrash by checking if ppmu is set.\n\nFixes: 2ca13a4cc56c (\"powerpc/perf: Use regs->nip when SIAR is zero\")\nCc: stable@vger.kernel.org # v5.11+\nReported-by: Christophe Leroy \nSigned-off-by: Athira Rajeev \nTested-by: Christophe Leroy \nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/1623952506-1431-1-git-send-email-atrajeev@linux.vnet.ibm.com", "target": 0, "func": "unsigned long perf_instruction_pointer(struct pt_regs *regs)\n{\n\tbool use_siar = regs_use_siar(regs);\n\tunsigned long siar = mfspr(SPRN_SIAR);\n\n\tif (ppmu && (ppmu->flags & PPMU_P10_DD1)) {\n\t\tif (siar)\n\t\t\treturn siar;\n\t\telse\n\t\t\treturn regs->nip;\n\t} else if (use_siar && siar_valid(regs))\n\t\treturn mfspr(SPRN_SIAR) + perf_ip_adjust(regs);\n\telse if (use_siar)\n\t\treturn 0;\t\t// no valid instruction pointer\n\telse\n\t\treturn regs->nip;\n}", "func_hash": 264190048422488895434044632944977250855, "file_name": "core-book3s.c", "file_hash": 10648462065209883139963100898614550970, "cwe": ["CWE-476"], "cve": "CVE-2021-38200", "cve_desc": "arch/powerpc/perf/core-book3s.c in the Linux kernel before 5.12.13, on systems with perf_event_paranoid=-1 and no specific PMU driver support registered, allows local users to cause a denial of service (perf_instruction_pointer NULL pointer dereference and OOPS) via a \"perf record\" command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38200"} {"idx": 205909, "project": "php-src", "commit_id": "6559fe912661ca5ce5f0eeeb591d928451428ed0", "project_url": "https://github.com/php/php-src", "commit_url": "https://git.php.net/?p=php-src.git;a=commit;h=6559fe912661ca5ce5f0eeeb591d928451428ed0", "commit_message": "Do not decode cookie names anymore", "target": 1, "func": "SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data)\n{\n\tchar *res = NULL, *var, *val, *separator = NULL;\n\tconst char *c_var;\n\tzval array;\n\tint free_buffer = 0;\n\tchar *strtok_buf = NULL;\n\tzend_long count = 0;\n\n\tZVAL_UNDEF(&array);\n\tswitch (arg) {\n\t\tcase PARSE_POST:\n\t\tcase PARSE_GET:\n\t\tcase PARSE_COOKIE:\n\t\t\tarray_init(&array);\n\t\t\tswitch (arg) {\n\t\t\t\tcase PARSE_POST:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_POST], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_GET:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_GET], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_COOKIE:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_COOKIE], &array);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tZVAL_COPY_VALUE(&array, destArray);\n\t\t\tbreak;\n\t}\n\n\tif (arg == PARSE_POST) {\n\t\tsapi_handle_post(&array);\n\t\treturn;\n\t}\n\n\tif (arg == PARSE_GET) {\t\t/* GET data */\n\t\tc_var = SG(request_info).query_string;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_COOKIE) {\t\t/* Cookie data */\n\t\tc_var = SG(request_info).cookie_data;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_STRING) {\t\t/* String data */\n\t\tres = str;\n\t\tfree_buffer = 1;\n\t}\n\n\tif (!res) {\n\t\treturn;\n\t}\n\n\tswitch (arg) {\n\t\tcase PARSE_GET:\n\t\tcase PARSE_STRING:\n\t\t\tseparator = PG(arg_separator).input;\n\t\t\tbreak;\n\t\tcase PARSE_COOKIE:\n\t\t\tseparator = \";\\0\";\n\t\t\tbreak;\n\t}\n\n\tvar = php_strtok_r(res, separator, &strtok_buf);\n\n\twhile (var) {\n\t\tval = strchr(var, '=');\n\n\t\tif (arg == PARSE_COOKIE) {\n\t\t\t/* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */\n\t\t\twhile (isspace(*var)) {\n\t\t\t\tvar++;\n\t\t\t}\n\t\t\tif (var == val || *var == '\\0') {\n\t\t\t\tgoto next_cookie;\n\t\t\t}\n\t\t}\n\n\t\tif (++count > PG(max_input_vars)) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Input variables exceeded \" ZEND_LONG_FMT \". To increase the limit change max_input_vars in php.ini.\", PG(max_input_vars));\n\t\t\tbreak;\n\t\t}\n\n\t\tif (val) { /* have a value */\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\t*val++ = '\\0';\n\t\t\tphp_url_decode(var, strlen(var));\n\t\t\tval_len = php_url_decode(val, strlen(val));\n\t\t\tval = estrndup(val, val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t} else {\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\tphp_url_decode(var, strlen(var));\n\t\t\tval_len = 0;\n\t\t\tval = estrndup(\"\", val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t}\nnext_cookie:\n\t\tvar = php_strtok_r(NULL, separator, &strtok_buf);\n\t}\n\n\tif (free_buffer) {\n\t\tefree(res);\n\t}\n}", "func_hash": 218589916266494256142680864977223559826, "file_name": "php_variables.c", "file_hash": 160954826800682995087822056490986555335, "cwe": ["CWE-565"], "cve": "CVE-2020-7070", "cve_desc": "In PHP versions 7.2.x below 7.2.34, 7.3.x below 7.3.23 and 7.4.x below 7.4.11, when PHP is processing incoming HTTP cookie values, the cookie names are url-decoded. This may lead to cookies with prefixes like __Host confused with cookies that decode to such prefix, thus leading to an attacker being able to forge cookie which is supposed to be secure. See also CVE-2020-8184 for more information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7070"} {"idx": 374974, "project": "php-src", "commit_id": "6559fe912661ca5ce5f0eeeb591d928451428ed0", "project_url": "https://github.com/php/php-src", "commit_url": "https://git.php.net/?p=php-src.git;a=commit;h=6559fe912661ca5ce5f0eeeb591d928451428ed0", "commit_message": "Do not decode cookie names anymore", "target": 0, "func": "SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data)\n{\n\tchar *res = NULL, *var, *val, *separator = NULL;\n\tconst char *c_var;\n\tzval array;\n\tint free_buffer = 0;\n\tchar *strtok_buf = NULL;\n\tzend_long count = 0;\n\n\tZVAL_UNDEF(&array);\n\tswitch (arg) {\n\t\tcase PARSE_POST:\n\t\tcase PARSE_GET:\n\t\tcase PARSE_COOKIE:\n\t\t\tarray_init(&array);\n\t\t\tswitch (arg) {\n\t\t\t\tcase PARSE_POST:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_POST], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_GET:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_GET], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_COOKIE:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_COOKIE], &array);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tZVAL_COPY_VALUE(&array, destArray);\n\t\t\tbreak;\n\t}\n\n\tif (arg == PARSE_POST) {\n\t\tsapi_handle_post(&array);\n\t\treturn;\n\t}\n\n\tif (arg == PARSE_GET) {\t\t/* GET data */\n\t\tc_var = SG(request_info).query_string;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_COOKIE) {\t\t/* Cookie data */\n\t\tc_var = SG(request_info).cookie_data;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_STRING) {\t\t/* String data */\n\t\tres = str;\n\t\tfree_buffer = 1;\n\t}\n\n\tif (!res) {\n\t\treturn;\n\t}\n\n\tswitch (arg) {\n\t\tcase PARSE_GET:\n\t\tcase PARSE_STRING:\n\t\t\tseparator = PG(arg_separator).input;\n\t\t\tbreak;\n\t\tcase PARSE_COOKIE:\n\t\t\tseparator = \";\\0\";\n\t\t\tbreak;\n\t}\n\n\tvar = php_strtok_r(res, separator, &strtok_buf);\n\n\twhile (var) {\n\t\tval = strchr(var, '=');\n\n\t\tif (arg == PARSE_COOKIE) {\n\t\t\t/* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */\n\t\t\twhile (isspace(*var)) {\n\t\t\t\tvar++;\n\t\t\t}\n\t\t\tif (var == val || *var == '\\0') {\n\t\t\t\tgoto next_cookie;\n\t\t\t}\n\t\t}\n\n\t\tif (++count > PG(max_input_vars)) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Input variables exceeded \" ZEND_LONG_FMT \". To increase the limit change max_input_vars in php.ini.\", PG(max_input_vars));\n\t\t\tbreak;\n\t\t}\n\n\t\tif (val) { /* have a value */\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\t*val++ = '\\0';\n\t\t\tif (arg != PARSE_COOKIE) {\n\t\t\t\tphp_url_decode(var, strlen(var));\n\t\t\t}\n\t\t\tval_len = php_url_decode(val, strlen(val));\n\t\t\tval = estrndup(val, val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t} else {\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\tif (arg != PARSE_COOKIE) {\n\t\t\t\tphp_url_decode(var, strlen(var));\n\t\t\t}\n\t\t\tval_len = 0;\n\t\t\tval = estrndup(\"\", val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t}\nnext_cookie:\n\t\tvar = php_strtok_r(NULL, separator, &strtok_buf);\n\t}\n\n\tif (free_buffer) {\n\t\tefree(res);\n\t}\n}", "func_hash": 143176642944182258927266694387408357931, "file_name": "php_variables.c", "file_hash": 297970641375041686201864789141383529575, "cwe": ["CWE-565"], "cve": "CVE-2020-7070", "cve_desc": "In PHP versions 7.2.x below 7.2.34, 7.3.x below 7.3.23 and 7.4.x below 7.4.11, when PHP is processing incoming HTTP cookie values, the cookie names are url-decoded. This may lead to cookies with prefixes like __Host confused with cookies that decode to such prefix, thus leading to an attacker being able to forge cookie which is supposed to be secure. See also CVE-2020-8184 for more information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7070"} {"idx": 205956, "project": "linux", "commit_id": "d1e7fd6462ca9fc76650fbe6ca800e35b24267da", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d1e7fd6462ca9fc76650fbe6ca800e35b24267da", "commit_message": "signal: Extend exec_id to 64bits\n\nReplace the 32bit exec_id with a 64bit exec_id to make it impossible\nto wrap the exec_id counter. With care an attacker can cause exec_id\nwrap and send arbitrary signals to a newly exec'd parent. This\nbypasses the signal sending checks if the parent changes their\ncredentials during exec.\n\nThe severity of this problem can been seen that in my limited testing\nof a 32bit exec_id it can take as little as 19s to exec 65536 times.\nWhich means that it can take as little as 14 days to wrap a 32bit\nexec_id. Adam Zabrocki has succeeded wrapping the self_exe_id in 7\ndays. Even my slower timing is in the uptime of a typical server.\nWhich means self_exec_id is simply a speed bump today, and if exec\ngets noticably faster self_exec_id won't even be a speed bump.\n\nExtending self_exec_id to 64bits introduces a problem on 32bit\narchitectures where reading self_exec_id is no longer atomic and can\ntake two read instructions. Which means that is is possible to hit\na window where the read value of exec_id does not match the written\nvalue. So with very lucky timing after this change this still\nremains expoiltable.\n\nI have updated the update of exec_id on exec to use WRITE_ONCE\nand the read of exec_id in do_notify_parent to use READ_ONCE\nto make it clear that there is no locking between these two\nlocations.\n\nLink: https://lore.kernel.org/kernel-hardening/20200324215049.GA3710@pi3.com.pl\nFixes: 2.3.23pre2\nCc: stable@vger.kernel.org\nSigned-off-by: \"Eric W. Biederman\" ", "target": 1, "func": "bool do_notify_parent(struct task_struct *tsk, int sig)\n{\n\tstruct kernel_siginfo info;\n\tunsigned long flags;\n\tstruct sighand_struct *psig;\n\tbool autoreap = false;\n\tu64 utime, stime;\n\n\tBUG_ON(sig == -1);\n\n \t/* do_notify_parent_cldstop should have been called instead. */\n \tBUG_ON(task_is_stopped_or_traced(tsk));\n\n\tBUG_ON(!tsk->ptrace &&\n\t (tsk->group_leader != tsk || !thread_group_empty(tsk)));\n\n\t/* Wake up all pidfd waiters */\n\tdo_notify_pidfd(tsk);\n\n\tif (sig != SIGCHLD) {\n\t\t/*\n\t\t * This is only possible if parent == real_parent.\n\t\t * Check if it has changed security domain.\n\t\t */\n\t\tif (tsk->parent_exec_id != tsk->parent->self_exec_id)\n\t\t\tsig = SIGCHLD;\n\t}\n\n\tclear_siginfo(&info);\n\tinfo.si_signo = sig;\n\tinfo.si_errno = 0;\n\t/*\n\t * We are under tasklist_lock here so our parent is tied to\n\t * us and cannot change.\n\t *\n\t * task_active_pid_ns will always return the same pid namespace\n\t * until a task passes through release_task.\n\t *\n\t * write_lock() currently calls preempt_disable() which is the\n\t * same as rcu_read_lock(), but according to Oleg, this is not\n\t * correct to rely on this\n\t */\n\trcu_read_lock();\n\tinfo.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent));\n\tinfo.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns),\n\t\t\t\t task_uid(tsk));\n\trcu_read_unlock();\n\n\ttask_cputime(tsk, &utime, &stime);\n\tinfo.si_utime = nsec_to_clock_t(utime + tsk->signal->utime);\n\tinfo.si_stime = nsec_to_clock_t(stime + tsk->signal->stime);\n\n\tinfo.si_status = tsk->exit_code & 0x7f;\n\tif (tsk->exit_code & 0x80)\n\t\tinfo.si_code = CLD_DUMPED;\n\telse if (tsk->exit_code & 0x7f)\n\t\tinfo.si_code = CLD_KILLED;\n\telse {\n\t\tinfo.si_code = CLD_EXITED;\n\t\tinfo.si_status = tsk->exit_code >> 8;\n\t}\n\n\tpsig = tsk->parent->sighand;\n\tspin_lock_irqsave(&psig->siglock, flags);\n\tif (!tsk->ptrace && sig == SIGCHLD &&\n\t (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN ||\n\t (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) {\n\t\t/*\n\t\t * We are exiting and our parent doesn't care. POSIX.1\n\t\t * defines special semantics for setting SIGCHLD to SIG_IGN\n\t\t * or setting the SA_NOCLDWAIT flag: we should be reaped\n\t\t * automatically and not left for our parent's wait4 call.\n\t\t * Rather than having the parent do it as a magic kind of\n\t\t * signal handler, we just set this to tell do_exit that we\n\t\t * can be cleaned up without becoming a zombie. Note that\n\t\t * we still call __wake_up_parent in this case, because a\n\t\t * blocked sys_wait4 might now return -ECHILD.\n\t\t *\n\t\t * Whether we send SIGCHLD or not for SA_NOCLDWAIT\n\t\t * is implementation-defined: we do (if you don't want\n\t\t * it, just use SIG_IGN instead).\n\t\t */\n\t\tautoreap = true;\n\t\tif (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN)\n\t\t\tsig = 0;\n\t}\n\tif (valid_signal(sig) && sig)\n\t\t__group_send_sig_info(sig, &info, tsk->parent);\n\t__wake_up_parent(tsk, tsk->parent);\n\tspin_unlock_irqrestore(&psig->siglock, flags);\n\n\treturn autoreap;\n}", "func_hash": 112499058710817698926673620794800549011, "file_name": "signal.c", "file_hash": 156325553596301250420865558440601928859, "cwe": ["CWE-190"], "cve": "CVE-2020-12826", "cve_desc": "A signal access-control issue was discovered in the Linux kernel before 5.6.5, aka CID-7395ea4e65c2. Because exec_id in include/linux/sched.h is only 32 bits, an integer overflow can interfere with a do_notify_parent protection mechanism. A child process can send an arbitrary signal to a parent process in a different security domain. Exploitation limitations include the amount of elapsed time before an integer overflow occurs, and the lack of scenarios where signals to a parent process present a substantial operational threat.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12826"} {"idx": 375155, "project": "linux", "commit_id": "d1e7fd6462ca9fc76650fbe6ca800e35b24267da", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d1e7fd6462ca9fc76650fbe6ca800e35b24267da", "commit_message": "signal: Extend exec_id to 64bits\n\nReplace the 32bit exec_id with a 64bit exec_id to make it impossible\nto wrap the exec_id counter. With care an attacker can cause exec_id\nwrap and send arbitrary signals to a newly exec'd parent. This\nbypasses the signal sending checks if the parent changes their\ncredentials during exec.\n\nThe severity of this problem can been seen that in my limited testing\nof a 32bit exec_id it can take as little as 19s to exec 65536 times.\nWhich means that it can take as little as 14 days to wrap a 32bit\nexec_id. Adam Zabrocki has succeeded wrapping the self_exe_id in 7\ndays. Even my slower timing is in the uptime of a typical server.\nWhich means self_exec_id is simply a speed bump today, and if exec\ngets noticably faster self_exec_id won't even be a speed bump.\n\nExtending self_exec_id to 64bits introduces a problem on 32bit\narchitectures where reading self_exec_id is no longer atomic and can\ntake two read instructions. Which means that is is possible to hit\na window where the read value of exec_id does not match the written\nvalue. So with very lucky timing after this change this still\nremains expoiltable.\n\nI have updated the update of exec_id on exec to use WRITE_ONCE\nand the read of exec_id in do_notify_parent to use READ_ONCE\nto make it clear that there is no locking between these two\nlocations.\n\nLink: https://lore.kernel.org/kernel-hardening/20200324215049.GA3710@pi3.com.pl\nFixes: 2.3.23pre2\nCc: stable@vger.kernel.org\nSigned-off-by: \"Eric W. Biederman\" ", "target": 0, "func": "bool do_notify_parent(struct task_struct *tsk, int sig)\n{\n\tstruct kernel_siginfo info;\n\tunsigned long flags;\n\tstruct sighand_struct *psig;\n\tbool autoreap = false;\n\tu64 utime, stime;\n\n\tBUG_ON(sig == -1);\n\n \t/* do_notify_parent_cldstop should have been called instead. */\n \tBUG_ON(task_is_stopped_or_traced(tsk));\n\n\tBUG_ON(!tsk->ptrace &&\n\t (tsk->group_leader != tsk || !thread_group_empty(tsk)));\n\n\t/* Wake up all pidfd waiters */\n\tdo_notify_pidfd(tsk);\n\n\tif (sig != SIGCHLD) {\n\t\t/*\n\t\t * This is only possible if parent == real_parent.\n\t\t * Check if it has changed security domain.\n\t\t */\n\t\tif (tsk->parent_exec_id != READ_ONCE(tsk->parent->self_exec_id))\n\t\t\tsig = SIGCHLD;\n\t}\n\n\tclear_siginfo(&info);\n\tinfo.si_signo = sig;\n\tinfo.si_errno = 0;\n\t/*\n\t * We are under tasklist_lock here so our parent is tied to\n\t * us and cannot change.\n\t *\n\t * task_active_pid_ns will always return the same pid namespace\n\t * until a task passes through release_task.\n\t *\n\t * write_lock() currently calls preempt_disable() which is the\n\t * same as rcu_read_lock(), but according to Oleg, this is not\n\t * correct to rely on this\n\t */\n\trcu_read_lock();\n\tinfo.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent));\n\tinfo.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns),\n\t\t\t\t task_uid(tsk));\n\trcu_read_unlock();\n\n\ttask_cputime(tsk, &utime, &stime);\n\tinfo.si_utime = nsec_to_clock_t(utime + tsk->signal->utime);\n\tinfo.si_stime = nsec_to_clock_t(stime + tsk->signal->stime);\n\n\tinfo.si_status = tsk->exit_code & 0x7f;\n\tif (tsk->exit_code & 0x80)\n\t\tinfo.si_code = CLD_DUMPED;\n\telse if (tsk->exit_code & 0x7f)\n\t\tinfo.si_code = CLD_KILLED;\n\telse {\n\t\tinfo.si_code = CLD_EXITED;\n\t\tinfo.si_status = tsk->exit_code >> 8;\n\t}\n\n\tpsig = tsk->parent->sighand;\n\tspin_lock_irqsave(&psig->siglock, flags);\n\tif (!tsk->ptrace && sig == SIGCHLD &&\n\t (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN ||\n\t (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) {\n\t\t/*\n\t\t * We are exiting and our parent doesn't care. POSIX.1\n\t\t * defines special semantics for setting SIGCHLD to SIG_IGN\n\t\t * or setting the SA_NOCLDWAIT flag: we should be reaped\n\t\t * automatically and not left for our parent's wait4 call.\n\t\t * Rather than having the parent do it as a magic kind of\n\t\t * signal handler, we just set this to tell do_exit that we\n\t\t * can be cleaned up without becoming a zombie. Note that\n\t\t * we still call __wake_up_parent in this case, because a\n\t\t * blocked sys_wait4 might now return -ECHILD.\n\t\t *\n\t\t * Whether we send SIGCHLD or not for SA_NOCLDWAIT\n\t\t * is implementation-defined: we do (if you don't want\n\t\t * it, just use SIG_IGN instead).\n\t\t */\n\t\tautoreap = true;\n\t\tif (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN)\n\t\t\tsig = 0;\n\t}\n\tif (valid_signal(sig) && sig)\n\t\t__group_send_sig_info(sig, &info, tsk->parent);\n\t__wake_up_parent(tsk, tsk->parent);\n\tspin_unlock_irqrestore(&psig->siglock, flags);\n\n\treturn autoreap;\n}", "func_hash": 192217419013721044454921305049485290456, "file_name": "signal.c", "file_hash": 304357389878841702184016619587732431733, "cwe": ["CWE-190"], "cve": "CVE-2020-12826", "cve_desc": "A signal access-control issue was discovered in the Linux kernel before 5.6.5, aka CID-7395ea4e65c2. Because exec_id in include/linux/sched.h is only 32 bits, an integer overflow can interfere with a do_notify_parent protection mechanism. A child process can send an arbitrary signal to a parent process in a different security domain. Exploitation limitations include the amount of elapsed time before an integer overflow occurs, and the lack of scenarios where signals to a parent process present a substantial operational threat.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12826"} {"idx": 205959, "project": "libslirp", "commit_id": "126c04acbabd7ad32c2b018fe10dfac2a3bc1210", "project_url": "https://gitlab.freedesktop.org/slirp/libslirp", "commit_url": "https://gitlab.freedesktop.org/slirp/libslirp/commit/126c04acbabd7ad32c2b018fe10dfac2a3bc1210", "commit_message": "Fix heap overflow in ip_reass on big packet input\n\nWhen the first fragment does not fit in the preallocated buffer, q will\nalready be pointing to the ext buffer, so we mustn't try to update it.\n\nSigned-off-by: Samuel Thibault ", "target": 1, "func": "static struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n register struct mbuf *m = dtom(slirp, ip);\n register struct ipasfrag *q;\n int hlen = ip->ip_hl << 2;\n int i, next;\n\n DEBUG_CALL(\"ip_reass\");\n DEBUG_ARG(\"ip = %p\", ip);\n DEBUG_ARG(\"fp = %p\", fp);\n DEBUG_ARG(\"m = %p\", m);\n\n /*\n * Presence of header sizes in mbufs\n * would confuse code below.\n * Fragment m_data is concatenated.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n /*\n * If first fragment to arrive, create a reassembly queue.\n */\n if (fp == NULL) {\n struct mbuf *t = m_get(slirp);\n\n if (t == NULL) {\n goto dropfrag;\n }\n fp = mtod(t, struct ipq *);\n insque(&fp->ip_link, &slirp->ipq.ip_link);\n fp->ipq_ttl = IPFRAGTTL;\n fp->ipq_p = ip->ip_p;\n fp->ipq_id = ip->ip_id;\n fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n fp->ipq_src = ip->ip_src;\n fp->ipq_dst = ip->ip_dst;\n q = (struct ipasfrag *)fp;\n goto insert;\n }\n\n /*\n * Find a segment which begins after this one does.\n */\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n if (q->ipf_off > ip->ip_off)\n break;\n\n /*\n * If there is a preceding segment, it may provide some of\n * our data already. If so, drop the data from the incoming\n * segment. If it provides all of our data, drop us.\n */\n if (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n i = pq->ipf_off + pq->ipf_len - ip->ip_off;\n if (i > 0) {\n if (i >= ip->ip_len)\n goto dropfrag;\n m_adj(dtom(slirp, ip), i);\n ip->ip_off += i;\n ip->ip_len -= i;\n }\n }\n\n /*\n * While we overlap succeeding segments trim them or,\n * if they are completely covered, dequeue them.\n */\n while (q != (struct ipasfrag *)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n i = (ip->ip_off + ip->ip_len) - q->ipf_off;\n if (i < q->ipf_len) {\n q->ipf_len -= i;\n q->ipf_off += i;\n m_adj(dtom(slirp, q), i);\n break;\n }\n q = q->ipf_next;\n m_free(dtom(slirp, q->ipf_prev));\n ip_deq(q->ipf_prev);\n }\n\ninsert:\n /*\n * Stick new segment in its place;\n * check for complete reassembly.\n */\n ip_enq(iptofrag(ip), q->ipf_prev);\n next = 0;\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next) {\n if (q->ipf_off != next)\n return NULL;\n next += q->ipf_len;\n }\n if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n /*\n * Reassembly is complete; concatenate fragments.\n */\n q = fp->frag_link.next;\n m = dtom(slirp, q);\n\n q = (struct ipasfrag *)q->ipf_next;\n while (q != (struct ipasfrag *)&fp->frag_link) {\n struct mbuf *t = dtom(slirp, q);\n q = (struct ipasfrag *)q->ipf_next;\n m_cat(m, t);\n }\n\n /*\n * Create header for new ip packet by\n * modifying header of first packet;\n * dequeue and discard fragment reassembly header.\n * Make header visible.\n */\n q = fp->frag_link.next;\n\n /*\n * If the fragments concatenated to an mbuf that's\n * bigger than the total size of the fragment, then and\n * m_ext buffer was alloced. But fp->ipq_next points to\n * the old buffer (in the mbuf), so we must point ip\n * into the new buffer.\n */\n if (m->m_flags & M_EXT) {\n int delta = (char *)q - m->m_dat;\n q = (struct ipasfrag *)(m->m_ext + delta);\n }\n\n ip = fragtoip(q);\n ip->ip_len = next;\n ip->ip_tos &= ~1;\n ip->ip_src = fp->ipq_src;\n ip->ip_dst = fp->ipq_dst;\n remque(&fp->ip_link);\n (void)m_free(dtom(slirp, fp));\n m->m_len += (ip->ip_hl << 2);\n m->m_data -= (ip->ip_hl << 2);\n\n return ip;\n\ndropfrag:\n m_free(m);\n return NULL;\n}", "func_hash": 134094906824992214990255712017768945660, "file_name": "ip_input.c", "file_hash": 5232704323351266277829122962210206650, "cwe": ["CWE-787"], "cve": "CVE-2019-14378", "cve_desc": "ip_reass in ip_input.c in libslirp 4.0.0 has a heap-based buffer overflow via a large packet because it mishandles a case involving the first fragment.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14378"} {"idx": 375358, "project": "libslirp", "commit_id": "126c04acbabd7ad32c2b018fe10dfac2a3bc1210", "project_url": "https://gitlab.freedesktop.org/slirp/libslirp", "commit_url": "https://gitlab.freedesktop.org/slirp/libslirp/commit/126c04acbabd7ad32c2b018fe10dfac2a3bc1210", "commit_message": "Fix heap overflow in ip_reass on big packet input\n\nWhen the first fragment does not fit in the preallocated buffer, q will\nalready be pointing to the ext buffer, so we mustn't try to update it.\n\nSigned-off-by: Samuel Thibault ", "target": 0, "func": "static struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n register struct mbuf *m = dtom(slirp, ip);\n register struct ipasfrag *q;\n int hlen = ip->ip_hl << 2;\n int i, next;\n\n DEBUG_CALL(\"ip_reass\");\n DEBUG_ARG(\"ip = %p\", ip);\n DEBUG_ARG(\"fp = %p\", fp);\n DEBUG_ARG(\"m = %p\", m);\n\n /*\n * Presence of header sizes in mbufs\n * would confuse code below.\n * Fragment m_data is concatenated.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n /*\n * If first fragment to arrive, create a reassembly queue.\n */\n if (fp == NULL) {\n struct mbuf *t = m_get(slirp);\n\n if (t == NULL) {\n goto dropfrag;\n }\n fp = mtod(t, struct ipq *);\n insque(&fp->ip_link, &slirp->ipq.ip_link);\n fp->ipq_ttl = IPFRAGTTL;\n fp->ipq_p = ip->ip_p;\n fp->ipq_id = ip->ip_id;\n fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n fp->ipq_src = ip->ip_src;\n fp->ipq_dst = ip->ip_dst;\n q = (struct ipasfrag *)fp;\n goto insert;\n }\n\n /*\n * Find a segment which begins after this one does.\n */\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n if (q->ipf_off > ip->ip_off)\n break;\n\n /*\n * If there is a preceding segment, it may provide some of\n * our data already. If so, drop the data from the incoming\n * segment. If it provides all of our data, drop us.\n */\n if (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n i = pq->ipf_off + pq->ipf_len - ip->ip_off;\n if (i > 0) {\n if (i >= ip->ip_len)\n goto dropfrag;\n m_adj(dtom(slirp, ip), i);\n ip->ip_off += i;\n ip->ip_len -= i;\n }\n }\n\n /*\n * While we overlap succeeding segments trim them or,\n * if they are completely covered, dequeue them.\n */\n while (q != (struct ipasfrag *)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n i = (ip->ip_off + ip->ip_len) - q->ipf_off;\n if (i < q->ipf_len) {\n q->ipf_len -= i;\n q->ipf_off += i;\n m_adj(dtom(slirp, q), i);\n break;\n }\n q = q->ipf_next;\n m_free(dtom(slirp, q->ipf_prev));\n ip_deq(q->ipf_prev);\n }\n\ninsert:\n /*\n * Stick new segment in its place;\n * check for complete reassembly.\n */\n ip_enq(iptofrag(ip), q->ipf_prev);\n next = 0;\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next) {\n if (q->ipf_off != next)\n return NULL;\n next += q->ipf_len;\n }\n if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n /*\n * Reassembly is complete; concatenate fragments.\n */\n q = fp->frag_link.next;\n m = dtom(slirp, q);\n\n int was_ext = m->m_flags & M_EXT;\n\n q = (struct ipasfrag *)q->ipf_next;\n while (q != (struct ipasfrag *)&fp->frag_link) {\n struct mbuf *t = dtom(slirp, q);\n q = (struct ipasfrag *)q->ipf_next;\n m_cat(m, t);\n }\n\n /*\n * Create header for new ip packet by\n * modifying header of first packet;\n * dequeue and discard fragment reassembly header.\n * Make header visible.\n */\n q = fp->frag_link.next;\n\n /*\n * If the fragments concatenated to an mbuf that's\n * bigger than the total size of the fragment, then and\n * m_ext buffer was alloced. But fp->ipq_next points to\n * the old buffer (in the mbuf), so we must point ip\n * into the new buffer.\n */\n if (!was_ext && m->m_flags & M_EXT) {\n int delta = (char *)q - m->m_dat;\n q = (struct ipasfrag *)(m->m_ext + delta);\n }\n\n ip = fragtoip(q);\n ip->ip_len = next;\n ip->ip_tos &= ~1;\n ip->ip_src = fp->ipq_src;\n ip->ip_dst = fp->ipq_dst;\n remque(&fp->ip_link);\n (void)m_free(dtom(slirp, fp));\n m->m_len += (ip->ip_hl << 2);\n m->m_data -= (ip->ip_hl << 2);\n\n return ip;\n\ndropfrag:\n m_free(m);\n return NULL;\n}", "func_hash": 188033006410302823547137390896964227068, "file_name": "ip_input.c", "file_hash": 45327983918101270246019411052296851546, "cwe": ["CWE-787"], "cve": "CVE-2019-14378", "cve_desc": "ip_reass in ip_input.c in libslirp 4.0.0 has a heap-based buffer overflow via a large packet because it mishandles a case involving the first fragment.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14378"} {"idx": 206023, "project": "git", "commit_id": "f82a97eb9197c1e3768e72648f37ce0ca3233734", "project_url": "https://github.com/git/git", "commit_url": "https://git.kernel.org/pub/scm/git/git.git/commit/?id=f82a97eb9197c1e3768e72648f37ce0ca3233734)", "commit_message": "mingw: handle `subst`-ed \"DOS drives\"\n\nOver a decade ago, in 25fe217b86c (Windows: Treat Windows style path\nnames., 2008-03-05), Git was taught to handle absolute Windows paths,\ni.e. paths that start with a drive letter and a colon.\n\nUnbeknownst to us, while drive letters of physical drives are limited to\nletters of the English alphabet, there is a way to assign virtual drive\nletters to arbitrary directories, via the `subst` command, which is\n_not_ limited to English letters.\n\nIt is therefore possible to have absolute Windows paths of the form\n`1:\\what\\the\\hex.txt`. Even \"better\": pretty much arbitrary Unicode\nletters can also be used, e.g. `\u00e4:\\tschib\u00e4t.sch`.\n\nWhile it can be sensibly argued that users who set up such funny drive\nletters really seek adverse consequences, the Windows Operating System\nis known to be a platform where many users are at the mercy of\nadministrators who have their very own idea of what constitutes a\nreasonable setup.\n\nTherefore, let's just make sure that such funny paths are still\nconsidered absolute paths by Git, on Windows.\n\nIn addition to Unicode characters, pretty much any character is a valid\ndrive letter, as far as `subst` is concerned, even `:` and `\"` or even a\nspace character. While it is probably the opposite of smart to use them,\nlet's safeguard `is_dos_drive_prefix()` against all of them.\n\nNote: `[::1]:repo` is a valid URL, but not a valid path on Windows.\nAs `[` is now considered a valid drive letter, we need to be very\ncareful to avoid misinterpreting such a string as valid local path in\n`url_is_local_not_ssh()`. To do that, we use the just-introduced\nfunction `is_valid_path()` (which will label the string as invalid file\nname because of the colon characters).\n\nThis fixes CVE-2019-1351.\n\nReported-by: Nicolas Joly \nSigned-off-by: Johannes Schindelin ", "target": 1, "func": "int url_is_local_not_ssh(const char *url)\n{\n\tconst char *colon = strchr(url, ':');\n\tconst char *slash = strchr(url, '/');\n\treturn !colon || (slash && slash < colon) ||\n\t\thas_dos_drive_prefix(url);\n}", "func_hash": 213026960539630453860676208298859005761, "file_name": "connect.c", "file_hash": 165057177250435354546363030947271641588, "cwe": ["CWE-706"], "cve": "CVE-2019-1351", "cve_desc": "A tampering vulnerability exists when Git for Visual Studio improperly handles virtual drive paths, aka 'Git for Visual Studio Tampering Vulnerability'.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-1351"} {"idx": 376250, "project": "git", "commit_id": "f82a97eb9197c1e3768e72648f37ce0ca3233734", "project_url": "https://github.com/git/git", "commit_url": "https://git.kernel.org/pub/scm/git/git.git/commit/?id=f82a97eb9197c1e3768e72648f37ce0ca3233734)", "commit_message": "mingw: handle `subst`-ed \"DOS drives\"\n\nOver a decade ago, in 25fe217b86c (Windows: Treat Windows style path\nnames., 2008-03-05), Git was taught to handle absolute Windows paths,\ni.e. paths that start with a drive letter and a colon.\n\nUnbeknownst to us, while drive letters of physical drives are limited to\nletters of the English alphabet, there is a way to assign virtual drive\nletters to arbitrary directories, via the `subst` command, which is\n_not_ limited to English letters.\n\nIt is therefore possible to have absolute Windows paths of the form\n`1:\\what\\the\\hex.txt`. Even \"better\": pretty much arbitrary Unicode\nletters can also be used, e.g. `\u00e4:\\tschib\u00e4t.sch`.\n\nWhile it can be sensibly argued that users who set up such funny drive\nletters really seek adverse consequences, the Windows Operating System\nis known to be a platform where many users are at the mercy of\nadministrators who have their very own idea of what constitutes a\nreasonable setup.\n\nTherefore, let's just make sure that such funny paths are still\nconsidered absolute paths by Git, on Windows.\n\nIn addition to Unicode characters, pretty much any character is a valid\ndrive letter, as far as `subst` is concerned, even `:` and `\"` or even a\nspace character. While it is probably the opposite of smart to use them,\nlet's safeguard `is_dos_drive_prefix()` against all of them.\n\nNote: `[::1]:repo` is a valid URL, but not a valid path on Windows.\nAs `[` is now considered a valid drive letter, we need to be very\ncareful to avoid misinterpreting such a string as valid local path in\n`url_is_local_not_ssh()`. To do that, we use the just-introduced\nfunction `is_valid_path()` (which will label the string as invalid file\nname because of the colon characters).\n\nThis fixes CVE-2019-1351.\n\nReported-by: Nicolas Joly \nSigned-off-by: Johannes Schindelin ", "target": 0, "func": "int url_is_local_not_ssh(const char *url)\n{\n\tconst char *colon = strchr(url, ':');\n\tconst char *slash = strchr(url, '/');\n\treturn !colon || (slash && slash < colon) ||\n\t\t(has_dos_drive_prefix(url) && is_valid_path(url));\n}", "func_hash": 56353996920357208929726080257893824068, "file_name": "connect.c", "file_hash": 147339334321019311360035375470426726672, "cwe": ["CWE-706"], "cve": "CVE-2019-1351", "cve_desc": "A tampering vulnerability exists when Git for Visual Studio improperly handles virtual drive paths, aka 'Git for Visual Studio Tampering Vulnerability'.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-1351"} {"idx": 206039, "project": "linux", "commit_id": "a58d9166a756a0f4a6618e4f593232593d6df134", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a58d9166a756a0f4a6618e4f593232593d6df134", "commit_message": "KVM: SVM: load control fields from VMCB12 before checking them\n\nAvoid races between check and use of the nested VMCB controls. This\nfor example ensures that the VMRUN intercept is always reflected to the\nnested hypervisor, instead of being processed by the host. Without this\npatch, it is possible to end up with svm->nested.hsave pointing to\nthe MSR permission bitmap for nested guests.\n\nThis bug is CVE-2021-29657.\n\nReported-by: Felix Wilhelm \nCc: stable@vger.kernel.org\nFixes: 2fcf4876ada (\"KVM: nSVM: implement on demand allocation of the nested state\")\nSigned-off-by: Paolo Bonzini ", "target": 1, "func": "int nested_svm_vmrun(struct vcpu_svm *svm)\n{\n\tint ret;\n\tstruct vmcb *vmcb12;\n\tstruct vmcb *hsave = svm->nested.hsave;\n\tstruct vmcb *vmcb = svm->vmcb;\n\tstruct kvm_host_map map;\n\tu64 vmcb12_gpa;\n\n\tif (is_smm(&svm->vcpu)) {\n\t\tkvm_queue_exception(&svm->vcpu, UD_VECTOR);\n\t\treturn 1;\n\t}\n\n\tvmcb12_gpa = svm->vmcb->save.rax;\n\tret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb12_gpa), &map);\n\tif (ret == -EINVAL) {\n\t\tkvm_inject_gp(&svm->vcpu, 0);\n\t\treturn 1;\n\t} else if (ret) {\n\t\treturn kvm_skip_emulated_instruction(&svm->vcpu);\n\t}\n\n\tret = kvm_skip_emulated_instruction(&svm->vcpu);\n\n\tvmcb12 = map.hva;\n\n\tif (WARN_ON_ONCE(!svm->nested.initialized))\n\t\treturn -EINVAL;\n\n\tif (!nested_vmcb_checks(svm, vmcb12)) {\n\t\tvmcb12->control.exit_code = SVM_EXIT_ERR;\n\t\tvmcb12->control.exit_code_hi = 0;\n\t\tvmcb12->control.exit_info_1 = 0;\n\t\tvmcb12->control.exit_info_2 = 0;\n\t\tgoto out;\n\t}\n\n\ttrace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb12_gpa,\n\t\t\t vmcb12->save.rip,\n\t\t\t vmcb12->control.int_ctl,\n\t\t\t vmcb12->control.event_inj,\n\t\t\t vmcb12->control.nested_ctl);\n\n\ttrace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_CR] >> 16,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_EXCEPTION],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD3],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD4],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD5]);\n\n\t/* Clear internal status */\n\tkvm_clear_exception_queue(&svm->vcpu);\n\tkvm_clear_interrupt_queue(&svm->vcpu);\n\n\t/*\n\t * Save the old vmcb, so we don't need to pick what we save, but can\n\t * restore everything when a VMEXIT occurs\n\t */\n\thsave->save.es = vmcb->save.es;\n\thsave->save.cs = vmcb->save.cs;\n\thsave->save.ss = vmcb->save.ss;\n\thsave->save.ds = vmcb->save.ds;\n\thsave->save.gdtr = vmcb->save.gdtr;\n\thsave->save.idtr = vmcb->save.idtr;\n\thsave->save.efer = svm->vcpu.arch.efer;\n\thsave->save.cr0 = kvm_read_cr0(&svm->vcpu);\n\thsave->save.cr4 = svm->vcpu.arch.cr4;\n\thsave->save.rflags = kvm_get_rflags(&svm->vcpu);\n\thsave->save.rip = kvm_rip_read(&svm->vcpu);\n\thsave->save.rsp = vmcb->save.rsp;\n\thsave->save.rax = vmcb->save.rax;\n\tif (npt_enabled)\n\t\thsave->save.cr3 = vmcb->save.cr3;\n\telse\n\t\thsave->save.cr3 = kvm_read_cr3(&svm->vcpu);\n\n\tcopy_vmcb_control_area(&hsave->control, &vmcb->control);\n\n\tsvm->nested.nested_run_pending = 1;\n\n\tif (enter_svm_guest_mode(svm, vmcb12_gpa, vmcb12))\n\t\tgoto out_exit_err;\n\n\tif (nested_svm_vmrun_msrpm(svm))\n\t\tgoto out;\n\nout_exit_err:\n\tsvm->nested.nested_run_pending = 0;\n\n\tsvm->vmcb->control.exit_code = SVM_EXIT_ERR;\n\tsvm->vmcb->control.exit_code_hi = 0;\n\tsvm->vmcb->control.exit_info_1 = 0;\n\tsvm->vmcb->control.exit_info_2 = 0;\n\n\tnested_svm_vmexit(svm);\n\nout:\n\tkvm_vcpu_unmap(&svm->vcpu, &map, true);\n\n\treturn ret;\n}", "func_hash": 25639392037164644871082245207140159557, "file_name": "nested.c", "file_hash": 208554455632768339129074753872658543357, "cwe": ["CWE-416"], "cve": "CVE-2021-29657", "cve_desc": "arch/x86/kvm/svm/nested.c in the Linux kernel before 5.11.12 has a use-after-free in which an AMD KVM guest can bypass access control on host OS MSRs when there are nested guests, aka CID-a58d9166a756. This occurs because of a TOCTOU race condition associated with a VMCB12 double fetch in nested_svm_vmrun.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29657"} {"idx": 376647, "project": "linux", "commit_id": "a58d9166a756a0f4a6618e4f593232593d6df134", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a58d9166a756a0f4a6618e4f593232593d6df134", "commit_message": "KVM: SVM: load control fields from VMCB12 before checking them\n\nAvoid races between check and use of the nested VMCB controls. This\nfor example ensures that the VMRUN intercept is always reflected to the\nnested hypervisor, instead of being processed by the host. Without this\npatch, it is possible to end up with svm->nested.hsave pointing to\nthe MSR permission bitmap for nested guests.\n\nThis bug is CVE-2021-29657.\n\nReported-by: Felix Wilhelm \nCc: stable@vger.kernel.org\nFixes: 2fcf4876ada (\"KVM: nSVM: implement on demand allocation of the nested state\")\nSigned-off-by: Paolo Bonzini ", "target": 0, "func": "int nested_svm_vmrun(struct vcpu_svm *svm)\n{\n\tint ret;\n\tstruct vmcb *vmcb12;\n\tstruct vmcb *hsave = svm->nested.hsave;\n\tstruct vmcb *vmcb = svm->vmcb;\n\tstruct kvm_host_map map;\n\tu64 vmcb12_gpa;\n\n\tif (is_smm(&svm->vcpu)) {\n\t\tkvm_queue_exception(&svm->vcpu, UD_VECTOR);\n\t\treturn 1;\n\t}\n\n\tvmcb12_gpa = svm->vmcb->save.rax;\n\tret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb12_gpa), &map);\n\tif (ret == -EINVAL) {\n\t\tkvm_inject_gp(&svm->vcpu, 0);\n\t\treturn 1;\n\t} else if (ret) {\n\t\treturn kvm_skip_emulated_instruction(&svm->vcpu);\n\t}\n\n\tret = kvm_skip_emulated_instruction(&svm->vcpu);\n\n\tvmcb12 = map.hva;\n\n\tif (WARN_ON_ONCE(!svm->nested.initialized))\n\t\treturn -EINVAL;\n\n\tload_nested_vmcb_control(svm, &vmcb12->control);\n\n\tif (!nested_vmcb_check_save(svm, vmcb12) ||\n\t !nested_vmcb_check_controls(&svm->nested.ctl)) {\n\t\tvmcb12->control.exit_code = SVM_EXIT_ERR;\n\t\tvmcb12->control.exit_code_hi = 0;\n\t\tvmcb12->control.exit_info_1 = 0;\n\t\tvmcb12->control.exit_info_2 = 0;\n\t\tgoto out;\n\t}\n\n\ttrace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb12_gpa,\n\t\t\t vmcb12->save.rip,\n\t\t\t vmcb12->control.int_ctl,\n\t\t\t vmcb12->control.event_inj,\n\t\t\t vmcb12->control.nested_ctl);\n\n\ttrace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_CR] >> 16,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_EXCEPTION],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD3],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD4],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD5]);\n\n\t/* Clear internal status */\n\tkvm_clear_exception_queue(&svm->vcpu);\n\tkvm_clear_interrupt_queue(&svm->vcpu);\n\n\t/*\n\t * Save the old vmcb, so we don't need to pick what we save, but can\n\t * restore everything when a VMEXIT occurs\n\t */\n\thsave->save.es = vmcb->save.es;\n\thsave->save.cs = vmcb->save.cs;\n\thsave->save.ss = vmcb->save.ss;\n\thsave->save.ds = vmcb->save.ds;\n\thsave->save.gdtr = vmcb->save.gdtr;\n\thsave->save.idtr = vmcb->save.idtr;\n\thsave->save.efer = svm->vcpu.arch.efer;\n\thsave->save.cr0 = kvm_read_cr0(&svm->vcpu);\n\thsave->save.cr4 = svm->vcpu.arch.cr4;\n\thsave->save.rflags = kvm_get_rflags(&svm->vcpu);\n\thsave->save.rip = kvm_rip_read(&svm->vcpu);\n\thsave->save.rsp = vmcb->save.rsp;\n\thsave->save.rax = vmcb->save.rax;\n\tif (npt_enabled)\n\t\thsave->save.cr3 = vmcb->save.cr3;\n\telse\n\t\thsave->save.cr3 = kvm_read_cr3(&svm->vcpu);\n\n\tcopy_vmcb_control_area(&hsave->control, &vmcb->control);\n\n\tsvm->nested.nested_run_pending = 1;\n\n\tif (enter_svm_guest_mode(svm, vmcb12_gpa, vmcb12))\n\t\tgoto out_exit_err;\n\n\tif (nested_svm_vmrun_msrpm(svm))\n\t\tgoto out;\n\nout_exit_err:\n\tsvm->nested.nested_run_pending = 0;\n\n\tsvm->vmcb->control.exit_code = SVM_EXIT_ERR;\n\tsvm->vmcb->control.exit_code_hi = 0;\n\tsvm->vmcb->control.exit_info_1 = 0;\n\tsvm->vmcb->control.exit_info_2 = 0;\n\n\tnested_svm_vmexit(svm);\n\nout:\n\tkvm_vcpu_unmap(&svm->vcpu, &map, true);\n\n\treturn ret;\n}", "func_hash": 210421472923011897413923326817117614085, "file_name": "nested.c", "file_hash": 108011292709121623935842232206389598409, "cwe": ["CWE-416"], "cve": "CVE-2021-29657", "cve_desc": "arch/x86/kvm/svm/nested.c in the Linux kernel before 5.11.12 has a use-after-free in which an AMD KVM guest can bypass access control on host OS MSRs when there are nested guests, aka CID-a58d9166a756. This occurs because of a TOCTOU race condition associated with a VMCB12 double fetch in nested_svm_vmrun.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29657"} {"idx": 206065, "project": "libavif", "commit_id": "0a8e7244d494ae98e9756355dfbfb6697ded2ff9", "project_url": "https://github.com/AOMediaCodec/libavif", "commit_url": "https://github.com/AOMediaCodec/libavif/commit/0a8e7244d494ae98e9756355dfbfb6697ded2ff9", "commit_message": "Set max image size to 16384 * 16384\n\nFix https://crbug.com/oss-fuzz/24728 and\nhttps://crbug.com/oss-fuzz/24734.", "target": 1, "func": "static avifBool avifParseImageGridBox(avifImageGrid * grid, const uint8_t * raw, size_t rawLen)\n{\n BEGIN_STREAM(s, raw, rawLen);\n\n uint8_t version, flags;\n CHECK(avifROStreamRead(&s, &version, 1)); // unsigned int(8) version = 0;\n if (version != 0) {\n return AVIF_FALSE;\n }\n CHECK(avifROStreamRead(&s, &flags, 1)); // unsigned int(8) flags;\n CHECK(avifROStreamRead(&s, &grid->rows, 1)); // unsigned int(8) rows_minus_one;\n CHECK(avifROStreamRead(&s, &grid->columns, 1)); // unsigned int(8) columns_minus_one;\n ++grid->rows;\n ++grid->columns;\n\n uint32_t fieldLength = ((flags & 1) + 1) * 16;\n if (fieldLength == 16) {\n uint16_t outputWidth16, outputHeight16;\n CHECK(avifROStreamReadU16(&s, &outputWidth16)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU16(&s, &outputHeight16)); // unsigned int(FieldLength) output_height;\n grid->outputWidth = outputWidth16;\n grid->outputHeight = outputHeight16;\n } else {\n if (fieldLength != 32) {\n // This should be impossible\n return AVIF_FALSE;\n }\n CHECK(avifROStreamReadU32(&s, &grid->outputWidth)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU32(&s, &grid->outputHeight)); // unsigned int(FieldLength) output_height;\n }\n return AVIF_TRUE;\n}", "func_hash": 21228671590324805618177484564061778662, "file_name": "read.c", "file_hash": 266416958373011772961778131862764540285, "cwe": ["CWE-703"], "cve": "CVE-2020-36407", "cve_desc": "libavif 0.8.0 and 0.8.1 has an out-of-bounds write in avifDecoderDataFillImageGrid.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36407"} {"idx": 376801, "project": "libavif", "commit_id": "0a8e7244d494ae98e9756355dfbfb6697ded2ff9", "project_url": "https://github.com/AOMediaCodec/libavif", "commit_url": "https://github.com/AOMediaCodec/libavif/commit/0a8e7244d494ae98e9756355dfbfb6697ded2ff9", "commit_message": "Set max image size to 16384 * 16384\n\nFix https://crbug.com/oss-fuzz/24728 and\nhttps://crbug.com/oss-fuzz/24734.", "target": 0, "func": "static avifBool avifParseImageGridBox(avifImageGrid * grid, const uint8_t * raw, size_t rawLen)\n{\n BEGIN_STREAM(s, raw, rawLen);\n\n uint8_t version, flags;\n CHECK(avifROStreamRead(&s, &version, 1)); // unsigned int(8) version = 0;\n if (version != 0) {\n return AVIF_FALSE;\n }\n CHECK(avifROStreamRead(&s, &flags, 1)); // unsigned int(8) flags;\n CHECK(avifROStreamRead(&s, &grid->rows, 1)); // unsigned int(8) rows_minus_one;\n CHECK(avifROStreamRead(&s, &grid->columns, 1)); // unsigned int(8) columns_minus_one;\n ++grid->rows;\n ++grid->columns;\n\n uint32_t fieldLength = ((flags & 1) + 1) * 16;\n if (fieldLength == 16) {\n uint16_t outputWidth16, outputHeight16;\n CHECK(avifROStreamReadU16(&s, &outputWidth16)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU16(&s, &outputHeight16)); // unsigned int(FieldLength) output_height;\n grid->outputWidth = outputWidth16;\n grid->outputHeight = outputHeight16;\n } else {\n if (fieldLength != 32) {\n // This should be impossible\n return AVIF_FALSE;\n }\n CHECK(avifROStreamReadU32(&s, &grid->outputWidth)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU32(&s, &grid->outputHeight)); // unsigned int(FieldLength) output_height;\n }\n if (grid->outputWidth > AVIF_MAX_IMAGE_SIZE / grid->outputHeight) {\n return AVIF_FALSE;\n }\n return AVIF_TRUE;\n}", "func_hash": 34051233286643192917460190845097165361, "file_name": "read.c", "file_hash": 65167271341916980377337933640628474820, "cwe": ["CWE-703"], "cve": "CVE-2020-36407", "cve_desc": "libavif 0.8.0 and 0.8.1 has an out-of-bounds write in avifDecoderDataFillImageGrid.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36407"} {"idx": 206235, "project": "sqlite", "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/8654186b0236d556aa85528c2573ee0b6ab71be3", "commit_message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 1, "func": "static int codeCompare(\n Parse *pParse, /* The parsing (and code generating) context */\n Expr *pLeft, /* The left operand */\n Expr *pRight, /* The right operand */\n int opcode, /* The comparison opcode */\n int in1, int in2, /* Register holding operands */\n int dest, /* Jump here if true. */\n int jumpIfNull, /* If true, jump if either operand is NULL */\n int isCommuted /* The comparison has been commuted */\n){\n int p5;\n int addr;\n CollSeq *p4;\n\n if( isCommuted ){\n p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);\n }else{\n p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);\n }\n p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);\n addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,\n (void*)p4, P4_COLLSEQ);\n sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);\n return addr;\n}", "func_hash": 308693213256416686692478252875956026444, "file_name": "expr.c", "file_hash": 286600823016277504656031798190825734193, "cwe": ["CWE-755"], "cve": "CVE-2019-19924", "cve_desc": "SQLite 3.30.1 mishandles certain parser-tree rewriting, related to expr.c, vdbeaux.c, and window.c. This is caused by incorrect sqlite3WindowRewrite() error handling.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19924"} {"idx": 378666, "project": "sqlite", "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/8654186b0236d556aa85528c2573ee0b6ab71be3", "commit_message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 0, "func": "static int codeCompare(\n Parse *pParse, /* The parsing (and code generating) context */\n Expr *pLeft, /* The left operand */\n Expr *pRight, /* The right operand */\n int opcode, /* The comparison opcode */\n int in1, int in2, /* Register holding operands */\n int dest, /* Jump here if true. */\n int jumpIfNull, /* If true, jump if either operand is NULL */\n int isCommuted /* The comparison has been commuted */\n){\n int p5;\n int addr;\n CollSeq *p4;\n\n if( pParse->nErr ) return 0;\n if( isCommuted ){\n p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);\n }else{\n p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);\n }\n p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);\n addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,\n (void*)p4, P4_COLLSEQ);\n sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);\n return addr;\n}", "func_hash": 188300536130180868545305332871159937073, "file_name": "expr.c", "file_hash": 174834781511614628277827277345003810259, "cwe": ["CWE-755"], "cve": "CVE-2019-19924", "cve_desc": "SQLite 3.30.1 mishandles certain parser-tree rewriting, related to expr.c, vdbeaux.c, and window.c. This is caused by incorrect sqlite3WindowRewrite() error handling.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19924"} {"idx": 206236, "project": "sqlite", "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/8654186b0236d556aa85528c2573ee0b6ab71be3", "commit_message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 1, "func": "static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){\n assert( p->nOp>0 || p->aOp==0 );\n assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );\n if( p->nOp ){\n assert( p->aOp );\n sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);\n p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);\n }\n}", "func_hash": 57120224798488323028281499819258720642, "file_name": "vdbeaux.c", "file_hash": 130760200978108869428892635237264073306, "cwe": ["CWE-755"], "cve": "CVE-2019-19924", "cve_desc": "SQLite 3.30.1 mishandles certain parser-tree rewriting, related to expr.c, vdbeaux.c, and window.c. This is caused by incorrect sqlite3WindowRewrite() error handling.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19924"} {"idx": 378537, "project": "sqlite", "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/8654186b0236d556aa85528c2573ee0b6ab71be3", "commit_message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 0, "func": "static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){\n assert( p->nOp>0 || p->aOp==0 );\n assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed\n || p->pParse->nErr>0 );\n if( p->nOp ){\n assert( p->aOp );\n sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);\n p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);\n }\n}", "func_hash": 247440554889994950588793487651041171532, "file_name": "vdbeaux.c", "file_hash": 99893700070573433381160199341815892695, "cwe": ["CWE-755"], "cve": "CVE-2019-19924", "cve_desc": "SQLite 3.30.1 mishandles certain parser-tree rewriting, related to expr.c, vdbeaux.c, and window.c. This is caused by incorrect sqlite3WindowRewrite() error handling.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19924"} {"idx": 206237, "project": "sqlite", "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/8654186b0236d556aa85528c2573ee0b6ab71be3", "commit_message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 1, "func": "int sqlite3WindowRewrite(Parse *pParse, Select *p){\n int rc = SQLITE_OK;\n if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){\n Vdbe *v = sqlite3GetVdbe(pParse);\n sqlite3 *db = pParse->db;\n Select *pSub = 0; /* The subquery */\n SrcList *pSrc = p->pSrc;\n Expr *pWhere = p->pWhere;\n ExprList *pGroupBy = p->pGroupBy;\n Expr *pHaving = p->pHaving;\n ExprList *pSort = 0;\n\n ExprList *pSublist = 0; /* Expression list for sub-query */\n Window *pMWin = p->pWin; /* Master window object */\n Window *pWin; /* Window object iterator */\n Table *pTab;\n\n pTab = sqlite3DbMallocZero(db, sizeof(Table));\n if( pTab==0 ){\n return SQLITE_NOMEM;\n }\n\n p->pSrc = 0;\n p->pWhere = 0;\n p->pGroupBy = 0;\n p->pHaving = 0;\n p->selFlags &= ~SF_Aggregate;\n p->selFlags |= SF_WinRewrite;\n\n /* Create the ORDER BY clause for the sub-select. This is the concatenation\n ** of the window PARTITION and ORDER BY clauses. Then, if this makes it\n ** redundant, remove the ORDER BY from the parent SELECT. */\n pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);\n pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);\n if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){\n int nSave = pSort->nExpr;\n pSort->nExpr = p->pOrderBy->nExpr;\n if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){\n sqlite3ExprListDelete(db, p->pOrderBy);\n p->pOrderBy = 0;\n }\n pSort->nExpr = nSave;\n }\n\n /* Assign a cursor number for the ephemeral table used to buffer rows.\n ** The OpenEphemeral instruction is coded later, after it is known how\n ** many columns the table will have. */\n pMWin->iEphCsr = pParse->nTab++;\n pParse->nTab += 3;\n\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);\n pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);\n\n /* Append the PARTITION BY and ORDER BY expressions to the to the \n ** sub-select expression list. They are required to figure out where \n ** boundaries for partitions and sets of peer rows lie. */\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);\n\n /* Append the arguments passed to each window function to the\n ** sub-select expression list. Also allocate two registers for each\n ** window function - one for the accumulator, another for interim\n ** results. */\n for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n ExprList *pArgs = pWin->pOwner->x.pList;\n if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){\n selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pWin->bExprArgs = 1;\n }else{\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);\n }\n if( pWin->pFilter ){\n Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);\n pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);\n }\n pWin->regAccum = ++pParse->nMem;\n pWin->regResult = ++pParse->nMem;\n sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n }\n\n /* If there is no ORDER BY or PARTITION BY clause, and the window\n ** function accepts zero arguments, and there are no other columns\n ** selected (e.g. \"SELECT row_number() OVER () FROM t1\"), it is possible\n ** that pSublist is still NULL here. Add a constant expression here to \n ** keep everything legal in this case. \n */\n if( pSublist==0 ){\n pSublist = sqlite3ExprListAppend(pParse, 0, \n sqlite3Expr(db, TK_INTEGER, \"0\")\n );\n }\n\n pSub = sqlite3SelectNew(\n pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0\n );\n p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n if( p->pSrc ){\n Table *pTab2;\n p->pSrc->a[0].pSelect = pSub;\n sqlite3SrcListAssignCursors(pParse, p->pSrc);\n pSub->selFlags |= SF_Expanded;\n pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);\n if( pTab2==0 ){\n rc = SQLITE_NOMEM;\n }else{\n memcpy(pTab, pTab2, sizeof(Table));\n pTab->tabFlags |= TF_Ephemeral;\n p->pSrc->a[0].pTab = pTab;\n pTab = pTab2;\n }\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);\n }else{\n sqlite3SelectDelete(db, pSub);\n }\n if( db->mallocFailed ) rc = SQLITE_NOMEM;\n sqlite3DbFree(db, pTab);\n }\n\n return rc;\n}", "func_hash": 190438930528432440427410598810074473789, "file_name": "window.c", "file_hash": 220312818975938168923409601162965618407, "cwe": ["CWE-755"], "cve": "CVE-2019-19924", "cve_desc": "SQLite 3.30.1 mishandles certain parser-tree rewriting, related to expr.c, vdbeaux.c, and window.c. This is caused by incorrect sqlite3WindowRewrite() error handling.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19924"} {"idx": 378646, "project": "sqlite", "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/8654186b0236d556aa85528c2573ee0b6ab71be3", "commit_message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 0, "func": "int sqlite3WindowRewrite(Parse *pParse, Select *p){\n int rc = SQLITE_OK;\n if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){\n Vdbe *v = sqlite3GetVdbe(pParse);\n sqlite3 *db = pParse->db;\n Select *pSub = 0; /* The subquery */\n SrcList *pSrc = p->pSrc;\n Expr *pWhere = p->pWhere;\n ExprList *pGroupBy = p->pGroupBy;\n Expr *pHaving = p->pHaving;\n ExprList *pSort = 0;\n\n ExprList *pSublist = 0; /* Expression list for sub-query */\n Window *pMWin = p->pWin; /* Master window object */\n Window *pWin; /* Window object iterator */\n Table *pTab;\n\n pTab = sqlite3DbMallocZero(db, sizeof(Table));\n if( pTab==0 ){\n return sqlite3ErrorToParser(db, SQLITE_NOMEM);\n }\n\n p->pSrc = 0;\n p->pWhere = 0;\n p->pGroupBy = 0;\n p->pHaving = 0;\n p->selFlags &= ~SF_Aggregate;\n p->selFlags |= SF_WinRewrite;\n\n /* Create the ORDER BY clause for the sub-select. This is the concatenation\n ** of the window PARTITION and ORDER BY clauses. Then, if this makes it\n ** redundant, remove the ORDER BY from the parent SELECT. */\n pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);\n pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);\n if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){\n int nSave = pSort->nExpr;\n pSort->nExpr = p->pOrderBy->nExpr;\n if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){\n sqlite3ExprListDelete(db, p->pOrderBy);\n p->pOrderBy = 0;\n }\n pSort->nExpr = nSave;\n }\n\n /* Assign a cursor number for the ephemeral table used to buffer rows.\n ** The OpenEphemeral instruction is coded later, after it is known how\n ** many columns the table will have. */\n pMWin->iEphCsr = pParse->nTab++;\n pParse->nTab += 3;\n\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);\n pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);\n\n /* Append the PARTITION BY and ORDER BY expressions to the to the \n ** sub-select expression list. They are required to figure out where \n ** boundaries for partitions and sets of peer rows lie. */\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);\n\n /* Append the arguments passed to each window function to the\n ** sub-select expression list. Also allocate two registers for each\n ** window function - one for the accumulator, another for interim\n ** results. */\n for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n ExprList *pArgs = pWin->pOwner->x.pList;\n if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){\n selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pWin->bExprArgs = 1;\n }else{\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);\n }\n if( pWin->pFilter ){\n Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);\n pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);\n }\n pWin->regAccum = ++pParse->nMem;\n pWin->regResult = ++pParse->nMem;\n sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n }\n\n /* If there is no ORDER BY or PARTITION BY clause, and the window\n ** function accepts zero arguments, and there are no other columns\n ** selected (e.g. \"SELECT row_number() OVER () FROM t1\"), it is possible\n ** that pSublist is still NULL here. Add a constant expression here to \n ** keep everything legal in this case. \n */\n if( pSublist==0 ){\n pSublist = sqlite3ExprListAppend(pParse, 0, \n sqlite3Expr(db, TK_INTEGER, \"0\")\n );\n }\n\n pSub = sqlite3SelectNew(\n pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0\n );\n p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n if( p->pSrc ){\n Table *pTab2;\n p->pSrc->a[0].pSelect = pSub;\n sqlite3SrcListAssignCursors(pParse, p->pSrc);\n pSub->selFlags |= SF_Expanded;\n pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);\n if( pTab2==0 ){\n rc = SQLITE_NOMEM;\n }else{\n memcpy(pTab, pTab2, sizeof(Table));\n pTab->tabFlags |= TF_Ephemeral;\n p->pSrc->a[0].pTab = pTab;\n pTab = pTab2;\n }\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);\n }else{\n sqlite3SelectDelete(db, pSub);\n }\n if( db->mallocFailed ) rc = SQLITE_NOMEM;\n sqlite3DbFree(db, pTab);\n }\n\n if( rc && pParse->nErr==0 ){\n assert( pParse->db->mallocFailed );\n return sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);\n }\n return rc;\n}", "func_hash": 223463633895795769122103624562758013085, "file_name": "window.c", "file_hash": 246598162707228077957418771997179989014, "cwe": ["CWE-755"], "cve": "CVE-2019-19924", "cve_desc": "SQLite 3.30.1 mishandles certain parser-tree rewriting, related to expr.c, vdbeaux.c, and window.c. This is caused by incorrect sqlite3WindowRewrite() error handling.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19924"} {"idx": 206271, "project": "bash", "commit_id": "863d31ae775d56b785dc5b0105b6d251515d81d5", "project_url": "https://github.com/bminor/bash", "commit_url": "http://git.savannah.gnu.org/cgit/bash.git/commit/?h=devel&id=863d31ae775d56b785dc5b0105b6d251515d81d5", "commit_message": "commit bash-20120224 snapshot", "target": 1, "func": "ansicstr (string, len, flags, sawc, rlen)\n char *string;\n int len, flags, *sawc, *rlen;\n{\n int c, temp;\n char *ret, *r, *s;\n unsigned long v;\n\n if (string == 0 || *string == '\\0')\n return ((char *)NULL);\n\n#if defined (HANDLE_MULTIBYTE)\n if (strstr (string, \"\\\\U\") != 0)\n ret = (char *)xmalloc (6*len + 1);\n else\n ret = (char *)xmalloc (4*len + 1);\n#else\n ret = (char *)xmalloc (2*len + 1);\t/* 2*len for possible CTLESC */\n#endif\n for (r = ret, s = string; s && *s; )\n {\n c = *s++;\n if (c != '\\\\' || *s == '\\0')\n\t*r++ = c;\n else\n\t{\n\t switch (c = *s++)\n\t {\n#if defined (__STDC__)\n\t case 'a': c = '\\a'; break;\n\t case 'v': c = '\\v'; break;\n#else\n\t case 'a': c = (int) 0x07; break;\n\t case 'v': c = (int) 0x0B; break;\n#endif\n\t case 'b': c = '\\b'; break;\n\t case 'e': case 'E':\t\t/* ESC -- non-ANSI */\n\t c = ESC; break;\n\t case 'f': c = '\\f'; break;\n\t case 'n': c = '\\n'; break;\n\t case 'r': c = '\\r'; break;\n\t case 't': c = '\\t'; break;\n\t case '1': case '2': case '3':\n\t case '4': case '5': case '6':\n\t case '7':\n#if 1\n\t if (flags & 1)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t break;\n\t\t}\n\t /*FALLTHROUGH*/\n#endif\n\t case '0':\n\t /* If (FLAGS & 1), we're translating a string for echo -e (or\n\t\t the equivalent xpg_echo option), so we obey the SUSv3/\n\t\t POSIX-2001 requirement and accept 0-3 octal digits after\n\t\t a leading `0'. */\n\t temp = 2 + ((flags & 1) && (c == '0'));\n\t for (c -= '0'; ISOCTAL (*s) && temp--; s++)\n\t\tc = (c * 8) + OCTVALUE (*s);\n\t c &= 0xFF;\n\t break;\n\t case 'x':\t\t\t/* Hex digit -- non-ANSI */\n\t if ((flags & 2) && *s == '{')\n\t\t{\n\t\t flags |= 16;\t\t/* internal flag value */\n\t\t s++;\n\t\t}\n\t /* Consume at least two hex characters */\n\t for (temp = 2, c = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tc = (c * 16) + HEXVALUE (*s);\n\t /* DGK says that after a `\\x{' ksh93 consumes ISXDIGIT chars\n\t\t until a non-xdigit or `}', so potentially more than two\n\t\t chars are consumed. */\n\t if (flags & 16)\n\t\t{\n\t\t for ( ; ISXDIGIT ((unsigned char)*s); s++)\n\t\t c = (c * 16) + HEXVALUE (*s);\n\t\t flags &= ~16;\n\t\t if (*s == '}')\n\t\t s++;\n\t }\n\t /* \\x followed by non-hex digits is passed through unchanged */\n\t else if (temp == 2)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t c = 'x';\n\t\t}\n\t c &= 0xFF;\n\t break;\n#if defined (HANDLE_MULTIBYTE)\n\t case 'u':\n\t case 'U':\n\t temp = (c == 'u') ? 4 : 8;\t/* \\uNNNN \\UNNNNNNNN */\n\t for (v = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tv = (v * 16) + HEXVALUE (*s);\n\t if (temp == ((c == 'u') ? 4 : 8))\n\t\t{\n\t\t *r++ = '\\\\';\t/* c remains unchanged */\n\t\t break;\n\t\t}\n\t else if (v <= 0x7f)\t/* <= 0x7f translates directly */\n\t\t{\n\t\t c = v;\n\t\t break;\n\t\t}\n\t else\n\t\t{\n\t\t temp = u32cconv (v, r);\n\t\t r += temp;\n\t\t continue;\n\t\t}\n#endif\n\t case '\\\\':\n\t break;\n\t case '\\'': case '\"': case '?':\n\t if (flags & 1)\n\t\t*r++ = '\\\\';\n\t break;\n\t case 'c':\n\t if (sawc)\n\t\t{\n\t\t *sawc = 1;\n\t\t *r = '\\0';\n\t\t if (rlen)\n\t\t *rlen = r - ret;\n\t\t return ret;\n\t\t}\n\t else if ((flags & 1) == 0 && *s == 0)\n\t\t;\t\t/* pass \\c through */\n\t else if ((flags & 1) == 0 && (c = *s))\n\t\t{\n\t\t s++;\n\t\t if ((flags & 2) && c == '\\\\' && c == *s)\n\t\t s++;\t/* Posix requires $'\\c\\\\' do backslash escaping */\n\t\t c = TOCTRL(c);\n\t\t break;\n\t\t}\n\t\t/*FALLTHROUGH*/\n\t default:\n\t\tif ((flags & 4) == 0)\n\t\t *r++ = '\\\\';\n\t\tbreak;\n\t }\n\t if ((flags & 2) && (c == CTLESC || c == CTLNUL))\n\t *r++ = CTLESC;\n\t *r++ = c;\n\t}\n }\n *r = '\\0';\n if (rlen)\n *rlen = r - ret;\n return ret;\n}", "func_hash": 39462252945443137114432527197926842100, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2012-6711", "cve_desc": "A heap-based buffer overflow exists in GNU Bash before 4.3 when wide characters, not supported by the current locale set in the LC_CTYPE environment variable, are printed through the echo built-in function. A local attacker, who can provide data to print through the \"echo -e\" built-in function, may use this flaw to crash a script or execute code with the privileges of the bash process. This occurs because ansicstr() in lib/sh/strtrans.c mishandles u32cconv().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-6711"} {"idx": 379446, "project": "bash", "commit_id": "863d31ae775d56b785dc5b0105b6d251515d81d5", "project_url": "https://github.com/bminor/bash", "commit_url": "http://git.savannah.gnu.org/cgit/bash.git/commit/?h=devel&id=863d31ae775d56b785dc5b0105b6d251515d81d5", "commit_message": "commit bash-20120224 snapshot", "target": 0, "func": "ansicstr (string, len, flags, sawc, rlen)\n char *string;\n int len, flags, *sawc, *rlen;\n{\n int c, temp;\n char *ret, *r, *s;\n unsigned long v;\n\n if (string == 0 || *string == '\\0')\n return ((char *)NULL);\n\n#if defined (HANDLE_MULTIBYTE)\n ret = (char *)xmalloc (4*len + 1);\n#else\n ret = (char *)xmalloc (2*len + 1);\t/* 2*len for possible CTLESC */\n#endif\n for (r = ret, s = string; s && *s; )\n {\n c = *s++;\n if (c != '\\\\' || *s == '\\0')\n\t*r++ = c;\n else\n\t{\n\t switch (c = *s++)\n\t {\n#if defined (__STDC__)\n\t case 'a': c = '\\a'; break;\n\t case 'v': c = '\\v'; break;\n#else\n\t case 'a': c = (int) 0x07; break;\n\t case 'v': c = (int) 0x0B; break;\n#endif\n\t case 'b': c = '\\b'; break;\n\t case 'e': case 'E':\t\t/* ESC -- non-ANSI */\n\t c = ESC; break;\n\t case 'f': c = '\\f'; break;\n\t case 'n': c = '\\n'; break;\n\t case 'r': c = '\\r'; break;\n\t case 't': c = '\\t'; break;\n\t case '1': case '2': case '3':\n\t case '4': case '5': case '6':\n\t case '7':\n#if 1\n\t if (flags & 1)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t break;\n\t\t}\n\t /*FALLTHROUGH*/\n#endif\n\t case '0':\n\t /* If (FLAGS & 1), we're translating a string for echo -e (or\n\t\t the equivalent xpg_echo option), so we obey the SUSv3/\n\t\t POSIX-2001 requirement and accept 0-3 octal digits after\n\t\t a leading `0'. */\n\t temp = 2 + ((flags & 1) && (c == '0'));\n\t for (c -= '0'; ISOCTAL (*s) && temp--; s++)\n\t\tc = (c * 8) + OCTVALUE (*s);\n\t c &= 0xFF;\n\t break;\n\t case 'x':\t\t\t/* Hex digit -- non-ANSI */\n\t if ((flags & 2) && *s == '{')\n\t\t{\n\t\t flags |= 16;\t\t/* internal flag value */\n\t\t s++;\n\t\t}\n\t /* Consume at least two hex characters */\n\t for (temp = 2, c = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tc = (c * 16) + HEXVALUE (*s);\n\t /* DGK says that after a `\\x{' ksh93 consumes ISXDIGIT chars\n\t\t until a non-xdigit or `}', so potentially more than two\n\t\t chars are consumed. */\n\t if (flags & 16)\n\t\t{\n\t\t for ( ; ISXDIGIT ((unsigned char)*s); s++)\n\t\t c = (c * 16) + HEXVALUE (*s);\n\t\t flags &= ~16;\n\t\t if (*s == '}')\n\t\t s++;\n\t }\n\t /* \\x followed by non-hex digits is passed through unchanged */\n\t else if (temp == 2)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t c = 'x';\n\t\t}\n\t c &= 0xFF;\n\t break;\n#if defined (HANDLE_MULTIBYTE)\n\t case 'u':\n\t case 'U':\n\t temp = (c == 'u') ? 4 : 8;\t/* \\uNNNN \\UNNNNNNNN */\n\t for (v = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tv = (v * 16) + HEXVALUE (*s);\n\t if (temp == ((c == 'u') ? 4 : 8))\n\t\t{\n\t\t *r++ = '\\\\';\t/* c remains unchanged */\n\t\t break;\n\t\t}\n\t else if (v <= 0x7f)\t/* <= 0x7f translates directly */\n\t\t{\n\t\t c = v;\n\t\t break;\n\t\t}\n\t else\n\t\t{\n\t\t temp = u32cconv (v, r);\n\t\t r += temp;\n\t\t continue;\n\t\t}\n#endif\n\t case '\\\\':\n\t break;\n\t case '\\'': case '\"': case '?':\n\t if (flags & 1)\n\t\t*r++ = '\\\\';\n\t break;\n\t case 'c':\n\t if (sawc)\n\t\t{\n\t\t *sawc = 1;\n\t\t *r = '\\0';\n\t\t if (rlen)\n\t\t *rlen = r - ret;\n\t\t return ret;\n\t\t}\n\t else if ((flags & 1) == 0 && *s == 0)\n\t\t;\t\t/* pass \\c through */\n\t else if ((flags & 1) == 0 && (c = *s))\n\t\t{\n\t\t s++;\n\t\t if ((flags & 2) && c == '\\\\' && c == *s)\n\t\t s++;\t/* Posix requires $'\\c\\\\' do backslash escaping */\n\t\t c = TOCTRL(c);\n\t\t break;\n\t\t}\n\t\t/*FALLTHROUGH*/\n\t default:\n\t\tif ((flags & 4) == 0)\n\t\t *r++ = '\\\\';\n\t\tbreak;\n\t }\n\t if ((flags & 2) && (c == CTLESC || c == CTLNUL))\n\t *r++ = CTLESC;\n\t *r++ = c;\n\t}\n }\n *r = '\\0';\n if (rlen)\n *rlen = r - ret;\n return ret;\n}", "func_hash": 191757215573824704861773636339200984385, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2012-6711", "cve_desc": "A heap-based buffer overflow exists in GNU Bash before 4.3 when wide characters, not supported by the current locale set in the LC_CTYPE environment variable, are printed through the echo built-in function. A local attacker, who can provide data to print through the \"echo -e\" built-in function, may use this flaw to crash a script or execute code with the privileges of the bash process. This occurs because ansicstr() in lib/sh/strtrans.c mishandles u32cconv().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-6711"} {"idx": 206275, "project": "libjpeg-turbo", "commit_id": "f35fd27ec641c42d6b115bfa595e483ec58188d2", "project_url": "https://github.com/libjpeg-turbo/libjpeg-turbo", "commit_url": "https://github.com/libjpeg-turbo/libjpeg-turbo/commit/f35fd27ec641c42d6b115bfa595e483ec58188d2", "commit_message": "tjLoadImage: Fix issues w/loading 16-bit PPMs/PGMs\n\n- The PPM reader now throws an error rather than segfaulting (due to a\n buffer overrun) if an application attempts to load a 16-bit PPM file\n into a grayscale uncompressed image buffer. No known applications\n allowed that (not even the test applications in libjpeg-turbo),\n because that mode of operation was never expected to work and did not\n work under any circumstances. (In fact, it was necessary to modify\n TJBench in order to reproduce the issue outside of a fuzzing\n environment.) This was purely a matter of making the library bow out\n gracefully rather than crash if an application tries to do something\n really stupid.\n\n- The PPM reader now throws an error rather than generating incorrect\n pixels if an application attempts to load a 16-bit PGM file into an\n RGB uncompressed image buffer.\n\n- The PPM reader now correctly loads 16-bit PPM files into extended\n RGB uncompressed image buffers. (Previously it generated incorrect\n pixels unless the input colorspace was JCS_RGB or JCS_EXT_RGB.)\n\nThe only way that users could have potentially encountered these issues\nwas through the tjLoadImage() function. cjpeg and TJBench were\nunaffected.", "target": 1, "func": "get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n/* This version is for reading raw-word-format PPM files with any maxval */\n{\n ppm_source_ptr source = (ppm_source_ptr)sinfo;\n register JSAMPROW ptr;\n register U_CHAR *bufferptr;\n register JSAMPLE *rescale = source->rescale;\n JDIMENSION col;\n unsigned int maxval = source->maxval;\n\n if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n ptr = source->pub.buffer[0];\n bufferptr = source->iobuffer;\n for (col = cinfo->image_width; col > 0; col--) {\n register unsigned int temp;\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n }\n return 1;\n}", "func_hash": 45673663722955957995654505057800760253, "file_name": "rdppm.c", "file_hash": 217227986550072258034502320499219232162, "cwe": ["CWE-200"], "cve": "CVE-2021-46822", "cve_desc": "The PPM reader in libjpeg-turbo through 2.0.90 mishandles use of tjLoadImage for loading a 16-bit binary PPM file into a grayscale buffer and loading a 16-bit binary PGM file into an RGB buffer. This is related to a heap-based buffer overflow in the get_word_rgb_row function in rdppm.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46822"} {"idx": 379756, "project": "libjpeg-turbo", "commit_id": "f35fd27ec641c42d6b115bfa595e483ec58188d2", "project_url": "https://github.com/libjpeg-turbo/libjpeg-turbo", "commit_url": "https://github.com/libjpeg-turbo/libjpeg-turbo/commit/f35fd27ec641c42d6b115bfa595e483ec58188d2", "commit_message": "tjLoadImage: Fix issues w/loading 16-bit PPMs/PGMs\n\n- The PPM reader now throws an error rather than segfaulting (due to a\n buffer overrun) if an application attempts to load a 16-bit PPM file\n into a grayscale uncompressed image buffer. No known applications\n allowed that (not even the test applications in libjpeg-turbo),\n because that mode of operation was never expected to work and did not\n work under any circumstances. (In fact, it was necessary to modify\n TJBench in order to reproduce the issue outside of a fuzzing\n environment.) This was purely a matter of making the library bow out\n gracefully rather than crash if an application tries to do something\n really stupid.\n\n- The PPM reader now throws an error rather than generating incorrect\n pixels if an application attempts to load a 16-bit PGM file into an\n RGB uncompressed image buffer.\n\n- The PPM reader now correctly loads 16-bit PPM files into extended\n RGB uncompressed image buffers. (Previously it generated incorrect\n pixels unless the input colorspace was JCS_RGB or JCS_EXT_RGB.)\n\nThe only way that users could have potentially encountered these issues\nwas through the tjLoadImage() function. cjpeg and TJBench were\nunaffected.", "target": 0, "func": "get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n/* This version is for reading raw-word-format PPM files with any maxval */\n{\n ppm_source_ptr source = (ppm_source_ptr)sinfo;\n register JSAMPROW ptr;\n register U_CHAR *bufferptr;\n register JSAMPLE *rescale = source->rescale;\n JDIMENSION col;\n unsigned int maxval = source->maxval;\n register int rindex = rgb_red[cinfo->in_color_space];\n register int gindex = rgb_green[cinfo->in_color_space];\n register int bindex = rgb_blue[cinfo->in_color_space];\n register int aindex = alpha_index[cinfo->in_color_space];\n register int ps = rgb_pixelsize[cinfo->in_color_space];\n\n if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n ptr = source->pub.buffer[0];\n bufferptr = source->iobuffer;\n for (col = cinfo->image_width; col > 0; col--) {\n register unsigned int temp;\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n ptr[rindex] = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n ptr[gindex] = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n ptr[bindex] = rescale[temp];\n if (aindex >= 0)\n ptr[aindex] = 0xFF;\n ptr += ps;\n }\n return 1;\n}", "func_hash": 133514470541852682649664170690016728522, "file_name": "rdppm.c", "file_hash": 157218998394407980329052808710743325998, "cwe": ["CWE-200"], "cve": "CVE-2021-46822", "cve_desc": "The PPM reader in libjpeg-turbo through 2.0.90 mishandles use of tjLoadImage for loading a 16-bit binary PPM file into a grayscale buffer and loading a 16-bit binary PGM file into an RGB buffer. This is related to a heap-based buffer overflow in the get_word_rgb_row function in rdppm.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46822"} {"idx": 206293, "project": "linux", "commit_id": "f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5", "commit_message": "scsi: iscsi: Verify lengths on passthrough PDUs\n\nOpen-iSCSI sends passthrough PDUs over netlink, but the kernel should be\nverifying that the provided PDU header and data lengths fall within the\nnetlink message to prevent accessing beyond that in memory.\n\nCc: stable@vger.kernel.org\nReported-by: Adam Nichols \nReviewed-by: Lee Duncan \nReviewed-by: Mike Christie \nSigned-off-by: Chris Leech \nSigned-off-by: Martin K. Petersen ", "target": 1, "func": "\n\nstatic int\niscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group)\n{\n\tint err = 0;\n\tu32 portid;\n\tstruct iscsi_uevent *ev = nlmsg_data(nlh);\n\tstruct iscsi_transport *transport = NULL;\n\tstruct iscsi_internal *priv;\n\tstruct iscsi_cls_session *session;\n\tstruct iscsi_cls_conn *conn;\n\tstruct iscsi_endpoint *ep = NULL;\n\n\tif (!netlink_capable(skb, CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tif (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE)\n\t\t*group = ISCSI_NL_GRP_UIP;\n\telse\n\t\t*group = ISCSI_NL_GRP_ISCSID;\n\n\tpriv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle));\n\tif (!priv)\n\t\treturn -EINVAL;\n\ttransport = priv->iscsi_transport;\n\n\tif (!try_module_get(transport->owner))\n\t\treturn -EINVAL;\n\n\tportid = NETLINK_CB(skb).portid;\n\n\tswitch (nlh->nlmsg_type) {\n\tcase ISCSI_UEVENT_CREATE_SESSION:\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\t portid,\n\t\t\t\t\t ev->u.c_session.initial_cmdsn,\n\t\t\t\t\t ev->u.c_session.cmds_max,\n\t\t\t\t\t ev->u.c_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_BOUND_SESSION:\n\t\tep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle);\n\t\tif (!ep) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\tportid,\n\t\t\t\t\tev->u.c_bound_session.initial_cmdsn,\n\t\t\t\t\tev->u.c_bound_session.cmds_max,\n\t\t\t\t\tev->u.c_bound_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse\n\t\t\ttransport->destroy_session(session);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION_ASYNC:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse {\n\t\t\tunsigned long flags;\n\n\t\t\t/* Prevent this session from being found again */\n\t\t\tspin_lock_irqsave(&sesslock, flags);\n\t\t\tlist_del_init(&session->sess_list);\n\t\t\tspin_unlock_irqrestore(&sesslock, flags);\n\n\t\t\tqueue_work(iscsi_destroy_workq, &session->destroy_work);\n\t\t}\n\t\tbreak;\n\tcase ISCSI_UEVENT_UNBIND_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (session)\n\t\t\tscsi_queue_work(iscsi_session_to_shost(session),\n\t\t\t\t\t&session->unbind_work);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_CONN:\n\t\terr = iscsi_if_create_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_CONN:\n\t\terr = iscsi_if_destroy_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_BIND_CONN:\n\t\tsession = iscsi_session_lookup(ev->u.b_conn.sid);\n\t\tconn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid);\n\n\t\tif (conn && conn->ep)\n\t\t\tiscsi_if_ep_disconnect(transport, conn->ep->id);\n\n\t\tif (!session || !conn) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tmutex_lock(&conn_mutex);\n\t\tev->r.retcode =\ttransport->bind_conn(session, conn,\n\t\t\t\t\t\tev->u.b_conn.transport_eph,\n\t\t\t\t\t\tev->u.b_conn.is_leading);\n\t\tmutex_unlock(&conn_mutex);\n\n\t\tif (ev->r.retcode || !transport->ep_connect)\n\t\t\tbreak;\n\n\t\tep = iscsi_lookup_endpoint(ev->u.b_conn.transport_eph);\n\t\tif (ep) {\n\t\t\tep->conn = conn;\n\n\t\t\tmutex_lock(&conn->ep_mutex);\n\t\t\tconn->ep = ep;\n\t\t\tmutex_unlock(&conn->ep_mutex);\n\t\t} else\n\t\t\tiscsi_cls_conn_printk(KERN_ERR, conn,\n\t\t\t\t\t \"Could not set ep conn \"\n\t\t\t\t\t \"binding\\n\");\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_PARAM:\n\t\terr = iscsi_set_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_START_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode = transport->start_conn(conn);\n\t\t\tif (!ev->r.retcode)\n\t\t\t\tconn->state = ISCSI_CONN_UP;\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_STOP_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid);\n\t\tif (conn)\n\t\t\tiscsi_if_stop_conn(conn, ev->u.stop_conn.flag);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_SEND_PDU:\n\t\tconn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode =\ttransport->send_pdu(conn,\n\t\t\t\t(struct iscsi_hdr*)((char*)ev + sizeof(*ev)),\n\t\t\t\t(char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size,\n\t\t\t\tev->u.send_pdu.data_size);\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_STATS:\n\t\terr = iscsi_if_get_stats(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_POLL:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST:\n\t\terr = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TGT_DSCVR:\n\t\terr = iscsi_tgt_dscvr(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_HOST_PARAM:\n\t\terr = iscsi_set_host_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_PATH_UPDATE:\n\t\terr = iscsi_set_path(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_IFACE_PARAMS:\n\t\terr = iscsi_set_iface_params(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_PING:\n\t\terr = iscsi_send_ping(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_CHAP:\n\t\terr = iscsi_get_chap(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DELETE_CHAP:\n\t\terr = iscsi_delete_chap(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_FLASHNODE_PARAMS:\n\t\terr = iscsi_set_flashnode_param(transport, ev,\n\t\t\t\t\t\tnlmsg_attrlen(nlh,\n\t\t\t\t\t\t\t sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_NEW_FLASHNODE:\n\t\terr = iscsi_new_flashnode(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_DEL_FLASHNODE:\n\t\terr = iscsi_del_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGIN_FLASHNODE:\n\t\terr = iscsi_login_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE:\n\t\terr = iscsi_logout_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE_SID:\n\t\terr = iscsi_logout_flashnode_sid(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_CHAP:\n\t\terr = iscsi_set_chap(transport, ev,\n\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_HOST_STATS:\n\t\terr = iscsi_get_host_stats(transport, nlh);\n\t\tbreak;\n\tdefault:\n\t\terr = -ENOSYS;\n\t\tbreak;\n\t}\n", "func_hash": 329966858915660375193008231064997397907, "file_name": "scsi_transport_iscsi.c", "file_hash": 80314822017564185399990471228268665129, "cwe": ["CWE-125"], "cve": "CVE-2021-27364", "cve_desc": "An issue was discovered in the Linux kernel through 5.11.3. drivers/scsi/scsi_transport_iscsi.c is adversely affected by the ability of an unprivileged user to craft Netlink messages.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27364"} {"idx": 380003, "project": "linux", "commit_id": "f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5", "commit_message": "scsi: iscsi: Verify lengths on passthrough PDUs\n\nOpen-iSCSI sends passthrough PDUs over netlink, but the kernel should be\nverifying that the provided PDU header and data lengths fall within the\nnetlink message to prevent accessing beyond that in memory.\n\nCc: stable@vger.kernel.org\nReported-by: Adam Nichols \nReviewed-by: Lee Duncan \nReviewed-by: Mike Christie \nSigned-off-by: Chris Leech \nSigned-off-by: Martin K. Petersen ", "target": 0, "func": "\n\nstatic int\niscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group)\n{\n\tint err = 0;\n\tu32 portid;\n\tu32 pdu_len;\n\tstruct iscsi_uevent *ev = nlmsg_data(nlh);\n\tstruct iscsi_transport *transport = NULL;\n\tstruct iscsi_internal *priv;\n\tstruct iscsi_cls_session *session;\n\tstruct iscsi_cls_conn *conn;\n\tstruct iscsi_endpoint *ep = NULL;\n\n\tif (!netlink_capable(skb, CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tif (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE)\n\t\t*group = ISCSI_NL_GRP_UIP;\n\telse\n\t\t*group = ISCSI_NL_GRP_ISCSID;\n\n\tpriv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle));\n\tif (!priv)\n\t\treturn -EINVAL;\n\ttransport = priv->iscsi_transport;\n\n\tif (!try_module_get(transport->owner))\n\t\treturn -EINVAL;\n\n\tportid = NETLINK_CB(skb).portid;\n\n\tswitch (nlh->nlmsg_type) {\n\tcase ISCSI_UEVENT_CREATE_SESSION:\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\t portid,\n\t\t\t\t\t ev->u.c_session.initial_cmdsn,\n\t\t\t\t\t ev->u.c_session.cmds_max,\n\t\t\t\t\t ev->u.c_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_BOUND_SESSION:\n\t\tep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle);\n\t\tif (!ep) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\tportid,\n\t\t\t\t\tev->u.c_bound_session.initial_cmdsn,\n\t\t\t\t\tev->u.c_bound_session.cmds_max,\n\t\t\t\t\tev->u.c_bound_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse\n\t\t\ttransport->destroy_session(session);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION_ASYNC:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse {\n\t\t\tunsigned long flags;\n\n\t\t\t/* Prevent this session from being found again */\n\t\t\tspin_lock_irqsave(&sesslock, flags);\n\t\t\tlist_del_init(&session->sess_list);\n\t\t\tspin_unlock_irqrestore(&sesslock, flags);\n\n\t\t\tqueue_work(iscsi_destroy_workq, &session->destroy_work);\n\t\t}\n\t\tbreak;\n\tcase ISCSI_UEVENT_UNBIND_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (session)\n\t\t\tscsi_queue_work(iscsi_session_to_shost(session),\n\t\t\t\t\t&session->unbind_work);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_CONN:\n\t\terr = iscsi_if_create_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_CONN:\n\t\terr = iscsi_if_destroy_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_BIND_CONN:\n\t\tsession = iscsi_session_lookup(ev->u.b_conn.sid);\n\t\tconn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid);\n\n\t\tif (conn && conn->ep)\n\t\t\tiscsi_if_ep_disconnect(transport, conn->ep->id);\n\n\t\tif (!session || !conn) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tmutex_lock(&conn_mutex);\n\t\tev->r.retcode =\ttransport->bind_conn(session, conn,\n\t\t\t\t\t\tev->u.b_conn.transport_eph,\n\t\t\t\t\t\tev->u.b_conn.is_leading);\n\t\tmutex_unlock(&conn_mutex);\n\n\t\tif (ev->r.retcode || !transport->ep_connect)\n\t\t\tbreak;\n\n\t\tep = iscsi_lookup_endpoint(ev->u.b_conn.transport_eph);\n\t\tif (ep) {\n\t\t\tep->conn = conn;\n\n\t\t\tmutex_lock(&conn->ep_mutex);\n\t\t\tconn->ep = ep;\n\t\t\tmutex_unlock(&conn->ep_mutex);\n\t\t} else\n\t\t\tiscsi_cls_conn_printk(KERN_ERR, conn,\n\t\t\t\t\t \"Could not set ep conn \"\n\t\t\t\t\t \"binding\\n\");\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_PARAM:\n\t\terr = iscsi_set_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_START_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode = transport->start_conn(conn);\n\t\t\tif (!ev->r.retcode)\n\t\t\t\tconn->state = ISCSI_CONN_UP;\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_STOP_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid);\n\t\tif (conn)\n\t\t\tiscsi_if_stop_conn(conn, ev->u.stop_conn.flag);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_SEND_PDU:\n\t\tpdu_len = nlh->nlmsg_len - sizeof(*nlh) - sizeof(*ev);\n\n\t\tif ((ev->u.send_pdu.hdr_size > pdu_len) ||\n\t\t (ev->u.send_pdu.data_size > (pdu_len - ev->u.send_pdu.hdr_size))) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tconn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode =\ttransport->send_pdu(conn,\n\t\t\t\t(struct iscsi_hdr*)((char*)ev + sizeof(*ev)),\n\t\t\t\t(char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size,\n\t\t\t\tev->u.send_pdu.data_size);\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_STATS:\n\t\terr = iscsi_if_get_stats(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_POLL:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST:\n\t\terr = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TGT_DSCVR:\n\t\terr = iscsi_tgt_dscvr(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_HOST_PARAM:\n\t\terr = iscsi_set_host_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_PATH_UPDATE:\n\t\terr = iscsi_set_path(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_IFACE_PARAMS:\n\t\terr = iscsi_set_iface_params(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_PING:\n\t\terr = iscsi_send_ping(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_CHAP:\n\t\terr = iscsi_get_chap(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DELETE_CHAP:\n\t\terr = iscsi_delete_chap(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_FLASHNODE_PARAMS:\n\t\terr = iscsi_set_flashnode_param(transport, ev,\n\t\t\t\t\t\tnlmsg_attrlen(nlh,\n\t\t\t\t\t\t\t sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_NEW_FLASHNODE:\n\t\terr = iscsi_new_flashnode(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_DEL_FLASHNODE:\n\t\terr = iscsi_del_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGIN_FLASHNODE:\n\t\terr = iscsi_login_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE:\n\t\terr = iscsi_logout_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE_SID:\n\t\terr = iscsi_logout_flashnode_sid(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_CHAP:\n\t\terr = iscsi_set_chap(transport, ev,\n\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_HOST_STATS:\n\t\terr = iscsi_get_host_stats(transport, nlh);\n\t\tbreak;\n\tdefault:\n\t\terr = -ENOSYS;\n\t\tbreak;\n\t}\n", "func_hash": 199377341040899963181935971168271982879, "file_name": "scsi_transport_iscsi.c", "file_hash": 77480064353434641556948426270455864489, "cwe": ["CWE-125"], "cve": "CVE-2021-27364", "cve_desc": "An issue was discovered in the Linux kernel through 5.11.3. drivers/scsi/scsi_transport_iscsi.c is adversely affected by the ability of an unprivileged user to craft Netlink messages.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27364"} {"idx": 206300, "project": "linux", "commit_id": "efa9ace68e487ddd29c2b4d6dd23242158f1f607", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/powerpc/linux.git/commit/?id=efa9ace68e487ddd29c2b4d6dd23242158f1f607", "commit_message": "powerpc/pseries/dlpar: Fix a missing check in dlpar_parse_cc_property()\n\nIn dlpar_parse_cc_property(), 'prop->name' is allocated by kstrdup().\nkstrdup() may return NULL, so it should be checked and handle error.\nAnd prop should be freed if 'prop->name' is NULL.\n\nSigned-off-by: Gen Zhang \nSigned-off-by: Michael Ellerman ", "target": 1, "func": "static struct property *dlpar_parse_cc_property(struct cc_workarea *ccwa)\n{\n\tstruct property *prop;\n\tchar *name;\n\tchar *value;\n\n\tprop = kzalloc(sizeof(*prop), GFP_KERNEL);\n\tif (!prop)\n\t\treturn NULL;\n\n\tname = (char *)ccwa + be32_to_cpu(ccwa->name_offset);\n\tprop->name = kstrdup(name, GFP_KERNEL);\n\n\tprop->length = be32_to_cpu(ccwa->prop_length);\n\tvalue = (char *)ccwa + be32_to_cpu(ccwa->prop_offset);\n\tprop->value = kmemdup(value, prop->length, GFP_KERNEL);\n\tif (!prop->value) {\n\t\tdlpar_free_cc_property(prop);\n\t\treturn NULL;\n\t}\n\n\treturn prop;\n}", "func_hash": 183389732779890167437963874590868087701, "file_name": "dlpar.c", "file_hash": 170879712816697337148378604243536177855, "cwe": ["CWE-476"], "cve": "CVE-2019-12614", "cve_desc": "An issue was discovered in dlpar_parse_cc_property in arch/powerpc/platforms/pseries/dlpar.c in the Linux kernel through 5.1.6. There is an unchecked kstrdup of prop->name, which might allow an attacker to cause a denial of service (NULL pointer dereference and system crash).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-12614"} {"idx": 380132, "project": "linux", "commit_id": "efa9ace68e487ddd29c2b4d6dd23242158f1f607", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/powerpc/linux.git/commit/?id=efa9ace68e487ddd29c2b4d6dd23242158f1f607", "commit_message": "powerpc/pseries/dlpar: Fix a missing check in dlpar_parse_cc_property()\n\nIn dlpar_parse_cc_property(), 'prop->name' is allocated by kstrdup().\nkstrdup() may return NULL, so it should be checked and handle error.\nAnd prop should be freed if 'prop->name' is NULL.\n\nSigned-off-by: Gen Zhang \nSigned-off-by: Michael Ellerman ", "target": 0, "func": "static struct property *dlpar_parse_cc_property(struct cc_workarea *ccwa)\n{\n\tstruct property *prop;\n\tchar *name;\n\tchar *value;\n\n\tprop = kzalloc(sizeof(*prop), GFP_KERNEL);\n\tif (!prop)\n\t\treturn NULL;\n\n\tname = (char *)ccwa + be32_to_cpu(ccwa->name_offset);\n\tprop->name = kstrdup(name, GFP_KERNEL);\n\tif (!prop->name) {\n\t\tdlpar_free_cc_property(prop);\n\t\treturn NULL;\n\t}\n\n\tprop->length = be32_to_cpu(ccwa->prop_length);\n\tvalue = (char *)ccwa + be32_to_cpu(ccwa->prop_offset);\n\tprop->value = kmemdup(value, prop->length, GFP_KERNEL);\n\tif (!prop->value) {\n\t\tdlpar_free_cc_property(prop);\n\t\treturn NULL;\n\t}\n\n\treturn prop;\n}", "func_hash": 30928789740858152146094675490406957370, "file_name": "dlpar.c", "file_hash": 39810457144075915006692303530312069682, "cwe": ["CWE-476"], "cve": "CVE-2019-12614", "cve_desc": "An issue was discovered in dlpar_parse_cc_property in arch/powerpc/platforms/pseries/dlpar.c in the Linux kernel through 5.1.6. There is an unchecked kstrdup of prop->name, which might allow an attacker to cause a denial of service (NULL pointer dereference and system crash).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-12614"} {"idx": 206422, "project": "ImageMagick6", "commit_id": "3456724dff047db5adb32f8cf70c903c1b7d16d4", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/3456724dff047db5adb32f8cf70c903c1b7d16d4", "commit_message": "Always correct the width and height of the image.", "target": 1, "func": "static Image *ReadHEICImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n const StringInfo\n *profile;\n\n heif_item_id\n exif_id;\n\n Image\n *image;\n\n int\n count,\n stride_y,\n stride_cb,\n stride_cr;\n\n MagickBooleanType\n status;\n\n size_t\n length;\n\n ssize_t\n y;\n\n struct heif_context\n *heif_context;\n\n struct heif_decoding_options\n *decode_options;\n\n struct heif_error\n error;\n\n struct heif_image\n *heif_image;\n\n struct heif_image_handle\n *image_handle;\n\n const uint8_t\n *p_y,\n *p_cb,\n *p_cr;\n\n void\n *file_data;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (GetBlobSize(image) > (MagickSizeType) SSIZE_MAX)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n length=(size_t) GetBlobSize(image);\n file_data=AcquireMagickMemory(length);\n if (file_data == (void *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (ReadBlob(image,length,(unsigned char *) file_data) != (ssize_t) length)\n {\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n /*\n Decode HEIF file\n */\n heif_context=heif_context_alloc();\n error=heif_context_read_from_memory_without_copy(heif_context,file_data,\n length,NULL);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n image_handle=(struct heif_image_handle *) NULL;\n error=heif_context_get_primary_image_handle(heif_context,&image_handle);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n#if LIBHEIF_NUMERIC_VERSION >= 0x01040000\n length=heif_image_handle_get_raw_color_profile_size(image_handle);\n if (length > 0)\n {\n unsigned char\n *color_buffer;\n\n /*\n Read color profile.\n */ \n if ((MagickSizeType) length > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n color_buffer=(unsigned char *) AcquireMagickMemory(length);\n if (color_buffer != (unsigned char *) NULL)\n {\n error=heif_image_handle_get_raw_color_profile(image_handle,\n color_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n profile=BlobToStringInfo(color_buffer,length);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"icc\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n color_buffer=(unsigned char *) RelinquishMagickMemory(color_buffer);\n }\n#endif\n count=heif_image_handle_get_list_of_metadata_block_IDs(image_handle,\"Exif\",\n &exif_id,1);\n if (count > 0)\n {\n size_t\n exif_size;\n\n unsigned char\n *exif_buffer;\n\n /*\n Read Exif profile.\n */\n exif_size=heif_image_handle_get_metadata_size(image_handle,exif_id);\n if ((MagickSizeType) exif_size > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n exif_buffer=(unsigned char*) AcquireMagickMemory(exif_size);\n if (exif_buffer != (unsigned char*) NULL)\n {\n error=heif_image_handle_get_metadata(image_handle,\n exif_id,exif_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n /*\n The first 4 byte should be skipped since they indicate the\n offset to the start of the TIFF header of the Exif data.\n */\n profile=(StringInfo*) NULL;\n if (exif_size > 8)\n profile=BlobToStringInfo(exif_buffer+4,(size_t) exif_size-4);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"exif\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n exif_buffer=(unsigned char *) RelinquishMagickMemory(exif_buffer);\n }\n /*\n Set image size.\n */\n image->depth=8;\n image->columns=(size_t) heif_image_handle_get_width(image_handle);\n image->rows=(size_t) heif_image_handle_get_height(image_handle);\n if (image_info->ping != MagickFalse)\n {\n image->colorspace=YCbCrColorspace;\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n /*\n Copy HEIF image into ImageMagick data structures\n */\n (void) SetImageColorspace(image,YCbCrColorspace);\n decode_options=(struct heif_decoding_options *) NULL;\n option=GetImageOption(image_info,\"heic:preserve-orientation\");\n if (IsStringTrue(option) == MagickTrue)\n {\n decode_options=heif_decoding_options_alloc();\n decode_options->ignore_transformations=1;\n }\n else\n (void) SetImageProperty(image,\"exif:Orientation\",\"1\");\n error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr,\n heif_chroma_420,NULL);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n if (decode_options != (struct heif_decoding_options *) NULL)\n {\n /*\n Correct the width and height of the image.\n */\n image->columns=(size_t) heif_image_get_width(heif_image,heif_channel_Y);\n image->rows=(size_t) heif_image_get_height(heif_image,heif_channel_Y);\n status=SetImageExtent(image,image->columns,image->rows);\n heif_decoding_options_free(decode_options);\n if (status == MagickFalse)\n {\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n }\n p_y=heif_image_get_plane_readonly(heif_image,heif_channel_Y,&stride_y);\n p_cb=heif_image_get_plane_readonly(heif_image,heif_channel_Cb,&stride_cb);\n p_cr=heif_image_get_plane_readonly(heif_image,heif_channel_Cr,&stride_cr);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n PixelPacket\n *q;\n\n register ssize_t\n x;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum((unsigned char) p_y[y*\n stride_y+x]));\n SetPixelGreen(q,ScaleCharToQuantum((unsigned char) p_cb[(y/2)*\n stride_cb+x/2]));\n SetPixelBlue(q,ScaleCharToQuantum((unsigned char) p_cr[(y/2)*\n stride_cr+x/2]));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (const StringInfo *) NULL)\n (void) TransformImageColorspace(image,sRGBColorspace);\n return(GetFirstImageInList(image));\n}", "func_hash": 213031508242881886591813039418186858697, "file_name": "heic.c", "file_hash": 153082251729563235131038097030815774811, "cwe": ["CWE-125"], "cve": "CVE-2020-10251", "cve_desc": "In ImageMagick 7.0.9, an out-of-bounds read vulnerability exists within the ReadHEICImageByID function in coders\\heic.c. It can be triggered via an image with a width or height value that exceeds the actual size of the image.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10251"} {"idx": 381036, "project": "ImageMagick6", "commit_id": "3456724dff047db5adb32f8cf70c903c1b7d16d4", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/3456724dff047db5adb32f8cf70c903c1b7d16d4", "commit_message": "Always correct the width and height of the image.", "target": 0, "func": "static Image *ReadHEICImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n const StringInfo\n *profile;\n\n heif_item_id\n exif_id;\n\n Image\n *image;\n\n int\n count,\n stride_y,\n stride_cb,\n stride_cr;\n\n MagickBooleanType\n status;\n\n size_t\n length;\n\n ssize_t\n y;\n\n struct heif_context\n *heif_context;\n\n struct heif_decoding_options\n *decode_options;\n\n struct heif_error\n error;\n\n struct heif_image\n *heif_image;\n\n struct heif_image_handle\n *image_handle;\n\n const uint8_t\n *p_y,\n *p_cb,\n *p_cr;\n\n void\n *file_data;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (GetBlobSize(image) > (MagickSizeType) SSIZE_MAX)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n length=(size_t) GetBlobSize(image);\n file_data=AcquireMagickMemory(length);\n if (file_data == (void *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (ReadBlob(image,length,(unsigned char *) file_data) != (ssize_t) length)\n {\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n /*\n Decode HEIF file\n */\n heif_context=heif_context_alloc();\n error=heif_context_read_from_memory_without_copy(heif_context,file_data,\n length,NULL);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n image_handle=(struct heif_image_handle *) NULL;\n error=heif_context_get_primary_image_handle(heif_context,&image_handle);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n#if LIBHEIF_NUMERIC_VERSION >= 0x01040000\n length=heif_image_handle_get_raw_color_profile_size(image_handle);\n if (length > 0)\n {\n unsigned char\n *color_buffer;\n\n /*\n Read color profile.\n */ \n if ((MagickSizeType) length > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n color_buffer=(unsigned char *) AcquireMagickMemory(length);\n if (color_buffer != (unsigned char *) NULL)\n {\n error=heif_image_handle_get_raw_color_profile(image_handle,\n color_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n profile=BlobToStringInfo(color_buffer,length);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"icc\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n color_buffer=(unsigned char *) RelinquishMagickMemory(color_buffer);\n }\n#endif\n count=heif_image_handle_get_list_of_metadata_block_IDs(image_handle,\"Exif\",\n &exif_id,1);\n if (count > 0)\n {\n size_t\n exif_size;\n\n unsigned char\n *exif_buffer;\n\n /*\n Read Exif profile.\n */\n exif_size=heif_image_handle_get_metadata_size(image_handle,exif_id);\n if ((MagickSizeType) exif_size > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n exif_buffer=(unsigned char*) AcquireMagickMemory(exif_size);\n if (exif_buffer != (unsigned char*) NULL)\n {\n error=heif_image_handle_get_metadata(image_handle,\n exif_id,exif_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n /*\n The first 4 byte should be skipped since they indicate the\n offset to the start of the TIFF header of the Exif data.\n */\n profile=(StringInfo*) NULL;\n if (exif_size > 8)\n profile=BlobToStringInfo(exif_buffer+4,(size_t) exif_size-4);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"exif\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n exif_buffer=(unsigned char *) RelinquishMagickMemory(exif_buffer);\n }\n /*\n Set image size.\n */\n image->depth=8;\n image->columns=(size_t) heif_image_handle_get_width(image_handle);\n image->rows=(size_t) heif_image_handle_get_height(image_handle);\n if (image_info->ping != MagickFalse)\n {\n image->colorspace=YCbCrColorspace;\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n /*\n Copy HEIF image into ImageMagick data structures\n */\n (void) SetImageColorspace(image,YCbCrColorspace);\n decode_options=(struct heif_decoding_options *) NULL;\n option=GetImageOption(image_info,\"heic:preserve-orientation\");\n if (IsStringTrue(option) == MagickTrue)\n {\n decode_options=heif_decoding_options_alloc();\n decode_options->ignore_transformations=1;\n }\n else\n (void) SetImageProperty(image,\"exif:Orientation\",\"1\");\n error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr,\n heif_chroma_420,decode_options);\n if (decode_options != (struct heif_decoding_options *) NULL)\n heif_decoding_options_free(decode_options);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n /*\n Correct the width and height of the image.\n */\n image->columns=(size_t) heif_image_get_width(heif_image,heif_channel_Y);\n image->rows=(size_t) heif_image_get_height(heif_image,heif_channel_Y);\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n p_y=heif_image_get_plane_readonly(heif_image,heif_channel_Y,&stride_y);\n p_cb=heif_image_get_plane_readonly(heif_image,heif_channel_Cb,&stride_cb);\n p_cr=heif_image_get_plane_readonly(heif_image,heif_channel_Cr,&stride_cr);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n PixelPacket\n *q;\n\n register ssize_t\n x;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum((unsigned char) p_y[y*\n stride_y+x]));\n SetPixelGreen(q,ScaleCharToQuantum((unsigned char) p_cb[(y/2)*\n stride_cb+x/2]));\n SetPixelBlue(q,ScaleCharToQuantum((unsigned char) p_cr[(y/2)*\n stride_cr+x/2]));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (const StringInfo *) NULL)\n (void) TransformImageColorspace(image,sRGBColorspace);\n return(GetFirstImageInList(image));\n}", "func_hash": 192529277024779586852701465440932640084, "file_name": "heic.c", "file_hash": 46482764548237993158341127649970003471, "cwe": ["CWE-125"], "cve": "CVE-2020-10251", "cve_desc": "In ImageMagick 7.0.9, an out-of-bounds read vulnerability exists within the ReadHEICImageByID function in coders\\heic.c. It can be triggered via an image with a width or height value that exceeds the actual size of the image.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10251"} {"idx": 206468, "project": "linux", "commit_id": "fb18802a338b36f675a388fc03d2aa504a0d0899", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=fb18802a338b36f675a388fc03d2aa504a0d0899", "commit_message": "media: v4l: ioctl: Fix memory leak in video_usercopy\n\nWhen an IOCTL with argument size larger than 128 that also used array\narguments were handled, two memory allocations were made but alas, only\nthe latter one of them was released. This happened because there was only\na single local variable to hold such a temporary allocation.\n\nFix this by adding separate variables to hold the pointers to the\ntemporary allocations.\n\nReported-by: Arnd Bergmann \nReported-by: syzbot+1115e79c8df6472c612b@syzkaller.appspotmail.com\nFixes: d14e6d76ebf7 (\"[media] v4l: Add multi-planar ioctl handling code\")\nCc: stable@vger.kernel.org\nSigned-off-by: Sakari Ailus \nAcked-by: Arnd Bergmann \nAcked-by: Hans Verkuil \nReviewed-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "func": "video_usercopy(struct file *file, unsigned int orig_cmd, unsigned long arg,\n\t v4l2_kioctl func)\n{\n\tchar\tsbuf[128];\n\tvoid *mbuf = NULL;\n\tvoid\t*parg = (void *)arg;\n\tlong\terr = -EINVAL;\n\tbool\thas_array_args;\n\tbool\talways_copy = false;\n\tsize_t array_size = 0;\n\tvoid __user *user_ptr = NULL;\n\tvoid\t**kernel_ptr = NULL;\n\tunsigned int cmd = video_translate_cmd(orig_cmd);\n\tconst size_t ioc_size = _IOC_SIZE(cmd);\n\n\t/* Copy arguments into temp kernel buffer */\n\tif (_IOC_DIR(cmd) != _IOC_NONE) {\n\t\tif (ioc_size <= sizeof(sbuf)) {\n\t\t\tparg = sbuf;\n\t\t} else {\n\t\t\t/* too big to allocate from stack */\n\t\t\tmbuf = kvmalloc(ioc_size, GFP_KERNEL);\n\t\t\tif (NULL == mbuf)\n\t\t\t\treturn -ENOMEM;\n\t\t\tparg = mbuf;\n\t\t}\n\n\t\terr = video_get_user((void __user *)arg, parg, cmd,\n\t\t\t\t orig_cmd, &always_copy);\n\t\tif (err)\n\t\t\tgoto out;\n\t}\n\n\terr = check_array_args(cmd, parg, &array_size, &user_ptr, &kernel_ptr);\n\tif (err < 0)\n\t\tgoto out;\n\thas_array_args = err;\n\n\tif (has_array_args) {\n\t\t/*\n\t\t * When adding new types of array args, make sure that the\n\t\t * parent argument to ioctl (which contains the pointer to the\n\t\t * array) fits into sbuf (so that mbuf will still remain\n\t\t * unused up to here).\n\t\t */\n\t\tmbuf = kvmalloc(array_size, GFP_KERNEL);\n\t\terr = -ENOMEM;\n\t\tif (NULL == mbuf)\n\t\t\tgoto out_array_args;\n\t\terr = -EFAULT;\n\t\tif (in_compat_syscall())\n\t\t\terr = v4l2_compat_get_array_args(file, mbuf, user_ptr,\n\t\t\t\t\t\t\t array_size, orig_cmd,\n\t\t\t\t\t\t\t parg);\n\t\telse\n\t\t\terr = copy_from_user(mbuf, user_ptr, array_size) ?\n\t\t\t\t\t\t\t\t-EFAULT : 0;\n\t\tif (err)\n\t\t\tgoto out_array_args;\n\t\t*kernel_ptr = mbuf;\n\t}\n\n\t/* Handles IOCTL */\n\terr = func(file, cmd, parg);\n\tif (err == -ENOTTY || err == -ENOIOCTLCMD) {\n\t\terr = -ENOTTY;\n\t\tgoto out;\n\t}\n\n\tif (err == 0) {\n\t\tif (cmd == VIDIOC_DQBUF)\n\t\t\ttrace_v4l2_dqbuf(video_devdata(file)->minor, parg);\n\t\telse if (cmd == VIDIOC_QBUF)\n\t\t\ttrace_v4l2_qbuf(video_devdata(file)->minor, parg);\n\t}\n\n\tif (has_array_args) {\n\t\t*kernel_ptr = (void __force *)user_ptr;\n\t\tif (in_compat_syscall()) {\n\t\t\tint put_err;\n\n\t\t\tput_err = v4l2_compat_put_array_args(file, user_ptr, mbuf,\n\t\t\t\t\t\t\t array_size, orig_cmd,\n\t\t\t\t\t\t\t parg);\n\t\t\tif (put_err)\n\t\t\t\terr = put_err;\n\t\t} else if (copy_to_user(user_ptr, mbuf, array_size)) {\n\t\t\terr = -EFAULT;\n\t\t}\n\t\tgoto out_array_args;\n\t}\n\t/*\n\t * Some ioctls can return an error, but still have valid\n\t * results that must be returned.\n\t */\n\tif (err < 0 && !always_copy)\n\t\tgoto out;\n\nout_array_args:\n\tif (video_put_user((void __user *)arg, parg, cmd, orig_cmd))\n\t\terr = -EFAULT;\nout:\n\tkvfree(mbuf);\n\treturn err;\n}", "func_hash": 280691480045664692791764886060113103944, "file_name": "v4l2-ioctl.c", "file_hash": 103824589512750105989571674404544579764, "cwe": ["CWE-401"], "cve": "CVE-2021-30002", "cve_desc": "An issue was discovered in the Linux kernel before 5.11.3 when a webcam device exists. video_usercopy in drivers/media/v4l2-core/v4l2-ioctl.c has a memory leak for large arguments, aka CID-fb18802a338b.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30002"} {"idx": 381516, "project": "linux", "commit_id": "fb18802a338b36f675a388fc03d2aa504a0d0899", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=fb18802a338b36f675a388fc03d2aa504a0d0899", "commit_message": "media: v4l: ioctl: Fix memory leak in video_usercopy\n\nWhen an IOCTL with argument size larger than 128 that also used array\narguments were handled, two memory allocations were made but alas, only\nthe latter one of them was released. This happened because there was only\na single local variable to hold such a temporary allocation.\n\nFix this by adding separate variables to hold the pointers to the\ntemporary allocations.\n\nReported-by: Arnd Bergmann \nReported-by: syzbot+1115e79c8df6472c612b@syzkaller.appspotmail.com\nFixes: d14e6d76ebf7 (\"[media] v4l: Add multi-planar ioctl handling code\")\nCc: stable@vger.kernel.org\nSigned-off-by: Sakari Ailus \nAcked-by: Arnd Bergmann \nAcked-by: Hans Verkuil \nReviewed-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "func": "video_usercopy(struct file *file, unsigned int orig_cmd, unsigned long arg,\n\t v4l2_kioctl func)\n{\n\tchar\tsbuf[128];\n\tvoid *mbuf = NULL, *array_buf = NULL;\n\tvoid\t*parg = (void *)arg;\n\tlong\terr = -EINVAL;\n\tbool\thas_array_args;\n\tbool\talways_copy = false;\n\tsize_t array_size = 0;\n\tvoid __user *user_ptr = NULL;\n\tvoid\t**kernel_ptr = NULL;\n\tunsigned int cmd = video_translate_cmd(orig_cmd);\n\tconst size_t ioc_size = _IOC_SIZE(cmd);\n\n\t/* Copy arguments into temp kernel buffer */\n\tif (_IOC_DIR(cmd) != _IOC_NONE) {\n\t\tif (ioc_size <= sizeof(sbuf)) {\n\t\t\tparg = sbuf;\n\t\t} else {\n\t\t\t/* too big to allocate from stack */\n\t\t\tmbuf = kvmalloc(ioc_size, GFP_KERNEL);\n\t\t\tif (NULL == mbuf)\n\t\t\t\treturn -ENOMEM;\n\t\t\tparg = mbuf;\n\t\t}\n\n\t\terr = video_get_user((void __user *)arg, parg, cmd,\n\t\t\t\t orig_cmd, &always_copy);\n\t\tif (err)\n\t\t\tgoto out;\n\t}\n\n\terr = check_array_args(cmd, parg, &array_size, &user_ptr, &kernel_ptr);\n\tif (err < 0)\n\t\tgoto out;\n\thas_array_args = err;\n\n\tif (has_array_args) {\n\t\tarray_buf = kvmalloc(array_size, GFP_KERNEL);\n\t\terr = -ENOMEM;\n\t\tif (array_buf == NULL)\n\t\t\tgoto out_array_args;\n\t\terr = -EFAULT;\n\t\tif (in_compat_syscall())\n\t\t\terr = v4l2_compat_get_array_args(file, array_buf,\n\t\t\t\t\t\t\t user_ptr, array_size,\n\t\t\t\t\t\t\t orig_cmd, parg);\n\t\telse\n\t\t\terr = copy_from_user(array_buf, user_ptr, array_size) ?\n\t\t\t\t\t\t\t\t-EFAULT : 0;\n\t\tif (err)\n\t\t\tgoto out_array_args;\n\t\t*kernel_ptr = array_buf;\n\t}\n\n\t/* Handles IOCTL */\n\terr = func(file, cmd, parg);\n\tif (err == -ENOTTY || err == -ENOIOCTLCMD) {\n\t\terr = -ENOTTY;\n\t\tgoto out;\n\t}\n\n\tif (err == 0) {\n\t\tif (cmd == VIDIOC_DQBUF)\n\t\t\ttrace_v4l2_dqbuf(video_devdata(file)->minor, parg);\n\t\telse if (cmd == VIDIOC_QBUF)\n\t\t\ttrace_v4l2_qbuf(video_devdata(file)->minor, parg);\n\t}\n\n\tif (has_array_args) {\n\t\t*kernel_ptr = (void __force *)user_ptr;\n\t\tif (in_compat_syscall()) {\n\t\t\tint put_err;\n\n\t\t\tput_err = v4l2_compat_put_array_args(file, user_ptr,\n\t\t\t\t\t\t\t array_buf,\n\t\t\t\t\t\t\t array_size,\n\t\t\t\t\t\t\t orig_cmd, parg);\n\t\t\tif (put_err)\n\t\t\t\terr = put_err;\n\t\t} else if (copy_to_user(user_ptr, array_buf, array_size)) {\n\t\t\terr = -EFAULT;\n\t\t}\n\t\tgoto out_array_args;\n\t}\n\t/*\n\t * Some ioctls can return an error, but still have valid\n\t * results that must be returned.\n\t */\n\tif (err < 0 && !always_copy)\n\t\tgoto out;\n\nout_array_args:\n\tif (video_put_user((void __user *)arg, parg, cmd, orig_cmd))\n\t\terr = -EFAULT;\nout:\n\tkvfree(array_buf);\n\tkvfree(mbuf);\n\treturn err;\n}", "func_hash": 139571859309538876044647515341352302583, "file_name": "v4l2-ioctl.c", "file_hash": 37584717290370939425987581081557500186, "cwe": ["CWE-401"], "cve": "CVE-2021-30002", "cve_desc": "An issue was discovered in the Linux kernel before 5.11.3 when a webcam device exists. video_usercopy in drivers/media/v4l2-core/v4l2-ioctl.c has a memory leak for large arguments, aka CID-fb18802a338b.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30002"} {"idx": 206517, "project": "teeworlds", "commit_id": "c68402fa7e279d42886d5951d1ea8ac2facc1ea5", "project_url": "https://github.com/teeworlds/teeworlds", "commit_url": "https://github.com/teeworlds/teeworlds/commit/c68402fa7e279d42886d5951d1ea8ac2facc1ea5", "commit_message": "changed a check", "target": 1, "func": "int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)\n{\n\tCNetChunk Packet;\n\tif(!pMsg)\n\t\treturn -1;\n\n\t// drop packet to dummy client\n\tif(0 <= ClientID && ClientID < MAX_CLIENTS && GameServer()->IsClientBot(ClientID))\n\t\treturn 0;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = ClientID;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\t// write message to demo recorder\n\tif(!(Flags&MSGFLAG_NORECORD))\n\t\tm_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t{\n\t\tif(ClientID == -1)\n\t\t{\n\t\t\t// broadcast\n\t\t\tint i;\n\t\t\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\tif(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)\n\t\t\t\t{\n\t\t\t\t\tPacket.m_ClientID = i;\n\t\t\t\t\tm_NetServer.Send(&Packet);\n\t\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_NetServer.Send(&Packet);\n\t}\n\treturn 0;\n}", "func_hash": 145222806457384873160648923667467705022, "file_name": "server.cpp", "file_hash": 234614107574548158053288772073851135034, "cwe": ["CWE-703"], "cve": "CVE-2020-12066", "cve_desc": "CServer::SendMsg in engine/server/server.cpp in Teeworlds 0.7.x before 0.7.5 allows remote attackers to shut down the server.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12066"} {"idx": 381986, "project": "teeworlds", "commit_id": "c68402fa7e279d42886d5951d1ea8ac2facc1ea5", "project_url": "https://github.com/teeworlds/teeworlds", "commit_url": "https://github.com/teeworlds/teeworlds/commit/c68402fa7e279d42886d5951d1ea8ac2facc1ea5", "commit_message": "changed a check", "target": 0, "func": "int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)\n{\n\tCNetChunk Packet;\n\tif(!pMsg)\n\t\treturn -1;\n\n\t// drop invalid packet\n\tif(ClientID != -1 && (ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY || m_aClients[ClientID].m_Quitting))\n\t\treturn 0;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = ClientID;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\t// write message to demo recorder\n\tif(!(Flags&MSGFLAG_NORECORD))\n\t\tm_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t{\n\t\tif(ClientID == -1)\n\t\t{\n\t\t\t// broadcast\n\t\t\tint i;\n\t\t\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\tif(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)\n\t\t\t\t{\n\t\t\t\t\tPacket.m_ClientID = i;\n\t\t\t\t\tm_NetServer.Send(&Packet);\n\t\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_NetServer.Send(&Packet);\n\t}\n\treturn 0;\n}", "func_hash": 305700993158187652878459248339558096784, "file_name": "server.cpp", "file_hash": 212778892116100883921235888860552189280, "cwe": ["CWE-703"], "cve": "CVE-2020-12066", "cve_desc": "CServer::SendMsg in engine/server/server.cpp in Teeworlds 0.7.x before 0.7.5 allows remote attackers to shut down the server.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12066"} {"idx": 206554, "project": "php-src", "commit_id": "7cf7148a8f8f4f55fb04de2a517d740bb6253eac", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=7cf7148a8f8f4f55fb04de2a517d740bb6253eac", "commit_message": "Fix bug #78069 - Out-of-bounds read in iconv.c:_php_iconv_mime_decode() due to integer overflow", "target": 1, "func": "static php_iconv_err_t _php_iconv_mime_decode(smart_str *pretval, const char *str, size_t str_nbytes, const char *enc, const char **next_pos, int mode)\n{\n\tphp_iconv_err_t err = PHP_ICONV_ERR_SUCCESS;\n\n\ticonv_t cd = (iconv_t)(-1), cd_pl = (iconv_t)(-1);\n\n\tconst char *p1;\n\tsize_t str_left;\n\tunsigned int scan_stat = 0;\n\tconst char *csname = NULL;\n\tsize_t csname_len;\n\tconst char *encoded_text = NULL;\n\tsize_t encoded_text_len = 0;\n\tconst char *encoded_word = NULL;\n\tconst char *spaces = NULL;\n\n\tphp_iconv_enc_scheme_t enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = NULL;\n\t}\n\n\tcd_pl = iconv_open(enc, ICONV_ASCII_ENCODING);\n\n\tif (cd_pl == (iconv_t)(-1)) {\n#if ICONV_SUPPORTS_ERRNO\n\t\tif (errno == EINVAL) {\n\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t} else {\n\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t}\n#else\n\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\tgoto out;\n\t}\n\n\tp1 = str;\n\tfor (str_left = str_nbytes; str_left > 0; str_left--, p1++) {\n\t\tint eos = 0;\n\n\t\tswitch (scan_stat) {\n\t\t\tcase 0: /* expecting any character */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t': /* a chunk of whitespaces */\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\terr = _php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif (mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 1: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif (*p1 == '\\r' || *p1 == '\\n') {\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t}\n\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcsname = p1 + 1;\n\t\t\t\tscan_stat = 2;\n\t\t\t\tbreak;\n\n\t\t\tcase 2: /* expecting a charset name */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '?': /* normal delimiter: encoding scheme follows */\n\t\t\t\t\t\tscan_stat = 3;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '*': /* new style delimiter: locale id follows */\n\t\t\t\t\t\tscan_stat = 10;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\r': case '\\n': /* not an encoded-word */\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '?', cd_pl);\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, csname, (size_t)((p1 + 1) - csname), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcsname = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (scan_stat != 2) {\n\t\t\t\t\tchar tmpbuf[80];\n\n\t\t\t\t\tif (csname == NULL) {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\n\t\t\t\t\tcsname_len = (size_t)(p1 - csname);\n\n\t\t\t\t\tif (csname_len > sizeof(tmpbuf) - 1) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tmemcpy(tmpbuf, csname, csname_len);\n\t\t\t\t\ttmpbuf[csname_len] = '\\0';\n\n\t\t\t\t\tif (cd != (iconv_t)(-1)) {\n\t\t\t\t\t\ticonv_close(cd);\n\t\t\t\t\t}\n\n\t\t\t\t\tcd = iconv_open(enc, tmpbuf);\n\n\t\t\t\t\tif (cd == (iconv_t)(-1)) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t/* Bad character set, but the user wants us to\n\t\t\t\t\t\t\t * press on. In this case, we'll just insert the\n\t\t\t\t\t\t\t * undecoded encoded word, since there isn't really\n\t\t\t\t\t\t\t * a more sensible behaviour available; the only\n\t\t\t\t\t\t\t * other options are to swallow the encoded word\n\t\t\t\t\t\t\t * entirely or decode it with an arbitrarily chosen\n\t\t\t\t\t\t\t * single byte encoding, both of which seem to have\n\t\t\t\t\t\t\t * a higher WTF factor than leaving it undecoded.\n\t\t\t\t\t\t\t *\n\t\t\t\t\t\t\t * Given this approach, we need to skip ahead to\n\t\t\t\t\t\t\t * the end of the encoded word. */\n\t\t\t\t\t\t\tint qmarks = 2;\n\t\t\t\t\t\t\twhile (qmarks > 0 && str_left > 1) {\n\t\t\t\t\t\t\t\tif (*(++p1) == '?') {\n\t\t\t\t\t\t\t\t\t--qmarks;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Look ahead to check for the terminating = that\n\t\t\t\t\t\t\t * should be there as well; if it's there, we'll\n\t\t\t\t\t\t\t * also include that. If it's not, there isn't much\n\t\t\t\t\t\t\t * we can do at this point. */\n\t\t\t\t\t\t\tif (*(p1 + 1) == '=') {\n\t\t\t\t\t\t\t\t++p1;\n\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Let's go back and see if there are further\n\t\t\t\t\t\t\t * encoded words or bare content, and hope they\n\t\t\t\t\t\t\t * might actually have a valid character set. */\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n#if ICONV_SUPPORTS_ERRNO\n\t\t\t\t\t\t\tif (errno == EINVAL) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 3: /* expecting a encoding scheme specifier */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase 'b':\n\t\t\t\t\tcase 'B':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'q':\n\t\t\t\t\tcase 'Q':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_QPRINT;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 4: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tencoded_text = p1 + 1;\n\t\t\t\tscan_stat = 5;\n\t\t\t\tbreak;\n\n\t\t\tcase 5: /* expecting an encoded portion */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tencoded_text_len = (size_t)(p1 - encoded_text);\n\t\t\t\t\tscan_stat = 6;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 7: /* expecting a \"\\n\" character */\n\t\t\t\tif (*p1 == '\\n') {\n\t\t\t\t\tscan_stat = 8;\n\t\t\t\t} else {\n\t\t\t\t\t/* bare CR */\n\t\t\t\t\t_php_iconv_appendc(pretval, '\\r', cd_pl);\n\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\tscan_stat = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 8: /* checking whether the following line is part of a\n\t\t\t\t\t folded header */\n\t\t\t\tif (*p1 != ' ' && *p1 != '\\t') {\n\t\t\t\t\t--p1;\n\t\t\t\t\tstr_left = 1; /* quit_loop */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (encoded_word == NULL) {\n\t\t\t\t\t_php_iconv_appendc(pretval, ' ', cd_pl);\n\t\t\t\t}\n\t\t\t\tspaces = NULL;\n\t\t\t\tscan_stat = 11;\n\t\t\t\tbreak;\n\n\t\t\tcase 6: /* expecting a End-Of-Chunk character \"=\" */\n\t\t\t\tif (*p1 != '=') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscan_stat = 9;\n\t\t\t\tif (str_left == 1) {\n\t\t\t\t\teos = 1;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tcase 9: /* choice point, seeing what to do next.*/\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t/* Handle non-RFC-compliant formats\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * RFC2047 requires the character that comes right\n\t\t\t\t\t\t * after an encoded word (chunk) to be a whitespace,\n\t\t\t\t\t\t * while there are lots of broken implementations that\n\t\t\t\t\t\t * generate such malformed headers that don't fulfill\n\t\t\t\t\t\t * that requirement.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!eos) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tcase '\\r': case '\\n': case ' ': case '\\t': {\n\t\t\t\t\t\tzend_string *decoded_text;\n\n\t\t\t\t\t\tswitch (enc_scheme) {\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_BASE64:\n\t\t\t\t\t\t\t\tdecoded_text = php_base64_decode((unsigned char*)encoded_text, encoded_text_len);\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_QPRINT:\n\t\t\t\t\t\t\t\tdecoded_text = php_quot_print_decode((unsigned char*)encoded_text, encoded_text_len, 1);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tdecoded_text = NULL;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (decoded_text == NULL) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, ZSTR_VAL(decoded_text), ZSTR_LEN(decoded_text), cd);\n\t\t\t\t\t\tzend_string_release(decoded_text);\n\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)(p1 - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (eos) { /* reached end-of-string. done. */\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tswitch (*p1) {\n\t\t\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase ' ': case '\\t': /* medial whitespaces */\n\t\t\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} break;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 10: /* expects a language specifier. dismiss it for now */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tscan_stat = 3;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 11: /* expecting a chunk of whitespaces */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (spaces != NULL && encoded_word == NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\tif (spaces != NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 12: /* expecting a non-encoded word */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (!(mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tswitch (scan_stat) {\n\t\tcase 0: case 8: case 11: case 12:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\tif (scan_stat == 1) {\n\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t}\n\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t} else {\n\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\tgoto out;\n\t\t\t}\n\t}\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = p1;\n\t}\n\n\tsmart_str_0(pretval);\nout:\n\tif (cd != (iconv_t)(-1)) {\n\t\ticonv_close(cd);\n\t}\n\tif (cd_pl != (iconv_t)(-1)) {\n\t\ticonv_close(cd_pl);\n\t}\n\treturn err;\n}", "func_hash": 75655294989171103317638219740496299808, "file_name": "iconv.c", "file_hash": 119096787585162882446829234974432672598, "cwe": ["CWE-125"], "cve": "CVE-2019-11039", "cve_desc": "Function iconv_mime_decode_headers() in PHP versions 7.1.x below 7.1.30, 7.2.x below 7.2.19 and 7.3.x below 7.3.6 may perform out-of-buffer read due to integer overflow when parsing MIME headers. This may lead to information disclosure or crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11039"} {"idx": 382780, "project": "php-src", "commit_id": "7cf7148a8f8f4f55fb04de2a517d740bb6253eac", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=7cf7148a8f8f4f55fb04de2a517d740bb6253eac", "commit_message": "Fix bug #78069 - Out-of-bounds read in iconv.c:_php_iconv_mime_decode() due to integer overflow", "target": 0, "func": "static php_iconv_err_t _php_iconv_mime_decode(smart_str *pretval, const char *str, size_t str_nbytes, const char *enc, const char **next_pos, int mode)\n{\n\tphp_iconv_err_t err = PHP_ICONV_ERR_SUCCESS;\n\n\ticonv_t cd = (iconv_t)(-1), cd_pl = (iconv_t)(-1);\n\n\tconst char *p1;\n\tsize_t str_left;\n\tunsigned int scan_stat = 0;\n\tconst char *csname = NULL;\n\tsize_t csname_len;\n\tconst char *encoded_text = NULL;\n\tsize_t encoded_text_len = 0;\n\tconst char *encoded_word = NULL;\n\tconst char *spaces = NULL;\n\n\tphp_iconv_enc_scheme_t enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = NULL;\n\t}\n\n\tcd_pl = iconv_open(enc, ICONV_ASCII_ENCODING);\n\n\tif (cd_pl == (iconv_t)(-1)) {\n#if ICONV_SUPPORTS_ERRNO\n\t\tif (errno == EINVAL) {\n\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t} else {\n\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t}\n#else\n\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\tgoto out;\n\t}\n\n\tp1 = str;\n\tfor (str_left = str_nbytes; str_left > 0; str_left--, p1++) {\n\t\tint eos = 0;\n\n\t\tswitch (scan_stat) {\n\t\t\tcase 0: /* expecting any character */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t': /* a chunk of whitespaces */\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\terr = _php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif (mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 1: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif (*p1 == '\\r' || *p1 == '\\n') {\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t}\n\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcsname = p1 + 1;\n\t\t\t\tscan_stat = 2;\n\t\t\t\tbreak;\n\n\t\t\tcase 2: /* expecting a charset name */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '?': /* normal delimiter: encoding scheme follows */\n\t\t\t\t\t\tscan_stat = 3;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '*': /* new style delimiter: locale id follows */\n\t\t\t\t\t\tscan_stat = 10;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\r': case '\\n': /* not an encoded-word */\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '?', cd_pl);\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, csname, (size_t)((p1 + 1) - csname), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcsname = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (scan_stat != 2) {\n\t\t\t\t\tchar tmpbuf[80];\n\n\t\t\t\t\tif (csname == NULL) {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\n\t\t\t\t\tcsname_len = (size_t)(p1 - csname);\n\n\t\t\t\t\tif (csname_len > sizeof(tmpbuf) - 1) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tmemcpy(tmpbuf, csname, csname_len);\n\t\t\t\t\ttmpbuf[csname_len] = '\\0';\n\n\t\t\t\t\tif (cd != (iconv_t)(-1)) {\n\t\t\t\t\t\ticonv_close(cd);\n\t\t\t\t\t}\n\n\t\t\t\t\tcd = iconv_open(enc, tmpbuf);\n\n\t\t\t\t\tif (cd == (iconv_t)(-1)) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t/* Bad character set, but the user wants us to\n\t\t\t\t\t\t\t * press on. In this case, we'll just insert the\n\t\t\t\t\t\t\t * undecoded encoded word, since there isn't really\n\t\t\t\t\t\t\t * a more sensible behaviour available; the only\n\t\t\t\t\t\t\t * other options are to swallow the encoded word\n\t\t\t\t\t\t\t * entirely or decode it with an arbitrarily chosen\n\t\t\t\t\t\t\t * single byte encoding, both of which seem to have\n\t\t\t\t\t\t\t * a higher WTF factor than leaving it undecoded.\n\t\t\t\t\t\t\t *\n\t\t\t\t\t\t\t * Given this approach, we need to skip ahead to\n\t\t\t\t\t\t\t * the end of the encoded word. */\n\t\t\t\t\t\t\tint qmarks = 2;\n\t\t\t\t\t\t\twhile (qmarks > 0 && str_left > 1) {\n\t\t\t\t\t\t\t\tif (*(++p1) == '?') {\n\t\t\t\t\t\t\t\t\t--qmarks;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Look ahead to check for the terminating = that\n\t\t\t\t\t\t\t * should be there as well; if it's there, we'll\n\t\t\t\t\t\t\t * also include that. If it's not, there isn't much\n\t\t\t\t\t\t\t * we can do at this point. */\n\t\t\t\t\t\t\tif (*(p1 + 1) == '=') {\n\t\t\t\t\t\t\t\t++p1;\n\t\t\t\t\t\t\t\tif (str_left > 1) {\n\t\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Let's go back and see if there are further\n\t\t\t\t\t\t\t * encoded words or bare content, and hope they\n\t\t\t\t\t\t\t * might actually have a valid character set. */\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n#if ICONV_SUPPORTS_ERRNO\n\t\t\t\t\t\t\tif (errno == EINVAL) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 3: /* expecting a encoding scheme specifier */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase 'b':\n\t\t\t\t\tcase 'B':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'q':\n\t\t\t\t\tcase 'Q':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_QPRINT;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 4: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tencoded_text = p1 + 1;\n\t\t\t\tscan_stat = 5;\n\t\t\t\tbreak;\n\n\t\t\tcase 5: /* expecting an encoded portion */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tencoded_text_len = (size_t)(p1 - encoded_text);\n\t\t\t\t\tscan_stat = 6;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 7: /* expecting a \"\\n\" character */\n\t\t\t\tif (*p1 == '\\n') {\n\t\t\t\t\tscan_stat = 8;\n\t\t\t\t} else {\n\t\t\t\t\t/* bare CR */\n\t\t\t\t\t_php_iconv_appendc(pretval, '\\r', cd_pl);\n\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\tscan_stat = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 8: /* checking whether the following line is part of a\n\t\t\t\t\t folded header */\n\t\t\t\tif (*p1 != ' ' && *p1 != '\\t') {\n\t\t\t\t\t--p1;\n\t\t\t\t\tstr_left = 1; /* quit_loop */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (encoded_word == NULL) {\n\t\t\t\t\t_php_iconv_appendc(pretval, ' ', cd_pl);\n\t\t\t\t}\n\t\t\t\tspaces = NULL;\n\t\t\t\tscan_stat = 11;\n\t\t\t\tbreak;\n\n\t\t\tcase 6: /* expecting a End-Of-Chunk character \"=\" */\n\t\t\t\tif (*p1 != '=') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscan_stat = 9;\n\t\t\t\tif (str_left == 1) {\n\t\t\t\t\teos = 1;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tcase 9: /* choice point, seeing what to do next.*/\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t/* Handle non-RFC-compliant formats\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * RFC2047 requires the character that comes right\n\t\t\t\t\t\t * after an encoded word (chunk) to be a whitespace,\n\t\t\t\t\t\t * while there are lots of broken implementations that\n\t\t\t\t\t\t * generate such malformed headers that don't fulfill\n\t\t\t\t\t\t * that requirement.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!eos) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tcase '\\r': case '\\n': case ' ': case '\\t': {\n\t\t\t\t\t\tzend_string *decoded_text;\n\n\t\t\t\t\t\tswitch (enc_scheme) {\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_BASE64:\n\t\t\t\t\t\t\t\tdecoded_text = php_base64_decode((unsigned char*)encoded_text, encoded_text_len);\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_QPRINT:\n\t\t\t\t\t\t\t\tdecoded_text = php_quot_print_decode((unsigned char*)encoded_text, encoded_text_len, 1);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tdecoded_text = NULL;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (decoded_text == NULL) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, ZSTR_VAL(decoded_text), ZSTR_LEN(decoded_text), cd);\n\t\t\t\t\t\tzend_string_release(decoded_text);\n\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)(p1 - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (eos) { /* reached end-of-string. done. */\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tswitch (*p1) {\n\t\t\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase ' ': case '\\t': /* medial whitespaces */\n\t\t\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} break;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 10: /* expects a language specifier. dismiss it for now */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tscan_stat = 3;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 11: /* expecting a chunk of whitespaces */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (spaces != NULL && encoded_word == NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\tif (spaces != NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 12: /* expecting a non-encoded word */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (!(mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tswitch (scan_stat) {\n\t\tcase 0: case 8: case 11: case 12:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\tif (scan_stat == 1) {\n\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t}\n\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t} else {\n\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\tgoto out;\n\t\t\t}\n\t}\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = p1;\n\t}\n\n\tsmart_str_0(pretval);\nout:\n\tif (cd != (iconv_t)(-1)) {\n\t\ticonv_close(cd);\n\t}\n\tif (cd_pl != (iconv_t)(-1)) {\n\t\ticonv_close(cd_pl);\n\t}\n\treturn err;\n}", "func_hash": 318453555377892401808100320722436007857, "file_name": "iconv.c", "file_hash": 193292424036730772428759775185913821065, "cwe": ["CWE-125"], "cve": "CVE-2019-11039", "cve_desc": "Function iconv_mime_decode_headers() in PHP versions 7.1.x below 7.1.30, 7.2.x below 7.2.19 and 7.3.x below 7.3.6 may perform out-of-buffer read due to integer overflow when parsing MIME headers. This may lead to information disclosure or crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11039"} {"idx": 206559, "project": "gssproxy", "commit_id": "cb761412e299ef907f22cd7c4146d50c8a792003", "project_url": "https://github.com/gssapi/gssproxy", "commit_url": "https://github.com/gssapi/gssproxy/commit/cb761412e299ef907f22cd7c4146d50c8a792003", "commit_message": "Unlock cond_mutex before pthread exit in gp_worker_main()\n\nSigned-off-by: GuiYao \n[rharwood@redhat.com: whitespace, tweak commit message]\nReviewed-by: Robbie Harwood ", "target": 1, "func": "static void *gp_worker_main(void *pvt)\n{\n struct gp_thread *t = (struct gp_thread *)pvt;\n struct gp_query *q = NULL;\n char dummy = 0;\n int ret;\n\n while (!t->pool->shutdown) {\n\n /* initialize debug client id to 0 until work is scheduled */\n gp_debug_set_conn_id(0);\n\n /* ======> COND_MUTEX */\n pthread_mutex_lock(&t->cond_mutex);\n while (t->query == NULL) {\n /* wait for next query */\n pthread_cond_wait(&t->cond_wakeup, &t->cond_mutex);\n if (t->pool->shutdown) {\n pthread_exit(NULL);\n }\n }\n\n /* grab the query off the shared pointer */\n q = t->query;\n t->query = NULL;\n\n /* <====== COND_MUTEX */\n pthread_mutex_unlock(&t->cond_mutex);\n\n /* set client id before hndling requests */\n gp_debug_set_conn_id(gp_conn_get_cid(q->conn));\n\n /* handle the client request */\n GPDEBUGN(3, \"[status] Handling query input: %p (%zu)\\n\", q->buffer,\n q->buflen);\n gp_handle_query(t->pool, q);\n GPDEBUGN(3 ,\"[status] Handling query output: %p (%zu)\\n\", q->buffer,\n q->buflen);\n\n /* now get lock on main queue, to play with the reply list */\n /* ======> POOL LOCK */\n pthread_mutex_lock(&t->pool->lock);\n\n /* put back query so that dispatcher can send reply */\n q->next = t->pool->reply_list;\n t->pool->reply_list = q;\n\n /* add us back to the free list but only if we are not\n * shutting down */\n if (!t->pool->shutdown) {\n LIST_DEL(t->pool->busy_list, t);\n LIST_ADD(t->pool->free_list, t);\n }\n\n /* <====== POOL LOCK */\n pthread_mutex_unlock(&t->pool->lock);\n\n /* and wake up dispatcher so it will handle it */\n ret = write(t->pool->sig_pipe[1], &dummy, 1);\n if (ret == -1) {\n GPERROR(\"Failed to signal dispatcher!\");\n }\n }\n\n pthread_exit(NULL);\n}", "func_hash": 324156952033520733425641915289050741451, "file_name": "gp_workers.c", "file_hash": 50599271153021979744721029704972263777, "cwe": ["CWE-667"], "cve": "CVE-2020-12658", "cve_desc": "gssproxy (aka gss-proxy) before 0.8.3 does not unlock cond_mutex before pthread exit in gp_worker_main() in gp_workers.c. NOTE: An upstream comment states \"We are already on a shutdown path when running the code in question, so a DoS there doesn't make any sense, and there has been no additional information provided us (as upstream) to indicate why this would be a problem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12658"} {"idx": 382874, "project": "gssproxy", "commit_id": "cb761412e299ef907f22cd7c4146d50c8a792003", "project_url": "https://github.com/gssapi/gssproxy", "commit_url": "https://github.com/gssapi/gssproxy/commit/cb761412e299ef907f22cd7c4146d50c8a792003", "commit_message": "Unlock cond_mutex before pthread exit in gp_worker_main()\n\nSigned-off-by: GuiYao \n[rharwood@redhat.com: whitespace, tweak commit message]\nReviewed-by: Robbie Harwood ", "target": 0, "func": "static void *gp_worker_main(void *pvt)\n{\n struct gp_thread *t = (struct gp_thread *)pvt;\n struct gp_query *q = NULL;\n char dummy = 0;\n int ret;\n\n while (!t->pool->shutdown) {\n\n /* initialize debug client id to 0 until work is scheduled */\n gp_debug_set_conn_id(0);\n\n /* ======> COND_MUTEX */\n pthread_mutex_lock(&t->cond_mutex);\n while (t->query == NULL) {\n /* wait for next query */\n pthread_cond_wait(&t->cond_wakeup, &t->cond_mutex);\n if (t->pool->shutdown) {\n pthread_mutex_unlock(&t->cond_mutex);\n pthread_exit(NULL);\n }\n }\n\n /* grab the query off the shared pointer */\n q = t->query;\n t->query = NULL;\n\n /* <====== COND_MUTEX */\n pthread_mutex_unlock(&t->cond_mutex);\n\n /* set client id before hndling requests */\n gp_debug_set_conn_id(gp_conn_get_cid(q->conn));\n\n /* handle the client request */\n GPDEBUGN(3, \"[status] Handling query input: %p (%zu)\\n\", q->buffer,\n q->buflen);\n gp_handle_query(t->pool, q);\n GPDEBUGN(3 ,\"[status] Handling query output: %p (%zu)\\n\", q->buffer,\n q->buflen);\n\n /* now get lock on main queue, to play with the reply list */\n /* ======> POOL LOCK */\n pthread_mutex_lock(&t->pool->lock);\n\n /* put back query so that dispatcher can send reply */\n q->next = t->pool->reply_list;\n t->pool->reply_list = q;\n\n /* add us back to the free list but only if we are not\n * shutting down */\n if (!t->pool->shutdown) {\n LIST_DEL(t->pool->busy_list, t);\n LIST_ADD(t->pool->free_list, t);\n }\n\n /* <====== POOL LOCK */\n pthread_mutex_unlock(&t->pool->lock);\n\n /* and wake up dispatcher so it will handle it */\n ret = write(t->pool->sig_pipe[1], &dummy, 1);\n if (ret == -1) {\n GPERROR(\"Failed to signal dispatcher!\");\n }\n }\n\n pthread_exit(NULL);\n}", "func_hash": 169377863966060863826347264233780759785, "file_name": "gp_workers.c", "file_hash": 12158970781137989442864047714961133761, "cwe": ["CWE-667"], "cve": "CVE-2020-12658", "cve_desc": "gssproxy (aka gss-proxy) before 0.8.3 does not unlock cond_mutex before pthread exit in gp_worker_main() in gp_workers.c. NOTE: An upstream comment states \"We are already on a shutdown path when running the code in question, so a DoS there doesn't make any sense, and there has been no additional information provided us (as upstream) to indicate why this would be a problem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12658"} {"idx": 206589, "project": "linux", "commit_id": "4ac06a1e013cf5fdd963317ffd3b968560f33bba", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/4ac06a1e013cf5fdd963317ffd3b968560f33bba", "commit_message": "nfc: fix NULL ptr dereference in llcp_sock_getname() after failed connect\n\nIt's possible to trigger NULL pointer dereference by local unprivileged\nuser, when calling getsockname() after failed bind() (e.g. the bind\nfails because LLCP_SAP_MAX used as SAP):\n\n BUG: kernel NULL pointer dereference, address: 0000000000000000\n CPU: 1 PID: 426 Comm: llcp_sock_getna Not tainted 5.13.0-rc2-next-20210521+ #9\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-1 04/01/2014\n Call Trace:\n llcp_sock_getname+0xb1/0xe0\n __sys_getpeername+0x95/0xc0\n ? lockdep_hardirqs_on_prepare+0xd5/0x180\n ? syscall_enter_from_user_mode+0x1c/0x40\n __x64_sys_getpeername+0x11/0x20\n do_syscall_64+0x36/0x70\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nThis can be reproduced with Syzkaller C repro (bind followed by\ngetpeername):\nhttps://syzkaller.appspot.com/x/repro.c?x=14def446e00000\n\nCc: \nFixes: d646960f7986 (\"NFC: Initial LLCP support\")\nReported-by: syzbot+80fb126e7f7d8b1a5914@syzkaller.appspotmail.com\nReported-by: butt3rflyh4ck \nSigned-off-by: Krzysztof Kozlowski \nLink: https://lore.kernel.org/r/20210531072138.5219-1-krzysztof.kozlowski@canonical.com\nSigned-off-by: Jakub Kicinski ", "target": 1, "func": "static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);\n\tstruct nfc_llcp_local *local;\n\tstruct nfc_dev *dev;\n\tstruct sockaddr_nfc_llcp llcp_addr;\n\tint len, ret = 0;\n\n\tif (!addr || alen < offsetofend(struct sockaddr, sa_family) ||\n\t addr->sa_family != AF_NFC)\n\t\treturn -EINVAL;\n\n\tpr_debug(\"sk %p addr %p family %d\\n\", sk, addr, addr->sa_family);\n\n\tmemset(&llcp_addr, 0, sizeof(llcp_addr));\n\tlen = min_t(unsigned int, sizeof(llcp_addr), alen);\n\tmemcpy(&llcp_addr, addr, len);\n\n\t/* This is going to be a listening socket, dsap must be 0 */\n\tif (llcp_addr.dsap != 0)\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != LLCP_CLOSED) {\n\t\tret = -EBADFD;\n\t\tgoto error;\n\t}\n\n\tdev = nfc_get_device(llcp_addr.dev_idx);\n\tif (dev == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto error;\n\t}\n\n\tlocal = nfc_llcp_find_local(dev);\n\tif (local == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->dev = dev;\n\tllcp_sock->local = nfc_llcp_local_get(local);\n\tllcp_sock->nfc_protocol = llcp_addr.nfc_protocol;\n\tllcp_sock->service_name_len = min_t(unsigned int,\n\t\t\t\t\t llcp_addr.service_name_len,\n\t\t\t\t\t NFC_LLCP_MAX_SERVICE_NAME);\n\tllcp_sock->service_name = kmemdup(llcp_addr.service_name,\n\t\t\t\t\t llcp_sock->service_name_len,\n\t\t\t\t\t GFP_KERNEL);\n\tif (!llcp_sock->service_name) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tret = -ENOMEM;\n\t\tgoto put_dev;\n\t}\n\tllcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock);\n\tif (llcp_sock->ssap == LLCP_SAP_MAX) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tkfree(llcp_sock->service_name);\n\t\tllcp_sock->service_name = NULL;\n\t\tret = -EADDRINUSE;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->reserved_ssap = llcp_sock->ssap;\n\n\tnfc_llcp_sock_link(&local->sockets, sk);\n\n\tpr_debug(\"Socket bound to SAP %d\\n\", llcp_sock->ssap);\n\n\tsk->sk_state = LLCP_BOUND;\n\nput_dev:\n\tnfc_put_device(dev);\n\nerror:\n\trelease_sock(sk);\n\treturn ret;\n}", "func_hash": 129413629557467973825307497255499843594, "file_name": "llcp_sock.c", "file_hash": 62544305467606792353979846729190213095, "cwe": ["CWE-476"], "cve": "CVE-2021-38208", "cve_desc": "net/nfc/llcp_sock.c in the Linux kernel before 5.12.10 allows local unprivileged users to cause a denial of service (NULL pointer dereference and BUG) by making a getsockname call after a certain type of failure of a bind call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38208"} {"idx": 383386, "project": "linux", "commit_id": "4ac06a1e013cf5fdd963317ffd3b968560f33bba", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/4ac06a1e013cf5fdd963317ffd3b968560f33bba", "commit_message": "nfc: fix NULL ptr dereference in llcp_sock_getname() after failed connect\n\nIt's possible to trigger NULL pointer dereference by local unprivileged\nuser, when calling getsockname() after failed bind() (e.g. the bind\nfails because LLCP_SAP_MAX used as SAP):\n\n BUG: kernel NULL pointer dereference, address: 0000000000000000\n CPU: 1 PID: 426 Comm: llcp_sock_getna Not tainted 5.13.0-rc2-next-20210521+ #9\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-1 04/01/2014\n Call Trace:\n llcp_sock_getname+0xb1/0xe0\n __sys_getpeername+0x95/0xc0\n ? lockdep_hardirqs_on_prepare+0xd5/0x180\n ? syscall_enter_from_user_mode+0x1c/0x40\n __x64_sys_getpeername+0x11/0x20\n do_syscall_64+0x36/0x70\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nThis can be reproduced with Syzkaller C repro (bind followed by\ngetpeername):\nhttps://syzkaller.appspot.com/x/repro.c?x=14def446e00000\n\nCc: \nFixes: d646960f7986 (\"NFC: Initial LLCP support\")\nReported-by: syzbot+80fb126e7f7d8b1a5914@syzkaller.appspotmail.com\nReported-by: butt3rflyh4ck \nSigned-off-by: Krzysztof Kozlowski \nLink: https://lore.kernel.org/r/20210531072138.5219-1-krzysztof.kozlowski@canonical.com\nSigned-off-by: Jakub Kicinski ", "target": 0, "func": "static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);\n\tstruct nfc_llcp_local *local;\n\tstruct nfc_dev *dev;\n\tstruct sockaddr_nfc_llcp llcp_addr;\n\tint len, ret = 0;\n\n\tif (!addr || alen < offsetofend(struct sockaddr, sa_family) ||\n\t addr->sa_family != AF_NFC)\n\t\treturn -EINVAL;\n\n\tpr_debug(\"sk %p addr %p family %d\\n\", sk, addr, addr->sa_family);\n\n\tmemset(&llcp_addr, 0, sizeof(llcp_addr));\n\tlen = min_t(unsigned int, sizeof(llcp_addr), alen);\n\tmemcpy(&llcp_addr, addr, len);\n\n\t/* This is going to be a listening socket, dsap must be 0 */\n\tif (llcp_addr.dsap != 0)\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != LLCP_CLOSED) {\n\t\tret = -EBADFD;\n\t\tgoto error;\n\t}\n\n\tdev = nfc_get_device(llcp_addr.dev_idx);\n\tif (dev == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto error;\n\t}\n\n\tlocal = nfc_llcp_find_local(dev);\n\tif (local == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->dev = dev;\n\tllcp_sock->local = nfc_llcp_local_get(local);\n\tllcp_sock->nfc_protocol = llcp_addr.nfc_protocol;\n\tllcp_sock->service_name_len = min_t(unsigned int,\n\t\t\t\t\t llcp_addr.service_name_len,\n\t\t\t\t\t NFC_LLCP_MAX_SERVICE_NAME);\n\tllcp_sock->service_name = kmemdup(llcp_addr.service_name,\n\t\t\t\t\t llcp_sock->service_name_len,\n\t\t\t\t\t GFP_KERNEL);\n\tif (!llcp_sock->service_name) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tllcp_sock->dev = NULL;\n\t\tret = -ENOMEM;\n\t\tgoto put_dev;\n\t}\n\tllcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock);\n\tif (llcp_sock->ssap == LLCP_SAP_MAX) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tkfree(llcp_sock->service_name);\n\t\tllcp_sock->service_name = NULL;\n\t\tllcp_sock->dev = NULL;\n\t\tret = -EADDRINUSE;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->reserved_ssap = llcp_sock->ssap;\n\n\tnfc_llcp_sock_link(&local->sockets, sk);\n\n\tpr_debug(\"Socket bound to SAP %d\\n\", llcp_sock->ssap);\n\n\tsk->sk_state = LLCP_BOUND;\n\nput_dev:\n\tnfc_put_device(dev);\n\nerror:\n\trelease_sock(sk);\n\treturn ret;\n}", "func_hash": 214049455817803737826479702974981058106, "file_name": "llcp_sock.c", "file_hash": 251609882252130305703566919223598710612, "cwe": ["CWE-476"], "cve": "CVE-2021-38208", "cve_desc": "net/nfc/llcp_sock.c in the Linux kernel before 5.12.10 allows local unprivileged users to cause a denial of service (NULL pointer dereference and BUG) by making a getsockname call after a certain type of failure of a bind call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38208"} {"idx": 206616, "project": "libjpeg-turbo", "commit_id": "1719d12e51641cce5c77e259516649ba5ef6303c", "project_url": "https://github.com/libjpeg-turbo/libjpeg-turbo", "commit_url": "https://github.com/libjpeg-turbo/libjpeg-turbo/commit/1719d12e51641cce5c77e259516649ba5ef6303c", "commit_message": "cjpeg: Fix FPE when compressing 0-width GIF\n\nFixes #493", "target": 1, "func": "start_input_gif(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n{\n gif_source_ptr source = (gif_source_ptr)sinfo;\n U_CHAR hdrbuf[10]; /* workspace for reading control blocks */\n unsigned int width, height; /* image dimensions */\n int colormaplen, aspectRatio;\n int c;\n\n /* Read and verify GIF Header */\n if (!ReadOK(source->pub.input_file, hdrbuf, 6))\n ERREXIT(cinfo, JERR_GIF_NOT);\n if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')\n ERREXIT(cinfo, JERR_GIF_NOT);\n /* Check for expected version numbers.\n * If unknown version, give warning and try to process anyway;\n * this is per recommendation in GIF89a standard.\n */\n if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&\n (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))\n TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);\n\n /* Read and decipher Logical Screen Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 7))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n width = LM_to_uint(hdrbuf, 0);\n height = LM_to_uint(hdrbuf, 2);\n /* we ignore the color resolution, sort flag, and background color index */\n aspectRatio = UCH(hdrbuf[6]);\n if (aspectRatio != 0 && aspectRatio != 49)\n TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);\n\n /* Allocate space to store the colormap */\n source->colormap = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)MAXCOLORMAPSIZE,\n (JDIMENSION)NUMCOLORS);\n colormaplen = 0; /* indicate initialization */\n\n /* Read global colormap if header indicates it is present */\n if (BitSet(hdrbuf[4], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[4] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n /* Scan until we reach start of desired image.\n * We don't currently support skipping images, but could add it easily.\n */\n for (;;) {\n c = ReadByte(source);\n\n if (c == ';') /* GIF terminator?? */\n ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);\n\n if (c == '!') { /* Extension */\n DoExtension(source);\n continue;\n }\n\n if (c != ',') { /* Not an image separator? */\n WARNMS1(cinfo, JWRN_GIF_CHAR, c);\n continue;\n }\n\n /* Read and decipher Local Image Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 9))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n /* we ignore top/left position info, also sort flag */\n width = LM_to_uint(hdrbuf, 4);\n height = LM_to_uint(hdrbuf, 6);\n source->is_interlaced = (BitSet(hdrbuf[8], INTERLACE) != 0);\n\n /* Read local colormap if header indicates it is present */\n /* Note: if we wanted to support skipping images, */\n /* we'd need to skip rather than read colormap for ignored images */\n if (BitSet(hdrbuf[8], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[8] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n source->input_code_size = ReadByte(source); /* get min-code-size byte */\n if (source->input_code_size < 2 || source->input_code_size > 8)\n ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);\n\n /* Reached desired image, so break out of loop */\n /* If we wanted to skip this image, */\n /* we'd call SkipDataBlocks and then continue the loop */\n break;\n }\n\n /* Prepare to read selected image: first initialize LZW decompressor */\n source->symbol_head = (UINT16 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT16));\n source->symbol_tail = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n source->symbol_stack = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n InitLZWCode(source);\n\n /*\n * If image is interlaced, we read it into a full-size sample array,\n * decompressing as we go; then get_interlaced_row selects rows from the\n * sample array in the proper order.\n */\n if (source->is_interlaced) {\n /* We request the virtual array now, but can't access it until virtual\n * arrays have been allocated. Hence, the actual work of reading the\n * image is postponed until the first call to get_pixel_rows.\n */\n source->interlaced_image = (*cinfo->mem->request_virt_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,\n (JDIMENSION)width, (JDIMENSION)height, (JDIMENSION)1);\n if (cinfo->progress != NULL) {\n cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;\n progress->total_extra_passes++; /* count file input as separate pass */\n }\n source->pub.get_pixel_rows = load_interlaced_image;\n } else {\n source->pub.get_pixel_rows = get_pixel_rows;\n }\n\n /* Create compressor input buffer. */\n source->pub.buffer = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)width * NUMCOLORS,\n (JDIMENSION)1);\n source->pub.buffer_height = 1;\n\n /* Pad colormap for safety. */\n for (c = colormaplen; c < source->clear_code; c++) {\n source->colormap[CM_RED][c] =\n source->colormap[CM_GREEN][c] =\n source->colormap[CM_BLUE][c] = CENTERJSAMPLE;\n }\n\n /* Return info about the image. */\n cinfo->in_color_space = JCS_RGB;\n cinfo->input_components = NUMCOLORS;\n cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */\n cinfo->image_width = width;\n cinfo->image_height = height;\n\n TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);\n}", "func_hash": 281910960268386384720019985553541121694, "file_name": "rdgif.c", "file_hash": 257404318709898346771279287013536723864, "cwe": ["CWE-369"], "cve": "CVE-2021-20205", "cve_desc": "Libjpeg-turbo versions 2.0.91 and 2.0.90 is vulnerable to a denial of service vulnerability caused by a divide by zero when processing a crafted GIF image.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20205"} {"idx": 383920, "project": "libjpeg-turbo", "commit_id": "1719d12e51641cce5c77e259516649ba5ef6303c", "project_url": "https://github.com/libjpeg-turbo/libjpeg-turbo", "commit_url": "https://github.com/libjpeg-turbo/libjpeg-turbo/commit/1719d12e51641cce5c77e259516649ba5ef6303c", "commit_message": "cjpeg: Fix FPE when compressing 0-width GIF\n\nFixes #493", "target": 0, "func": "start_input_gif(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n{\n gif_source_ptr source = (gif_source_ptr)sinfo;\n U_CHAR hdrbuf[10]; /* workspace for reading control blocks */\n unsigned int width, height; /* image dimensions */\n int colormaplen, aspectRatio;\n int c;\n\n /* Read and verify GIF Header */\n if (!ReadOK(source->pub.input_file, hdrbuf, 6))\n ERREXIT(cinfo, JERR_GIF_NOT);\n if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')\n ERREXIT(cinfo, JERR_GIF_NOT);\n /* Check for expected version numbers.\n * If unknown version, give warning and try to process anyway;\n * this is per recommendation in GIF89a standard.\n */\n if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&\n (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))\n TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);\n\n /* Read and decipher Logical Screen Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 7))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n width = LM_to_uint(hdrbuf, 0);\n height = LM_to_uint(hdrbuf, 2);\n if (width == 0 || height == 0)\n ERREXIT(cinfo, JERR_GIF_EMPTY);\n /* we ignore the color resolution, sort flag, and background color index */\n aspectRatio = UCH(hdrbuf[6]);\n if (aspectRatio != 0 && aspectRatio != 49)\n TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);\n\n /* Allocate space to store the colormap */\n source->colormap = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)MAXCOLORMAPSIZE,\n (JDIMENSION)NUMCOLORS);\n colormaplen = 0; /* indicate initialization */\n\n /* Read global colormap if header indicates it is present */\n if (BitSet(hdrbuf[4], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[4] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n /* Scan until we reach start of desired image.\n * We don't currently support skipping images, but could add it easily.\n */\n for (;;) {\n c = ReadByte(source);\n\n if (c == ';') /* GIF terminator?? */\n ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);\n\n if (c == '!') { /* Extension */\n DoExtension(source);\n continue;\n }\n\n if (c != ',') { /* Not an image separator? */\n WARNMS1(cinfo, JWRN_GIF_CHAR, c);\n continue;\n }\n\n /* Read and decipher Local Image Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 9))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n /* we ignore top/left position info, also sort flag */\n width = LM_to_uint(hdrbuf, 4);\n height = LM_to_uint(hdrbuf, 6);\n if (width == 0 || height == 0)\n ERREXIT(cinfo, JERR_GIF_EMPTY);\n source->is_interlaced = (BitSet(hdrbuf[8], INTERLACE) != 0);\n\n /* Read local colormap if header indicates it is present */\n /* Note: if we wanted to support skipping images, */\n /* we'd need to skip rather than read colormap for ignored images */\n if (BitSet(hdrbuf[8], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[8] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n source->input_code_size = ReadByte(source); /* get min-code-size byte */\n if (source->input_code_size < 2 || source->input_code_size > 8)\n ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);\n\n /* Reached desired image, so break out of loop */\n /* If we wanted to skip this image, */\n /* we'd call SkipDataBlocks and then continue the loop */\n break;\n }\n\n /* Prepare to read selected image: first initialize LZW decompressor */\n source->symbol_head = (UINT16 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT16));\n source->symbol_tail = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n source->symbol_stack = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n InitLZWCode(source);\n\n /*\n * If image is interlaced, we read it into a full-size sample array,\n * decompressing as we go; then get_interlaced_row selects rows from the\n * sample array in the proper order.\n */\n if (source->is_interlaced) {\n /* We request the virtual array now, but can't access it until virtual\n * arrays have been allocated. Hence, the actual work of reading the\n * image is postponed until the first call to get_pixel_rows.\n */\n source->interlaced_image = (*cinfo->mem->request_virt_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,\n (JDIMENSION)width, (JDIMENSION)height, (JDIMENSION)1);\n if (cinfo->progress != NULL) {\n cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;\n progress->total_extra_passes++; /* count file input as separate pass */\n }\n source->pub.get_pixel_rows = load_interlaced_image;\n } else {\n source->pub.get_pixel_rows = get_pixel_rows;\n }\n\n /* Create compressor input buffer. */\n source->pub.buffer = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)width * NUMCOLORS,\n (JDIMENSION)1);\n source->pub.buffer_height = 1;\n\n /* Pad colormap for safety. */\n for (c = colormaplen; c < source->clear_code; c++) {\n source->colormap[CM_RED][c] =\n source->colormap[CM_GREEN][c] =\n source->colormap[CM_BLUE][c] = CENTERJSAMPLE;\n }\n\n /* Return info about the image. */\n cinfo->in_color_space = JCS_RGB;\n cinfo->input_components = NUMCOLORS;\n cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */\n cinfo->image_width = width;\n cinfo->image_height = height;\n\n TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);\n}", "func_hash": 334260485799175843984445445638952819898, "file_name": "rdgif.c", "file_hash": 141327226434088431184558631783155467658, "cwe": ["CWE-369"], "cve": "CVE-2021-20205", "cve_desc": "Libjpeg-turbo versions 2.0.91 and 2.0.90 is vulnerable to a denial of service vulnerability caused by a divide by zero when processing a crafted GIF image.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20205"} {"idx": 206645, "project": "libexif", "commit_id": "9266d14b5ca4e29b970fa03272318e5f99386e06", "project_url": "https://github.com/libexif/libexif", "commit_url": "https://github.com/libexif/libexif/commit/9266d14b5ca4e29b970fa03272318e5f99386e06#diff-7ee66c4f1536ac84dc5bbff1b8312e2eef24b974b3e48a5c5c2bcfdf2eb8f3ce", "commit_message": "fixed a incorrect overflow check that could be optimized away.\n\ninspired by:\nhttps://android.googlesource.com/platform/external/libexif/+/8e7345f3bc0bad06ac369d6cbc1124c8ceaf7d4b\n\nhttps://source.android.com/security/bulletin/2020-11-01\n\nCVE-2020-0452", "target": 1, "func": "exif_entry_get_value (ExifEntry *e, char *val, unsigned int maxlen)\n{\n\tunsigned int i, j, k;\n\tExifShort v_short, v_short2, v_short3, v_short4;\n\tExifByte v_byte;\n\tExifRational v_rat;\n\tExifSRational v_srat;\n\tchar b[64];\n\tconst char *c;\n\tExifByteOrder o;\n\tdouble d;\n\tExifEntry *entry;\n\tstatic const struct {\n\t\tchar label[5];\n\t\tchar major, minor;\n\t} versions[] = {\n\t\t{\"0110\", 1, 1},\n\t\t{\"0120\", 1, 2},\n\t\t{\"0200\", 2, 0},\n\t\t{\"0210\", 2, 1},\n\t\t{\"0220\", 2, 2},\n\t\t{\"0221\", 2, 21},\n\t\t{\"0230\", 2, 3},\n\t\t{\"\" , 0, 0}\n\t};\n\n\t(void) bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);\n\n\tif (!e || !e->parent || !e->parent->parent || !maxlen || !val)\n\t\treturn val;\n\n\t/* make sure the returned string is zero terminated */\n\t/* FIXME: this is inefficient in the case of long buffers and should\n\t * instead be taken care of on each write instead. */\n\tmemset (val, 0, maxlen);\n\n\t/* We need the byte order */\n\to = exif_data_get_byte_order (e->parent->parent);\n\n\t/* Sanity check */\n\tif (e->size != e->components * exif_format_get_size (e->format)) {\n\t\tsnprintf (val, maxlen, _(\"Invalid size of entry (%i, \"\n\t\t\t\"expected %li x %i).\"), e->size, e->components,\n\t\t\t\texif_format_get_size (e->format));\n\t\treturn val;\n\t}\n\n\tswitch (e->tag) {\n\tcase EXIF_TAG_USER_COMMENT:\n\n\t\t/*\n\t\t * The specification says UNDEFINED, but some\n\t\t * manufacturers don't care and use ASCII. If this is the\n\t\t * case here, only refuse to read it if there is no chance\n\t\t * of finding readable data.\n\t\t */\n\t\tif ((e->format != EXIF_FORMAT_ASCII) || \n\t\t (e->size <= 8) ||\n\t\t ( memcmp (e->data, \"ASCII\\0\\0\\0\" , 8) &&\n\t\t memcmp (e->data, \"UNICODE\\0\" , 8) &&\n\t\t memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8) &&\n\t\t memcmp (e->data, \"\\0\\0\\0\\0\\0\\0\\0\\0\", 8)))\n\t\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\n\t\t/*\n\t\t * Note that, according to the specification (V2.1, p 40),\n\t\t * the user comment field does not have to be \n\t\t * NULL terminated.\n\t\t */\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"ASCII\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, (char *) e->data + 8, MIN (e->size - 8, maxlen-1));\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"UNICODE\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported UNICODE string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding.\n\t\t * EXIF 2.2 implies (but does not say) that this encoding is\n\t\t * UCS-2.\n\t\t */\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported JIS string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Check if there is really some information in the tag. */\n\t\tfor (i = 0; (i < e->size) &&\n\t\t\t (!e->data[i] || (e->data[i] == ' ')); i++);\n\t\tif (i == e->size) break;\n\n\t\t/*\n\t\t * If we reach this point, the tag does not\n \t\t * comply with the standard but seems to contain data.\n\t\t * Print as much as possible.\n\t\t * Note: make sure we do not overwrite the final \\0 at maxlen-1\n\t\t */\n\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t_(\"Tag UserComment contains data but is \"\n\t\t\t \"against specification.\"));\n \t\tfor (j = 0; (i < e->size) && (j < maxlen-1); i++, j++) {\n\t\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t_(\"Byte at position %i: 0x%02x\"), i, e->data[i]);\n \t\t\tval[j] = isprint (e->data[i]) ? e->data[i] : '.';\n\t\t}\n\t\tbreak;\n\n\tcase EXIF_TAG_EXIF_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tstrncpy (val, _(\"Unknown Exif Version\"), maxlen-1);\n\t\tfor (i = 0; *versions[i].label; i++) {\n\t\t\tif (!memcmp (e->data, versions[i].label, 4)) {\n \t\t\t\tsnprintf (val, maxlen,\n\t\t\t\t\t_(\"Exif Version %d.%d\"),\n\t\t\t\t\tversions[i].major,\n\t\t\t\t\tversions[i].minor);\n \t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_FLASH_PIX_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tif (!memcmp (e->data, \"0100\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.0\"), maxlen-1);\n\t\telse if (!memcmp (e->data, \"0101\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.01\"), maxlen-1);\n\t\telse\n\t\t\tstrncpy (val, _(\"Unknown FlashPix Version\"), maxlen-1);\n\t\tbreak;\n\tcase EXIF_TAG_COPYRIGHT:\n\t\tCF (e, EXIF_FORMAT_ASCII, val, maxlen);\n\n\t\t/*\n\t\t * First part: Photographer.\n\t\t * Some cameras store a string like \" \" here. Ignore it.\n\t\t * Remember that a corrupted tag might not be NUL-terminated\n\t\t */\n\t\tif (e->size && e->data && match_repeated_char(e->data, ' ', e->size))\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\telse\n\t\t\tstrncpy (val, _(\"[None]\"), maxlen-1);\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Photographer)\"), maxlen-1 - strlen (val));\n\n\t\t/* Second part: Editor. */\n\t\tstrncat (val, \" - \", maxlen-1 - strlen (val));\n\t\tk = 0;\n\t\tif (e->size && e->data) {\n\t\t\tconst unsigned char *tagdata = memchr(e->data, 0, e->size);\n\t\t\tif (tagdata++) {\n\t\t\t\tunsigned int editor_ofs = tagdata - e->data;\n\t\t\t\tunsigned int remaining = e->size - editor_ofs;\n\t\t\t\tif (match_repeated_char(tagdata, ' ', remaining)) {\n\t\t\t\t\tstrncat (val, (const char*)tagdata, MIN (maxlen-1 - strlen (val), remaining));\n\t\t\t\t\t++k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!k)\n\t\t\tstrncat (val, _(\"[None]\"), maxlen-1 - strlen (val));\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Editor)\"), maxlen-1 - strlen (val));\n\n\t\tbreak;\n\tcase EXIF_TAG_FNUMBER:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"f/%.01f\", d);\n\t\tbreak;\n\tcase EXIF_TAG_APERTURE_VALUE:\n\tcase EXIF_TAG_MAX_APERTURE_VALUE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator || (0x80000000 == v_rat.numerator)) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (f/%.01f)\"), pow (2, d / 2.));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FOCAL_LENGTH:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * For calculation of the 35mm equivalent,\n\t\t * Minolta cameras need a multiplier that depends on the\n\t\t * camera model.\n\t\t */\n\t\td = 0.;\n\t\tentry = exif_content_get_entry (\n\t\t\te->parent->parent->ifd[EXIF_IFD_0], EXIF_TAG_MAKE);\n\t\tif (entry && entry->data && entry->size >= 7 &&\n\t\t !strncmp ((char *)entry->data, \"Minolta\", 7)) {\n\t\t\tentry = exif_content_get_entry (\n\t\t\t\t\te->parent->parent->ifd[EXIF_IFD_0],\n\t\t\t\t\tEXIF_TAG_MODEL);\n\t\t\tif (entry && entry->data && entry->size >= 8) {\n\t\t\t\tif (!strncmp ((char *)entry->data, \"DiMAGE 7\", 8))\n\t\t\t\t\td = 3.9;\n\t\t\t\telse if (!strncmp ((char *)entry->data, \"DiMAGE 5\", 8))\n\t\t\t\t\td = 4.9;\n\t\t\t}\n\t\t}\n\t\tif (d)\n\t\t\tsnprintf (b, sizeof (b), _(\" (35 equivalent: %.0f mm)\"),\n\t\t\t\t (d * (double) v_rat.numerator /\n\t\t\t\t (double) v_rat.denominator));\n\t\telse\n\t\t\tb[0] = 0;\n\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f mm\", d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_DISTANCE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f m\", d);\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_TIME:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tif (d < 1 && d)\n\t\t\tsnprintf (val, maxlen, _(\"1/%.0f\"), 1. / d);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%.0f\", d);\n\t\tstrncat (val, _(\" sec.\"), maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SHUTTER_SPEED_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tif (pow (2, d))\n\t\t\td = 1. / pow (2, d);\n\t\tif (d < 1 && d)\n\t\t snprintf (b, sizeof (b), _(\" (1/%.0f sec.)\"), 1. / d);\n\t\telse\n\t\t snprintf (b, sizeof (b), _(\" (%.0f sec.)\"), d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_BRIGHTNESS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (%.02f cd/m^2)\"),\n\t\t\t1. / (M_PI * 0.3048 * 0.3048) * pow (2, d));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FILE_SOURCE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 3)\n\t\t\tstrncpy (val, _(\"DSC\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_COMPONENTS_CONFIGURATION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tfor (i = 0; i < 4; i++) {\n\t\t\tswitch (e->data[i]) {\n\t\t\tcase 0: c = _(\"-\"); break;\n\t\t\tcase 1: c = _(\"Y\"); break;\n\t\t\tcase 2: c = _(\"Cb\"); break;\n\t\t\tcase 3: c = _(\"Cr\"); break;\n\t\t\tcase 4: c = _(\"R\"); break;\n\t\t\tcase 5: c = _(\"G\"); break;\n\t\t\tcase 6: c = _(\"B\"); break;\n\t\t\tdefault: c = _(\"Reserved\"); break;\n\t\t\t}\n\t\t\tstrncat (val, c, maxlen-1 - strlen (val));\n\t\t\tif (i < 3)\n\t\t\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_BIAS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tbreak;\n\tcase EXIF_TAG_SCENE_TYPE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Directly photographed\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_YCBCR_SUB_SAMPLING:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 2, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\t\tv_short2 = exif_get_short (\n\t\t\te->data + exif_format_get_size (e->format),\n\t\t\to);\n\t\tif ((v_short == 2) && (v_short2 == 1))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:2\"), maxlen-1);\n\t\telse if ((v_short == 2) && (v_short2 == 2))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:0\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%u, %u\", v_short, v_short2);\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_AREA:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tswitch (e->components) {\n\t\tcase 2:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tsnprintf (val, maxlen, \"(x,y) = (%i,%i)\",\n\t\t\t\t v_short, v_short2);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within distance %i of \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short,\n\t\t\t\tv_short2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tv_short4 = exif_get_short (e->data + 6, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within rectangle \"\n\t\t\t\t\"(width %i, height %i) around \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short4,\n\t\t\t\tv_short, v_short2);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf (val, maxlen, _(\"Unexpected number \"\n\t\t\t\t\"of components (%li, expected 2, 3, or 4).\"),\n\t\t\t\te->components);\t\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_GPS_VERSION_ID:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tsnprintf (val, maxlen, \"%u\", v_byte);\n\t\tfor (i = 1; i < e->components; i++) {\n\t\t\tv_byte = e->data[i];\n\t\t\tsnprintf (b, sizeof (b), \".%u\", v_byte);\n\t\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_INTEROPERABILITY_VERSION:\n\t/* a.k.a. case EXIF_TAG_GPS_LATITUDE: */\n\t\t/* This tag occurs in EXIF_IFD_INTEROPERABILITY */\n\t\tif (e->format == EXIF_FORMAT_UNDEFINED) {\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\t\tbreak;\n\t\t}\n\t\t/* EXIF_TAG_GPS_LATITUDE is the same numerically as\n\t\t * EXIF_TAG_INTEROPERABILITY_VERSION but in EXIF_IFD_GPS\n\t\t */\n\t\texif_entry_format_value(e, val, maxlen);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_ALTITUDE_REF:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 0)\n\t\t\tstrncpy (val, _(\"Sea level\"), maxlen-1);\n\t\telse if (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Sea level reference\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_TIME_STAMP:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 3, val, maxlen);\n\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\ti = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\tj = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t 2*exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%02u:%02u:%05.2f\", i, j, d);\n\t\tbreak;\n\n\tcase EXIF_TAG_METERING_MODE:\n\tcase EXIF_TAG_COMPRESSION:\n\tcase EXIF_TAG_LIGHT_SOURCE:\n\tcase EXIF_TAG_FOCAL_PLANE_RESOLUTION_UNIT:\n\tcase EXIF_TAG_RESOLUTION_UNIT:\n\tcase EXIF_TAG_EXPOSURE_PROGRAM:\n\tcase EXIF_TAG_FLASH:\n\tcase EXIF_TAG_SUBJECT_DISTANCE_RANGE:\n\tcase EXIF_TAG_COLOR_SPACE:\n\t\tCF (e,EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list2[i].tag && (list2[i].tag != e->tag); i++);\n\t\tif (!list2[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list2[i].elem[j].values[0] &&\n\t\t\t (list2[i].elem[j].index < v_short); j++);\n\t\tif (list2[i].elem[j].index != v_short) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find a short enough value */\n\t\tmemset (val, 0, maxlen);\n\t\tfor (k = 0; list2[i].elem[j].values[k]; k++) {\n\t\t\tsize_t l = strlen (_(list2[i].elem[j].values[k]));\n\t\t\tif ((maxlen > l) && (strlen (val) < l))\n\t\t\t\tstrncpy (val, _(list2[i].elem[j].values[k]), maxlen-1);\n\t\t}\n\t\tif (!val[0]) snprintf (val, maxlen, \"%i\", v_short);\n\n\t\tbreak;\n\n\tcase EXIF_TAG_PLANAR_CONFIGURATION:\n\tcase EXIF_TAG_SENSING_METHOD:\n\tcase EXIF_TAG_ORIENTATION:\n\tcase EXIF_TAG_YCBCR_POSITIONING:\n\tcase EXIF_TAG_PHOTOMETRIC_INTERPRETATION:\n\tcase EXIF_TAG_CUSTOM_RENDERED:\n\tcase EXIF_TAG_EXPOSURE_MODE:\n\tcase EXIF_TAG_WHITE_BALANCE:\n\tcase EXIF_TAG_SCENE_CAPTURE_TYPE:\n\tcase EXIF_TAG_GAIN_CONTROL:\n\tcase EXIF_TAG_SATURATION:\n\tcase EXIF_TAG_CONTRAST:\n\tcase EXIF_TAG_SHARPNESS:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list[i].tag && (list[i].tag != e->tag); i++);\n\t\tif (!list[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list[i].strings[j] && (j < v_short); j++);\n\t\tif (!list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, \"%i\", v_short);\n\t\telse if (!*list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, _(\"Unknown value %i\"), v_short);\n\t\telse\n\t\t\tstrncpy (val, _(list[i].strings[j]), maxlen-1);\n\t\tbreak;\n\n\tcase EXIF_TAG_XP_TITLE:\n\tcase EXIF_TAG_XP_COMMENT:\n\tcase EXIF_TAG_XP_AUTHOR:\n\tcase EXIF_TAG_XP_KEYWORDS:\n\tcase EXIF_TAG_XP_SUBJECT:\n\t{\n\t\tunsigned char *utf16;\n\n\t\t/* Sanity check the size to prevent overflow */\n\t\tif (e->size+sizeof(uint16_t)+1 < e->size) break;\n\n\t\t/* The tag may not be U+0000-terminated , so make a local\n\t\t U+0000-terminated copy before converting it */\n\t\tutf16 = exif_mem_alloc (e->priv->mem, e->size+sizeof(uint16_t)+1);\n\t\tif (!utf16) break;\n\t\tmemcpy(utf16, e->data, e->size);\n\n\t\t/* NUL terminate the string. If the size is odd (which isn't possible\n\t\t * for a valid UTF16 string), then this will overwrite the high byte of\n\t\t * the final half word, plus add a full zero NUL word at the end.\n\t\t */\n\t\tutf16[e->size] = 0;\n\t\tutf16[e->size+1] = 0;\n\t\tutf16[e->size+2] = 0;\n\n\t\t/* Warning! The texts are converted from UTF16 to UTF8 */\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\texif_convert_utf16_to_utf8(val, utf16, maxlen);\n\t\texif_mem_free(e->priv->mem, utf16);\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\t/* Use a generic value formatting */\n\t\texif_entry_format_value(e, val, maxlen);\n\t}\n\n\treturn val;\n}", "func_hash": 179560989380426094230189764563489129683, "file_name": "exif-entry.c", "file_hash": 200273757417260136844293172775051194385, "cwe": ["CWE-787"], "cve": "CVE-2020-0452", "cve_desc": "In exif_entry_get_value of exif-entry.c, there is a possible out of bounds write due to an integer overflow. This could lead to remote code execution if a third party app used this library to process remote image data with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android-8.1 Android-9 Android-10 Android-11 Android-8.0Android ID: A-159625731", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0452"} {"idx": 384338, "project": "libexif", "commit_id": "9266d14b5ca4e29b970fa03272318e5f99386e06", "project_url": "https://github.com/libexif/libexif", "commit_url": "https://github.com/libexif/libexif/commit/9266d14b5ca4e29b970fa03272318e5f99386e06#diff-7ee66c4f1536ac84dc5bbff1b8312e2eef24b974b3e48a5c5c2bcfdf2eb8f3ce", "commit_message": "fixed a incorrect overflow check that could be optimized away.\n\ninspired by:\nhttps://android.googlesource.com/platform/external/libexif/+/8e7345f3bc0bad06ac369d6cbc1124c8ceaf7d4b\n\nhttps://source.android.com/security/bulletin/2020-11-01\n\nCVE-2020-0452", "target": 0, "func": "exif_entry_get_value (ExifEntry *e, char *val, unsigned int maxlen)\n{\n\tunsigned int i, j, k;\n\tExifShort v_short, v_short2, v_short3, v_short4;\n\tExifByte v_byte;\n\tExifRational v_rat;\n\tExifSRational v_srat;\n\tchar b[64];\n\tconst char *c;\n\tExifByteOrder o;\n\tdouble d;\n\tExifEntry *entry;\n\tstatic const struct {\n\t\tchar label[5];\n\t\tchar major, minor;\n\t} versions[] = {\n\t\t{\"0110\", 1, 1},\n\t\t{\"0120\", 1, 2},\n\t\t{\"0200\", 2, 0},\n\t\t{\"0210\", 2, 1},\n\t\t{\"0220\", 2, 2},\n\t\t{\"0221\", 2, 21},\n\t\t{\"0230\", 2, 3},\n\t\t{\"\" , 0, 0}\n\t};\n\n\t(void) bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);\n\n\tif (!e || !e->parent || !e->parent->parent || !maxlen || !val)\n\t\treturn val;\n\n\t/* make sure the returned string is zero terminated */\n\t/* FIXME: this is inefficient in the case of long buffers and should\n\t * instead be taken care of on each write instead. */\n\tmemset (val, 0, maxlen);\n\n\t/* We need the byte order */\n\to = exif_data_get_byte_order (e->parent->parent);\n\n\t/* Sanity check */\n\tif (e->size != e->components * exif_format_get_size (e->format)) {\n\t\tsnprintf (val, maxlen, _(\"Invalid size of entry (%i, \"\n\t\t\t\"expected %li x %i).\"), e->size, e->components,\n\t\t\t\texif_format_get_size (e->format));\n\t\treturn val;\n\t}\n\n\tswitch (e->tag) {\n\tcase EXIF_TAG_USER_COMMENT:\n\n\t\t/*\n\t\t * The specification says UNDEFINED, but some\n\t\t * manufacturers don't care and use ASCII. If this is the\n\t\t * case here, only refuse to read it if there is no chance\n\t\t * of finding readable data.\n\t\t */\n\t\tif ((e->format != EXIF_FORMAT_ASCII) || \n\t\t (e->size <= 8) ||\n\t\t ( memcmp (e->data, \"ASCII\\0\\0\\0\" , 8) &&\n\t\t memcmp (e->data, \"UNICODE\\0\" , 8) &&\n\t\t memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8) &&\n\t\t memcmp (e->data, \"\\0\\0\\0\\0\\0\\0\\0\\0\", 8)))\n\t\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\n\t\t/*\n\t\t * Note that, according to the specification (V2.1, p 40),\n\t\t * the user comment field does not have to be \n\t\t * NULL terminated.\n\t\t */\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"ASCII\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, (char *) e->data + 8, MIN (e->size - 8, maxlen-1));\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"UNICODE\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported UNICODE string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding.\n\t\t * EXIF 2.2 implies (but does not say) that this encoding is\n\t\t * UCS-2.\n\t\t */\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported JIS string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Check if there is really some information in the tag. */\n\t\tfor (i = 0; (i < e->size) &&\n\t\t\t (!e->data[i] || (e->data[i] == ' ')); i++);\n\t\tif (i == e->size) break;\n\n\t\t/*\n\t\t * If we reach this point, the tag does not\n \t\t * comply with the standard but seems to contain data.\n\t\t * Print as much as possible.\n\t\t * Note: make sure we do not overwrite the final \\0 at maxlen-1\n\t\t */\n\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t_(\"Tag UserComment contains data but is \"\n\t\t\t \"against specification.\"));\n \t\tfor (j = 0; (i < e->size) && (j < maxlen-1); i++, j++) {\n\t\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t_(\"Byte at position %i: 0x%02x\"), i, e->data[i]);\n \t\t\tval[j] = isprint (e->data[i]) ? e->data[i] : '.';\n\t\t}\n\t\tbreak;\n\n\tcase EXIF_TAG_EXIF_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tstrncpy (val, _(\"Unknown Exif Version\"), maxlen-1);\n\t\tfor (i = 0; *versions[i].label; i++) {\n\t\t\tif (!memcmp (e->data, versions[i].label, 4)) {\n \t\t\t\tsnprintf (val, maxlen,\n\t\t\t\t\t_(\"Exif Version %d.%d\"),\n\t\t\t\t\tversions[i].major,\n\t\t\t\t\tversions[i].minor);\n \t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_FLASH_PIX_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tif (!memcmp (e->data, \"0100\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.0\"), maxlen-1);\n\t\telse if (!memcmp (e->data, \"0101\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.01\"), maxlen-1);\n\t\telse\n\t\t\tstrncpy (val, _(\"Unknown FlashPix Version\"), maxlen-1);\n\t\tbreak;\n\tcase EXIF_TAG_COPYRIGHT:\n\t\tCF (e, EXIF_FORMAT_ASCII, val, maxlen);\n\n\t\t/*\n\t\t * First part: Photographer.\n\t\t * Some cameras store a string like \" \" here. Ignore it.\n\t\t * Remember that a corrupted tag might not be NUL-terminated\n\t\t */\n\t\tif (e->size && e->data && match_repeated_char(e->data, ' ', e->size))\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\telse\n\t\t\tstrncpy (val, _(\"[None]\"), maxlen-1);\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Photographer)\"), maxlen-1 - strlen (val));\n\n\t\t/* Second part: Editor. */\n\t\tstrncat (val, \" - \", maxlen-1 - strlen (val));\n\t\tk = 0;\n\t\tif (e->size && e->data) {\n\t\t\tconst unsigned char *tagdata = memchr(e->data, 0, e->size);\n\t\t\tif (tagdata++) {\n\t\t\t\tunsigned int editor_ofs = tagdata - e->data;\n\t\t\t\tunsigned int remaining = e->size - editor_ofs;\n\t\t\t\tif (match_repeated_char(tagdata, ' ', remaining)) {\n\t\t\t\t\tstrncat (val, (const char*)tagdata, MIN (maxlen-1 - strlen (val), remaining));\n\t\t\t\t\t++k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!k)\n\t\t\tstrncat (val, _(\"[None]\"), maxlen-1 - strlen (val));\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Editor)\"), maxlen-1 - strlen (val));\n\n\t\tbreak;\n\tcase EXIF_TAG_FNUMBER:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"f/%.01f\", d);\n\t\tbreak;\n\tcase EXIF_TAG_APERTURE_VALUE:\n\tcase EXIF_TAG_MAX_APERTURE_VALUE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator || (0x80000000 == v_rat.numerator)) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (f/%.01f)\"), pow (2, d / 2.));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FOCAL_LENGTH:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * For calculation of the 35mm equivalent,\n\t\t * Minolta cameras need a multiplier that depends on the\n\t\t * camera model.\n\t\t */\n\t\td = 0.;\n\t\tentry = exif_content_get_entry (\n\t\t\te->parent->parent->ifd[EXIF_IFD_0], EXIF_TAG_MAKE);\n\t\tif (entry && entry->data && entry->size >= 7 &&\n\t\t !strncmp ((char *)entry->data, \"Minolta\", 7)) {\n\t\t\tentry = exif_content_get_entry (\n\t\t\t\t\te->parent->parent->ifd[EXIF_IFD_0],\n\t\t\t\t\tEXIF_TAG_MODEL);\n\t\t\tif (entry && entry->data && entry->size >= 8) {\n\t\t\t\tif (!strncmp ((char *)entry->data, \"DiMAGE 7\", 8))\n\t\t\t\t\td = 3.9;\n\t\t\t\telse if (!strncmp ((char *)entry->data, \"DiMAGE 5\", 8))\n\t\t\t\t\td = 4.9;\n\t\t\t}\n\t\t}\n\t\tif (d)\n\t\t\tsnprintf (b, sizeof (b), _(\" (35 equivalent: %.0f mm)\"),\n\t\t\t\t (d * (double) v_rat.numerator /\n\t\t\t\t (double) v_rat.denominator));\n\t\telse\n\t\t\tb[0] = 0;\n\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f mm\", d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_DISTANCE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f m\", d);\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_TIME:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tif (d < 1 && d)\n\t\t\tsnprintf (val, maxlen, _(\"1/%.0f\"), 1. / d);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%.0f\", d);\n\t\tstrncat (val, _(\" sec.\"), maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SHUTTER_SPEED_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tif (pow (2, d))\n\t\t\td = 1. / pow (2, d);\n\t\tif (d < 1 && d)\n\t\t snprintf (b, sizeof (b), _(\" (1/%.0f sec.)\"), 1. / d);\n\t\telse\n\t\t snprintf (b, sizeof (b), _(\" (%.0f sec.)\"), d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_BRIGHTNESS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (%.02f cd/m^2)\"),\n\t\t\t1. / (M_PI * 0.3048 * 0.3048) * pow (2, d));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FILE_SOURCE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 3)\n\t\t\tstrncpy (val, _(\"DSC\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_COMPONENTS_CONFIGURATION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tfor (i = 0; i < 4; i++) {\n\t\t\tswitch (e->data[i]) {\n\t\t\tcase 0: c = _(\"-\"); break;\n\t\t\tcase 1: c = _(\"Y\"); break;\n\t\t\tcase 2: c = _(\"Cb\"); break;\n\t\t\tcase 3: c = _(\"Cr\"); break;\n\t\t\tcase 4: c = _(\"R\"); break;\n\t\t\tcase 5: c = _(\"G\"); break;\n\t\t\tcase 6: c = _(\"B\"); break;\n\t\t\tdefault: c = _(\"Reserved\"); break;\n\t\t\t}\n\t\t\tstrncat (val, c, maxlen-1 - strlen (val));\n\t\t\tif (i < 3)\n\t\t\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_BIAS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tbreak;\n\tcase EXIF_TAG_SCENE_TYPE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Directly photographed\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_YCBCR_SUB_SAMPLING:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 2, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\t\tv_short2 = exif_get_short (\n\t\t\te->data + exif_format_get_size (e->format),\n\t\t\to);\n\t\tif ((v_short == 2) && (v_short2 == 1))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:2\"), maxlen-1);\n\t\telse if ((v_short == 2) && (v_short2 == 2))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:0\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%u, %u\", v_short, v_short2);\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_AREA:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tswitch (e->components) {\n\t\tcase 2:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tsnprintf (val, maxlen, \"(x,y) = (%i,%i)\",\n\t\t\t\t v_short, v_short2);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within distance %i of \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short,\n\t\t\t\tv_short2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tv_short4 = exif_get_short (e->data + 6, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within rectangle \"\n\t\t\t\t\"(width %i, height %i) around \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short4,\n\t\t\t\tv_short, v_short2);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf (val, maxlen, _(\"Unexpected number \"\n\t\t\t\t\"of components (%li, expected 2, 3, or 4).\"),\n\t\t\t\te->components);\t\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_GPS_VERSION_ID:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tsnprintf (val, maxlen, \"%u\", v_byte);\n\t\tfor (i = 1; i < e->components; i++) {\n\t\t\tv_byte = e->data[i];\n\t\t\tsnprintf (b, sizeof (b), \".%u\", v_byte);\n\t\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_INTEROPERABILITY_VERSION:\n\t/* a.k.a. case EXIF_TAG_GPS_LATITUDE: */\n\t\t/* This tag occurs in EXIF_IFD_INTEROPERABILITY */\n\t\tif (e->format == EXIF_FORMAT_UNDEFINED) {\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\t\tbreak;\n\t\t}\n\t\t/* EXIF_TAG_GPS_LATITUDE is the same numerically as\n\t\t * EXIF_TAG_INTEROPERABILITY_VERSION but in EXIF_IFD_GPS\n\t\t */\n\t\texif_entry_format_value(e, val, maxlen);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_ALTITUDE_REF:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 0)\n\t\t\tstrncpy (val, _(\"Sea level\"), maxlen-1);\n\t\telse if (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Sea level reference\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_TIME_STAMP:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 3, val, maxlen);\n\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\ti = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\tj = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t 2*exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%02u:%02u:%05.2f\", i, j, d);\n\t\tbreak;\n\n\tcase EXIF_TAG_METERING_MODE:\n\tcase EXIF_TAG_COMPRESSION:\n\tcase EXIF_TAG_LIGHT_SOURCE:\n\tcase EXIF_TAG_FOCAL_PLANE_RESOLUTION_UNIT:\n\tcase EXIF_TAG_RESOLUTION_UNIT:\n\tcase EXIF_TAG_EXPOSURE_PROGRAM:\n\tcase EXIF_TAG_FLASH:\n\tcase EXIF_TAG_SUBJECT_DISTANCE_RANGE:\n\tcase EXIF_TAG_COLOR_SPACE:\n\t\tCF (e,EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list2[i].tag && (list2[i].tag != e->tag); i++);\n\t\tif (!list2[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list2[i].elem[j].values[0] &&\n\t\t\t (list2[i].elem[j].index < v_short); j++);\n\t\tif (list2[i].elem[j].index != v_short) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find a short enough value */\n\t\tmemset (val, 0, maxlen);\n\t\tfor (k = 0; list2[i].elem[j].values[k]; k++) {\n\t\t\tsize_t l = strlen (_(list2[i].elem[j].values[k]));\n\t\t\tif ((maxlen > l) && (strlen (val) < l))\n\t\t\t\tstrncpy (val, _(list2[i].elem[j].values[k]), maxlen-1);\n\t\t}\n\t\tif (!val[0]) snprintf (val, maxlen, \"%i\", v_short);\n\n\t\tbreak;\n\n\tcase EXIF_TAG_PLANAR_CONFIGURATION:\n\tcase EXIF_TAG_SENSING_METHOD:\n\tcase EXIF_TAG_ORIENTATION:\n\tcase EXIF_TAG_YCBCR_POSITIONING:\n\tcase EXIF_TAG_PHOTOMETRIC_INTERPRETATION:\n\tcase EXIF_TAG_CUSTOM_RENDERED:\n\tcase EXIF_TAG_EXPOSURE_MODE:\n\tcase EXIF_TAG_WHITE_BALANCE:\n\tcase EXIF_TAG_SCENE_CAPTURE_TYPE:\n\tcase EXIF_TAG_GAIN_CONTROL:\n\tcase EXIF_TAG_SATURATION:\n\tcase EXIF_TAG_CONTRAST:\n\tcase EXIF_TAG_SHARPNESS:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list[i].tag && (list[i].tag != e->tag); i++);\n\t\tif (!list[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list[i].strings[j] && (j < v_short); j++);\n\t\tif (!list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, \"%i\", v_short);\n\t\telse if (!*list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, _(\"Unknown value %i\"), v_short);\n\t\telse\n\t\t\tstrncpy (val, _(list[i].strings[j]), maxlen-1);\n\t\tbreak;\n\n\tcase EXIF_TAG_XP_TITLE:\n\tcase EXIF_TAG_XP_COMMENT:\n\tcase EXIF_TAG_XP_AUTHOR:\n\tcase EXIF_TAG_XP_KEYWORDS:\n\tcase EXIF_TAG_XP_SUBJECT:\n\t{\n\t\tunsigned char *utf16;\n\n\t\t/* Sanity check the size to prevent overflow. Note EXIF files are 64kb at most. */\n\t\tif (e->size >= 65536 - sizeof(uint16_t)*2) break;\n\n\t\t/* The tag may not be U+0000-terminated , so make a local\n\t\t U+0000-terminated copy before converting it */\n\t\tutf16 = exif_mem_alloc (e->priv->mem, e->size+sizeof(uint16_t)+1);\n\t\tif (!utf16) break;\n\t\tmemcpy(utf16, e->data, e->size);\n\n\t\t/* NUL terminate the string. If the size is odd (which isn't possible\n\t\t * for a valid UTF16 string), then this will overwrite the high byte of\n\t\t * the final half word, plus add a full zero NUL word at the end.\n\t\t */\n\t\tutf16[e->size] = 0;\n\t\tutf16[e->size+1] = 0;\n\t\tutf16[e->size+2] = 0;\n\n\t\t/* Warning! The texts are converted from UTF16 to UTF8 */\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\texif_convert_utf16_to_utf8(val, utf16, maxlen);\n\t\texif_mem_free(e->priv->mem, utf16);\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\t/* Use a generic value formatting */\n\t\texif_entry_format_value(e, val, maxlen);\n\t}\n\n\treturn val;\n}", "func_hash": 208577582075189571580900372803695396814, "file_name": "exif-entry.c", "file_hash": 168929589483017098755049678071545935527, "cwe": ["CWE-787"], "cve": "CVE-2020-0452", "cve_desc": "In exif_entry_get_value of exif-entry.c, there is a possible out of bounds write due to an integer overflow. This could lead to remote code execution if a third party app used this library to process remote image data with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android-8.1 Android-9 Android-10 Android-11 Android-8.0Android ID: A-159625731", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0452"} {"idx": 206661, "project": "linux", "commit_id": "b4b814fec1a5a849383f7b3886b654a13abbda7d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/b4b814fec1a5a849383f7b3886b654a13abbda7d", "commit_message": "iwlwifi: dbg_ini: fix memory leak in alloc_sgtable\n\nIn alloc_sgtable if alloc_page fails, the alocated table should be\nreleased.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Luca Coelho ", "target": 1, "func": "static struct scatterlist *alloc_sgtable(int size)\n{\n\tint alloc_size, nents, i;\n\tstruct page *new_page;\n\tstruct scatterlist *iter;\n\tstruct scatterlist *table;\n\n\tnents = DIV_ROUND_UP(size, PAGE_SIZE);\n\ttable = kcalloc(nents, sizeof(*table), GFP_KERNEL);\n\tif (!table)\n\t\treturn NULL;\n\tsg_init_table(table, nents);\n\titer = table;\n\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\tnew_page = alloc_page(GFP_KERNEL);\n\t\tif (!new_page) {\n\t\t\t/* release all previous allocated pages in the table */\n\t\t\titer = table;\n\t\t\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\t\t\tnew_page = sg_page(iter);\n\t\t\t\tif (new_page)\n\t\t\t\t\t__free_page(new_page);\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\t\talloc_size = min_t(int, size, PAGE_SIZE);\n\t\tsize -= PAGE_SIZE;\n\t\tsg_set_page(iter, new_page, alloc_size, 0);\n\t}\n\treturn table;\n}", "func_hash": 194503570483133827627911350945318235426, "file_name": "dbg.c", "file_hash": 219263866465176544489021307308972472349, "cwe": ["CWE-401"], "cve": "CVE-2019-19058", "cve_desc": "A memory leak in the alloc_sgtable() function in drivers/net/wireless/intel/iwlwifi/fw/dbg.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering alloc_page() failures, aka CID-b4b814fec1a5.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19058"} {"idx": 384469, "project": "linux", "commit_id": "b4b814fec1a5a849383f7b3886b654a13abbda7d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/b4b814fec1a5a849383f7b3886b654a13abbda7d", "commit_message": "iwlwifi: dbg_ini: fix memory leak in alloc_sgtable\n\nIn alloc_sgtable if alloc_page fails, the alocated table should be\nreleased.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Luca Coelho ", "target": 0, "func": "static struct scatterlist *alloc_sgtable(int size)\n{\n\tint alloc_size, nents, i;\n\tstruct page *new_page;\n\tstruct scatterlist *iter;\n\tstruct scatterlist *table;\n\n\tnents = DIV_ROUND_UP(size, PAGE_SIZE);\n\ttable = kcalloc(nents, sizeof(*table), GFP_KERNEL);\n\tif (!table)\n\t\treturn NULL;\n\tsg_init_table(table, nents);\n\titer = table;\n\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\tnew_page = alloc_page(GFP_KERNEL);\n\t\tif (!new_page) {\n\t\t\t/* release all previous allocated pages in the table */\n\t\t\titer = table;\n\t\t\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\t\t\tnew_page = sg_page(iter);\n\t\t\t\tif (new_page)\n\t\t\t\t\t__free_page(new_page);\n\t\t\t}\n\t\t\tkfree(table);\n\t\t\treturn NULL;\n\t\t}\n\t\talloc_size = min_t(int, size, PAGE_SIZE);\n\t\tsize -= PAGE_SIZE;\n\t\tsg_set_page(iter, new_page, alloc_size, 0);\n\t}\n\treturn table;\n}", "func_hash": 202311053496689381695229983393462446086, "file_name": "dbg.c", "file_hash": 152279803512541666073398498327224765987, "cwe": ["CWE-401"], "cve": "CVE-2019-19058", "cve_desc": "A memory leak in the alloc_sgtable() function in drivers/net/wireless/intel/iwlwifi/fw/dbg.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering alloc_page() failures, aka CID-b4b814fec1a5.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19058"} {"idx": 206666, "project": "ceph", "commit_id": "ff72c50a2c43c57aead933eb4903ad1ca6d1748a", "project_url": "https://github.com/ceph/ceph", "commit_url": "https://github.com/ceph/ceph/commit/ff72c50a2c43c57aead933eb4903ad1ca6d1748a", "commit_message": "rgw: improve beast\n\nAvoid leaking connections that had partially-consumed\nclient data on unexpected disconnect.\n\nResolves CVE-2020-1700 (moderate impact flaw).\n\nFixes: https://tracker.ceph.com/issues/42531\n\nSigned-off-by: Or Friedmann \nSigned-off-by: Matt Benjamin ", "target": 1, "func": " size_t recv_body(char* buf, size_t max) override {\n auto& message = parser.get();\n auto& body_remaining = message.body();\n body_remaining.data = buf;\n body_remaining.size = max;\n\n while (body_remaining.size && !parser.is_done()) {\n boost::system::error_code ec;\n http::async_read_some(stream, buffer, parser, yield[ec]);\n if (ec == http::error::partial_message ||\n ec == http::error::need_buffer) {\n break;\n }\n if (ec) {\n ldout(cct, 4) << \"failed to read body: \" << ec.message() << dendl;\n throw rgw::io::Exception(ec.value(), std::system_category());\n }\n }\n return max - body_remaining.size;\n }", "func_hash": 174141585878683436574948394100370285842, "file_name": "rgw_asio_frontend.cc", "file_hash": 85648787665645832404370929383260334149, "cwe": ["CWE-400"], "cve": "CVE-2020-1700", "cve_desc": "A flaw was found in the way the Ceph RGW Beast front-end handles unexpected disconnects. An authenticated attacker can abuse this flaw by making multiple disconnect attempts resulting in a permanent leak of a socket connection by radosgw. This flaw could lead to a denial of service condition by pile up of CLOSE_WAIT sockets, eventually leading to the exhaustion of available resources, preventing legitimate users from connecting to the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1700"} {"idx": 384543, "project": "ceph", "commit_id": "ff72c50a2c43c57aead933eb4903ad1ca6d1748a", "project_url": "https://github.com/ceph/ceph", "commit_url": "https://github.com/ceph/ceph/commit/ff72c50a2c43c57aead933eb4903ad1ca6d1748a", "commit_message": "rgw: improve beast\n\nAvoid leaking connections that had partially-consumed\nclient data on unexpected disconnect.\n\nResolves CVE-2020-1700 (moderate impact flaw).\n\nFixes: https://tracker.ceph.com/issues/42531\n\nSigned-off-by: Or Friedmann \nSigned-off-by: Matt Benjamin ", "target": 0, "func": " size_t recv_body(char* buf, size_t max) override {\n auto& message = parser.get();\n auto& body_remaining = message.body();\n body_remaining.data = buf;\n body_remaining.size = max;\n\n while (body_remaining.size && !parser.is_done()) {\n boost::system::error_code ec;\n http::async_read_some(stream, buffer, parser, yield[ec]);\n if (ec == http::error::need_buffer) {\n break;\n }\n if (ec) {\n ldout(cct, 4) << \"failed to read body: \" << ec.message() << dendl;\n throw rgw::io::Exception(ec.value(), std::system_category());\n }\n }\n return max - body_remaining.size;\n }", "func_hash": 204168791261315762427200933496047685016, "file_name": "rgw_asio_frontend.cc", "file_hash": 85027027995983373400780407429769409751, "cwe": ["CWE-400"], "cve": "CVE-2020-1700", "cve_desc": "A flaw was found in the way the Ceph RGW Beast front-end handles unexpected disconnects. An authenticated attacker can abuse this flaw by making multiple disconnect attempts resulting in a permanent leak of a socket connection by radosgw. This flaw could lead to a denial of service condition by pile up of CLOSE_WAIT sockets, eventually leading to the exhaustion of available resources, preventing legitimate users from connecting to the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1700"} {"idx": 206691, "project": "wireshark", "commit_id": "7f3fe6164a68b76d9988c4253b24d43f498f1753", "project_url": "https://github.com/wireshark/wireshark", "commit_url": "https://gitlab.com/wireshark/wireshark/-/commit/7f3fe6164a68b76d9988c4253b24d43f498f1753", "commit_message": "TCP: do not use an unknown status when the checksum is 0xffff\n\nOtherwise it triggers an assert when adding the column as the field is\ndefined as BASE_NONE and not BASE_DEC or BASE_HEX. Thus an unknown value\n(not in proto_checksum_vals[)array) cannot be represented.\nMark the checksum as bad even if we process the packet.\nCloses #16816\n\nConflicts:\n\tepan/dissectors/packet-tcp.c", "target": 1, "func": "dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n guint8 th_off_x2; /* combines th_off and th_x2 */\n guint16 th_sum;\n guint32 th_urp;\n proto_tree *tcp_tree = NULL, *field_tree = NULL;\n proto_item *ti = NULL, *tf, *hidden_item;\n proto_item *options_item;\n proto_tree *options_tree;\n int offset = 0;\n const char *flags_str, *flags_str_first_letter;\n guint optlen;\n guint32 nxtseq = 0;\n guint reported_len;\n vec_t cksum_vec[4];\n guint32 phdr[2];\n guint16 computed_cksum;\n guint16 real_window;\n guint captured_length_remaining;\n gboolean desegment_ok;\n struct tcpinfo tcpinfo;\n struct tcpheader *tcph;\n proto_item *tf_syn = NULL, *tf_fin = NULL, *tf_rst = NULL, *scaled_pi;\n conversation_t *conv=NULL, *other_conv;\n guint32 save_last_frame = 0;\n struct tcp_analysis *tcpd=NULL;\n struct tcp_per_packet_data_t *tcppd=NULL;\n proto_item *item;\n proto_tree *checksum_tree;\n gboolean icmp_ip = FALSE;\n\n tcph = wmem_new0(wmem_packet_scope(), struct tcpheader);\n tcph->th_sport = tvb_get_ntohs(tvb, offset);\n tcph->th_dport = tvb_get_ntohs(tvb, offset + 2);\n copy_address_shallow(&tcph->ip_src, &pinfo->src);\n copy_address_shallow(&tcph->ip_dst, &pinfo->dst);\n\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"TCP\");\n col_clear(pinfo->cinfo, COL_INFO);\n col_append_ports(pinfo->cinfo, COL_INFO, PT_TCP, tcph->th_sport, tcph->th_dport);\n\n if (tree) {\n ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, ENC_NA);\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Src Port: %s, Dst Port: %s\",\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_sport),\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_dport));\n }\n tcp_tree = proto_item_add_subtree(ti, ett_tcp);\n p_add_proto_data(pinfo->pool, pinfo, proto_tcp, pinfo->curr_layer_num, tcp_tree);\n\n proto_tree_add_item(tcp_tree, hf_tcp_srcport, tvb, offset, 2, ENC_BIG_ENDIAN);\n proto_tree_add_item(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n\n /* If we're dissecting the headers of a TCP packet in an ICMP packet\n * then go ahead and put the sequence numbers in the tree now (because\n * they won't be put in later because the ICMP packet only contains up\n * to the sequence number).\n * We should only need to do this for IPv4 since IPv6 will hopefully\n * carry enough TCP payload for this dissector to put the sequence\n * numbers in via the regular code path.\n */\n {\n wmem_list_frame_t *frame;\n frame = wmem_list_frame_prev(wmem_list_tail(pinfo->layers));\n if (proto_ip == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n frame = wmem_list_frame_prev(frame);\n if (proto_icmp == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n proto_tree_add_item(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, ENC_BIG_ENDIAN);\n icmp_ip = TRUE;\n }\n }\n }\n }\n\n /* Set the source and destination port numbers as soon as we get them,\n so that they're available to the \"Follow TCP Stream\" code even if\n we throw an exception dissecting the rest of the TCP header. */\n pinfo->ptype = PT_TCP;\n pinfo->srcport = tcph->th_sport;\n pinfo->destport = tcph->th_dport;\n\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_srcport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_sport));\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_dstport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_dport));\n\n tcph->th_rawseq = tvb_get_ntohl(tvb, offset + 4);\n tcph->th_seq = tcph->th_rawseq;\n tcph->th_ack = tvb_get_ntohl(tvb, offset + 8);\n th_off_x2 = tvb_get_guint8(tvb, offset + 12);\n tcpinfo.flags = tcph->th_flags = tvb_get_ntohs(tvb, offset + 12) & TH_MASK;\n tcph->th_win = tvb_get_ntohs(tvb, offset + 14);\n real_window = tcph->th_win;\n tcph->th_hlen = hi_nibble(th_off_x2) * 4; /* TCP header length, in bytes */\n\n /* find(or create if needed) the conversation for this tcp session\n * This is a slight deviation from find_or_create_conversation so it's\n * done manually. This is done to save the last frame of the conversation\n * in case a new conversation is found and the previous conversation needs\n * to be adjusted,\n */\n if((conv = find_conversation_pinfo(pinfo, 0)) != NULL) {\n /* Update how far the conversation reaches */\n if (pinfo->num > conv->last_frame) {\n save_last_frame = conv->last_frame;\n conv->last_frame = pinfo->num;\n }\n }\n else {\n conv = conversation_new(pinfo->num, &pinfo->src,\n &pinfo->dst, ENDPOINT_TCP,\n pinfo->srcport, pinfo->destport, 0);\n }\n tcpd=get_tcp_conversation_data(conv,pinfo);\n\n /* If this is a SYN packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, create a new conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==TH_SYN) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n\n conv=conversation_new(pinfo->num, &pinfo->src, &pinfo->dst, ENDPOINT_TCP, pinfo->srcport, pinfo->destport, 0);\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n /* If this is a SYN/ACK packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, try to find a conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n }\n\n other_conv = find_conversation(pinfo->num, &pinfo->dst, &pinfo->src, ENDPOINT_TCP, pinfo->destport, pinfo->srcport, 0);\n if (other_conv != NULL)\n {\n conv = other_conv;\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n\n if (tcpd) {\n item = proto_tree_add_uint(tcp_tree, hf_tcp_stream, tvb, offset, 0, tcpd->stream);\n PROTO_ITEM_SET_GENERATED(item);\n\n /* Copy the stream index into the header as well to make it available\n * to tap listeners.\n */\n tcph->th_stream = tcpd->stream;\n }\n\n /* Do we need to calculate timestamps relative to the tcp-stream? */\n if (tcp_calculate_ts) {\n tcppd = (struct tcp_per_packet_data_t *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tcp, pinfo->curr_layer_num);\n\n /*\n * Calculate the timestamps relative to this conversation (but only on the\n * first run when frames are accessed sequentially)\n */\n if (!(pinfo->fd->visited))\n tcp_calculate_timestamps(pinfo, tcpd, tcppd);\n }\n\n /*\n * If we've been handed an IP fragment, we don't know how big the TCP\n * segment is, so don't do anything that requires that we know that.\n *\n * The same applies if we're part of an error packet. (XXX - if the\n * ICMP and ICMPv6 dissectors could set a \"this is how big the IP\n * header says it is\" length in the tvbuff, we could use that; such\n * a length might also be useful for handling packets where the IP\n * length is bigger than the actual data available in the frame; the\n * dissectors should trust that length, and then throw a\n * ReportedBoundsError exception when they go past the end of the frame.)\n *\n * We also can't determine the segment length if the reported length\n * of the TCP packet is less than the TCP header length.\n */\n reported_len = tvb_reported_length(tvb);\n\n if (!pinfo->fragmented && !pinfo->flags.in_error_pkt) {\n if (reported_len < tcph->th_hlen) {\n proto_tree_add_expert_format(tcp_tree, pinfo, &ei_tcp_short_segment, tvb, offset, 0,\n \"Short segment. Segment/fragment does not contain a full TCP header\"\n \" (might be NMAP or someone else deliberately sending unusual packets)\");\n tcph->th_have_seglen = FALSE;\n } else {\n proto_item *pi;\n\n /* Compute the length of data in this segment. */\n tcph->th_seglen = reported_len - tcph->th_hlen;\n tcph->th_have_seglen = TRUE;\n\n pi = proto_tree_add_uint(ti, hf_tcp_len, tvb, offset+12, 1, tcph->th_seglen);\n PROTO_ITEM_SET_GENERATED(pi);\n\n /* handle TCP seq# analysis parse all new segments we see */\n if(tcp_analyze_seq) {\n if(!(pinfo->fd->visited)) {\n tcp_analyze_sequence_number(pinfo, tcph->th_seq, tcph->th_ack, tcph->th_seglen, tcph->th_flags, tcph->th_win, tcpd);\n }\n if(tcpd && tcp_relative_seq) {\n (tcph->th_seq) -= tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n (tcph->th_ack) -= tcpd->rev->base_seq;\n }\n }\n }\n\n /* re-calculate window size, based on scaling factor */\n if (!(tcph->th_flags&TH_SYN)) { /* SYNs are never scaled */\n if (tcpd && (tcpd->fwd->win_scale>=0)) {\n (tcph->th_win)<<=tcpd->fwd->win_scale;\n }\n else {\n /* Don't have it stored, so use preference setting instead! */\n if (tcp_default_window_scaling>=0) {\n (tcph->th_win)<<=tcp_default_window_scaling;\n }\n }\n }\n\n /* Compute the sequence number of next octet after this segment. */\n nxtseq = tcph->th_seq + tcph->th_seglen;\n if ((tcph->th_flags&(TH_SYN|TH_FIN)) && (tcph->th_seglen > 0)) {\n nxtseq += 1;\n }\n }\n } else\n tcph->th_have_seglen = FALSE;\n\n flags_str = tcp_flags_to_str(wmem_packet_scope(), tcph);\n flags_str_first_letter = tcp_flags_to_str_first_letter(tcph);\n\n col_append_lstr(pinfo->cinfo, COL_INFO,\n \" [\", flags_str, \"]\",\n COL_ADD_LSTR_TERMINATOR);\n tcp_info_append_uint(pinfo, \"Seq\", tcph->th_seq);\n if (tcph->th_flags&TH_ACK)\n tcp_info_append_uint(pinfo, \"Ack\", tcph->th_ack);\n\n tcp_info_append_uint(pinfo, \"Win\", tcph->th_win);\n\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Seq: %u\", tcph->th_seq);\n }\n\n if (!icmp_ip) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n proto_tree_add_uint_format_value(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq, \"%u (relative sequence number)\", tcph->th_seq);\n } else {\n proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq);\n }\n }\n\n if (tcph->th_hlen < TCPH_MIN_LEN) {\n /* Give up at this point; we put the source and destination port in\n the tree, before fetching the header length, so that they'll\n show up if this is in the failing packet in an ICMP error packet,\n but it's now time to give up if the header length is bogus. */\n col_append_fstr(pinfo->cinfo, COL_INFO, \", bogus TCP header length (%u, must be at least %u)\",\n tcph->th_hlen, TCPH_MIN_LEN);\n if (tree) {\n tf = proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen >> 2);\n expert_add_info_format(pinfo, tf, &ei_tcp_bogus_header_length,\n \"Bogus TCP header length (%u, must be at least %u)\", tcph->th_hlen, TCPH_MIN_LEN);\n }\n return offset+12;\n }\n\n if (tcp_summary_in_tree) {\n if(tcph->th_flags&TH_ACK) {\n proto_item_append_text(ti, \", Ack: %u\", tcph->th_ack);\n }\n if (tcph->th_have_seglen)\n proto_item_append_text(ti, \", Len: %u\", tcph->th_seglen);\n }\n proto_item_set_len(ti, tcph->th_hlen);\n if (tcph->th_have_seglen) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n tf=proto_tree_add_uint_format_value(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq, \"%u (relative sequence number)\", nxtseq);\n } else {\n tf=proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);\n }\n PROTO_ITEM_SET_GENERATED(tf);\n }\n\n tf = proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack);\n if (tcph->th_flags & TH_ACK) {\n if (tcp_relative_seq && tcp_analyze_seq) {\n proto_item_append_text(tf, \" (relative ack number)\");\n }\n } else {\n /* Note if the ACK field is non-zero */\n if (tvb_get_ntohl(tvb, offset+8) != 0) {\n expert_add_info(pinfo, tf, &ei_tcp_ack_nonzero);\n }\n }\n\n if (tree) {\n // This should be consistent with ip.hdr_len.\n proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen>>2);\n tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 12, 2,\n tcph->th_flags, \"Flags: 0x%03x (%s)\", tcph->th_flags, flags_str);\n field_tree = proto_item_add_subtree(tf, ett_tcp_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_res, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ns, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, tcph->th_flags);\n tf_rst = proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, tcph->th_flags);\n tf_syn = proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, tcph->th_flags);\n tf_fin = proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, tcph->th_flags);\n\n tf = proto_tree_add_string(field_tree, hf_tcp_flags_str, tvb, offset + 12, 2, flags_str_first_letter);\n PROTO_ITEM_SET_GENERATED(tf);\n /* As discussed in bug 5541, it is better to use two separate\n * fields for the real and calculated window size.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_window_size_value, tvb, offset + 14, 2, real_window);\n scaled_pi = proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n\n if( !(tcph->th_flags&TH_SYN) && tcpd ) {\n switch (tcpd->fwd->win_scale) {\n\n case -1:\n {\n gint16 win_scale = tcpd->fwd->win_scale;\n gboolean override_with_pref = FALSE;\n\n /* Use preference setting (if set) */\n if (tcp_default_window_scaling != WindowScaling_NotKnown) {\n win_scale = tcp_default_window_scaling;\n override_with_pref = TRUE;\n }\n\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2,\n win_scale, \"%d (%s)\",\n win_scale,\n (override_with_pref) ? \"missing - taken from preference\" : \"unknown\");\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n break;\n\n case -2:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, tcpd->fwd->win_scale, \"%d (no window scaling used)\", tcpd->fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n break;\n\n default:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, 1<fwd->win_scale, \"%d\", 1<fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n }\n }\n\n if(tcph->th_flags & TH_SYN) {\n if(tcph->th_flags & TH_ACK) {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_sack,\n \"Connection establish acknowledge (SYN+ACK): server port %u\", tcph->th_sport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_sport;\n }\n else {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_syn,\n \"Connection establish request (SYN): server port %u\", tcph->th_dport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_dport;\n tcpd->ts_mru_syn = pinfo->abs_ts;\n }\n /* Remember where the next segment will start. */\n if (tcp_desegment && tcp_reassemble_out_of_order && tcpd && !PINFO_FD_VISITED(pinfo)) {\n if (tcpd->fwd->maxnextseq == 0) {\n tcpd->fwd->maxnextseq = tcph->th_seq + 1;\n }\n }\n }\n if(tcph->th_flags & TH_FIN) {\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_fin, &ei_tcp_connection_fin);\n }\n if(tcph->th_flags & TH_RST)\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_rst, &ei_tcp_connection_rst);\n\n if(tcp_analyze_seq\n && (tcph->th_flags & (TH_SYN|TH_ACK)) == TH_ACK\n && !nstime_is_zero(&tcpd->ts_mru_syn)\n && nstime_is_zero(&tcpd->ts_first_rtt)) {\n /* If all of the following:\n * - we care (the pref is set)\n * - this is a pure ACK\n * - we have a timestamp for the most-recently-transmitted SYN\n * - we haven't seen a pure ACK yet (no ts_first_rtt stored)\n * then assume it's the last part of the handshake and store the initial\n * RTT time\n */\n nstime_delta(&(tcpd->ts_first_rtt), &(pinfo->abs_ts), &(tcpd->ts_mru_syn));\n }\n\n /* Supply the sequence number of the first byte and of the first byte\n after the segment. */\n tcpinfo.seq = tcph->th_seq;\n tcpinfo.nxtseq = nxtseq;\n tcpinfo.lastackseq = tcph->th_ack;\n\n /* Assume we'll pass un-reassembled data to subdissectors. */\n tcpinfo.is_reassembled = FALSE;\n\n /*\n * Assume, initially, that we can't desegment.\n */\n pinfo->can_desegment = 0;\n th_sum = tvb_get_ntohs(tvb, offset + 16);\n if (!pinfo->fragmented && tvb_bytes_exist(tvb, 0, reported_len)) {\n /* The packet isn't part of an un-reassembled fragmented datagram\n and isn't truncated. This means we have all the data, and thus\n can checksum it and, unless it's being returned in an error\n packet, are willing to allow subdissectors to request reassembly\n on it. */\n\n if (tcp_check_checksum) {\n /* We haven't turned checksum checking off; checksum it. */\n\n /* Set up the fields of the pseudo-header. */\n SET_CKSUM_VEC_PTR(cksum_vec[0], (const guint8 *)pinfo->src.data, pinfo->src.len);\n SET_CKSUM_VEC_PTR(cksum_vec[1], (const guint8 *)pinfo->dst.data, pinfo->dst.len);\n switch (pinfo->src.type) {\n\n case AT_IPv4:\n phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 4);\n break;\n\n case AT_IPv6:\n phdr[0] = g_htonl(reported_len);\n phdr[1] = g_htonl(IP_PROTO_TCP);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 8);\n break;\n\n default:\n /* TCP runs only atop IPv4 and IPv6.... */\n DISSECTOR_ASSERT_NOT_REACHED();\n break;\n }\n SET_CKSUM_VEC_TVB(cksum_vec[3], tvb, offset, reported_len);\n computed_cksum = in_cksum(cksum_vec, 4);\n if (computed_cksum == 0 && th_sum == 0xffff) {\n item = proto_tree_add_uint_format_value(tcp_tree, hf_tcp_checksum, tvb,\n offset + 16, 2, th_sum,\n \"0x%04x [should be 0x0000 (see RFC 1624)]\", th_sum);\n\n checksum_tree = proto_item_add_subtree(item, ett_tcp_checksum);\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, 0x0000);\n PROTO_ITEM_SET_GENERATED(item);\n /* XXX - What should this special status be? */\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_status, tvb,\n offset + 16, 0, 4);\n PROTO_ITEM_SET_GENERATED(item);\n expert_add_info(pinfo, item, &ei_tcp_checksum_ffff);\n\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM 0xFFFF]\");\n\n /* Checksum is treated as valid on most systems, so we're willing to desegment it. */\n desegment_ok = TRUE;\n } else {\n proto_item* calc_item;\n item = proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, computed_cksum,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_VERIFY|PROTO_CHECKSUM_IN_CKSUM);\n\n calc_item = proto_tree_add_uint(tcp_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, in_cksum_shouldbe(th_sum, computed_cksum));\n PROTO_ITEM_SET_GENERATED(calc_item);\n\n /* Checksum is valid, so we're willing to desegment it. */\n if (computed_cksum == 0) {\n desegment_ok = TRUE;\n } else {\n proto_item_append_text(item, \"(maybe caused by \\\"TCP checksum offload\\\"?)\");\n\n /* Checksum is invalid, so we're not willing to desegment it. */\n desegment_ok = FALSE;\n pinfo->noreassembly_reason = \" [incorrect TCP checksum]\";\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM INCORRECT]\");\n }\n }\n } else {\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* We didn't check the checksum, and don't care if it's valid,\n so we're willing to desegment it. */\n desegment_ok = TRUE;\n }\n } else {\n /* We don't have all the packet data, so we can't checksum it... */\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* ...and aren't willing to desegment it. */\n desegment_ok = FALSE;\n }\n\n if (desegment_ok) {\n /* We're willing to desegment this. Is desegmentation enabled? */\n if (tcp_desegment) {\n /* Yes - is this segment being returned in an error packet? */\n if (!pinfo->flags.in_error_pkt) {\n /* No - indicate that we will desegment.\n We do NOT want to desegment segments returned in error\n packets, as they're not part of a TCP connection. */\n pinfo->can_desegment = 2;\n }\n }\n }\n\n item = proto_tree_add_item_ret_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, ENC_BIG_ENDIAN, &th_urp);\n\n if (IS_TH_URG(tcph->th_flags)) {\n /* Export the urgent pointer, for the benefit of protocols such as\n rlogin. */\n tcpinfo.urgent_pointer = (guint16)th_urp;\n tcp_info_append_uint(pinfo, \"Urg\", th_urp);\n } else {\n if (th_urp) {\n /* Note if the urgent pointer field is non-zero */\n expert_add_info(pinfo, item, &ei_tcp_urgent_pointer_non_zero);\n }\n }\n\n if (tcph->th_have_seglen)\n tcp_info_append_uint(pinfo, \"Len\", tcph->th_seglen);\n\n /* If there's more than just the fixed-length header (20 bytes), create\n a protocol tree item for the options. (We already know there's\n not less than the fixed-length header - we checked that above.)\n\n We ensure that we don't throw an exception here, so that we can\n do some analysis before we dissect the options and possibly\n throw an exception. (Trying to avoid throwing an exception when\n dissecting options is not something we should do.) */\n optlen = tcph->th_hlen - TCPH_MIN_LEN; /* length of options, in bytes */\n options_item = NULL;\n options_tree = NULL;\n if (optlen != 0) {\n guint bc = (guint)tvb_captured_length_remaining(tvb, offset + 20);\n\n if (tcp_tree != NULL) {\n options_item = proto_tree_add_item(tcp_tree, hf_tcp_options, tvb, offset + 20,\n bc < optlen ? bc : optlen, ENC_NA);\n proto_item_set_text(options_item, \"Options: (%u bytes)\", optlen);\n options_tree = proto_item_add_subtree(options_item, ett_tcp_options);\n }\n }\n\n tcph->num_sack_ranges = 0;\n\n /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/\n if(tcp_analyze_seq) {\n guint32 use_seq = tcph->th_seq;\n guint32 use_ack = tcph->th_ack;\n /* May need to recover absolute values here... */\n if (tcp_relative_seq) {\n use_seq += tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n use_ack += tcpd->rev->base_seq;\n }\n }\n tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree, tcpd, use_seq, use_ack);\n }\n\n /* handle conversation timestamps */\n if(tcp_calculate_ts) {\n tcp_print_timestamps(pinfo, tvb, tcp_tree, tcpd, tcppd);\n }\n\n /* Now dissect the options. */\n if (optlen) {\n rvbd_option_data* option_data;\n\n tcp_dissect_options(tvb, offset + 20, optlen,\n TCPOPT_EOL, pinfo, options_tree,\n options_item, tcph);\n\n /* Do some post evaluation of some Riverbed probe options in the list */\n option_data = (rvbd_option_data*)p_get_proto_data(pinfo->pool, pinfo, proto_tcp_option_rvbd_probe, pinfo->curr_layer_num);\n if (option_data != NULL)\n {\n if (option_data->valid)\n {\n /* Distinguish S+ from S+* */\n col_prepend_fstr(pinfo->cinfo, COL_INFO, \"S%s, \",\n option_data->type == PROBE_TRACE ? \"#\" :\n (option_data->probe_flags & RVBD_FLAGS_PROBE_NCFE) ? \"+*\" : \"+\");\n }\n }\n\n }\n\n if(!pinfo->fd->visited) {\n if((tcph->th_flags & TH_SYN)==TH_SYN) {\n /* Check the validity of the window scale value\n */\n verify_tcp_window_scaling((tcph->th_flags&TH_ACK)==TH_ACK,tcpd);\n }\n\n if((tcph->th_flags & (TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) {\n /* If the SYN or the SYN+ACK offered SCPS capabilities,\n * validate the flow's bidirectional scps capabilities.\n * The or protects against broken implementations offering\n * SCPS capabilities on SYN+ACK even if it wasn't offered with the SYN\n */\n if(tcpd && ((tcpd->rev->scps_capable) || (tcpd->fwd->scps_capable))) {\n verify_scps(pinfo, tf_syn, tcpd);\n }\n\n }\n }\n\n if (tcph->th_mptcp) {\n\n if (tcp_analyze_mptcp) {\n mptcp_add_analysis_subtree(pinfo, tvb, tcp_tree, tcpd, tcpd->mptcp_analysis, tcph );\n }\n }\n\n /* Skip over header + options */\n offset += tcph->th_hlen;\n\n /* Check the packet length to see if there's more data\n (it could be an ACK-only packet) */\n captured_length_remaining = tvb_captured_length_remaining(tvb, offset);\n\n if (tcph->th_have_seglen) {\n if(have_tap_listener(tcp_follow_tap)) {\n tcp_follow_tap_data_t* follow_data = wmem_new0(wmem_packet_scope(), tcp_follow_tap_data_t);\n\n follow_data->tvb = tvb_new_subset_remaining(tvb, offset);\n follow_data->tcph = tcph;\n follow_data->tcpd = tcpd;\n\n tap_queue_packet(tcp_follow_tap, pinfo, follow_data);\n }\n }\n\n tap_queue_packet(tcp_tap, pinfo, tcph);\n\n /* if it is an MPTCP packet */\n if(tcpd->mptcp_analysis) {\n tap_queue_packet(mptcp_tap, pinfo, tcpd);\n }\n\n /* If we're reassembling something whose length isn't known\n * beforehand, and that runs all the way to the end of\n * the data stream, a FIN indicates the end of the data\n * stream and thus the completion of reassembly, so we\n * need to explicitly check for that here.\n */\n if(tcph->th_have_seglen && tcpd && (tcph->th_flags & TH_FIN)\n && (tcpd->fwd->flags&TCP_FLOW_REASSEMBLE_UNTIL_FIN) ) {\n struct tcp_multisegment_pdu *msp;\n\n /* Is this the FIN that ended the data stream or is it a\n * retransmission of that FIN?\n */\n if (tcpd->fwd->fin == 0 || tcpd->fwd->fin == pinfo->num) {\n /* Either we haven't seen a FIN for this flow or we\n * have and it's this frame. Note that this is the FIN\n * for this flow, terminate reassembly and dissect the\n * results. */\n tcpd->fwd->fin = pinfo->num;\n msp=(struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(tcpd->fwd->multisegment_pdus, tcph->th_seq-1);\n if(msp) {\n fragment_head *ipfd_head;\n\n ipfd_head = fragment_add(&tcp_reassembly_table, tvb, offset,\n pinfo, msp->first_frame, NULL,\n tcph->th_seq - msp->seq,\n tcph->th_seglen,\n FALSE );\n if(ipfd_head) {\n tvbuff_t *next_tvb;\n\n /* create a new TVB structure for desegmented data\n * datalen-1 to strip the dummy FIN byte off\n */\n next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);\n\n /* add desegmented data to the data source list */\n add_new_data_source(pinfo, next_tvb, \"Reassembled TCP\");\n\n /* Show details of the reassembly */\n print_tcp_fragment_tree(ipfd_head, tree, tcp_tree, pinfo, next_tvb);\n\n /* call the payload dissector\n * but make sure we don't offer desegmentation any more\n */\n pinfo->can_desegment = 0;\n\n process_tcp_payload(next_tvb, 0, pinfo, tree, tcp_tree, tcph->th_sport, tcph->th_dport, tcph->th_seq,\n nxtseq, FALSE, tcpd, &tcpinfo);\n\n return tvb_captured_length(tvb);\n }\n }\n } else {\n /* Yes. This is a retransmission of the final FIN (or it's\n * the final FIN transmitted via a different path).\n * XXX - we need to flag retransmissions a bit better.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_fin_retransmission, tvb, 0, 0, tcpd->fwd->fin);\n }\n }\n\n if (tcp_display_process_info && tcpd && ((tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) ||\n (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command))) {\n field_tree = proto_tree_add_subtree(tcp_tree, tvb, offset, 0, ett_tcp_process_info, &ti, \"Process Information\");\n PROTO_ITEM_SET_GENERATED(ti);\n if (tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_uid, tvb, 0, 0, tcpd->fwd->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_pid, tvb, 0, 0, tcpd->fwd->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_uname, tvb, 0, 0, tcpd->fwd->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_cmd, tvb, 0, 0, tcpd->fwd->process_info->command);\n }\n if (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_uid, tvb, 0, 0, tcpd->rev->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_pid, tvb, 0, 0, tcpd->rev->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_uname, tvb, 0, 0, tcpd->rev->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_cmd, tvb, 0, 0, tcpd->rev->process_info->command);\n }\n }\n\n /*\n * XXX - what, if any, of this should we do if this is included in an\n * error packet? It might be nice to see the details of the packet\n * that caused the ICMP error, but it might not be nice to have the\n * dissector update state based on it.\n * Also, we probably don't want to run TCP taps on those packets.\n */\n if (captured_length_remaining != 0) {\n if (tcph->th_flags & TH_RST) {\n /*\n * RFC1122 says:\n *\n * 4.2.2.12 RST Segment: RFC-793 Section 3.4\n *\n * A TCP SHOULD allow a received RST segment to include data.\n *\n * DISCUSSION\n * It has been suggested that a RST segment could contain\n * ASCII text that encoded and explained the cause of the\n * RST. No standard has yet been established for such\n * data.\n *\n * so for segments with RST we just display the data as text.\n */\n proto_tree_add_item(tcp_tree, hf_tcp_reset_cause, tvb, offset, captured_length_remaining, ENC_NA|ENC_ASCII);\n } else {\n /*\n * XXX - dissect_tcp_payload() expects the payload length, however\n * SYN and FIN increments the nxtseq by one without having\n * the data.\n */\n if ((tcph->th_flags&(TH_FIN|TH_SYN)) && (tcph->th_seglen > 0)) {\n nxtseq -= 1;\n }\n dissect_tcp_payload(tvb, pinfo, offset, tcph->th_seq, nxtseq,\n tcph->th_sport, tcph->th_dport, tree, tcp_tree, tcpd, &tcpinfo);\n }\n }\n return tvb_captured_length(tvb);\n}", "func_hash": 24683503942167461199776570007988322461, "file_name": "packet-tcp.c", "file_hash": 328561331850978279427129333702838412423, "cwe": ["CWE-354"], "cve": "CVE-2020-25862", "cve_desc": "In Wireshark 3.2.0 to 3.2.6, 3.0.0 to 3.0.13, and 2.6.0 to 2.6.20, the TCP dissector could crash. This was addressed in epan/dissectors/packet-tcp.c by changing the handling of the invalid 0xFFFF checksum.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25862"} {"idx": 385216, "project": "wireshark", "commit_id": "7f3fe6164a68b76d9988c4253b24d43f498f1753", "project_url": "https://github.com/wireshark/wireshark", "commit_url": "https://gitlab.com/wireshark/wireshark/-/commit/7f3fe6164a68b76d9988c4253b24d43f498f1753", "commit_message": "TCP: do not use an unknown status when the checksum is 0xffff\n\nOtherwise it triggers an assert when adding the column as the field is\ndefined as BASE_NONE and not BASE_DEC or BASE_HEX. Thus an unknown value\n(not in proto_checksum_vals[)array) cannot be represented.\nMark the checksum as bad even if we process the packet.\nCloses #16816\n\nConflicts:\n\tepan/dissectors/packet-tcp.c", "target": 0, "func": "dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n guint8 th_off_x2; /* combines th_off and th_x2 */\n guint16 th_sum;\n guint32 th_urp;\n proto_tree *tcp_tree = NULL, *field_tree = NULL;\n proto_item *ti = NULL, *tf, *hidden_item;\n proto_item *options_item;\n proto_tree *options_tree;\n int offset = 0;\n const char *flags_str, *flags_str_first_letter;\n guint optlen;\n guint32 nxtseq = 0;\n guint reported_len;\n vec_t cksum_vec[4];\n guint32 phdr[2];\n guint16 computed_cksum;\n guint16 real_window;\n guint captured_length_remaining;\n gboolean desegment_ok;\n struct tcpinfo tcpinfo;\n struct tcpheader *tcph;\n proto_item *tf_syn = NULL, *tf_fin = NULL, *tf_rst = NULL, *scaled_pi;\n conversation_t *conv=NULL, *other_conv;\n guint32 save_last_frame = 0;\n struct tcp_analysis *tcpd=NULL;\n struct tcp_per_packet_data_t *tcppd=NULL;\n proto_item *item;\n proto_tree *checksum_tree;\n gboolean icmp_ip = FALSE;\n\n tcph = wmem_new0(wmem_packet_scope(), struct tcpheader);\n tcph->th_sport = tvb_get_ntohs(tvb, offset);\n tcph->th_dport = tvb_get_ntohs(tvb, offset + 2);\n copy_address_shallow(&tcph->ip_src, &pinfo->src);\n copy_address_shallow(&tcph->ip_dst, &pinfo->dst);\n\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"TCP\");\n col_clear(pinfo->cinfo, COL_INFO);\n col_append_ports(pinfo->cinfo, COL_INFO, PT_TCP, tcph->th_sport, tcph->th_dport);\n\n if (tree) {\n ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, ENC_NA);\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Src Port: %s, Dst Port: %s\",\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_sport),\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_dport));\n }\n tcp_tree = proto_item_add_subtree(ti, ett_tcp);\n p_add_proto_data(pinfo->pool, pinfo, proto_tcp, pinfo->curr_layer_num, tcp_tree);\n\n proto_tree_add_item(tcp_tree, hf_tcp_srcport, tvb, offset, 2, ENC_BIG_ENDIAN);\n proto_tree_add_item(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n\n /* If we're dissecting the headers of a TCP packet in an ICMP packet\n * then go ahead and put the sequence numbers in the tree now (because\n * they won't be put in later because the ICMP packet only contains up\n * to the sequence number).\n * We should only need to do this for IPv4 since IPv6 will hopefully\n * carry enough TCP payload for this dissector to put the sequence\n * numbers in via the regular code path.\n */\n {\n wmem_list_frame_t *frame;\n frame = wmem_list_frame_prev(wmem_list_tail(pinfo->layers));\n if (proto_ip == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n frame = wmem_list_frame_prev(frame);\n if (proto_icmp == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n proto_tree_add_item(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, ENC_BIG_ENDIAN);\n icmp_ip = TRUE;\n }\n }\n }\n }\n\n /* Set the source and destination port numbers as soon as we get them,\n so that they're available to the \"Follow TCP Stream\" code even if\n we throw an exception dissecting the rest of the TCP header. */\n pinfo->ptype = PT_TCP;\n pinfo->srcport = tcph->th_sport;\n pinfo->destport = tcph->th_dport;\n\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_srcport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_sport));\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_dstport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_dport));\n\n tcph->th_rawseq = tvb_get_ntohl(tvb, offset + 4);\n tcph->th_seq = tcph->th_rawseq;\n tcph->th_ack = tvb_get_ntohl(tvb, offset + 8);\n th_off_x2 = tvb_get_guint8(tvb, offset + 12);\n tcpinfo.flags = tcph->th_flags = tvb_get_ntohs(tvb, offset + 12) & TH_MASK;\n tcph->th_win = tvb_get_ntohs(tvb, offset + 14);\n real_window = tcph->th_win;\n tcph->th_hlen = hi_nibble(th_off_x2) * 4; /* TCP header length, in bytes */\n\n /* find(or create if needed) the conversation for this tcp session\n * This is a slight deviation from find_or_create_conversation so it's\n * done manually. This is done to save the last frame of the conversation\n * in case a new conversation is found and the previous conversation needs\n * to be adjusted,\n */\n if((conv = find_conversation_pinfo(pinfo, 0)) != NULL) {\n /* Update how far the conversation reaches */\n if (pinfo->num > conv->last_frame) {\n save_last_frame = conv->last_frame;\n conv->last_frame = pinfo->num;\n }\n }\n else {\n conv = conversation_new(pinfo->num, &pinfo->src,\n &pinfo->dst, ENDPOINT_TCP,\n pinfo->srcport, pinfo->destport, 0);\n }\n tcpd=get_tcp_conversation_data(conv,pinfo);\n\n /* If this is a SYN packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, create a new conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==TH_SYN) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n\n conv=conversation_new(pinfo->num, &pinfo->src, &pinfo->dst, ENDPOINT_TCP, pinfo->srcport, pinfo->destport, 0);\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n /* If this is a SYN/ACK packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, try to find a conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n }\n\n other_conv = find_conversation(pinfo->num, &pinfo->dst, &pinfo->src, ENDPOINT_TCP, pinfo->destport, pinfo->srcport, 0);\n if (other_conv != NULL)\n {\n conv = other_conv;\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n\n if (tcpd) {\n item = proto_tree_add_uint(tcp_tree, hf_tcp_stream, tvb, offset, 0, tcpd->stream);\n PROTO_ITEM_SET_GENERATED(item);\n\n /* Copy the stream index into the header as well to make it available\n * to tap listeners.\n */\n tcph->th_stream = tcpd->stream;\n }\n\n /* Do we need to calculate timestamps relative to the tcp-stream? */\n if (tcp_calculate_ts) {\n tcppd = (struct tcp_per_packet_data_t *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tcp, pinfo->curr_layer_num);\n\n /*\n * Calculate the timestamps relative to this conversation (but only on the\n * first run when frames are accessed sequentially)\n */\n if (!(pinfo->fd->visited))\n tcp_calculate_timestamps(pinfo, tcpd, tcppd);\n }\n\n /*\n * If we've been handed an IP fragment, we don't know how big the TCP\n * segment is, so don't do anything that requires that we know that.\n *\n * The same applies if we're part of an error packet. (XXX - if the\n * ICMP and ICMPv6 dissectors could set a \"this is how big the IP\n * header says it is\" length in the tvbuff, we could use that; such\n * a length might also be useful for handling packets where the IP\n * length is bigger than the actual data available in the frame; the\n * dissectors should trust that length, and then throw a\n * ReportedBoundsError exception when they go past the end of the frame.)\n *\n * We also can't determine the segment length if the reported length\n * of the TCP packet is less than the TCP header length.\n */\n reported_len = tvb_reported_length(tvb);\n\n if (!pinfo->fragmented && !pinfo->flags.in_error_pkt) {\n if (reported_len < tcph->th_hlen) {\n proto_tree_add_expert_format(tcp_tree, pinfo, &ei_tcp_short_segment, tvb, offset, 0,\n \"Short segment. Segment/fragment does not contain a full TCP header\"\n \" (might be NMAP or someone else deliberately sending unusual packets)\");\n tcph->th_have_seglen = FALSE;\n } else {\n proto_item *pi;\n\n /* Compute the length of data in this segment. */\n tcph->th_seglen = reported_len - tcph->th_hlen;\n tcph->th_have_seglen = TRUE;\n\n pi = proto_tree_add_uint(ti, hf_tcp_len, tvb, offset+12, 1, tcph->th_seglen);\n PROTO_ITEM_SET_GENERATED(pi);\n\n /* handle TCP seq# analysis parse all new segments we see */\n if(tcp_analyze_seq) {\n if(!(pinfo->fd->visited)) {\n tcp_analyze_sequence_number(pinfo, tcph->th_seq, tcph->th_ack, tcph->th_seglen, tcph->th_flags, tcph->th_win, tcpd);\n }\n if(tcpd && tcp_relative_seq) {\n (tcph->th_seq) -= tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n (tcph->th_ack) -= tcpd->rev->base_seq;\n }\n }\n }\n\n /* re-calculate window size, based on scaling factor */\n if (!(tcph->th_flags&TH_SYN)) { /* SYNs are never scaled */\n if (tcpd && (tcpd->fwd->win_scale>=0)) {\n (tcph->th_win)<<=tcpd->fwd->win_scale;\n }\n else {\n /* Don't have it stored, so use preference setting instead! */\n if (tcp_default_window_scaling>=0) {\n (tcph->th_win)<<=tcp_default_window_scaling;\n }\n }\n }\n\n /* Compute the sequence number of next octet after this segment. */\n nxtseq = tcph->th_seq + tcph->th_seglen;\n if ((tcph->th_flags&(TH_SYN|TH_FIN)) && (tcph->th_seglen > 0)) {\n nxtseq += 1;\n }\n }\n } else\n tcph->th_have_seglen = FALSE;\n\n flags_str = tcp_flags_to_str(wmem_packet_scope(), tcph);\n flags_str_first_letter = tcp_flags_to_str_first_letter(tcph);\n\n col_append_lstr(pinfo->cinfo, COL_INFO,\n \" [\", flags_str, \"]\",\n COL_ADD_LSTR_TERMINATOR);\n tcp_info_append_uint(pinfo, \"Seq\", tcph->th_seq);\n if (tcph->th_flags&TH_ACK)\n tcp_info_append_uint(pinfo, \"Ack\", tcph->th_ack);\n\n tcp_info_append_uint(pinfo, \"Win\", tcph->th_win);\n\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Seq: %u\", tcph->th_seq);\n }\n\n if (!icmp_ip) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n proto_tree_add_uint_format_value(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq, \"%u (relative sequence number)\", tcph->th_seq);\n } else {\n proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq);\n }\n }\n\n if (tcph->th_hlen < TCPH_MIN_LEN) {\n /* Give up at this point; we put the source and destination port in\n the tree, before fetching the header length, so that they'll\n show up if this is in the failing packet in an ICMP error packet,\n but it's now time to give up if the header length is bogus. */\n col_append_fstr(pinfo->cinfo, COL_INFO, \", bogus TCP header length (%u, must be at least %u)\",\n tcph->th_hlen, TCPH_MIN_LEN);\n if (tree) {\n tf = proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen >> 2);\n expert_add_info_format(pinfo, tf, &ei_tcp_bogus_header_length,\n \"Bogus TCP header length (%u, must be at least %u)\", tcph->th_hlen, TCPH_MIN_LEN);\n }\n return offset+12;\n }\n\n if (tcp_summary_in_tree) {\n if(tcph->th_flags&TH_ACK) {\n proto_item_append_text(ti, \", Ack: %u\", tcph->th_ack);\n }\n if (tcph->th_have_seglen)\n proto_item_append_text(ti, \", Len: %u\", tcph->th_seglen);\n }\n proto_item_set_len(ti, tcph->th_hlen);\n if (tcph->th_have_seglen) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n tf=proto_tree_add_uint_format_value(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq, \"%u (relative sequence number)\", nxtseq);\n } else {\n tf=proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);\n }\n PROTO_ITEM_SET_GENERATED(tf);\n }\n\n tf = proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack);\n if (tcph->th_flags & TH_ACK) {\n if (tcp_relative_seq && tcp_analyze_seq) {\n proto_item_append_text(tf, \" (relative ack number)\");\n }\n } else {\n /* Note if the ACK field is non-zero */\n if (tvb_get_ntohl(tvb, offset+8) != 0) {\n expert_add_info(pinfo, tf, &ei_tcp_ack_nonzero);\n }\n }\n\n if (tree) {\n // This should be consistent with ip.hdr_len.\n proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen>>2);\n tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 12, 2,\n tcph->th_flags, \"Flags: 0x%03x (%s)\", tcph->th_flags, flags_str);\n field_tree = proto_item_add_subtree(tf, ett_tcp_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_res, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ns, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, tcph->th_flags);\n tf_rst = proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, tcph->th_flags);\n tf_syn = proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, tcph->th_flags);\n tf_fin = proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, tcph->th_flags);\n\n tf = proto_tree_add_string(field_tree, hf_tcp_flags_str, tvb, offset + 12, 2, flags_str_first_letter);\n PROTO_ITEM_SET_GENERATED(tf);\n /* As discussed in bug 5541, it is better to use two separate\n * fields for the real and calculated window size.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_window_size_value, tvb, offset + 14, 2, real_window);\n scaled_pi = proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n\n if( !(tcph->th_flags&TH_SYN) && tcpd ) {\n switch (tcpd->fwd->win_scale) {\n\n case -1:\n {\n gint16 win_scale = tcpd->fwd->win_scale;\n gboolean override_with_pref = FALSE;\n\n /* Use preference setting (if set) */\n if (tcp_default_window_scaling != WindowScaling_NotKnown) {\n win_scale = tcp_default_window_scaling;\n override_with_pref = TRUE;\n }\n\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2,\n win_scale, \"%d (%s)\",\n win_scale,\n (override_with_pref) ? \"missing - taken from preference\" : \"unknown\");\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n break;\n\n case -2:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, tcpd->fwd->win_scale, \"%d (no window scaling used)\", tcpd->fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n break;\n\n default:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, 1<fwd->win_scale, \"%d\", 1<fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n }\n }\n\n if(tcph->th_flags & TH_SYN) {\n if(tcph->th_flags & TH_ACK) {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_sack,\n \"Connection establish acknowledge (SYN+ACK): server port %u\", tcph->th_sport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_sport;\n }\n else {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_syn,\n \"Connection establish request (SYN): server port %u\", tcph->th_dport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_dport;\n tcpd->ts_mru_syn = pinfo->abs_ts;\n }\n /* Remember where the next segment will start. */\n if (tcp_desegment && tcp_reassemble_out_of_order && tcpd && !PINFO_FD_VISITED(pinfo)) {\n if (tcpd->fwd->maxnextseq == 0) {\n tcpd->fwd->maxnextseq = tcph->th_seq + 1;\n }\n }\n }\n if(tcph->th_flags & TH_FIN) {\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_fin, &ei_tcp_connection_fin);\n }\n if(tcph->th_flags & TH_RST)\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_rst, &ei_tcp_connection_rst);\n\n if(tcp_analyze_seq\n && (tcph->th_flags & (TH_SYN|TH_ACK)) == TH_ACK\n && !nstime_is_zero(&tcpd->ts_mru_syn)\n && nstime_is_zero(&tcpd->ts_first_rtt)) {\n /* If all of the following:\n * - we care (the pref is set)\n * - this is a pure ACK\n * - we have a timestamp for the most-recently-transmitted SYN\n * - we haven't seen a pure ACK yet (no ts_first_rtt stored)\n * then assume it's the last part of the handshake and store the initial\n * RTT time\n */\n nstime_delta(&(tcpd->ts_first_rtt), &(pinfo->abs_ts), &(tcpd->ts_mru_syn));\n }\n\n /* Supply the sequence number of the first byte and of the first byte\n after the segment. */\n tcpinfo.seq = tcph->th_seq;\n tcpinfo.nxtseq = nxtseq;\n tcpinfo.lastackseq = tcph->th_ack;\n\n /* Assume we'll pass un-reassembled data to subdissectors. */\n tcpinfo.is_reassembled = FALSE;\n\n /*\n * Assume, initially, that we can't desegment.\n */\n pinfo->can_desegment = 0;\n th_sum = tvb_get_ntohs(tvb, offset + 16);\n if (!pinfo->fragmented && tvb_bytes_exist(tvb, 0, reported_len)) {\n /* The packet isn't part of an un-reassembled fragmented datagram\n and isn't truncated. This means we have all the data, and thus\n can checksum it and, unless it's being returned in an error\n packet, are willing to allow subdissectors to request reassembly\n on it. */\n\n if (tcp_check_checksum) {\n /* We haven't turned checksum checking off; checksum it. */\n\n /* Set up the fields of the pseudo-header. */\n SET_CKSUM_VEC_PTR(cksum_vec[0], (const guint8 *)pinfo->src.data, pinfo->src.len);\n SET_CKSUM_VEC_PTR(cksum_vec[1], (const guint8 *)pinfo->dst.data, pinfo->dst.len);\n switch (pinfo->src.type) {\n\n case AT_IPv4:\n phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 4);\n break;\n\n case AT_IPv6:\n phdr[0] = g_htonl(reported_len);\n phdr[1] = g_htonl(IP_PROTO_TCP);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 8);\n break;\n\n default:\n /* TCP runs only atop IPv4 and IPv6.... */\n DISSECTOR_ASSERT_NOT_REACHED();\n break;\n }\n SET_CKSUM_VEC_TVB(cksum_vec[3], tvb, offset, reported_len);\n computed_cksum = in_cksum(cksum_vec, 4);\n if (computed_cksum == 0 && th_sum == 0xffff) {\n item = proto_tree_add_uint_format_value(tcp_tree, hf_tcp_checksum, tvb,\n offset + 16, 2, th_sum,\n \"0x%04x [should be 0x0000 (see RFC 1624)]\", th_sum);\n\n checksum_tree = proto_item_add_subtree(item, ett_tcp_checksum);\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, 0x0000);\n PROTO_ITEM_SET_GENERATED(item);\n /* XXX - What should this special status be? */\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_status, tvb,\n offset + 16, 0, PROTO_CHECKSUM_E_BAD);\n PROTO_ITEM_SET_GENERATED(item);\n expert_add_info(pinfo, item, &ei_tcp_checksum_ffff);\n\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM 0xFFFF]\");\n\n /* Checksum is treated as valid on most systems, so we're willing to desegment it. */\n desegment_ok = TRUE;\n } else {\n proto_item* calc_item;\n item = proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, computed_cksum,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_VERIFY|PROTO_CHECKSUM_IN_CKSUM);\n\n calc_item = proto_tree_add_uint(tcp_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, in_cksum_shouldbe(th_sum, computed_cksum));\n PROTO_ITEM_SET_GENERATED(calc_item);\n\n /* Checksum is valid, so we're willing to desegment it. */\n if (computed_cksum == 0) {\n desegment_ok = TRUE;\n } else {\n proto_item_append_text(item, \"(maybe caused by \\\"TCP checksum offload\\\"?)\");\n\n /* Checksum is invalid, so we're not willing to desegment it. */\n desegment_ok = FALSE;\n pinfo->noreassembly_reason = \" [incorrect TCP checksum]\";\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM INCORRECT]\");\n }\n }\n } else {\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* We didn't check the checksum, and don't care if it's valid,\n so we're willing to desegment it. */\n desegment_ok = TRUE;\n }\n } else {\n /* We don't have all the packet data, so we can't checksum it... */\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* ...and aren't willing to desegment it. */\n desegment_ok = FALSE;\n }\n\n if (desegment_ok) {\n /* We're willing to desegment this. Is desegmentation enabled? */\n if (tcp_desegment) {\n /* Yes - is this segment being returned in an error packet? */\n if (!pinfo->flags.in_error_pkt) {\n /* No - indicate that we will desegment.\n We do NOT want to desegment segments returned in error\n packets, as they're not part of a TCP connection. */\n pinfo->can_desegment = 2;\n }\n }\n }\n\n item = proto_tree_add_item_ret_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, ENC_BIG_ENDIAN, &th_urp);\n\n if (IS_TH_URG(tcph->th_flags)) {\n /* Export the urgent pointer, for the benefit of protocols such as\n rlogin. */\n tcpinfo.urgent_pointer = (guint16)th_urp;\n tcp_info_append_uint(pinfo, \"Urg\", th_urp);\n } else {\n if (th_urp) {\n /* Note if the urgent pointer field is non-zero */\n expert_add_info(pinfo, item, &ei_tcp_urgent_pointer_non_zero);\n }\n }\n\n if (tcph->th_have_seglen)\n tcp_info_append_uint(pinfo, \"Len\", tcph->th_seglen);\n\n /* If there's more than just the fixed-length header (20 bytes), create\n a protocol tree item for the options. (We already know there's\n not less than the fixed-length header - we checked that above.)\n\n We ensure that we don't throw an exception here, so that we can\n do some analysis before we dissect the options and possibly\n throw an exception. (Trying to avoid throwing an exception when\n dissecting options is not something we should do.) */\n optlen = tcph->th_hlen - TCPH_MIN_LEN; /* length of options, in bytes */\n options_item = NULL;\n options_tree = NULL;\n if (optlen != 0) {\n guint bc = (guint)tvb_captured_length_remaining(tvb, offset + 20);\n\n if (tcp_tree != NULL) {\n options_item = proto_tree_add_item(tcp_tree, hf_tcp_options, tvb, offset + 20,\n bc < optlen ? bc : optlen, ENC_NA);\n proto_item_set_text(options_item, \"Options: (%u bytes)\", optlen);\n options_tree = proto_item_add_subtree(options_item, ett_tcp_options);\n }\n }\n\n tcph->num_sack_ranges = 0;\n\n /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/\n if(tcp_analyze_seq) {\n guint32 use_seq = tcph->th_seq;\n guint32 use_ack = tcph->th_ack;\n /* May need to recover absolute values here... */\n if (tcp_relative_seq) {\n use_seq += tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n use_ack += tcpd->rev->base_seq;\n }\n }\n tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree, tcpd, use_seq, use_ack);\n }\n\n /* handle conversation timestamps */\n if(tcp_calculate_ts) {\n tcp_print_timestamps(pinfo, tvb, tcp_tree, tcpd, tcppd);\n }\n\n /* Now dissect the options. */\n if (optlen) {\n rvbd_option_data* option_data;\n\n tcp_dissect_options(tvb, offset + 20, optlen,\n TCPOPT_EOL, pinfo, options_tree,\n options_item, tcph);\n\n /* Do some post evaluation of some Riverbed probe options in the list */\n option_data = (rvbd_option_data*)p_get_proto_data(pinfo->pool, pinfo, proto_tcp_option_rvbd_probe, pinfo->curr_layer_num);\n if (option_data != NULL)\n {\n if (option_data->valid)\n {\n /* Distinguish S+ from S+* */\n col_prepend_fstr(pinfo->cinfo, COL_INFO, \"S%s, \",\n option_data->type == PROBE_TRACE ? \"#\" :\n (option_data->probe_flags & RVBD_FLAGS_PROBE_NCFE) ? \"+*\" : \"+\");\n }\n }\n\n }\n\n if(!pinfo->fd->visited) {\n if((tcph->th_flags & TH_SYN)==TH_SYN) {\n /* Check the validity of the window scale value\n */\n verify_tcp_window_scaling((tcph->th_flags&TH_ACK)==TH_ACK,tcpd);\n }\n\n if((tcph->th_flags & (TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) {\n /* If the SYN or the SYN+ACK offered SCPS capabilities,\n * validate the flow's bidirectional scps capabilities.\n * The or protects against broken implementations offering\n * SCPS capabilities on SYN+ACK even if it wasn't offered with the SYN\n */\n if(tcpd && ((tcpd->rev->scps_capable) || (tcpd->fwd->scps_capable))) {\n verify_scps(pinfo, tf_syn, tcpd);\n }\n\n }\n }\n\n if (tcph->th_mptcp) {\n\n if (tcp_analyze_mptcp) {\n mptcp_add_analysis_subtree(pinfo, tvb, tcp_tree, tcpd, tcpd->mptcp_analysis, tcph );\n }\n }\n\n /* Skip over header + options */\n offset += tcph->th_hlen;\n\n /* Check the packet length to see if there's more data\n (it could be an ACK-only packet) */\n captured_length_remaining = tvb_captured_length_remaining(tvb, offset);\n\n if (tcph->th_have_seglen) {\n if(have_tap_listener(tcp_follow_tap)) {\n tcp_follow_tap_data_t* follow_data = wmem_new0(wmem_packet_scope(), tcp_follow_tap_data_t);\n\n follow_data->tvb = tvb_new_subset_remaining(tvb, offset);\n follow_data->tcph = tcph;\n follow_data->tcpd = tcpd;\n\n tap_queue_packet(tcp_follow_tap, pinfo, follow_data);\n }\n }\n\n tap_queue_packet(tcp_tap, pinfo, tcph);\n\n /* if it is an MPTCP packet */\n if(tcpd->mptcp_analysis) {\n tap_queue_packet(mptcp_tap, pinfo, tcpd);\n }\n\n /* If we're reassembling something whose length isn't known\n * beforehand, and that runs all the way to the end of\n * the data stream, a FIN indicates the end of the data\n * stream and thus the completion of reassembly, so we\n * need to explicitly check for that here.\n */\n if(tcph->th_have_seglen && tcpd && (tcph->th_flags & TH_FIN)\n && (tcpd->fwd->flags&TCP_FLOW_REASSEMBLE_UNTIL_FIN) ) {\n struct tcp_multisegment_pdu *msp;\n\n /* Is this the FIN that ended the data stream or is it a\n * retransmission of that FIN?\n */\n if (tcpd->fwd->fin == 0 || tcpd->fwd->fin == pinfo->num) {\n /* Either we haven't seen a FIN for this flow or we\n * have and it's this frame. Note that this is the FIN\n * for this flow, terminate reassembly and dissect the\n * results. */\n tcpd->fwd->fin = pinfo->num;\n msp=(struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(tcpd->fwd->multisegment_pdus, tcph->th_seq-1);\n if(msp) {\n fragment_head *ipfd_head;\n\n ipfd_head = fragment_add(&tcp_reassembly_table, tvb, offset,\n pinfo, msp->first_frame, NULL,\n tcph->th_seq - msp->seq,\n tcph->th_seglen,\n FALSE );\n if(ipfd_head) {\n tvbuff_t *next_tvb;\n\n /* create a new TVB structure for desegmented data\n * datalen-1 to strip the dummy FIN byte off\n */\n next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);\n\n /* add desegmented data to the data source list */\n add_new_data_source(pinfo, next_tvb, \"Reassembled TCP\");\n\n /* Show details of the reassembly */\n print_tcp_fragment_tree(ipfd_head, tree, tcp_tree, pinfo, next_tvb);\n\n /* call the payload dissector\n * but make sure we don't offer desegmentation any more\n */\n pinfo->can_desegment = 0;\n\n process_tcp_payload(next_tvb, 0, pinfo, tree, tcp_tree, tcph->th_sport, tcph->th_dport, tcph->th_seq,\n nxtseq, FALSE, tcpd, &tcpinfo);\n\n return tvb_captured_length(tvb);\n }\n }\n } else {\n /* Yes. This is a retransmission of the final FIN (or it's\n * the final FIN transmitted via a different path).\n * XXX - we need to flag retransmissions a bit better.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_fin_retransmission, tvb, 0, 0, tcpd->fwd->fin);\n }\n }\n\n if (tcp_display_process_info && tcpd && ((tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) ||\n (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command))) {\n field_tree = proto_tree_add_subtree(tcp_tree, tvb, offset, 0, ett_tcp_process_info, &ti, \"Process Information\");\n PROTO_ITEM_SET_GENERATED(ti);\n if (tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_uid, tvb, 0, 0, tcpd->fwd->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_pid, tvb, 0, 0, tcpd->fwd->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_uname, tvb, 0, 0, tcpd->fwd->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_cmd, tvb, 0, 0, tcpd->fwd->process_info->command);\n }\n if (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_uid, tvb, 0, 0, tcpd->rev->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_pid, tvb, 0, 0, tcpd->rev->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_uname, tvb, 0, 0, tcpd->rev->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_cmd, tvb, 0, 0, tcpd->rev->process_info->command);\n }\n }\n\n /*\n * XXX - what, if any, of this should we do if this is included in an\n * error packet? It might be nice to see the details of the packet\n * that caused the ICMP error, but it might not be nice to have the\n * dissector update state based on it.\n * Also, we probably don't want to run TCP taps on those packets.\n */\n if (captured_length_remaining != 0) {\n if (tcph->th_flags & TH_RST) {\n /*\n * RFC1122 says:\n *\n * 4.2.2.12 RST Segment: RFC-793 Section 3.4\n *\n * A TCP SHOULD allow a received RST segment to include data.\n *\n * DISCUSSION\n * It has been suggested that a RST segment could contain\n * ASCII text that encoded and explained the cause of the\n * RST. No standard has yet been established for such\n * data.\n *\n * so for segments with RST we just display the data as text.\n */\n proto_tree_add_item(tcp_tree, hf_tcp_reset_cause, tvb, offset, captured_length_remaining, ENC_NA|ENC_ASCII);\n } else {\n /*\n * XXX - dissect_tcp_payload() expects the payload length, however\n * SYN and FIN increments the nxtseq by one without having\n * the data.\n */\n if ((tcph->th_flags&(TH_FIN|TH_SYN)) && (tcph->th_seglen > 0)) {\n nxtseq -= 1;\n }\n dissect_tcp_payload(tvb, pinfo, offset, tcph->th_seq, nxtseq,\n tcph->th_sport, tcph->th_dport, tree, tcp_tree, tcpd, &tcpinfo);\n }\n }\n return tvb_captured_length(tvb);\n}", "func_hash": 253847630952050505529323358407275133849, "file_name": "packet-tcp.c", "file_hash": 309950411622796714718699134292653440494, "cwe": ["CWE-354"], "cve": "CVE-2020-25862", "cve_desc": "In Wireshark 3.2.0 to 3.2.6, 3.0.0 to 3.0.13, and 2.6.0 to 2.6.20, the TCP dissector could crash. This was addressed in epan/dissectors/packet-tcp.c by changing the handling of the invalid 0xFFFF checksum.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25862"} {"idx": 206697, "project": "linux", "commit_id": "f60a85cad677c4f9bb4cadd764f1d106c38c7cf8", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f60a85cad677c4f9bb4cadd764f1d106c38c7cf8", "commit_message": "bpf: Fix umd memory leak in copy_process()\n\nThe syzbot reported a memleak as follows:\n\nBUG: memory leak\nunreferenced object 0xffff888101b41d00 (size 120):\n comm \"kworker/u4:0\", pid 8, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] alloc_pid+0x66/0x560\n [] copy_process+0x1465/0x25e0\n [] kernel_clone+0xf3/0x670\n [] kernel_thread+0x61/0x80\n [] call_usermodehelper_exec_work\n [] call_usermodehelper_exec_work+0xc4/0x120\n [] process_one_work+0x2c9/0x600\n [] worker_thread+0x59/0x5d0\n [] kthread+0x178/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nunreferenced object 0xffff888110ef5c00 (size 232):\n comm \"kworker/u4:0\", pid 8414, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] kmem_cache_zalloc\n [] __alloc_file+0x1f/0xf0\n [] alloc_empty_file+0x69/0x120\n [] alloc_file+0x33/0x1b0\n [] alloc_file_pseudo+0xb2/0x140\n [] create_pipe_files+0x138/0x2e0\n [] umd_setup+0x33/0x220\n [] call_usermodehelper_exec_async+0xb4/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nAfter the UMD process exits, the pipe_to_umh/pipe_from_umh and\ntgid need to be released.\n\nFixes: d71fa5c9763c (\"bpf: Add kernel module with user mode driver that populates bpffs.\")\nReported-by: syzbot+44908bb56d2bfe56b28e@syzkaller.appspotmail.com\nSigned-off-by: Zqiang \nSigned-off-by: Daniel Borkmann \nLink: https://lore.kernel.org/bpf/20210317030915.2865-1-qiang.zhang@windriver.com", "target": 1, "func": "static void umd_cleanup(struct subprocess_info *info)\n{\n\tstruct umd_info *umd_info = info->data;\n\n\t/* cleanup if umh_setup() was successful but exec failed */\n\tif (info->retval) {\n\t\tfput(umd_info->pipe_to_umh);\n\t\tfput(umd_info->pipe_from_umh);\n\t\tput_pid(umd_info->tgid);\n\t\tumd_info->tgid = NULL;\n\t}\n}", "func_hash": 284673767217898920508895555052981783519, "file_name": "usermode_driver.c", "file_hash": 30512964958620639927921347909016208818, "cwe": ["CWE-401"], "cve": "CVE-2021-29649", "cve_desc": "An issue was discovered in the Linux kernel before 5.11.11. The user mode driver (UMD) has a copy_process() memory leak, related to a lack of cleanup steps in kernel/usermode_driver.c and kernel/bpf/preload/bpf_preload_kern.c, aka CID-f60a85cad677.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29649"} {"idx": 385297, "project": "linux", "commit_id": "f60a85cad677c4f9bb4cadd764f1d106c38c7cf8", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f60a85cad677c4f9bb4cadd764f1d106c38c7cf8", "commit_message": "bpf: Fix umd memory leak in copy_process()\n\nThe syzbot reported a memleak as follows:\n\nBUG: memory leak\nunreferenced object 0xffff888101b41d00 (size 120):\n comm \"kworker/u4:0\", pid 8, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] alloc_pid+0x66/0x560\n [] copy_process+0x1465/0x25e0\n [] kernel_clone+0xf3/0x670\n [] kernel_thread+0x61/0x80\n [] call_usermodehelper_exec_work\n [] call_usermodehelper_exec_work+0xc4/0x120\n [] process_one_work+0x2c9/0x600\n [] worker_thread+0x59/0x5d0\n [] kthread+0x178/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nunreferenced object 0xffff888110ef5c00 (size 232):\n comm \"kworker/u4:0\", pid 8414, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] kmem_cache_zalloc\n [] __alloc_file+0x1f/0xf0\n [] alloc_empty_file+0x69/0x120\n [] alloc_file+0x33/0x1b0\n [] alloc_file_pseudo+0xb2/0x140\n [] create_pipe_files+0x138/0x2e0\n [] umd_setup+0x33/0x220\n [] call_usermodehelper_exec_async+0xb4/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nAfter the UMD process exits, the pipe_to_umh/pipe_from_umh and\ntgid need to be released.\n\nFixes: d71fa5c9763c (\"bpf: Add kernel module with user mode driver that populates bpffs.\")\nReported-by: syzbot+44908bb56d2bfe56b28e@syzkaller.appspotmail.com\nSigned-off-by: Zqiang \nSigned-off-by: Daniel Borkmann \nLink: https://lore.kernel.org/bpf/20210317030915.2865-1-qiang.zhang@windriver.com", "target": 0, "func": "static void umd_cleanup(struct subprocess_info *info)\n{\n\tstruct umd_info *umd_info = info->data;\n\n\t/* cleanup if umh_setup() was successful but exec failed */\n\tif (info->retval)\n\t\tumd_cleanup_helper(umd_info);\n}", "func_hash": 200814887829006881188832719302911463261, "file_name": "usermode_driver.c", "file_hash": 111399352715123077084179875656597529489, "cwe": ["CWE-401"], "cve": "CVE-2021-29649", "cve_desc": "An issue was discovered in the Linux kernel before 5.11.11. The user mode driver (UMD) has a copy_process() memory leak, related to a lack of cleanup steps in kernel/usermode_driver.c and kernel/bpf/preload/bpf_preload_kern.c, aka CID-f60a85cad677.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29649"} {"idx": 206698, "project": "libxml2", "commit_id": "0f3b843b3534784ef57a4f9b874238aa1fda5a73", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://git.gnome.org/browse/libxml2/commit/?id=0f3b843b3534784ef57a4f9b874238aa1fda5a73", "commit_message": "Fix XPath stack frame logic\n\nMove the calls to xmlXPathSetFrame and xmlXPathPopFrame around in\nxmlXPathCompOpEvalPositionalPredicate to make sure that the context\nobject on the stack is actually protected. Otherwise, memory corruption\ncan occur when calling sloppily coded XPath extension functions.\n\nFixes bug 783160.", "target": 1, "func": "\nstatic int\nxmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,\n\t\t\t\t xmlXPathStepOpPtr op,\n\t\t\t\t xmlNodeSetPtr set,\n\t\t\t\t int contextSize,\n\t\t\t\t int minPos,\n\t\t\t\t int maxPos,\n\t\t\t\t int hasNsNodes)\n{\n if (op->ch1 != -1) {\n\txmlXPathCompExprPtr comp = ctxt->comp;\n\tif (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {\n\t /*\n\t * TODO: raise an internal error.\n\t */\n\t}\n\tcontextSize = xmlXPathCompOpEvalPredicate(ctxt,\n\t &comp->steps[op->ch1], set, contextSize, hasNsNodes);\n\tCHECK_ERROR0;\n\tif (contextSize <= 0)\n\t return(0);\n }\n /*\n * Check if the node set contains a sufficient number of nodes for\n * the requested range.\n */\n if (contextSize < minPos) {\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\treturn(0);\n }\n if (op->ch2 == -1) {\n\t/*\n\t* TODO: Can this ever happen?\n\t*/\n\treturn (contextSize);\n } else {\n\txmlDocPtr oldContextDoc;\n\tint i, pos = 0, newContextSize = 0, contextPos = 0, res;\n\txmlXPathStepOpPtr exprOp;\n\txmlXPathObjectPtr contextObj = NULL, exprRes = NULL;\n\txmlNodePtr oldContextNode, contextNode = NULL;\n\txmlXPathContextPtr xpctxt = ctxt->context;\n int frame;\n\n#ifdef LIBXML_XPTR_ENABLED\n\t /*\n\t * URGENT TODO: Check the following:\n\t * We don't expect location sets if evaluating prediates, right?\n\t * Only filters should expect location sets, right?\n\t*/\n#endif /* LIBXML_XPTR_ENABLED */\n\n\t/*\n\t* Save old context.\n\t*/\n\toldContextNode = xpctxt->node;\n\toldContextDoc = xpctxt->doc;\n\t/*\n\t* Get the expression of this predicate.\n\t*/\n\texprOp = &ctxt->comp->steps[op->ch2];\n\tfor (i = 0; i < set->nodeNr; i++) {\n xmlXPathObjectPtr tmp;\n\n\t if (set->nodeTab[i] == NULL)\n\t\tcontinue;\n\n\t contextNode = set->nodeTab[i];\n\t xpctxt->node = contextNode;\n\t xpctxt->contextSize = contextSize;\n\t xpctxt->proximityPosition = ++contextPos;\n\n\t /*\n\t * Initialize the new set.\n\t * Also set the xpath document in case things like\n\t * key() evaluation are attempted on the predicate\n\t */\n\t if ((contextNode->type != XML_NAMESPACE_DECL) &&\n\t\t(contextNode->doc != NULL))\n\t\txpctxt->doc = contextNode->doc;\n\t /*\n\t * Evaluate the predicate expression with 1 context node\n\t * at a time; this node is packaged into a node set; this\n\t * node set is handed over to the evaluation mechanism.\n\t */\n\t if (contextObj == NULL)\n\t\tcontextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);\n\t else {\n\t\tif (xmlXPathNodeSetAddUnique(contextObj->nodesetval,\n\t\t contextNode) < 0) {\n\t\t ctxt->error = XPATH_MEMORY_ERROR;\n\t\t goto evaluation_exit;\n\t\t}\n\t }\n\n frame = xmlXPathSetFrame(ctxt);\n\t valuePush(ctxt, contextObj);\n\t res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);\n tmp = valuePop(ctxt);\n xmlXPathPopFrame(ctxt, frame);\n\n\t if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {\n while (tmp != contextObj) {\n /*\n * Free up the result\n * then pop off contextObj, which will be freed later\n */\n xmlXPathReleaseObject(xpctxt, tmp);\n tmp = valuePop(ctxt);\n }\n\t\tgoto evaluation_error;\n\t }\n /* push the result back onto the stack */\n valuePush(ctxt, tmp);\n\n\t if (res)\n\t\tpos++;\n\n\t if (res && (pos >= minPos) && (pos <= maxPos)) {\n\t\t/*\n\t\t* Fits in the requested range.\n\t\t*/\n\t\tnewContextSize++;\n\t\tif (minPos == maxPos) {\n\t\t /*\n\t\t * Only 1 node was requested.\n\t\t */\n\t\t if (contextNode->type == XML_NAMESPACE_DECL) {\n\t\t\t/*\n\t\t\t* As always: take care of those nasty\n\t\t\t* namespace nodes.\n\t\t\t*/\n\t\t\tset->nodeTab[i] = NULL;\n\t\t }\n\t\t xmlXPathNodeSetClear(set, hasNsNodes);\n\t\t set->nodeNr = 1;\n\t\t set->nodeTab[0] = contextNode;\n\t\t goto evaluation_exit;\n\t\t}\n\t\tif (pos == maxPos) {\n\t\t /*\n\t\t * We are done.\n\t\t */\n\t\t xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);\n\t\t goto evaluation_exit;\n\t\t}\n\t } else {\n\t\t/*\n\t\t* Remove the entry from the initial node set.\n\t\t*/\n\t\tset->nodeTab[i] = NULL;\n\t\tif (contextNode->type == XML_NAMESPACE_DECL)\n\t\t xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);\n\t }\n\t if (exprRes != NULL) {\n\t\txmlXPathReleaseObject(ctxt->context, exprRes);\n\t\texprRes = NULL;\n\t }\n\t if (ctxt->value == contextObj) {\n\t\t/*\n\t\t* Don't free the temporary XPath object holding the\n\t\t* context node, in order to avoid massive recreation\n\t\t* inside this loop.\n\t\t*/\n\t\tvaluePop(ctxt);\n\t\txmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);\n\t } else {\n\t\t/*\n\t\t* The object was lost in the evaluation machinery.\n\t\t* Can this happen? Maybe in case of internal-errors.\n\t\t*/\n\t\tcontextObj = NULL;\n\t }\n\t}\n\tgoto evaluation_exit;\n\nevaluation_error:\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\tnewContextSize = 0;\n\nevaluation_exit:\n\tif (contextObj != NULL) {\n\t if (ctxt->value == contextObj)\n\t\tvaluePop(ctxt);\n\t xmlXPathReleaseObject(xpctxt, contextObj);\n\t}\n\tif (exprRes != NULL)\n\t xmlXPathReleaseObject(ctxt->context, exprRes);\n\t/*\n\t* Reset/invalidate the context.\n\t*/\n\txpctxt->node = oldContextNode;\n\txpctxt->doc = oldContextDoc;\n\txpctxt->contextSize = -1;\n\txpctxt->proximityPosition = -1;\n\treturn(newContextSize);\n }", "func_hash": 45146702256567686136588631232718839847, "file_name": "xpath.c", "file_hash": 38437311185312491365831130874782803027, "cwe": ["CWE-416"], "cve": "CVE-2017-15412", "cve_desc": "Use after free in libxml2 before 2.9.5, as used in Google Chrome prior to 63.0.3239.84 and other products, allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-15412"} {"idx": 385345, "project": "libxml2", "commit_id": "0f3b843b3534784ef57a4f9b874238aa1fda5a73", "project_url": "https://github.com/GNOME/libxml2", "commit_url": "https://git.gnome.org/browse/libxml2/commit/?id=0f3b843b3534784ef57a4f9b874238aa1fda5a73", "commit_message": "Fix XPath stack frame logic\n\nMove the calls to xmlXPathSetFrame and xmlXPathPopFrame around in\nxmlXPathCompOpEvalPositionalPredicate to make sure that the context\nobject on the stack is actually protected. Otherwise, memory corruption\ncan occur when calling sloppily coded XPath extension functions.\n\nFixes bug 783160.", "target": 0, "func": "\nstatic int\nxmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,\n\t\t\t\t xmlXPathStepOpPtr op,\n\t\t\t\t xmlNodeSetPtr set,\n\t\t\t\t int contextSize,\n\t\t\t\t int minPos,\n\t\t\t\t int maxPos,\n\t\t\t\t int hasNsNodes)\n{\n if (op->ch1 != -1) {\n\txmlXPathCompExprPtr comp = ctxt->comp;\n\tif (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {\n\t /*\n\t * TODO: raise an internal error.\n\t */\n\t}\n\tcontextSize = xmlXPathCompOpEvalPredicate(ctxt,\n\t &comp->steps[op->ch1], set, contextSize, hasNsNodes);\n\tCHECK_ERROR0;\n\tif (contextSize <= 0)\n\t return(0);\n }\n /*\n * Check if the node set contains a sufficient number of nodes for\n * the requested range.\n */\n if (contextSize < minPos) {\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\treturn(0);\n }\n if (op->ch2 == -1) {\n\t/*\n\t* TODO: Can this ever happen?\n\t*/\n\treturn (contextSize);\n } else {\n\txmlDocPtr oldContextDoc;\n\tint i, pos = 0, newContextSize = 0, contextPos = 0, res;\n\txmlXPathStepOpPtr exprOp;\n\txmlXPathObjectPtr contextObj = NULL, exprRes = NULL;\n\txmlNodePtr oldContextNode, contextNode = NULL;\n\txmlXPathContextPtr xpctxt = ctxt->context;\n int frame;\n\n#ifdef LIBXML_XPTR_ENABLED\n\t /*\n\t * URGENT TODO: Check the following:\n\t * We don't expect location sets if evaluating prediates, right?\n\t * Only filters should expect location sets, right?\n\t*/\n#endif /* LIBXML_XPTR_ENABLED */\n\n\t/*\n\t* Save old context.\n\t*/\n\toldContextNode = xpctxt->node;\n\toldContextDoc = xpctxt->doc;\n\t/*\n\t* Get the expression of this predicate.\n\t*/\n\texprOp = &ctxt->comp->steps[op->ch2];\n\tfor (i = 0; i < set->nodeNr; i++) {\n xmlXPathObjectPtr tmp;\n\n\t if (set->nodeTab[i] == NULL)\n\t\tcontinue;\n\n\t contextNode = set->nodeTab[i];\n\t xpctxt->node = contextNode;\n\t xpctxt->contextSize = contextSize;\n\t xpctxt->proximityPosition = ++contextPos;\n\n\t /*\n\t * Initialize the new set.\n\t * Also set the xpath document in case things like\n\t * key() evaluation are attempted on the predicate\n\t */\n\t if ((contextNode->type != XML_NAMESPACE_DECL) &&\n\t\t(contextNode->doc != NULL))\n\t\txpctxt->doc = contextNode->doc;\n\t /*\n\t * Evaluate the predicate expression with 1 context node\n\t * at a time; this node is packaged into a node set; this\n\t * node set is handed over to the evaluation mechanism.\n\t */\n\t if (contextObj == NULL)\n\t\tcontextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);\n\t else {\n\t\tif (xmlXPathNodeSetAddUnique(contextObj->nodesetval,\n\t\t contextNode) < 0) {\n\t\t ctxt->error = XPATH_MEMORY_ERROR;\n\t\t goto evaluation_exit;\n\t\t}\n\t }\n\n\t valuePush(ctxt, contextObj);\n frame = xmlXPathSetFrame(ctxt);\n\t res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);\n xmlXPathPopFrame(ctxt, frame);\n tmp = valuePop(ctxt);\n\n\t if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {\n while (tmp != contextObj) {\n /*\n * Free up the result\n * then pop off contextObj, which will be freed later\n */\n xmlXPathReleaseObject(xpctxt, tmp);\n tmp = valuePop(ctxt);\n }\n\t\tgoto evaluation_error;\n\t }\n /* push the result back onto the stack */\n valuePush(ctxt, tmp);\n\n\t if (res)\n\t\tpos++;\n\n\t if (res && (pos >= minPos) && (pos <= maxPos)) {\n\t\t/*\n\t\t* Fits in the requested range.\n\t\t*/\n\t\tnewContextSize++;\n\t\tif (minPos == maxPos) {\n\t\t /*\n\t\t * Only 1 node was requested.\n\t\t */\n\t\t if (contextNode->type == XML_NAMESPACE_DECL) {\n\t\t\t/*\n\t\t\t* As always: take care of those nasty\n\t\t\t* namespace nodes.\n\t\t\t*/\n\t\t\tset->nodeTab[i] = NULL;\n\t\t }\n\t\t xmlXPathNodeSetClear(set, hasNsNodes);\n\t\t set->nodeNr = 1;\n\t\t set->nodeTab[0] = contextNode;\n\t\t goto evaluation_exit;\n\t\t}\n\t\tif (pos == maxPos) {\n\t\t /*\n\t\t * We are done.\n\t\t */\n\t\t xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);\n\t\t goto evaluation_exit;\n\t\t}\n\t } else {\n\t\t/*\n\t\t* Remove the entry from the initial node set.\n\t\t*/\n\t\tset->nodeTab[i] = NULL;\n\t\tif (contextNode->type == XML_NAMESPACE_DECL)\n\t\t xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);\n\t }\n\t if (exprRes != NULL) {\n\t\txmlXPathReleaseObject(ctxt->context, exprRes);\n\t\texprRes = NULL;\n\t }\n\t if (ctxt->value == contextObj) {\n\t\t/*\n\t\t* Don't free the temporary XPath object holding the\n\t\t* context node, in order to avoid massive recreation\n\t\t* inside this loop.\n\t\t*/\n\t\tvaluePop(ctxt);\n\t\txmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);\n\t } else {\n\t\t/*\n\t\t* The object was lost in the evaluation machinery.\n\t\t* Can this happen? Maybe in case of internal-errors.\n\t\t*/\n\t\tcontextObj = NULL;\n\t }\n\t}\n\tgoto evaluation_exit;\n\nevaluation_error:\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\tnewContextSize = 0;\n\nevaluation_exit:\n\tif (contextObj != NULL) {\n\t if (ctxt->value == contextObj)\n\t\tvaluePop(ctxt);\n\t xmlXPathReleaseObject(xpctxt, contextObj);\n\t}\n\tif (exprRes != NULL)\n\t xmlXPathReleaseObject(ctxt->context, exprRes);\n\t/*\n\t* Reset/invalidate the context.\n\t*/\n\txpctxt->node = oldContextNode;\n\txpctxt->doc = oldContextDoc;\n\txpctxt->contextSize = -1;\n\txpctxt->proximityPosition = -1;\n\treturn(newContextSize);\n }", "func_hash": 185640488108337847461278803673896303338, "file_name": "xpath.c", "file_hash": 84125593628260997591778623036540967842, "cwe": ["CWE-416"], "cve": "CVE-2017-15412", "cve_desc": "Use after free in libxml2 before 2.9.5, as used in Google Chrome prior to 63.0.3239.84 and other products, allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-15412"} {"idx": 206709, "project": "node", "commit_id": "78b0e30954111cfaba0edbeee85450d8cbc6fdf6", "project_url": "https://github.com/joyent/node", "commit_url": "https://github.com/joyent/node/commit/78b0e30954111cfaba0edbeee85450d8cbc6fdf6", "commit_message": "deps: fix out-of-band write in utf8 decoder\n\nOriginally reported by: Kris Reeves \n\nReviewed-By: Trevor Norris ", "target": 1, "func": "void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream,\n uint16_t* data,\n unsigned data_length) {\n while (data_length != 0) {\n unsigned cursor = 0;\n uint32_t character = Utf8::ValueOf(stream, Utf8::kMaxEncodedSize, &cursor);\n // There's a total lack of bounds checking for stream\n // as it was already done in Reset.\n stream += cursor;\n if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {\n *data++ = Utf16::LeadSurrogate(character);\n *data++ = Utf16::TrailSurrogate(character);\n DCHECK(data_length > 1);\n data_length -= 2;\n } else {\n *data++ = character;\n data_length -= 1;\n }\n }\n}", "func_hash": 25026083626451502544099433623350761201, "file_name": "unicode.cc", "file_hash": 172207421956168610334742347461355431017, "cwe": ["CWE-119"], "cve": "CVE-2015-5380", "cve_desc": "The Utf8DecoderBase::WriteUtf16Slow function in unicode-decoder.cc in Google V8, as used in Node.js before 0.12.6, io.js before 1.8.3 and 2.x before 2.3.3, and other products, does not verify that there is memory available for a UTF-16 surrogate pair, which allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via a crafted byte sequence.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-5380"} {"idx": 385616, "project": "node", "commit_id": "78b0e30954111cfaba0edbeee85450d8cbc6fdf6", "project_url": "https://github.com/joyent/node", "commit_url": "https://github.com/joyent/node/commit/78b0e30954111cfaba0edbeee85450d8cbc6fdf6", "commit_message": "deps: fix out-of-band write in utf8 decoder\n\nOriginally reported by: Kris Reeves \n\nReviewed-By: Trevor Norris ", "target": 0, "func": "void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream,\n unsigned stream_length,\n uint16_t* data,\n unsigned data_length) {\n while (data_length != 0) {\n unsigned cursor = 0;\n\n uint32_t character = Utf8::ValueOf(stream, stream_length, &cursor);\n // There's a total lack of bounds checking for stream\n // as it was already done in Reset.\n stream += cursor;\n stream_length -= cursor;\n if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {\n *data++ = Utf16::LeadSurrogate(character);\n *data++ = Utf16::TrailSurrogate(character);\n DCHECK(data_length > 1);\n data_length -= 2;\n } else {\n *data++ = character;\n data_length -= 1;\n }\n }\n DCHECK(stream_length >= 0);\n}", "func_hash": 140615092666559155814326398961597227970, "file_name": "unicode.cc", "file_hash": 259801141799572658852712353381336449789, "cwe": ["CWE-119"], "cve": "CVE-2015-5380", "cve_desc": "The Utf8DecoderBase::WriteUtf16Slow function in unicode-decoder.cc in Google V8, as used in Node.js before 0.12.6, io.js before 1.8.3 and 2.x before 2.3.3, and other products, does not verify that there is memory available for a UTF-16 surrogate pair, which allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via a crafted byte sequence.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-5380"} {"idx": 206717, "project": "ImageMagick6", "commit_id": "f1e68d22d1b35459421710587a0dcbab6900b51f", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/f1e68d22d1b35459421710587a0dcbab6900b51f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 1, "func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickPixelPacket\n zero;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*\n fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n return((Image *) NULL);\n if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse)\n {\n InheritException(exception,&wave_image->exception);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n if (wave_image->background_color.opacity != OpaqueOpacity)\n wave_image->matte=MagickTrue;\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)/wave_length));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n GetMagickPixelPacket(wave_image,&zero);\n image_view=AcquireVirtualCacheView(image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n MagickPixelPacket\n pixel;\n\n IndexPacket\n *magick_restrict indexes;\n\n PixelPacket\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n indexes=GetCacheViewAuthenticIndexQueue(wave_view);\n pixel=zero;\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolateMagickPixelPacket(image,image_view,\n UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel,\n exception);\n if (status == MagickFalse)\n break;\n SetPixelPacket(wave_image,&pixel,q,indexes+x);\n q++;\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,WaveImageTag,progress,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n image_view=DestroyCacheView(image_view);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "func_hash": 276242036580088300470105426744826418691, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-20309", "cve_desc": "A flaw was found in ImageMagick in versions before 7.0.11 and before 6.9.12, where a division by zero in WaveImage() of MagickCore/visual-effects.c may trigger undefined behavior via a crafted image file submitted to an application using ImageMagick. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20309"} {"idx": 385763, "project": "ImageMagick6", "commit_id": "f1e68d22d1b35459421710587a0dcbab6900b51f", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/f1e68d22d1b35459421710587a0dcbab6900b51f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 0, "func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickPixelPacket\n zero;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*\n fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n return((Image *) NULL);\n if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse)\n {\n InheritException(exception,&wave_image->exception);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n if (wave_image->background_color.opacity != OpaqueOpacity)\n wave_image->matte=MagickTrue;\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)*PerceptibleReciprocal(wave_length)));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n GetMagickPixelPacket(wave_image,&zero);\n image_view=AcquireVirtualCacheView(image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n MagickPixelPacket\n pixel;\n\n IndexPacket\n *magick_restrict indexes;\n\n PixelPacket\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n indexes=GetCacheViewAuthenticIndexQueue(wave_view);\n pixel=zero;\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolateMagickPixelPacket(image,image_view,\n UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel,\n exception);\n if (status == MagickFalse)\n break;\n SetPixelPacket(wave_image,&pixel,q,indexes+x);\n q++;\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,WaveImageTag,progress,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n image_view=DestroyCacheView(image_view);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "func_hash": 7313424828127488814617824667127893208, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-20309", "cve_desc": "A flaw was found in ImageMagick in versions before 7.0.11 and before 6.9.12, where a division by zero in WaveImage() of MagickCore/visual-effects.c may trigger undefined behavior via a crafted image file submitted to an application using ImageMagick. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20309"} {"idx": 206718, "project": "linux", "commit_id": "ef299cc3fa1a9e1288665a9fdc8bff55629fd359", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ef299cc3fa1a9e1288665a9fdc8bff55629fd359", "commit_message": "net_sched: cls_route: remove the right filter from hashtable\n\nroute4_change() allocates a new filter and copies values from\nthe old one. After the new filter is inserted into the hash\ntable, the old filter should be removed and freed, as the final\nstep of the update.\n\nHowever, the current code mistakenly removes the new one. This\nlooks apparently wrong to me, and it causes double \"free\" and\nuse-after-free too, as reported by syzbot.\n\nReported-and-tested-by: syzbot+f9b32aaacd60305d9687@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+2f8c233f131943d6056d@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+9c2df9fd5e9445b74e01@syzkaller.appspotmail.com\nFixes: 1109c00547fc (\"net: sched: RCU cls_route\")\nCc: Jamal Hadi Salim \nCc: Jiri Pirko \nCc: John Fastabend \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 1, "func": "static int route4_change(struct net *net, struct sk_buff *in_skb,\n\t\t\t struct tcf_proto *tp, unsigned long base, u32 handle,\n\t\t\t struct nlattr **tca, void **arg, bool ovr,\n\t\t\t bool rtnl_held, struct netlink_ext_ack *extack)\n{\n\tstruct route4_head *head = rtnl_dereference(tp->root);\n\tstruct route4_filter __rcu **fp;\n\tstruct route4_filter *fold, *f1, *pfp, *f = NULL;\n\tstruct route4_bucket *b;\n\tstruct nlattr *opt = tca[TCA_OPTIONS];\n\tstruct nlattr *tb[TCA_ROUTE4_MAX + 1];\n\tunsigned int h, th;\n\tint err;\n\tbool new = true;\n\n\tif (opt == NULL)\n\t\treturn handle ? -EINVAL : 0;\n\n\terr = nla_parse_nested_deprecated(tb, TCA_ROUTE4_MAX, opt,\n\t\t\t\t\t route4_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tfold = *arg;\n\tif (fold && handle && fold->handle != handle)\n\t\t\treturn -EINVAL;\n\n\terr = -ENOBUFS;\n\tf = kzalloc(sizeof(struct route4_filter), GFP_KERNEL);\n\tif (!f)\n\t\tgoto errout;\n\n\terr = tcf_exts_init(&f->exts, net, TCA_ROUTE4_ACT, TCA_ROUTE4_POLICE);\n\tif (err < 0)\n\t\tgoto errout;\n\n\tif (fold) {\n\t\tf->id = fold->id;\n\t\tf->iif = fold->iif;\n\t\tf->res = fold->res;\n\t\tf->handle = fold->handle;\n\n\t\tf->tp = fold->tp;\n\t\tf->bkt = fold->bkt;\n\t\tnew = false;\n\t}\n\n\terr = route4_set_parms(net, tp, base, f, handle, head, tb,\n\t\t\t tca[TCA_RATE], new, ovr, extack);\n\tif (err < 0)\n\t\tgoto errout;\n\n\th = from_hash(f->handle >> 16);\n\tfp = &f->bkt->ht[h];\n\tfor (pfp = rtnl_dereference(*fp);\n\t (f1 = rtnl_dereference(*fp)) != NULL;\n\t fp = &f1->next)\n\t\tif (f->handle < f1->handle)\n\t\t\tbreak;\n\n\ttcf_block_netif_keep_dst(tp->chain->block);\n\trcu_assign_pointer(f->next, f1);\n\trcu_assign_pointer(*fp, f);\n\n\tif (fold && fold->handle && f->handle != fold->handle) {\n\t\tth = to_hash(fold->handle);\n\t\th = from_hash(fold->handle >> 16);\n\t\tb = rtnl_dereference(head->table[th]);\n\t\tif (b) {\n\t\t\tfp = &b->ht[h];\n\t\t\tfor (pfp = rtnl_dereference(*fp); pfp;\n\t\t\t fp = &pfp->next, pfp = rtnl_dereference(*fp)) {\n\t\t\t\tif (pfp == f) {\n\t\t\t\t\t*fp = f->next;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\troute4_reset_fastmap(head);\n\t*arg = f;\n\tif (fold) {\n\t\ttcf_unbind_filter(tp, &fold->res);\n\t\ttcf_exts_get_net(&fold->exts);\n\t\ttcf_queue_work(&fold->rwork, route4_delete_filter_work);\n\t}\n\treturn 0;\n\nerrout:\n\tif (f)\n\t\ttcf_exts_destroy(&f->exts);\n\tkfree(f);\n\treturn err;\n}", "func_hash": 104513129320709900646088556099859248779, "file_name": "cls_route.c", "file_hash": 319312350667195332056048609850198603512, "cwe": ["CWE-200"], "cve": "CVE-2021-3715", "cve_desc": "A flaw was found in the \"Routing decision\" classifier in the Linux kernel's Traffic Control networking subsystem in the way it handled changing of classification filters, leading to a use-after-free condition. This flaw allows unprivileged local users to escalate their privileges on the system. The highest threat from this vulnerability is to confidentiality, integrity, as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3715"} {"idx": 385783, "project": "linux", "commit_id": "ef299cc3fa1a9e1288665a9fdc8bff55629fd359", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ef299cc3fa1a9e1288665a9fdc8bff55629fd359", "commit_message": "net_sched: cls_route: remove the right filter from hashtable\n\nroute4_change() allocates a new filter and copies values from\nthe old one. After the new filter is inserted into the hash\ntable, the old filter should be removed and freed, as the final\nstep of the update.\n\nHowever, the current code mistakenly removes the new one. This\nlooks apparently wrong to me, and it causes double \"free\" and\nuse-after-free too, as reported by syzbot.\n\nReported-and-tested-by: syzbot+f9b32aaacd60305d9687@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+2f8c233f131943d6056d@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+9c2df9fd5e9445b74e01@syzkaller.appspotmail.com\nFixes: 1109c00547fc (\"net: sched: RCU cls_route\")\nCc: Jamal Hadi Salim \nCc: Jiri Pirko \nCc: John Fastabend \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 0, "func": "static int route4_change(struct net *net, struct sk_buff *in_skb,\n\t\t\t struct tcf_proto *tp, unsigned long base, u32 handle,\n\t\t\t struct nlattr **tca, void **arg, bool ovr,\n\t\t\t bool rtnl_held, struct netlink_ext_ack *extack)\n{\n\tstruct route4_head *head = rtnl_dereference(tp->root);\n\tstruct route4_filter __rcu **fp;\n\tstruct route4_filter *fold, *f1, *pfp, *f = NULL;\n\tstruct route4_bucket *b;\n\tstruct nlattr *opt = tca[TCA_OPTIONS];\n\tstruct nlattr *tb[TCA_ROUTE4_MAX + 1];\n\tunsigned int h, th;\n\tint err;\n\tbool new = true;\n\n\tif (opt == NULL)\n\t\treturn handle ? -EINVAL : 0;\n\n\terr = nla_parse_nested_deprecated(tb, TCA_ROUTE4_MAX, opt,\n\t\t\t\t\t route4_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tfold = *arg;\n\tif (fold && handle && fold->handle != handle)\n\t\t\treturn -EINVAL;\n\n\terr = -ENOBUFS;\n\tf = kzalloc(sizeof(struct route4_filter), GFP_KERNEL);\n\tif (!f)\n\t\tgoto errout;\n\n\terr = tcf_exts_init(&f->exts, net, TCA_ROUTE4_ACT, TCA_ROUTE4_POLICE);\n\tif (err < 0)\n\t\tgoto errout;\n\n\tif (fold) {\n\t\tf->id = fold->id;\n\t\tf->iif = fold->iif;\n\t\tf->res = fold->res;\n\t\tf->handle = fold->handle;\n\n\t\tf->tp = fold->tp;\n\t\tf->bkt = fold->bkt;\n\t\tnew = false;\n\t}\n\n\terr = route4_set_parms(net, tp, base, f, handle, head, tb,\n\t\t\t tca[TCA_RATE], new, ovr, extack);\n\tif (err < 0)\n\t\tgoto errout;\n\n\th = from_hash(f->handle >> 16);\n\tfp = &f->bkt->ht[h];\n\tfor (pfp = rtnl_dereference(*fp);\n\t (f1 = rtnl_dereference(*fp)) != NULL;\n\t fp = &f1->next)\n\t\tif (f->handle < f1->handle)\n\t\t\tbreak;\n\n\ttcf_block_netif_keep_dst(tp->chain->block);\n\trcu_assign_pointer(f->next, f1);\n\trcu_assign_pointer(*fp, f);\n\n\tif (fold && fold->handle && f->handle != fold->handle) {\n\t\tth = to_hash(fold->handle);\n\t\th = from_hash(fold->handle >> 16);\n\t\tb = rtnl_dereference(head->table[th]);\n\t\tif (b) {\n\t\t\tfp = &b->ht[h];\n\t\t\tfor (pfp = rtnl_dereference(*fp); pfp;\n\t\t\t fp = &pfp->next, pfp = rtnl_dereference(*fp)) {\n\t\t\t\tif (pfp == fold) {\n\t\t\t\t\trcu_assign_pointer(*fp, fold->next);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\troute4_reset_fastmap(head);\n\t*arg = f;\n\tif (fold) {\n\t\ttcf_unbind_filter(tp, &fold->res);\n\t\ttcf_exts_get_net(&fold->exts);\n\t\ttcf_queue_work(&fold->rwork, route4_delete_filter_work);\n\t}\n\treturn 0;\n\nerrout:\n\tif (f)\n\t\ttcf_exts_destroy(&f->exts);\n\tkfree(f);\n\treturn err;\n}", "func_hash": 4707058981203679357365035361515504552, "file_name": "cls_route.c", "file_hash": 278031893903737073519770074065910895013, "cwe": ["CWE-200"], "cve": "CVE-2021-3715", "cve_desc": "A flaw was found in the \"Routing decision\" classifier in the Linux kernel's Traffic Control networking subsystem in the way it handled changing of classification filters, leading to a use-after-free condition. This flaw allows unprivileged local users to escalate their privileges on the system. The highest threat from this vulnerability is to confidentiality, integrity, as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3715"} {"idx": 206735, "project": "linux", "commit_id": "42933c8aa14be1caa9eda41f65cde8a3a95d3e39", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=42933c8aa14be1caa9eda41f65cde8a3a95d3e39", "commit_message": "memstick: rtsx_usb_ms: fix UAF\n\nThis patch fixes the following issues:\n1. memstick_free_host() will free the host, so the use of ms_dev(host) after\nit will be a problem. To fix this, move memstick_free_host() after when we\nare done with ms_dev(host).\n2. In rtsx_usb_ms_drv_remove(), pm need to be disabled before we remove\nand free host otherwise memstick_check will be called and UAF will\nhappen.\n\n[ 11.351173] BUG: KASAN: use-after-free in rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357077] rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357376] platform_remove+0x2a/0x50\n[ 11.367531] Freed by task 298:\n[ 11.368537] kfree+0xa4/0x2a0\n[ 11.368711] device_release+0x51/0xe0\n[ 11.368905] kobject_put+0xa2/0x120\n[ 11.369090] rtsx_usb_ms_drv_remove+0x8c/0x140 [rtsx_usb_ms]\n[ 11.369386] platform_remove+0x2a/0x50\n\n[ 12.038408] BUG: KASAN: use-after-free in __mutex_lock.isra.0+0x3ec/0x7c0\n[ 12.045432] mutex_lock+0xc9/0xd0\n[ 12.046080] memstick_check+0x6a/0x578 [memstick]\n[ 12.046509] process_one_work+0x46d/0x750\n[ 12.052107] Freed by task 297:\n[ 12.053115] kfree+0xa4/0x2a0\n[ 12.053272] device_release+0x51/0xe0\n[ 12.053463] kobject_put+0xa2/0x120\n[ 12.053647] rtsx_usb_ms_drv_remove+0xc4/0x140 [rtsx_usb_ms]\n[ 12.053939] platform_remove+0x2a/0x50\n\nSigned-off-by: Tong Zhang \nCo-developed-by: Ulf Hansson \nLink: https://lore.kernel.org/r/20210511163944.1233295-1-ztong0001@gmail.com\nSigned-off-by: Ulf Hansson ", "target": 1, "func": "static int rtsx_usb_ms_drv_remove(struct platform_device *pdev)\n{\n\tstruct rtsx_usb_ms *host = platform_get_drvdata(pdev);\n\tstruct memstick_host *msh = host->msh;\n\tint err;\n\n\thost->eject = true;\n\tcancel_work_sync(&host->handle_req);\n\n\tmutex_lock(&host->host_mutex);\n\tif (host->req) {\n\t\tdev_dbg(ms_dev(host),\n\t\t\t\"%s: Controller removed during transfer\\n\",\n\t\t\tdev_name(&msh->dev));\n\t\thost->req->error = -ENOMEDIUM;\n\t\tdo {\n\t\t\terr = memstick_next_req(msh, &host->req);\n\t\t\tif (!err)\n\t\t\t\thost->req->error = -ENOMEDIUM;\n\t\t} while (!err);\n\t}\n\tmutex_unlock(&host->host_mutex);\n\n\tmemstick_remove_host(msh);\n\tmemstick_free_host(msh);\n\n\t/* Balance possible unbalanced usage count\n\t * e.g. unconditional module removal\n\t */\n\tif (pm_runtime_active(ms_dev(host)))\n\t\tpm_runtime_put(ms_dev(host));\n\n\tpm_runtime_disable(ms_dev(host));\n\tplatform_set_drvdata(pdev, NULL);\n\n\tdev_dbg(ms_dev(host),\n\t\t\": Realtek USB Memstick controller has been removed\\n\");\n\n\treturn 0;\n}", "func_hash": 163582843117226936175101585445688600655, "file_name": "rtsx_usb_ms.c", "file_hash": 31439511034957915663612869956115366028, "cwe": ["CWE-416"], "cve": "CVE-2022-0487", "cve_desc": "A use-after-free vulnerability was found in rtsx_usb_ms_drv_remove in drivers/memstick/host/rtsx_usb_ms.c in memstick in the Linux kernel. In this flaw, a local attacker with a user privilege may impact system Confidentiality. This flaw affects kernel versions prior to 5.14 rc1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0487"} {"idx": 386074, "project": "linux", "commit_id": "42933c8aa14be1caa9eda41f65cde8a3a95d3e39", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=42933c8aa14be1caa9eda41f65cde8a3a95d3e39", "commit_message": "memstick: rtsx_usb_ms: fix UAF\n\nThis patch fixes the following issues:\n1. memstick_free_host() will free the host, so the use of ms_dev(host) after\nit will be a problem. To fix this, move memstick_free_host() after when we\nare done with ms_dev(host).\n2. In rtsx_usb_ms_drv_remove(), pm need to be disabled before we remove\nand free host otherwise memstick_check will be called and UAF will\nhappen.\n\n[ 11.351173] BUG: KASAN: use-after-free in rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357077] rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357376] platform_remove+0x2a/0x50\n[ 11.367531] Freed by task 298:\n[ 11.368537] kfree+0xa4/0x2a0\n[ 11.368711] device_release+0x51/0xe0\n[ 11.368905] kobject_put+0xa2/0x120\n[ 11.369090] rtsx_usb_ms_drv_remove+0x8c/0x140 [rtsx_usb_ms]\n[ 11.369386] platform_remove+0x2a/0x50\n\n[ 12.038408] BUG: KASAN: use-after-free in __mutex_lock.isra.0+0x3ec/0x7c0\n[ 12.045432] mutex_lock+0xc9/0xd0\n[ 12.046080] memstick_check+0x6a/0x578 [memstick]\n[ 12.046509] process_one_work+0x46d/0x750\n[ 12.052107] Freed by task 297:\n[ 12.053115] kfree+0xa4/0x2a0\n[ 12.053272] device_release+0x51/0xe0\n[ 12.053463] kobject_put+0xa2/0x120\n[ 12.053647] rtsx_usb_ms_drv_remove+0xc4/0x140 [rtsx_usb_ms]\n[ 12.053939] platform_remove+0x2a/0x50\n\nSigned-off-by: Tong Zhang \nCo-developed-by: Ulf Hansson \nLink: https://lore.kernel.org/r/20210511163944.1233295-1-ztong0001@gmail.com\nSigned-off-by: Ulf Hansson ", "target": 0, "func": "static int rtsx_usb_ms_drv_remove(struct platform_device *pdev)\n{\n\tstruct rtsx_usb_ms *host = platform_get_drvdata(pdev);\n\tstruct memstick_host *msh = host->msh;\n\tint err;\n\n\thost->eject = true;\n\tcancel_work_sync(&host->handle_req);\n\n\tmutex_lock(&host->host_mutex);\n\tif (host->req) {\n\t\tdev_dbg(ms_dev(host),\n\t\t\t\"%s: Controller removed during transfer\\n\",\n\t\t\tdev_name(&msh->dev));\n\t\thost->req->error = -ENOMEDIUM;\n\t\tdo {\n\t\t\terr = memstick_next_req(msh, &host->req);\n\t\t\tif (!err)\n\t\t\t\thost->req->error = -ENOMEDIUM;\n\t\t} while (!err);\n\t}\n\tmutex_unlock(&host->host_mutex);\n\n\t/* Balance possible unbalanced usage count\n\t * e.g. unconditional module removal\n\t */\n\tif (pm_runtime_active(ms_dev(host)))\n\t\tpm_runtime_put(ms_dev(host));\n\n\tpm_runtime_disable(ms_dev(host));\n\tmemstick_remove_host(msh);\n\tdev_dbg(ms_dev(host),\n\t\t\": Realtek USB Memstick controller has been removed\\n\");\n\tmemstick_free_host(msh);\n\tplatform_set_drvdata(pdev, NULL);\n\n\treturn 0;\n}", "func_hash": 48644547196848811345649912708082821240, "file_name": "rtsx_usb_ms.c", "file_hash": 29368528562021395548196674811479119196, "cwe": ["CWE-416"], "cve": "CVE-2022-0487", "cve_desc": "A use-after-free vulnerability was found in rtsx_usb_ms_drv_remove in drivers/memstick/host/rtsx_usb_ms.c in memstick in the Linux kernel. In this flaw, a local attacker with a user privilege may impact system Confidentiality. This flaw affects kernel versions prior to 5.14 rc1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0487"} {"idx": 206866, "project": "linux", "commit_id": "75b0cea7bf307f362057cc778efe89af4c615354", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=75b0cea7bf307f362057cc778efe89af4c615354", "commit_message": "ACPI: configfs: Disallow loading ACPI tables when locked down\n\nLike other vectors already patched, this one here allows the root\nuser to load ACPI tables, which enables arbitrary physical address\nwrites, which in turn makes it possible to disable lockdown.\n\nPrevents this by checking the lockdown status before allowing a new\nACPI table to be installed. The link in the trailer shows a PoC of\nhow this might be used.\n\nLink: https://git.zx2c4.com/american-unsigned-language/tree/american-unsigned-language-2.sh\nCc: 5.4+ # 5.4+\nSigned-off-by: Jason A. Donenfeld \nSigned-off-by: Rafael J. Wysocki ", "target": 1, "func": "static ssize_t acpi_table_aml_write(struct config_item *cfg,\n\t\t\t\t const void *data, size_t size)\n{\n\tconst struct acpi_table_header *header = data;\n\tstruct acpi_table *table;\n\tint ret;\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\tif (table->header) {\n\t\tpr_err(\"table already loaded\\n\");\n\t\treturn -EBUSY;\n\t}\n\n\tif (header->length != size) {\n\t\tpr_err(\"invalid table length\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (memcmp(header->signature, ACPI_SIG_SSDT, 4)) {\n\t\tpr_err(\"invalid table signature\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\ttable->header = kmemdup(header, header->length, GFP_KERNEL);\n\tif (!table->header)\n\t\treturn -ENOMEM;\n\n\tret = acpi_load_table(table->header, &table->index);\n\tif (ret) {\n\t\tkfree(table->header);\n\t\ttable->header = NULL;\n\t}\n\n\treturn ret;\n}", "func_hash": 159359155250923431476576914835849242589, "file_name": "acpi_configfs.c", "file_hash": 272877779828775910421466487340384077828, "cwe": ["CWE-862"], "cve": "CVE-2020-15780", "cve_desc": "An issue was discovered in drivers/acpi/acpi_configfs.c in the Linux kernel before 5.7.7. Injection of malicious ACPI tables via configfs could be used by attackers to bypass lockdown and secure boot restrictions, aka CID-75b0cea7bf30.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15780"} {"idx": 387888, "project": "linux", "commit_id": "75b0cea7bf307f362057cc778efe89af4c615354", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=75b0cea7bf307f362057cc778efe89af4c615354", "commit_message": "ACPI: configfs: Disallow loading ACPI tables when locked down\n\nLike other vectors already patched, this one here allows the root\nuser to load ACPI tables, which enables arbitrary physical address\nwrites, which in turn makes it possible to disable lockdown.\n\nPrevents this by checking the lockdown status before allowing a new\nACPI table to be installed. The link in the trailer shows a PoC of\nhow this might be used.\n\nLink: https://git.zx2c4.com/american-unsigned-language/tree/american-unsigned-language-2.sh\nCc: 5.4+ # 5.4+\nSigned-off-by: Jason A. Donenfeld \nSigned-off-by: Rafael J. Wysocki ", "target": 0, "func": "static ssize_t acpi_table_aml_write(struct config_item *cfg,\n\t\t\t\t const void *data, size_t size)\n{\n\tconst struct acpi_table_header *header = data;\n\tstruct acpi_table *table;\n\tint ret = security_locked_down(LOCKDOWN_ACPI_TABLES);\n\n\tif (ret)\n\t\treturn ret;\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\tif (table->header) {\n\t\tpr_err(\"table already loaded\\n\");\n\t\treturn -EBUSY;\n\t}\n\n\tif (header->length != size) {\n\t\tpr_err(\"invalid table length\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (memcmp(header->signature, ACPI_SIG_SSDT, 4)) {\n\t\tpr_err(\"invalid table signature\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\ttable->header = kmemdup(header, header->length, GFP_KERNEL);\n\tif (!table->header)\n\t\treturn -ENOMEM;\n\n\tret = acpi_load_table(table->header, &table->index);\n\tif (ret) {\n\t\tkfree(table->header);\n\t\ttable->header = NULL;\n\t}\n\n\treturn ret;\n}", "func_hash": 315932968119582836407143430992058771349, "file_name": "acpi_configfs.c", "file_hash": 175732475861849844327743802972766489729, "cwe": ["CWE-862"], "cve": "CVE-2020-15780", "cve_desc": "An issue was discovered in drivers/acpi/acpi_configfs.c in the Linux kernel before 5.7.7. Injection of malicious ACPI tables via configfs could be used by attackers to bypass lockdown and secure boot restrictions, aka CID-75b0cea7bf30.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15780"} {"idx": 206867, "project": "bwm-ng", "commit_id": "9774f23bf78a6e6d3ae4cfe3d73bad34f2fdcd17", "project_url": "https://github.com/vgropp/bwm-ng", "commit_url": "https://github.com/vgropp/bwm-ng/commit/9774f23bf78a6e6d3ae4cfe3d73bad34f2fdcd17", "commit_message": "Fix https://github.com/vgropp/bwm-ng/issues/26", "target": 1, "func": "void get_cmdln_options(int argc, char *argv[]) {\n\tint o;\n#if CONFIG_FILE && HAVE_GETPWUID\n static struct passwd *pwd_entry;\n char *str;\n#endif\n#ifdef LONG_OPTIONS\n int option_index = 0;\n static struct option long_options[] = {\n {\"timeout\", 1, 0, 't'},\n#ifdef PROC_NET_DEV\n {\"procfile\",1,0,'f'},\n#endif\n#ifdef PROC_DISKSTATS\n\t\t\t{\"diskstatsfile\",1,0,1000},\n\t\t\t{\"partitionsfile\",1,0,1001},\n#endif\t\t \n#if NETSTAT && ALLOW_NETSTATPATH\n {\"netstat\",1,0,'n'},\n#endif\n#if IOSERVICE_IN\n\t\t {\"longdisknames\",0,0,1002},\n#endif\n {\"input\",1,0,'i'},\n {\"dynamic\",1,0,'d'},\n {\"help\", 0, 0, 'h'},\n {\"version\",0,0,'V'},\n {\"allif\",1,0,'a'},\n {\"unit\",1,0,'u'},\n\t\t {\"ansiout\",0,0,'N'},\n#if EXTENDED_STATS \n {\"type\",1,0,'T'},\n {\"avglength\",1,0,'A'},\n#endif \n {\"interfaces\",1,0,'I'},\n {\"sumhidden\",1,0,'S'},\n {\"output\",1,0,'o'},\n#ifdef CSV\n {\"csvchar\",1,0,'C'},\n {\"csvfile\",1,0,'F'},\n#endif\n {\"count\",1,0,'c'},\n {\"daemon\",1,0,'D'},\n#ifdef HTML\n {\"htmlrefresh\",1,0,'R'},\n {\"htmlheader\",1,0,'H'},\n#endif\n {0,0,0,0}\n };\n#endif\n#ifdef CONFIG_FILE\n /* loop till first non option argument */\n opterr=0;\n while (1) {\n#ifdef LONG_OPTIONS\n o=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n o=getopt (argc,argv,SHORT_OPTIONS);\n#endif\n if (o==-1) break;\n }\n opterr=1;\n if (optind < argc) {\n read_config(argv[optind]);\n } else {\n read_config(\"/etc/bwm-ng.conf\");\n#ifdef HAVE_GETPWUID \n pwd_entry=getpwuid(getuid());\n if (pwd_entry!=NULL) {\n str=(char*)malloc(strlen(pwd_entry->pw_dir)+14);\n snprintf(str,strlen(pwd_entry->pw_dir)+14,\"%s/.bwm-ng.conf\",pwd_entry->pw_dir);\n read_config(str);\n free(str);\n }\n#endif \n }\n /* reset getopt again */\n optind=1;\n#endif\n /* get command line arguments, kinda ugly, wanna rewrite it? */\n while (1) {\n#ifdef LONG_OPTIONS\n\t\to=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n\t\to=getopt (argc,argv,SHORT_OPTIONS);\n#endif\t\t\n if (o==-1) break;\n switch (o) {\n case '?': printf(\"unknown option: %s\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n break;\n /* ugly workaround to handle optional arguments for all platforms */ \n case ':': if (!strcmp(argv[optind-1],\"-a\") || !strcasecmp(argv[optind-1],\"--allif\")) \n show_all_if=1;\n else if (!strcmp(argv[optind-1],\"-d\") || !strcasecmp(argv[optind-1],\"--dynamic\"))\n dynamic=1;\n else if (!strcmp(argv[optind-1],\"-D\") || !strcasecmp(argv[optind-1],\"--daemon\"))\n daemonize=1;\n#ifdef HTML \n else if (!strcmp(argv[optind-1],\"-H\") || !strcasecmp(argv[optind-1],\"--htmlheader\"))\n html_header=1;\n#endif \n else if (!strcmp(argv[optind-1],\"-S\") || !strcasecmp(argv[optind-1],\"--sumhidden\"))\n sumhidden=1; \n else {\n printf(\"%s requires an argument!\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n }\n break;\n#ifdef PROC_DISKSTATS\n\t\t\tcase 1000:\n\t\t\t\tif (strlen(optarg)0) { html_refresh=atol(optarg); }\n\t\t\t\tbreak;\n\t\t\tcase 'H':\n\t\t\t\tif (optarg) html_header=atoi(optarg);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase 'c':\n\t\t\t\tif (optarg) output_count=atol(optarg);\n\t\t\t\tbreak;\n#if CSV || HTML\n case 'F':\n if (optarg) { \n if (out_file) fclose(out_file);\n out_file=fopen(optarg,\"a\"); \n if (!out_file) deinit(1, \"failed to open outfile\\n\");\n if (out_file_path) free(out_file_path);\n out_file_path=(char *)strdup(optarg);\n }\n break;\n#endif\n#ifdef CSV\n\t\t\tcase 'C':\n\t\t\t\tif (optarg) csv_char=optarg[0];\n\t\t\t\tbreak;\n#endif\n case 'h':\n cmdln_printhelp();\n break;\n#ifdef PROC_NET_DEV\n\t\t\tcase 'f':\n if (optarg && (strlen(optarg)0) { delay=atol(optarg); }\n break;\n#if EXTENDED_STATS \n case 'T':\n output_type=str2output_type(optarg);\n break;\n case 'A':\n if (optarg) avg_length=atoi(optarg)*1000;\n break;\n#endif \n case 'd':\n if (optarg) dynamic=atoi(optarg);\n break;\n case 'u':\n output_unit=str2output_unit(optarg);\n break;\n#if NETSTAT && ALLOW_NETSTATPATH\n case 'n':\n if (optarg && (strlen(optarg)=avg_length) deinit(1, \"avglength needs to be a least twice the value of timeout\\n\");\n#endif \n\t if ((output_unit==ERRORS_OUT && !net_input_method(input_method)) || \n\t\t\t (output_unit==PACKETS_OUT && input_method==LIBSTATDISK_IN)) \n\t\toutput_unit=BYTES_OUT;\n return;\n}", "func_hash": 193742356321939424700126054625716145048, "file_name": "options.c", "file_hash": 301182464760681288674703926671565318422, "cwe": ["CWE-476"], "cve": "CVE-2022-1341", "cve_desc": "An issue was discovered in in bwm-ng v0.6.2. An arbitrary null write exists in get_cmdln_options() function in src/options.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1341"} {"idx": 387905, "project": "bwm-ng", "commit_id": "9774f23bf78a6e6d3ae4cfe3d73bad34f2fdcd17", "project_url": "https://github.com/vgropp/bwm-ng", "commit_url": "https://github.com/vgropp/bwm-ng/commit/9774f23bf78a6e6d3ae4cfe3d73bad34f2fdcd17", "commit_message": "Fix https://github.com/vgropp/bwm-ng/issues/26", "target": 0, "func": "void get_cmdln_options(int argc, char *argv[]) {\n\tint o;\n#if CONFIG_FILE && HAVE_GETPWUID\n static struct passwd *pwd_entry;\n char *str;\n#endif\n#ifdef LONG_OPTIONS\n int option_index = 0;\n static struct option long_options[] = {\n {\"timeout\", 1, 0, 't'},\n#ifdef PROC_NET_DEV\n {\"procfile\",1,0,'f'},\n#endif\n#ifdef PROC_DISKSTATS\n\t\t\t{\"diskstatsfile\",1,0,1000},\n\t\t\t{\"partitionsfile\",1,0,1001},\n#endif\t\t \n#if NETSTAT && ALLOW_NETSTATPATH\n {\"netstat\",1,0,'n'},\n#endif\n#if IOSERVICE_IN\n\t\t {\"longdisknames\",0,0,1002},\n#endif\n {\"input\",1,0,'i'},\n {\"dynamic\",1,0,'d'},\n {\"help\", 0, 0, 'h'},\n {\"version\",0,0,'V'},\n {\"allif\",1,0,'a'},\n {\"unit\",1,0,'u'},\n\t\t {\"ansiout\",0,0,'N'},\n#if EXTENDED_STATS \n {\"type\",1,0,'T'},\n {\"avglength\",1,0,'A'},\n#endif \n {\"interfaces\",1,0,'I'},\n {\"sumhidden\",1,0,'S'},\n {\"output\",1,0,'o'},\n#ifdef CSV\n {\"csvchar\",1,0,'C'},\n {\"csvfile\",1,0,'F'},\n#endif\n {\"count\",1,0,'c'},\n {\"daemon\",1,0,'D'},\n#ifdef HTML\n {\"htmlrefresh\",1,0,'R'},\n {\"htmlheader\",1,0,'H'},\n#endif\n {0,0,0,0}\n };\n#endif\n#ifdef CONFIG_FILE\n /* loop till first non option argument */\n opterr=0;\n while (1) {\n#ifdef LONG_OPTIONS\n o=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n o=getopt (argc,argv,SHORT_OPTIONS);\n#endif\n if (o==-1) break;\n }\n opterr=1;\n if (optind < argc) {\n read_config(argv[optind]);\n } else {\n read_config(\"/etc/bwm-ng.conf\");\n#ifdef HAVE_GETPWUID \n pwd_entry=getpwuid(getuid());\n if (pwd_entry!=NULL) {\n str=(char*)malloc(strlen(pwd_entry->pw_dir)+14);\n if(!str) {\n printf(\"Fatal: failed to allocate %zu bytes.\\n\", strlen(pwd_entry->pw_dir)+14);\n exit(EXIT_FAILURE);\n }\n snprintf(str,strlen(pwd_entry->pw_dir)+14,\"%s/.bwm-ng.conf\",pwd_entry->pw_dir);\n read_config(str);\n free(str);\n }\n#endif \n }\n /* reset getopt again */\n optind=1;\n#endif\n /* get command line arguments, kinda ugly, wanna rewrite it? */\n while (1) {\n#ifdef LONG_OPTIONS\n\t\to=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n\t\to=getopt (argc,argv,SHORT_OPTIONS);\n#endif\t\t\n if (o==-1) break;\n switch (o) {\n case '?': printf(\"unknown option: %s\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n break;\n /* ugly workaround to handle optional arguments for all platforms */ \n case ':': if (!strcmp(argv[optind-1],\"-a\") || !strcasecmp(argv[optind-1],\"--allif\")) \n show_all_if=1;\n else if (!strcmp(argv[optind-1],\"-d\") || !strcasecmp(argv[optind-1],\"--dynamic\"))\n dynamic=1;\n else if (!strcmp(argv[optind-1],\"-D\") || !strcasecmp(argv[optind-1],\"--daemon\"))\n daemonize=1;\n#ifdef HTML \n else if (!strcmp(argv[optind-1],\"-H\") || !strcasecmp(argv[optind-1],\"--htmlheader\"))\n html_header=1;\n#endif \n else if (!strcmp(argv[optind-1],\"-S\") || !strcasecmp(argv[optind-1],\"--sumhidden\"))\n sumhidden=1; \n else {\n printf(\"%s requires an argument!\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n }\n break;\n#ifdef PROC_DISKSTATS\n\t\t\tcase 1000:\n\t\t\t\tif (strlen(optarg)0) { html_refresh=atol(optarg); }\n\t\t\t\tbreak;\n\t\t\tcase 'H':\n\t\t\t\tif (optarg) html_header=atoi(optarg);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase 'c':\n\t\t\t\tif (optarg) output_count=atol(optarg);\n\t\t\t\tbreak;\n#if CSV || HTML\n case 'F':\n if (optarg) { \n if (out_file) fclose(out_file);\n out_file=fopen(optarg,\"a\"); \n if (!out_file) deinit(1, \"failed to open outfile\\n\");\n if (out_file_path) free(out_file_path);\n out_file_path=(char *)strdup(optarg);\n }\n break;\n#endif\n#ifdef CSV\n\t\t\tcase 'C':\n\t\t\t\tif (optarg) csv_char=optarg[0];\n\t\t\t\tbreak;\n#endif\n case 'h':\n cmdln_printhelp();\n break;\n#ifdef PROC_NET_DEV\n\t\t\tcase 'f':\n if (optarg && (strlen(optarg)0) { delay=atol(optarg); }\n break;\n#if EXTENDED_STATS \n case 'T':\n output_type=str2output_type(optarg);\n break;\n case 'A':\n if (optarg) avg_length=atoi(optarg)*1000;\n break;\n#endif \n case 'd':\n if (optarg) dynamic=atoi(optarg);\n break;\n case 'u':\n output_unit=str2output_unit(optarg);\n break;\n#if NETSTAT && ALLOW_NETSTATPATH\n case 'n':\n if (optarg && (strlen(optarg)=avg_length) deinit(1, \"avglength needs to be a least twice the value of timeout\\n\");\n#endif \n\t if ((output_unit==ERRORS_OUT && !net_input_method(input_method)) || \n\t\t\t (output_unit==PACKETS_OUT && input_method==LIBSTATDISK_IN)) \n\t\toutput_unit=BYTES_OUT;\n return;\n}", "func_hash": 180991180322803367820117530730983801100, "file_name": "options.c", "file_hash": 257904542626356393007641310631518105604, "cwe": ["CWE-476"], "cve": "CVE-2022-1341", "cve_desc": "An issue was discovered in in bwm-ng v0.6.2. An arbitrary null write exists in get_cmdln_options() function in src/options.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1341"} {"idx": 206874, "project": "FreeRDP", "commit_id": "b73143cf7ee5fe4cdabcbf56908aa15d8a883821", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/b73143cf7ee5fe4cdabcbf56908aa15d8a883821", "commit_message": "Fixed oob read in cliprdr_read_format_list", "target": 1, "func": "UINT cliprdr_read_format_list(wStream* s, CLIPRDR_FORMAT_LIST* formatList, BOOL useLongFormatNames)\n{\n\tUINT32 index;\n\tsize_t position;\n\tBOOL asciiNames;\n\tint formatNameLength;\n\tchar* szFormatName;\n\tWCHAR* wszFormatName;\n\tUINT32 dataLen = formatList->dataLen;\n\tCLIPRDR_FORMAT* formats = NULL;\n\tUINT error = CHANNEL_RC_OK;\n\n\tasciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE;\n\n\tindex = 0;\n\tformatList->numFormats = 0;\n\tposition = Stream_GetPosition(s);\n\n\tif (!formatList->dataLen)\n\t{\n\t\t/* empty format list */\n\t\tformatList->formats = NULL;\n\t\tformatList->numFormats = 0;\n\t}\n\telse if (!useLongFormatNames)\n\t{\n\t\tformatList->numFormats = (dataLen / 36);\n\n\t\tif ((formatList->numFormats * 36) != dataLen)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Invalid short format list length: %\" PRIu32 \"\", dataLen);\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (dataLen)\n\t\t{\n\t\t\tStream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */\n\t\t\tdataLen -= 4;\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\t/* According to MS-RDPECLIP 2.2.3.1.1.1 formatName is \"a 32-byte block containing\n\t\t\t * the *null-terminated* name assigned to the Clipboard Format: (32 ASCII 8 characters\n\t\t\t * or 16 Unicode characters)\"\n\t\t\t * However, both Windows RDSH and mstsc violate this specs as seen in the following\n\t\t\t * example of a transferred short format name string: [R.i.c.h. .T.e.x.t. .F.o.r.m.a.t.]\n\t\t\t * These are 16 unicode charaters - *without* terminating null !\n\t\t\t */\n\n\t\t\tif (asciiNames)\n\t\t\t{\n\t\t\t\tszFormatName = (char*)Stream_Pointer(s);\n\n\t\t\t\tif (szFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ensure null termination */\n\t\t\t\t\tformats[index].formatName = (char*)malloc(32 + 1);\n\t\t\t\t\tif (!formats[index].formatName)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"malloc failed!\");\n\t\t\t\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t\tCopyMemory(formats[index].formatName, szFormatName, 32);\n\t\t\t\t\tformats[index].formatName[32] = '\\0';\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twszFormatName = (WCHAR*)Stream_Pointer(s);\n\n\t\t\t\tif (wszFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ConvertFromUnicode always returns a null-terminated\n\t\t\t\t\t * string on success, even if the source string isn't.\n\t\t\t\t\t */\n\t\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, 16,\n\t\t\t\t\t &(formats[index].formatName), 0, NULL, NULL) < 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"failed to convert short clipboard format name\");\n\t\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStream_Seek(s, 32);\n\t\t\tdataLen -= 32;\n\t\t\tindex++;\n\t\t}\n\t}\n\telse\n\t{\n\t\twhile (dataLen)\n\t\t{\n\t\t\tStream_Seek(s, 4); /* formatId (4 bytes) */\n\t\t\tdataLen -= 4;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(s);\n\n\t\t\tif (!wszFormatName[0])\n\t\t\t\tformatNameLength = 0;\n\t\t\telse\n\t\t\t\tformatNameLength = _wcslen(wszFormatName);\n\n\t\t\tStream_Seek(s, (formatNameLength + 1) * 2);\n\t\t\tdataLen -= ((formatNameLength + 1) * 2);\n\n\t\t\tformatList->numFormats++;\n\t\t}\n\n\t\tdataLen = formatList->dataLen;\n\t\tStream_SetPosition(s, position);\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (dataLen)\n\t\t{\n\t\t\tStream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */\n\t\t\tdataLen -= 4;\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(s);\n\n\t\t\tif (!wszFormatName[0])\n\t\t\t\tformatNameLength = 0;\n\t\t\telse\n\t\t\t\tformatNameLength = _wcslen(wszFormatName);\n\n\t\t\tif (formatNameLength)\n\t\t\t{\n\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, -1, &(formats[index].formatName),\n\t\t\t\t 0, NULL, NULL) < 1)\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"failed to convert long clipboard format name\");\n\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\tgoto error_out;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStream_Seek(s, (formatNameLength + 1) * 2);\n\t\t\tdataLen -= ((formatNameLength + 1) * 2);\n\n\t\t\tindex++;\n\t\t}\n\t}\n\n\treturn error;\n\nerror_out:\n\tcliprdr_free_format_list(formatList);\n\treturn error;\n}", "func_hash": 172374228134807162117389831200539965494, "file_name": "cliprdr_common.c", "file_hash": 19188733325837471026384942758021239525, "cwe": ["CWE-125"], "cve": "CVE-2020-11085", "cve_desc": "In FreeRDP before 2.1.0, there is an out-of-bounds read in cliprdr_read_format_list. Clipboard format data read (by client or server) might read data out-of-bounds. This has been fixed in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11085"} {"idx": 388319, "project": "FreeRDP", "commit_id": "b73143cf7ee5fe4cdabcbf56908aa15d8a883821", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/b73143cf7ee5fe4cdabcbf56908aa15d8a883821", "commit_message": "Fixed oob read in cliprdr_read_format_list", "target": 0, "func": "UINT cliprdr_read_format_list(wStream* s, CLIPRDR_FORMAT_LIST* formatList, BOOL useLongFormatNames)\n{\n\tUINT32 index;\n\tsize_t position;\n\tBOOL asciiNames;\n\tint formatNameLength;\n\tchar* szFormatName;\n\tWCHAR* wszFormatName;\n\twStream sub1, sub2;\n\tCLIPRDR_FORMAT* formats = NULL;\n\tUINT error = CHANNEL_RC_OK;\n\n\tasciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE;\n\n\tindex = 0;\n\t/* empty format list */\n\tformatList->formats = NULL;\n\tformatList->numFormats = 0;\n\n\tStream_StaticInit(&sub1, Stream_Pointer(s), formatList->dataLen);\n\tif (!Stream_SafeSeek(s, formatList->dataLen))\n\t\treturn ERROR_INVALID_DATA;\n\n\tif (!formatList->dataLen)\n\t{\n\t}\n\telse if (!useLongFormatNames)\n\t{\n\t\tconst size_t cap = Stream_Capacity(&sub1);\n\t\tformatList->numFormats = (cap / 36);\n\n\t\tif ((formatList->numFormats * 36) != cap)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Invalid short format list length: %\" PRIuz \"\", cap);\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (Stream_GetRemainingLength(&sub1) >= 4)\n\t\t{\n\t\t\tStream_Read_UINT32(&sub1, formats[index].formatId); /* formatId (4 bytes) */\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\t/* According to MS-RDPECLIP 2.2.3.1.1.1 formatName is \"a 32-byte block containing\n\t\t\t * the *null-terminated* name assigned to the Clipboard Format: (32 ASCII 8 characters\n\t\t\t * or 16 Unicode characters)\"\n\t\t\t * However, both Windows RDSH and mstsc violate this specs as seen in the following\n\t\t\t * example of a transferred short format name string: [R.i.c.h. .T.e.x.t. .F.o.r.m.a.t.]\n\t\t\t * These are 16 unicode charaters - *without* terminating null !\n\t\t\t */\n\n\t\t\tszFormatName = (char*)Stream_Pointer(&sub1);\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(&sub1);\n\t\t\tif (!Stream_SafeSeek(&sub1, 32))\n\t\t\t\tgoto error_out;\n\t\t\tif (asciiNames)\n\t\t\t{\n\t\t\t\tif (szFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ensure null termination */\n\t\t\t\t\tformats[index].formatName = (char*)malloc(32 + 1);\n\t\t\t\t\tif (!formats[index].formatName)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"malloc failed!\");\n\t\t\t\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t\tCopyMemory(formats[index].formatName, szFormatName, 32);\n\t\t\t\t\tformats[index].formatName[32] = '\\0';\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (wszFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ConvertFromUnicode always returns a null-terminated\n\t\t\t\t\t * string on success, even if the source string isn't.\n\t\t\t\t\t */\n\t\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, 16,\n\t\t\t\t\t &(formats[index].formatName), 0, NULL, NULL) < 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"failed to convert short clipboard format name\");\n\t\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tindex++;\n\t\t}\n\t}\n\telse\n\t{\n\t\tsub2 = sub1;\n\t\twhile (Stream_GetRemainingLength(&sub1) > 0)\n\t\t{\n\t\t\tsize_t rest;\n\t\t\tif (!Stream_SafeSeek(&sub1, 4)) /* formatId (4 bytes) */\n\t\t\t\tgoto error_out;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(&sub1);\n\t\t\trest = Stream_GetRemainingLength(&sub1);\n\t\t\tformatNameLength = _wcsnlen(wszFormatName, rest / sizeof(WCHAR));\n\n\t\t\tif (!Stream_SafeSeek(&sub1, (formatNameLength + 1) * sizeof(WCHAR)))\n\t\t\t\tgoto error_out;\n\t\t\tformatList->numFormats++;\n\t\t}\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (Stream_GetRemainingLength(&sub2) >= 4)\n\t\t{\n\t\t\tsize_t rest;\n\t\t\tStream_Read_UINT32(&sub2, formats[index].formatId); /* formatId (4 bytes) */\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(&sub2);\n\t\t\trest = Stream_GetRemainingLength(&sub2);\n\t\t\tformatNameLength = _wcsnlen(wszFormatName, rest / sizeof(WCHAR));\n\t\t\tif (!Stream_SafeSeek(&sub2, (formatNameLength + 1) * sizeof(WCHAR)))\n\t\t\t\tgoto error_out;\n\n\t\t\tif (formatNameLength)\n\t\t\t{\n\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, formatNameLength,\n\t\t\t\t &(formats[index].formatName), 0, NULL, NULL) < 1)\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"failed to convert long clipboard format name\");\n\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\tgoto error_out;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tindex++;\n\t\t}\n\t}\n\n\treturn error;\n\nerror_out:\n\tcliprdr_free_format_list(formatList);\n\treturn error;\n}", "func_hash": 217680322937957629135686952268647138922, "file_name": "cliprdr_common.c", "file_hash": 337180726304010209485554176802565680213, "cwe": ["CWE-125"], "cve": "CVE-2020-11085", "cve_desc": "In FreeRDP before 2.1.0, there is an out-of-bounds read in cliprdr_read_format_list. Clipboard format data read (by client or server) might read data out-of-bounds. This has been fixed in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11085"} {"idx": 206917, "project": "httpd", "commit_id": "7e09dd714fc62c08c5b0319ed7b9702594faf49b", "project_url": "https://github.com/apache/httpd", "commit_url": "https://github.com/apache/httpd/commit/7e09dd714fc62c08c5b0319ed7b9702594faf49b", "commit_message": "mod_session: account for the '&' in identity_concat().\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1887052 13f79535-47bb-0310-9956-ffa450edef68", "target": 1, "func": "static int identity_count(void *v, const char *key, const char *val)\n{\n int *count = v;\n *count += strlen(key) * 3 + strlen(val) * 3 + 1;\n return 1;\n}", "func_hash": 145454435489180962670656277607463838912, "file_name": "mod_session.c", "file_hash": 145800931233519139025491268646472943230, "cwe": ["CWE-787"], "cve": "CVE-2021-26691", "cve_desc": "In Apache HTTP Server versions 2.4.0 to 2.4.46 a specially crafted SessionHeader sent by an origin server could cause a heap overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-26691"} {"idx": 389228, "project": "httpd", "commit_id": "7e09dd714fc62c08c5b0319ed7b9702594faf49b", "project_url": "https://github.com/apache/httpd", "commit_url": "https://github.com/apache/httpd/commit/7e09dd714fc62c08c5b0319ed7b9702594faf49b", "commit_message": "mod_session: account for the '&' in identity_concat().\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1887052 13f79535-47bb-0310-9956-ffa450edef68", "target": 0, "func": "static int identity_count(void *v, const char *key, const char *val)\n{\n int *count = v;\n *count += strlen(key) * 3 + strlen(val) * 3 + 2;\n return 1;\n}", "func_hash": 177870692435305010994741100000166685159, "file_name": "mod_session.c", "file_hash": 249365757579755385096816479792364501382, "cwe": ["CWE-787"], "cve": "CVE-2021-26691", "cve_desc": "In Apache HTTP Server versions 2.4.0 to 2.4.46 a specially crafted SessionHeader sent by an origin server could cause a heap overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-26691"} {"idx": 206930, "project": "ImageMagick", "commit_id": "a6802e21d824e786d1e2a8440cf749a6e1a8d95f", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/a6802e21d824e786d1e2a8440cf749a6e1a8d95f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/587", "target": 1, "func": "static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image *image, *image2=NULL,\n *rotated_image;\n register Quantum *q;\n\n unsigned int status;\n MATHeader MATLAB_HDR;\n size_t size;\n size_t CellType;\n QuantumInfo *quantum_info;\n ImageInfo *clone_info;\n int i;\n ssize_t ldblk;\n unsigned char *BImgBuff = NULL;\n double MinVal, MaxVal;\n unsigned z, z2;\n unsigned Frames;\n int logging;\n int sample_size;\n MagickOffsetType filepos=0x80;\n BlobInfo *blob;\n size_t one;\n\n unsigned int (*ReadBlobXXXLong)(Image *image);\n unsigned short (*ReadBlobXXXShort)(Image *image);\n void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");\n\n /*\n Open image file.\n */\n image = AcquireImage(image_info,exception);\n\n status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read MATLAB image.\n */\n quantum_info=(QuantumInfo *) NULL;\n clone_info=(ImageInfo *) NULL;\n if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n {\n image2=ReadMATImageV4(image_info,image,exception);\n if (image2 == NULL)\n goto MATLAB_KO;\n image=image2;\n goto END_OF_READING;\n }\n MATLAB_HDR.Version = ReadBlobLSBShort(image);\n if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Endian %c%c\",\n MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n {\n ReadBlobXXXLong = ReadBlobLSBLong;\n ReadBlobXXXShort = ReadBlobLSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n image->endian = LSBEndian;\n }\n else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n {\n ReadBlobXXXLong = ReadBlobMSBLong;\n ReadBlobXXXShort = ReadBlobMSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n image->endian = MSBEndian;\n }\n else\n goto MATLAB_KO; /* unsupported endian */\n\n if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\nMATLAB_KO:\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n filepos = TellBlob(image);\n while(!EOFBlob(image)) /* object parser loop */\n {\n Frames = 1;\n (void) SeekBlob(image,filepos,SEEK_SET);\n /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))\n goto MATLAB_KO;\n filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n clone_info=CloneImageInfo(image_info);\n image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if(MATLAB_HDR.DataType == miCOMPRESSED)\n {\n image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n if(image2==NULL) continue;\n MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n }\n#endif\n\n if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */\n\n MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);\n\n MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;\n\n MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n if(image!=image2)\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);\n\n\n switch(MATLAB_HDR.DimFlag)\n {\n case 8: z2=z=1; break; /* 2D matrix*/\n case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/\n (void) ReadBlobXXXLong(image2);\n if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n break;\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n Frames = ReadBlobXXXLong(image2);\n if (Frames == 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }\n\n MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */\n MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */\n MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */\n MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */\n MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */\n MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */\n ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n switch (MATLAB_HDR.NameFlag)\n {\n case 0:\n size = ReadBlobXXXLong(image2); /* Object name string size */\n size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n (void) SeekBlob(image2, size, SEEK_CUR);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n break;\n default:\n goto MATLAB_KO;\n }\n\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */\n\n NEXT_FRAME:\n switch (CellType)\n {\n case miINT8:\n case miUINT8:\n sample_size = 8;\n if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n image->depth = 1;\n else\n image->depth = 8; /* Byte type cell */\n ldblk = (ssize_t) MATLAB_HDR.SizeX;\n break;\n case miINT16:\n case miUINT16:\n sample_size = 16;\n image->depth = 16; /* Word type cell */\n ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n break;\n case miINT32:\n case miUINT32:\n sample_size = 32;\n image->depth = 32; /* Dword type cell */\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miINT64:\n case miUINT64:\n sample_size = 64;\n image->depth = 64; /* Qword type cell */\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n case miSINGLE:\n sample_size = 32;\n image->depth = 32; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex float type cell */\n }\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miDOUBLE:\n sample_size = 64;\n image->depth = 64; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n if (sizeof(double) != 8)\nRestoreMSCWarning\n ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex double type cell */\n }\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n default:\n ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n }\n (void) sample_size;\n image->columns = MATLAB_HDR.SizeX;\n image->rows = MATLAB_HDR.SizeY;\n one=1;\n image->colors = one << image->depth;\n if (image->columns == 0 || image->rows == 0)\n goto MATLAB_KO;\n if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n goto MATLAB_KO;\n /* Image is gray when no complex flag is set and 2D Matrix */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n {\n image->type=GrayscaleType;\n SetImageColorspace(image,GRAYColorspace,exception);\n }\n\n\n /*\n If ping is true, then only set image size and colors without\n reading any image data.\n */\n if (image_info->ping)\n {\n size_t temp = image->columns;\n image->columns = image->rows;\n image->rows = temp;\n goto done_reading; /* !!!!!! BAD !!!! */\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n quantum_info=AcquireQuantumInfo(clone_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n /* ----- Load raster data ----- */\n BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */\n if (BImgBuff == NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));\n\n MinVal = 0;\n MaxVal = 0;\n if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n }\n\n /* Main loop for reading all scanlines */\n if(z==1) z=0; /* read grey scanlines */\n /* else read color scanlines */\n do\n {\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto done_reading; /* Skip image rotation, when cannot set image pixels */\n }\n if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n {\n FixLogical((unsigned char *)BImgBuff,ldblk);\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n {\nImportQuantumPixelsFailed:\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n break;\n }\n }\n else\n {\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n goto ImportQuantumPixelsFailed;\n\n\n if (z<=1 && /* fix only during a last pass z==0 || z==1 */\n (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n FixSignedValues(image,q,MATLAB_HDR.SizeX);\n }\n\n if (!SyncAuthenticPixels(image,exception))\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n }\n } while(z-- >= 2);\nExitLoop:\n\n\n /* Read complex part of numbers here */\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* Find Min and Max Values for complex parts of floats */\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/\n\n if (CellType==miDOUBLE || CellType==miSINGLE)\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n }\n\n if (CellType==miDOUBLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n exception);\n }\n\n if (CellType==miSINGLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n exception);\n }\n }\n\n /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n image->type=GrayscaleType;\n if (image->depth == 1)\n image->type=BilevelType;\n\n if(image2==image)\n image2 = NULL; /* Remove shadow copy to an image before rotation. */\n\n /* Rotate image. */\n rotated_image = RotateImage(image, 90.0, exception);\n if (rotated_image != (Image *) NULL)\n {\n /* Remove page offsets added by RotateImage */\n rotated_image->page.x=0;\n rotated_image->page.y=0;\n\n blob = rotated_image->blob;\n rotated_image->blob = image->blob;\n rotated_image->colors = image->colors;\n image->blob = blob;\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }\n\ndone_reading:\n\n if(image2!=NULL)\n if(image2!=image)\n {\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n if (image->next == (Image *) NULL) break;\n image=SyncNextImageInList(image);\n image->columns=image->rows=0;\n image->colors=0;\n\n /* row scan buffer is no longer needed */\n RelinquishMagickMemory(BImgBuff);\n BImgBuff = NULL;\n\n if(--Frames>0)\n {\n z = z2;\n if(image2==NULL) image2 = image;\n goto NEXT_FRAME;\n }\n if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */\n {\n/* CloseBlob(image2); */\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n }\n\n RelinquishMagickMemory(BImgBuff);\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n CloseBlob(image);\n\n\n {\n Image *p;\n ssize_t scene=0;\n\n /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;\n DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }\n\n /*\n Fix scene numbers\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=scene++;\n }\n\n if(clone_info != NULL) /* cleanup garbage file from compression */\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n DestroyImageInfo(clone_info);\n clone_info = NULL;\n }\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n if(image==NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n return (image);\n}", "func_hash": 79078380666323482029779347283279315279, "file_name": "mat.c", "file_hash": 232552103828044285256723124760364681488, "cwe": ["CWE-772"], "cve": "CVE-2017-11644", "cve_desc": "When ImageMagick 7.0.6-1 processes a crafted file in convert, it can lead to a Memory Leak in the ReadMATImage() function in coders/mat.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-11644"} {"idx": 389327, "project": "ImageMagick", "commit_id": "a6802e21d824e786d1e2a8440cf749a6e1a8d95f", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/a6802e21d824e786d1e2a8440cf749a6e1a8d95f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/587", "target": 0, "func": "static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image *image, *image2=NULL,\n *rotated_image;\n register Quantum *q;\n\n unsigned int status;\n MATHeader MATLAB_HDR;\n size_t size;\n size_t CellType;\n QuantumInfo *quantum_info;\n ImageInfo *clone_info;\n int i;\n ssize_t ldblk;\n unsigned char *BImgBuff = NULL;\n double MinVal, MaxVal;\n unsigned z, z2;\n unsigned Frames;\n int logging;\n int sample_size;\n MagickOffsetType filepos=0x80;\n BlobInfo *blob;\n size_t one;\n\n unsigned int (*ReadBlobXXXLong)(Image *image);\n unsigned short (*ReadBlobXXXShort)(Image *image);\n void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");\n\n /*\n Open image file.\n */\n image = AcquireImage(image_info,exception);\n\n status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read MATLAB image.\n */\n quantum_info=(QuantumInfo *) NULL;\n clone_info=(ImageInfo *) NULL;\n if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n {\n image2=ReadMATImageV4(image_info,image,exception);\n if (image2 == NULL)\n goto MATLAB_KO;\n image=image2;\n goto END_OF_READING;\n }\n MATLAB_HDR.Version = ReadBlobLSBShort(image);\n if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Endian %c%c\",\n MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n {\n ReadBlobXXXLong = ReadBlobLSBLong;\n ReadBlobXXXShort = ReadBlobLSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n image->endian = LSBEndian;\n }\n else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n {\n ReadBlobXXXLong = ReadBlobMSBLong;\n ReadBlobXXXShort = ReadBlobMSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n image->endian = MSBEndian;\n }\n else\n goto MATLAB_KO; /* unsupported endian */\n\n if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\nMATLAB_KO:\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n filepos = TellBlob(image);\n while(!EOFBlob(image)) /* object parser loop */\n {\n Frames = 1;\n (void) SeekBlob(image,filepos,SEEK_SET);\n /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))\n goto MATLAB_KO;\n filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n clone_info=CloneImageInfo(image_info);\n image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if(MATLAB_HDR.DataType == miCOMPRESSED)\n {\n image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n if(image2==NULL) continue;\n MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n }\n#endif\n\n if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */\n\n MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);\n\n MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;\n\n MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n if(image!=image2)\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);\n\n\n switch(MATLAB_HDR.DimFlag)\n {\n case 8: z2=z=1; break; /* 2D matrix*/\n case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/\n (void) ReadBlobXXXLong(image2);\n if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n break;\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n Frames = ReadBlobXXXLong(image2);\n if (Frames == 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }\n\n MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */\n MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */\n MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */\n MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */\n MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */\n MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */\n ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n switch (MATLAB_HDR.NameFlag)\n {\n case 0:\n size = ReadBlobXXXLong(image2); /* Object name string size */\n size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n (void) SeekBlob(image2, size, SEEK_CUR);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n break;\n default:\n goto MATLAB_KO;\n }\n\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */\n\n NEXT_FRAME:\n switch (CellType)\n {\n case miINT8:\n case miUINT8:\n sample_size = 8;\n if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n image->depth = 1;\n else\n image->depth = 8; /* Byte type cell */\n ldblk = (ssize_t) MATLAB_HDR.SizeX;\n break;\n case miINT16:\n case miUINT16:\n sample_size = 16;\n image->depth = 16; /* Word type cell */\n ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n break;\n case miINT32:\n case miUINT32:\n sample_size = 32;\n image->depth = 32; /* Dword type cell */\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miINT64:\n case miUINT64:\n sample_size = 64;\n image->depth = 64; /* Qword type cell */\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n case miSINGLE:\n sample_size = 32;\n image->depth = 32; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex float type cell */\n }\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miDOUBLE:\n sample_size = 64;\n image->depth = 64; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n if (sizeof(double) != 8)\nRestoreMSCWarning\n ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex double type cell */\n }\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n default:\n ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n }\n (void) sample_size;\n image->columns = MATLAB_HDR.SizeX;\n image->rows = MATLAB_HDR.SizeY;\n one=1;\n image->colors = one << image->depth;\n if (image->columns == 0 || image->rows == 0)\n goto MATLAB_KO;\n if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n goto MATLAB_KO;\n /* Image is gray when no complex flag is set and 2D Matrix */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n {\n image->type=GrayscaleType;\n SetImageColorspace(image,GRAYColorspace,exception);\n }\n\n\n /*\n If ping is true, then only set image size and colors without\n reading any image data.\n */\n if (image_info->ping)\n {\n size_t temp = image->columns;\n image->columns = image->rows;\n image->rows = temp;\n goto done_reading; /* !!!!!! BAD !!!! */\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n quantum_info=AcquireQuantumInfo(clone_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n /* ----- Load raster data ----- */\n BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */\n if (BImgBuff == NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));\n\n MinVal = 0;\n MaxVal = 0;\n if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n }\n\n /* Main loop for reading all scanlines */\n if(z==1) z=0; /* read grey scanlines */\n /* else read color scanlines */\n do\n {\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto done_reading; /* Skip image rotation, when cannot set image pixels */\n }\n if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n {\n FixLogical((unsigned char *)BImgBuff,ldblk);\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n {\nImportQuantumPixelsFailed:\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n break;\n }\n }\n else\n {\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n goto ImportQuantumPixelsFailed;\n\n\n if (z<=1 && /* fix only during a last pass z==0 || z==1 */\n (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n FixSignedValues(image,q,MATLAB_HDR.SizeX);\n }\n\n if (!SyncAuthenticPixels(image,exception))\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n }\n } while(z-- >= 2);\nExitLoop:\n\n\n /* Read complex part of numbers here */\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* Find Min and Max Values for complex parts of floats */\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/\n\n if (CellType==miDOUBLE || CellType==miSINGLE)\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n }\n\n if (CellType==miDOUBLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n exception);\n }\n\n if (CellType==miSINGLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n exception);\n }\n }\n\n /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n image->type=GrayscaleType;\n if (image->depth == 1)\n image->type=BilevelType;\n\n if(image2==image)\n image2 = NULL; /* Remove shadow copy to an image before rotation. */\n\n /* Rotate image. */\n rotated_image = RotateImage(image, 90.0, exception);\n if (rotated_image != (Image *) NULL)\n {\n /* Remove page offsets added by RotateImage */\n rotated_image->page.x=0;\n rotated_image->page.y=0;\n\n blob = rotated_image->blob;\n rotated_image->blob = image->blob;\n rotated_image->colors = image->colors;\n image->blob = blob;\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }\n\ndone_reading:\n\n if(image2!=NULL)\n if(image2!=image)\n {\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n if (image->next == (Image *) NULL) break;\n image=SyncNextImageInList(image);\n image->columns=image->rows=0;\n image->colors=0;\n\n /* row scan buffer is no longer needed */\n RelinquishMagickMemory(BImgBuff);\n BImgBuff = NULL;\n\n if(--Frames>0)\n {\n z = z2;\n if(image2==NULL) image2 = image;\n goto NEXT_FRAME;\n }\n if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */\n {\n/* CloseBlob(image2); */\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n }\n\n RelinquishMagickMemory(BImgBuff);\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n CloseBlob(image);\n\n\n {\n Image *p;\n ssize_t scene=0;\n\n /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;\n DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }\n\n /*\n Fix scene numbers\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=scene++;\n }\n\n if(clone_info != NULL) /* cleanup garbage file from compression */\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n DestroyImageInfo(clone_info);\n clone_info = NULL;\n }\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n if(image==NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n return (image);\n}", "func_hash": 225675730143832561123521586827548480247, "file_name": "mat.c", "file_hash": 334536777685230229392445256981141215240, "cwe": ["CWE-772"], "cve": "CVE-2017-11644", "cve_desc": "When ImageMagick 7.0.6-1 processes a crafted file in convert, it can lead to a Memory Leak in the ReadMATImage() function in coders/mat.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-11644"} {"idx": 206932, "project": "linux", "commit_id": "e8d5f92b8d30bb4ade76494490c3c065e12411b1", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e8d5f92b8d30bb4ade76494490c3c065e12411b1", "commit_message": "usb: gadget: function: printer: fix use-after-free in __lock_acquire\n\nFix this by increase object reference count.\n\nBUG: KASAN: use-after-free in __lock_acquire+0x3fd4/0x4180\nkernel/locking/lockdep.c:3831\nRead of size 8 at addr ffff8880683b0018 by task syz-executor.0/3377\n\nCPU: 1 PID: 3377 Comm: syz-executor.0 Not tainted 5.6.11 #1\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xce/0x128 lib/dump_stack.c:118\n print_address_description.constprop.4+0x21/0x3c0 mm/kasan/report.c:374\n __kasan_report+0x131/0x1b0 mm/kasan/report.c:506\n kasan_report+0x12/0x20 mm/kasan/common.c:641\n __asan_report_load8_noabort+0x14/0x20 mm/kasan/generic_report.c:135\n __lock_acquire+0x3fd4/0x4180 kernel/locking/lockdep.c:3831\n lock_acquire+0x127/0x350 kernel/locking/lockdep.c:4488\n __raw_spin_lock_irqsave include/linux/spinlock_api_smp.h:110 [inline]\n _raw_spin_lock_irqsave+0x35/0x50 kernel/locking/spinlock.c:159\n printer_ioctl+0x4a/0x110 drivers/usb/gadget/function/f_printer.c:723\n vfs_ioctl fs/ioctl.c:47 [inline]\n ksys_ioctl+0xfb/0x130 fs/ioctl.c:763\n __do_sys_ioctl fs/ioctl.c:772 [inline]\n __se_sys_ioctl fs/ioctl.c:770 [inline]\n __x64_sys_ioctl+0x73/0xb0 fs/ioctl.c:770\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x4531a9\nCode: ed 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 48 89 f8 48\n89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d\n01 f0 ff ff 0f 83 bb 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00\nRSP: 002b:00007fd14ad72c78 EFLAGS: 00000246 ORIG_RAX: 0000000000000010\nRAX: ffffffffffffffda RBX: 000000000073bfa8 RCX: 00000000004531a9\nRDX: fffffffffffffff9 RSI: 000000000000009e RDI: 0000000000000003\nRBP: 0000000000000003 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00000000004bbd61\nR13: 00000000004d0a98 R14: 00007fd14ad736d4 R15: 00000000ffffffff\n\nAllocated by task 2393:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n __kasan_kmalloc.constprop.3+0xa7/0xd0 mm/kasan/common.c:515\n kasan_kmalloc+0x9/0x10 mm/kasan/common.c:529\n kmem_cache_alloc_trace+0xfa/0x2d0 mm/slub.c:2813\n kmalloc include/linux/slab.h:555 [inline]\n kzalloc include/linux/slab.h:669 [inline]\n gprinter_alloc+0xa1/0x870 drivers/usb/gadget/function/f_printer.c:1416\n usb_get_function+0x58/0xc0 drivers/usb/gadget/functions.c:61\n config_usb_cfg_link+0x1ed/0x3e0 drivers/usb/gadget/configfs.c:444\n configfs_symlink+0x527/0x11d0 fs/configfs/symlink.c:202\n vfs_symlink+0x33d/0x5b0 fs/namei.c:4201\n do_symlinkat+0x11b/0x1d0 fs/namei.c:4228\n __do_sys_symlinkat fs/namei.c:4242 [inline]\n __se_sys_symlinkat fs/namei.c:4239 [inline]\n __x64_sys_symlinkat+0x73/0xb0 fs/namei.c:4239\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nFreed by task 3368:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n kasan_set_free_info mm/kasan/common.c:337 [inline]\n __kasan_slab_free+0x135/0x190 mm/kasan/common.c:476\n kasan_slab_free+0xe/0x10 mm/kasan/common.c:485\n slab_free_hook mm/slub.c:1444 [inline]\n slab_free_freelist_hook mm/slub.c:1477 [inline]\n slab_free mm/slub.c:3034 [inline]\n kfree+0xf7/0x410 mm/slub.c:3995\n gprinter_free+0x49/0xd0 drivers/usb/gadget/function/f_printer.c:1353\n usb_put_function+0x38/0x50 drivers/usb/gadget/functions.c:87\n config_usb_cfg_unlink+0x2db/0x3b0 drivers/usb/gadget/configfs.c:485\n configfs_unlink+0x3b9/0x7f0 fs/configfs/symlink.c:250\n vfs_unlink+0x287/0x570 fs/namei.c:4073\n do_unlinkat+0x4f9/0x620 fs/namei.c:4137\n __do_sys_unlink fs/namei.c:4184 [inline]\n __se_sys_unlink fs/namei.c:4182 [inline]\n __x64_sys_unlink+0x42/0x50 fs/namei.c:4182\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nThe buggy address belongs to the object at ffff8880683b0000\n which belongs to the cache kmalloc-1k of size 1024\nThe buggy address is located 24 bytes inside of\n 1024-byte region [ffff8880683b0000, ffff8880683b0400)\nThe buggy address belongs to the page:\npage:ffffea0001a0ec00 refcount:1 mapcount:0 mapping:ffff88806c00e300\nindex:0xffff8880683b1800 compound_mapcount: 0\nflags: 0x100000000010200(slab|head)\nraw: 0100000000010200 0000000000000000 0000000600000001 ffff88806c00e300\nraw: ffff8880683b1800 000000008010000a 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nReported-by: Kyungtae Kim \nSigned-off-by: Zqiang \nSigned-off-by: Felipe Balbi ", "target": 1, "func": "static void gprinter_free(struct usb_function *f)\n{\n\tstruct printer_dev *dev = func_to_printer(f);\n\tstruct f_printer_opts *opts;\n\n\topts = container_of(f->fi, struct f_printer_opts, func_inst);\n\tkfree(dev);\n\tmutex_lock(&opts->lock);\n\t--opts->refcnt;\n\tmutex_unlock(&opts->lock);\n}", "func_hash": 327378375587759270684816071184010028361, "file_name": "f_printer.c", "file_hash": 37638766286674752097108271239583326744, "cwe": ["CWE-416"], "cve": "CVE-2020-27784", "cve_desc": "A vulnerability was found in the Linux kernel, where accessing a deallocated instance in printer_ioctl() printer_ioctl() tries to access of a printer_dev instance. However, use-after-free arises because it had been freed by gprinter_free().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27784"} {"idx": 389362, "project": "linux", "commit_id": "e8d5f92b8d30bb4ade76494490c3c065e12411b1", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e8d5f92b8d30bb4ade76494490c3c065e12411b1", "commit_message": "usb: gadget: function: printer: fix use-after-free in __lock_acquire\n\nFix this by increase object reference count.\n\nBUG: KASAN: use-after-free in __lock_acquire+0x3fd4/0x4180\nkernel/locking/lockdep.c:3831\nRead of size 8 at addr ffff8880683b0018 by task syz-executor.0/3377\n\nCPU: 1 PID: 3377 Comm: syz-executor.0 Not tainted 5.6.11 #1\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xce/0x128 lib/dump_stack.c:118\n print_address_description.constprop.4+0x21/0x3c0 mm/kasan/report.c:374\n __kasan_report+0x131/0x1b0 mm/kasan/report.c:506\n kasan_report+0x12/0x20 mm/kasan/common.c:641\n __asan_report_load8_noabort+0x14/0x20 mm/kasan/generic_report.c:135\n __lock_acquire+0x3fd4/0x4180 kernel/locking/lockdep.c:3831\n lock_acquire+0x127/0x350 kernel/locking/lockdep.c:4488\n __raw_spin_lock_irqsave include/linux/spinlock_api_smp.h:110 [inline]\n _raw_spin_lock_irqsave+0x35/0x50 kernel/locking/spinlock.c:159\n printer_ioctl+0x4a/0x110 drivers/usb/gadget/function/f_printer.c:723\n vfs_ioctl fs/ioctl.c:47 [inline]\n ksys_ioctl+0xfb/0x130 fs/ioctl.c:763\n __do_sys_ioctl fs/ioctl.c:772 [inline]\n __se_sys_ioctl fs/ioctl.c:770 [inline]\n __x64_sys_ioctl+0x73/0xb0 fs/ioctl.c:770\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x4531a9\nCode: ed 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 48 89 f8 48\n89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d\n01 f0 ff ff 0f 83 bb 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00\nRSP: 002b:00007fd14ad72c78 EFLAGS: 00000246 ORIG_RAX: 0000000000000010\nRAX: ffffffffffffffda RBX: 000000000073bfa8 RCX: 00000000004531a9\nRDX: fffffffffffffff9 RSI: 000000000000009e RDI: 0000000000000003\nRBP: 0000000000000003 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00000000004bbd61\nR13: 00000000004d0a98 R14: 00007fd14ad736d4 R15: 00000000ffffffff\n\nAllocated by task 2393:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n __kasan_kmalloc.constprop.3+0xa7/0xd0 mm/kasan/common.c:515\n kasan_kmalloc+0x9/0x10 mm/kasan/common.c:529\n kmem_cache_alloc_trace+0xfa/0x2d0 mm/slub.c:2813\n kmalloc include/linux/slab.h:555 [inline]\n kzalloc include/linux/slab.h:669 [inline]\n gprinter_alloc+0xa1/0x870 drivers/usb/gadget/function/f_printer.c:1416\n usb_get_function+0x58/0xc0 drivers/usb/gadget/functions.c:61\n config_usb_cfg_link+0x1ed/0x3e0 drivers/usb/gadget/configfs.c:444\n configfs_symlink+0x527/0x11d0 fs/configfs/symlink.c:202\n vfs_symlink+0x33d/0x5b0 fs/namei.c:4201\n do_symlinkat+0x11b/0x1d0 fs/namei.c:4228\n __do_sys_symlinkat fs/namei.c:4242 [inline]\n __se_sys_symlinkat fs/namei.c:4239 [inline]\n __x64_sys_symlinkat+0x73/0xb0 fs/namei.c:4239\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nFreed by task 3368:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n kasan_set_free_info mm/kasan/common.c:337 [inline]\n __kasan_slab_free+0x135/0x190 mm/kasan/common.c:476\n kasan_slab_free+0xe/0x10 mm/kasan/common.c:485\n slab_free_hook mm/slub.c:1444 [inline]\n slab_free_freelist_hook mm/slub.c:1477 [inline]\n slab_free mm/slub.c:3034 [inline]\n kfree+0xf7/0x410 mm/slub.c:3995\n gprinter_free+0x49/0xd0 drivers/usb/gadget/function/f_printer.c:1353\n usb_put_function+0x38/0x50 drivers/usb/gadget/functions.c:87\n config_usb_cfg_unlink+0x2db/0x3b0 drivers/usb/gadget/configfs.c:485\n configfs_unlink+0x3b9/0x7f0 fs/configfs/symlink.c:250\n vfs_unlink+0x287/0x570 fs/namei.c:4073\n do_unlinkat+0x4f9/0x620 fs/namei.c:4137\n __do_sys_unlink fs/namei.c:4184 [inline]\n __se_sys_unlink fs/namei.c:4182 [inline]\n __x64_sys_unlink+0x42/0x50 fs/namei.c:4182\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nThe buggy address belongs to the object at ffff8880683b0000\n which belongs to the cache kmalloc-1k of size 1024\nThe buggy address is located 24 bytes inside of\n 1024-byte region [ffff8880683b0000, ffff8880683b0400)\nThe buggy address belongs to the page:\npage:ffffea0001a0ec00 refcount:1 mapcount:0 mapping:ffff88806c00e300\nindex:0xffff8880683b1800 compound_mapcount: 0\nflags: 0x100000000010200(slab|head)\nraw: 0100000000010200 0000000000000000 0000000600000001 ffff88806c00e300\nraw: ffff8880683b1800 000000008010000a 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nReported-by: Kyungtae Kim \nSigned-off-by: Zqiang \nSigned-off-by: Felipe Balbi ", "target": 0, "func": "static void gprinter_free(struct usb_function *f)\n{\n\tstruct printer_dev *dev = func_to_printer(f);\n\tstruct f_printer_opts *opts;\n\n\topts = container_of(f->fi, struct f_printer_opts, func_inst);\n\n\tkref_put(&dev->kref, printer_dev_free);\n\tmutex_lock(&opts->lock);\n\t--opts->refcnt;\n\tmutex_unlock(&opts->lock);\n}", "func_hash": 229775245538823429983493745101329450974, "file_name": "f_printer.c", "file_hash": 140001632269502492205176661016395877153, "cwe": ["CWE-416"], "cve": "CVE-2020-27784", "cve_desc": "A vulnerability was found in the Linux kernel, where accessing a deallocated instance in printer_ioctl() printer_ioctl() tries to access of a printer_dev instance. However, use-after-free arises because it had been freed by gprinter_free().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27784"} {"idx": 206948, "project": "ghostpdl", "commit_id": "714e8995cd582d418276915cbbec3c70711fb19e", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=714e8995cd582d418276915cbbec3c70711fb19e", "commit_message": "Bug 701807: avoid buffer overflow in tiff12_print_page().\n\nFixes:\n ./sanbin/gs -r650 -sOutputFile=tmp -sDEVICE=tiff12nc ../bug-701807.pdf", "target": 1, "func": "tiff12_print_page(gx_device_printer * pdev, gp_file * file)\n{\n gx_device_tiff *const tfdev = (gx_device_tiff *)pdev;\n int code;\n\n /* open the TIFF device */\n if (gdev_prn_file_is_new(pdev)) {\n tfdev->tif = tiff_from_filep(pdev, pdev->dname, file, tfdev->BigEndian, tfdev->UseBigTIFF);\n if (!tfdev->tif)\n return_error(gs_error_invalidfileaccess);\n }\n\n code = gdev_tiff_begin_page(tfdev, file);\n if (code < 0)\n return code;\n\n TIFFSetField(tfdev->tif, TIFFTAG_BITSPERSAMPLE, 4);\n tiff_set_rgb_fields(tfdev);\n\n TIFFCheckpointDirectory(tfdev->tif);\n\n /* Write the page data. */\n {\n int y;\n int size = gdev_prn_raster(pdev);\n byte *data = gs_alloc_bytes(pdev->memory, size, \"tiff12_print_page\");\n\n if (data == 0)\n return_error(gs_error_VMerror);\n\n memset(data, 0, size);\n\n for (y = 0; y < pdev->height; ++y) {\n const byte *src;\n byte *dest;\n int x;\n\n code = gdev_prn_copy_scan_lines(pdev, y, data, size);\n if (code < 0)\n break;\n\n for (src = data, dest = data, x = 0; x < size;\n src += 6, dest += 3, x += 6\n ) {\n dest[0] = (src[0] & 0xf0) | (src[1] >> 4);\n dest[1] = (src[2] & 0xf0) | (src[3] >> 4);\n dest[2] = (src[4] & 0xf0) | (src[5] >> 4);\n }\n TIFFWriteScanline(tfdev->tif, data, y, 0);\n }\n gs_free_object(pdev->memory, data, \"tiff12_print_page\");\n\n TIFFWriteDirectory(tfdev->tif);\n }\n\n return code;\n}", "func_hash": 27538471440457626772137757617736193904, "file_name": "gdevtfnx.c", "file_hash": 319455063093100559762576113680968399142, "cwe": ["CWE-787"], "cve": "CVE-2020-16300", "cve_desc": "A buffer overflow vulnerability in tiff12_print_page() in devices/gdevtfnx.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16300"} {"idx": 389796, "project": "ghostpdl", "commit_id": "714e8995cd582d418276915cbbec3c70711fb19e", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=714e8995cd582d418276915cbbec3c70711fb19e", "commit_message": "Bug 701807: avoid buffer overflow in tiff12_print_page().\n\nFixes:\n ./sanbin/gs -r650 -sOutputFile=tmp -sDEVICE=tiff12nc ../bug-701807.pdf", "target": 0, "func": "tiff12_print_page(gx_device_printer * pdev, gp_file * file)\n{\n gx_device_tiff *const tfdev = (gx_device_tiff *)pdev;\n int code;\n\n /* open the TIFF device */\n if (gdev_prn_file_is_new(pdev)) {\n tfdev->tif = tiff_from_filep(pdev, pdev->dname, file, tfdev->BigEndian, tfdev->UseBigTIFF);\n if (!tfdev->tif)\n return_error(gs_error_invalidfileaccess);\n }\n\n code = gdev_tiff_begin_page(tfdev, file);\n if (code < 0)\n return code;\n\n TIFFSetField(tfdev->tif, TIFFTAG_BITSPERSAMPLE, 4);\n tiff_set_rgb_fields(tfdev);\n\n TIFFCheckpointDirectory(tfdev->tif);\n\n /* Write the page data. */\n {\n int y;\n int size = gdev_prn_raster(pdev);\n\n /* We allocate an extra 5 bytes to avoid buffer overflow when accessing\n src[5] below, if size if not multiple of 6. This fixes bug-701807. */\n int size_alloc = size + 5;\n byte *data = gs_alloc_bytes(pdev->memory, size_alloc, \"tiff12_print_page\");\n\n if (data == 0)\n return_error(gs_error_VMerror);\n\n memset(data, 0, size_alloc);\n\n for (y = 0; y < pdev->height; ++y) {\n const byte *src;\n byte *dest;\n int x;\n\n code = gdev_prn_copy_scan_lines(pdev, y, data, size);\n if (code < 0)\n break;\n\n for (src = data, dest = data, x = 0; x < size;\n src += 6, dest += 3, x += 6\n ) {\n dest[0] = (src[0] & 0xf0) | (src[1] >> 4);\n dest[1] = (src[2] & 0xf0) | (src[3] >> 4);\n dest[2] = (src[4] & 0xf0) | (src[5] >> 4);\n }\n TIFFWriteScanline(tfdev->tif, data, y, 0);\n }\n gs_free_object(pdev->memory, data, \"tiff12_print_page\");\n\n TIFFWriteDirectory(tfdev->tif);\n }\n\n return code;\n}", "func_hash": 59154305660031873538749922160153037994, "file_name": "gdevtfnx.c", "file_hash": 66898638370582106647094152795587738612, "cwe": ["CWE-787"], "cve": "CVE-2020-16300", "cve_desc": "A buffer overflow vulnerability in tiff12_print_page() in devices/gdevtfnx.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16300"} {"idx": 206998, "project": "clamav-devel", "commit_id": "d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6", "project_url": "https://github.com/vrtadmin/clamav-devel", "commit_url": "https://github.com/Cisco-Talos/clamav-devel/commit/d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6", "commit_message": "bb11588 - fix out of bounds read.", "target": 1, "func": "static int xar_hash_check(int hash, const void * result, const void * expected)\n{\n int len;\n\n if (!result || !expected)\n return 1;\n switch (hash) {\n case XAR_CKSUM_SHA1:\n len = SHA1_HASH_SIZE;\n break;\n case XAR_CKSUM_MD5:\n len = CLI_HASH_MD5;\n break;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return 1;\n }\n return memcmp(result, expected, len);\n}", "func_hash": 123436481610572671443212515331013374302, "file_name": "xar.c", "file_hash": 202879046300903503737595072811151761952, "cwe": ["CWE-125"], "cve": "CVE-2018-1000085", "cve_desc": "ClamAV version version 0.99.3 contains a Out of bounds heap memory read vulnerability in XAR parser, function xar_hash_check() that can result in Leaking of memory, may help in developing exploit chains.. This attack appear to be exploitable via The victim must scan a crafted XAR file. This vulnerability appears to have been fixed in after commit d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-1000085"} {"idx": 390690, "project": "clamav-devel", "commit_id": "d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6", "project_url": "https://github.com/vrtadmin/clamav-devel", "commit_url": "https://github.com/Cisco-Talos/clamav-devel/commit/d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6", "commit_message": "bb11588 - fix out of bounds read.", "target": 0, "func": "static int xar_hash_check(int hash, const void * result, const void * expected)\n{\n int len;\n\n if (!result || !expected)\n return 1;\n switch (hash) {\n case XAR_CKSUM_SHA1:\n len = CLI_HASHLEN_SHA1;\n break;\n case XAR_CKSUM_MD5:\n len = CLI_HASHLEN_MD5;\n break;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return 1;\n }\n return memcmp(result, expected, len);\n}", "func_hash": 168639988115572580517356995829865142105, "file_name": "xar.c", "file_hash": 199129489153330895208987619887211421183, "cwe": ["CWE-125"], "cve": "CVE-2018-1000085", "cve_desc": "ClamAV version version 0.99.3 contains a Out of bounds heap memory read vulnerability in XAR parser, function xar_hash_check() that can result in Leaking of memory, may help in developing exploit chains.. This attack appear to be exploitable via The victim must scan a crafted XAR file. This vulnerability appears to have been fixed in after commit d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-1000085"} {"idx": 207059, "project": "LibRaw", "commit_id": "d13e8f6d1e987b7491182040a188c16a395f1d21", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/d13e8f6d1e987b7491182040a188c16a395f1d21", "commit_message": "CVE-2017-1438 credits; fix for Kodak 65000 out of bounds access", "target": 1, "func": "void CLASS kodak_65000_load_raw()\n{\n short buf[256];\n int row, col, len, pred[2], ret, i;\n\n for (row=0; row < height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col=0; col < width; col+=256) {\n pred[0] = pred[1] = 0;\n len = MIN (256, width-col);\n ret = kodak_65000_decode (buf, len);\n for (i=0; i < len; i++)\n\tif ((RAW(row,col+i) =\tcurve[ret ? buf[i] :\n\t\t(pred[i & 1] += buf[i])]) >> 12) derror();\n }\n }\n}", "func_hash": 193595394411360755503587909089489195860, "file_name": "dcraw.c", "file_hash": 65532579866829157140663234271634125833, "cwe": ["CWE-787"], "cve": "CVE-2017-14348", "cve_desc": "LibRaw before 0.18.4 has a heap-based Buffer Overflow in the processCanonCameraInfo function via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-14348"} {"idx": 391457, "project": "LibRaw", "commit_id": "d13e8f6d1e987b7491182040a188c16a395f1d21", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/d13e8f6d1e987b7491182040a188c16a395f1d21", "commit_message": "CVE-2017-1438 credits; fix for Kodak 65000 out of bounds access", "target": 0, "func": "void CLASS kodak_65000_load_raw()\n{\n short buf[256];\n int row, col, len, pred[2], ret, i;\n\n for (row=0; row < height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col=0; col < width; col+=256) {\n pred[0] = pred[1] = 0;\n len = MIN (256, width-col);\n ret = kodak_65000_decode (buf, len);\n for (i=0; i < len; i++)\n {\n\tint idx = ret ? buf[i] : (pred[i & 1] += buf[i]);\n\tif(idx >=0 && idx <= 0xffff)\n\t {\n\t if ((RAW(row,col+i) = curve[idx]) >> 12) derror();\n }\n\t else\n\t derror();\n }\n }\n }\n}", "func_hash": 251308369175262433692526384282922125519, "file_name": "dcraw.c", "file_hash": 328099487843809804470910139219018462943, "cwe": ["CWE-787"], "cve": "CVE-2017-14348", "cve_desc": "LibRaw before 0.18.4 has a heap-based Buffer Overflow in the processCanonCameraInfo function via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-14348"} {"idx": 207148, "project": "sqlite", "commit_id": "39df24a3f02495e5ef6bb5ea8ce029a2c1e377e6", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/39df24a3f02495e5ef6bb5ea8ce029a2c1e377e6", "commit_message": "Do not allow the constant-propagation optimization to apple to ON/USING clause\nterms as it does not help and it might cause downstream problems.\n\nFossilOrigin-Name: 1bc783da63d58b05c690468b569cb2787846357b63c1100d11777666c5787bf4", "target": 1, "func": "static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){\n int i;\n WhereConst *pConst;\n if( pExpr->op!=TK_COLUMN ) return WRC_Continue;\n if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;\n pConst = pWalker->u.pConst;\n for(i=0; inConst; i++){\n Expr *pColumn = pConst->apExpr[i*2];\n if( pColumn==pExpr ) continue;\n if( pColumn->iTable!=pExpr->iTable ) continue;\n if( pColumn->iColumn!=pExpr->iColumn ) continue;\n /* A match is found. Add the EP_FixedCol property */\n pConst->nChng++;\n ExprClearProperty(pExpr, EP_Leaf);\n ExprSetProperty(pExpr, EP_FixedCol);\n assert( pExpr->pLeft==0 );\n pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);\n break;\n }\n return WRC_Prune;\n}", "func_hash": 213143797040157222889544546734753638516, "file_name": "select.c", "file_hash": 22011899472848775616825833189035278966, "cwe": ["CWE-125"], "cve": "CVE-2020-6405", "cve_desc": "Out of bounds read in SQLite in Google Chrome prior to 80.0.3987.87 allowed a remote attacker to obtain potentially sensitive information from process memory via a crafted HTML page.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-6405"} {"idx": 393392, "project": "sqlite", "commit_id": "39df24a3f02495e5ef6bb5ea8ce029a2c1e377e6", "project_url": "https://github.com/sqlite/sqlite", "commit_url": "https://github.com/sqlite/sqlite/commit/39df24a3f02495e5ef6bb5ea8ce029a2c1e377e6", "commit_message": "Do not allow the constant-propagation optimization to apple to ON/USING clause\nterms as it does not help and it might cause downstream problems.\n\nFossilOrigin-Name: 1bc783da63d58b05c690468b569cb2787846357b63c1100d11777666c5787bf4", "target": 0, "func": "static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){\n int i;\n WhereConst *pConst;\n if( pExpr->op!=TK_COLUMN ) return WRC_Continue;\n if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ) return WRC_Continue;\n pConst = pWalker->u.pConst;\n for(i=0; inConst; i++){\n Expr *pColumn = pConst->apExpr[i*2];\n if( pColumn==pExpr ) continue;\n if( pColumn->iTable!=pExpr->iTable ) continue;\n if( pColumn->iColumn!=pExpr->iColumn ) continue;\n /* A match is found. Add the EP_FixedCol property */\n pConst->nChng++;\n ExprClearProperty(pExpr, EP_Leaf);\n ExprSetProperty(pExpr, EP_FixedCol);\n assert( pExpr->pLeft==0 );\n pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);\n break;\n }\n return WRC_Prune;\n}", "func_hash": 39056626103017498990290076275864244582, "file_name": "select.c", "file_hash": 270097080132124061162004769857868237433, "cwe": ["CWE-125"], "cve": "CVE-2020-6405", "cve_desc": "Out of bounds read in SQLite in Google Chrome prior to 80.0.3987.87 allowed a remote attacker to obtain potentially sensitive information from process memory via a crafted HTML page.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-6405"} {"idx": 207158, "project": "librepo", "commit_id": "7daea2a2429a54dad68b1de9b37a5f65c5cf2600", "project_url": "https://github.com/rpm-software-management/librepo", "commit_url": "https://github.com/rpm-software-management/librepo/commit/7daea2a2429a54dad68b1de9b37a5f65c5cf2600", "commit_message": "Validate path read from repomd.xml (RhBug:1868639)\n\n= changelog =\nmsg: Validate path read from repomd.xml\ntype: security\nresolves: https://bugzilla.redhat.com/show_bug.cgi?id=1868639", "target": 1, "func": "prepare_repo_download_targets(LrHandle *handle,\n LrYumRepo *repo,\n LrYumRepoMd *repomd,\n LrMetadataTarget *mdtarget,\n GSList **targets,\n GSList **cbdata_list,\n GError **err)\n{\n char *destdir; /* Destination dir */\n\n destdir = handle->destdir;\n assert(destdir);\n assert(strlen(destdir));\n assert(!err || *err == NULL);\n\n if(handle->cachedir) {\n lr_yum_switch_to_zchunk(handle, repomd);\n repo->use_zchunk = TRUE;\n } else {\n g_debug(\"%s: Cache directory not set, disabling zchunk\", __func__);\n repo->use_zchunk = FALSE;\n }\n\n for (GSList *elem = repomd->records; elem; elem = g_slist_next(elem)) {\n int fd;\n char *path;\n LrDownloadTarget *target;\n LrYumRepoMdRecord *record = elem->data;\n CbData *cbdata = NULL;\n void *user_cbdata = NULL;\n LrEndCb endcb = NULL;\n\n if (mdtarget != NULL) {\n user_cbdata = mdtarget->cbdata;\n endcb = mdtarget->endcb;\n }\n\n assert(record);\n\n if (!lr_yum_repomd_record_enabled(handle, record->type, repomd->records))\n continue;\n\n char *location_href = record->location_href;\n gboolean is_zchunk = FALSE;\n #ifdef WITH_ZCHUNK\n if (handle->cachedir && record->header_checksum)\n is_zchunk = TRUE;\n #endif /* WITH_ZCHUNK */\n\n GSList *checksums = NULL;\n if (is_zchunk) {\n #ifdef WITH_ZCHUNK\n if(!prepare_repo_download_zck_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n #endif /* WITH_ZCHUNK */\n } else {\n if(!prepare_repo_download_std_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n }\n\n if (handle->user_cb || handle->hmfcb) {\n cbdata = cbdata_new(handle->user_data,\n user_cbdata,\n handle->user_cb,\n handle->hmfcb,\n record->type);\n *cbdata_list = g_slist_append(*cbdata_list, cbdata);\n }\n\n target = lr_downloadtarget_new(handle,\n location_href,\n record->location_base,\n fd,\n NULL,\n checksums,\n 0,\n 0,\n NULL,\n cbdata,\n endcb,\n NULL,\n NULL,\n 0,\n 0,\n NULL,\n FALSE,\n is_zchunk);\n\n if(is_zchunk) {\n #ifdef WITH_ZCHUNK\n target->expectedsize = record->size_header;\n target->zck_header_size = record->size_header;\n #endif /* WITH_ZCHUNK */\n }\n\n if (mdtarget != NULL)\n mdtarget->repomd_records_to_download++;\n *targets = g_slist_append(*targets, target);\n\n /* Because path may already exists in repo (while update) */\n lr_yum_repo_update(repo, record->type, path);\n lr_free(path);\n }\n\n return TRUE;\n}", "func_hash": 169221103073295467762367238246677415452, "file_name": "yum.c", "file_hash": 94660655942085307584694438777341705526, "cwe": ["CWE-22"], "cve": "CVE-2020-14352", "cve_desc": "A flaw was found in librepo in versions before 1.12.1. A directory traversal vulnerability was found where it failed to sanitize paths in remote repository metadata. An attacker controlling a remote repository may be able to copy files outside of the destination directory on the targeted system via path traversal. This flaw could potentially result in system compromise via the overwriting of critical system files. The highest threat from this flaw is to users that make use of untrusted third-party repositories.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14352"} {"idx": 393607, "project": "librepo", "commit_id": "7daea2a2429a54dad68b1de9b37a5f65c5cf2600", "project_url": "https://github.com/rpm-software-management/librepo", "commit_url": "https://github.com/rpm-software-management/librepo/commit/7daea2a2429a54dad68b1de9b37a5f65c5cf2600", "commit_message": "Validate path read from repomd.xml (RhBug:1868639)\n\n= changelog =\nmsg: Validate path read from repomd.xml\ntype: security\nresolves: https://bugzilla.redhat.com/show_bug.cgi?id=1868639", "target": 0, "func": "prepare_repo_download_targets(LrHandle *handle,\n LrYumRepo *repo,\n LrYumRepoMd *repomd,\n LrMetadataTarget *mdtarget,\n GSList **targets,\n GSList **cbdata_list,\n GError **err)\n{\n char *destdir; /* Destination dir */\n\n destdir = handle->destdir;\n assert(destdir);\n assert(strlen(destdir));\n assert(!err || *err == NULL);\n\n if(handle->cachedir) {\n lr_yum_switch_to_zchunk(handle, repomd);\n repo->use_zchunk = TRUE;\n } else {\n g_debug(\"%s: Cache directory not set, disabling zchunk\", __func__);\n repo->use_zchunk = FALSE;\n }\n\n for (GSList *elem = repomd->records; elem; elem = g_slist_next(elem)) {\n int fd;\n char *path;\n LrDownloadTarget *target;\n LrYumRepoMdRecord *record = elem->data;\n CbData *cbdata = NULL;\n void *user_cbdata = NULL;\n LrEndCb endcb = NULL;\n\n if (mdtarget != NULL) {\n user_cbdata = mdtarget->cbdata;\n endcb = mdtarget->endcb;\n }\n\n assert(record);\n\n if (!lr_yum_repomd_record_enabled(handle, record->type, repomd->records))\n continue;\n\n char *location_href = record->location_href;\n\n char *dest_dir = realpath(handle->destdir, NULL);\n path = lr_pathconcat(handle->destdir, record->location_href, NULL);\n char *requested_dir = realpath(dirname(path), NULL);\n lr_free(path);\n if (!g_str_has_prefix(requested_dir, dest_dir)) {\n g_debug(\"%s: Invalid path: %s\", __func__, location_href);\n g_set_error(err, LR_YUM_ERROR, LRE_IO, \"Invalid path: %s\", location_href);\n g_slist_free_full(*targets, (GDestroyNotify) lr_downloadtarget_free);\n free(requested_dir);\n free(dest_dir);\n return FALSE;\n }\n free(requested_dir);\n free(dest_dir);\n\n gboolean is_zchunk = FALSE;\n #ifdef WITH_ZCHUNK\n if (handle->cachedir && record->header_checksum)\n is_zchunk = TRUE;\n #endif /* WITH_ZCHUNK */\n\n GSList *checksums = NULL;\n if (is_zchunk) {\n #ifdef WITH_ZCHUNK\n if(!prepare_repo_download_zck_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n #endif /* WITH_ZCHUNK */\n } else {\n if(!prepare_repo_download_std_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n }\n\n if (handle->user_cb || handle->hmfcb) {\n cbdata = cbdata_new(handle->user_data,\n user_cbdata,\n handle->user_cb,\n handle->hmfcb,\n record->type);\n *cbdata_list = g_slist_append(*cbdata_list, cbdata);\n }\n\n target = lr_downloadtarget_new(handle,\n location_href,\n record->location_base,\n fd,\n NULL,\n checksums,\n 0,\n 0,\n NULL,\n cbdata,\n endcb,\n NULL,\n NULL,\n 0,\n 0,\n NULL,\n FALSE,\n is_zchunk);\n\n if(is_zchunk) {\n #ifdef WITH_ZCHUNK\n target->expectedsize = record->size_header;\n target->zck_header_size = record->size_header;\n #endif /* WITH_ZCHUNK */\n }\n\n if (mdtarget != NULL)\n mdtarget->repomd_records_to_download++;\n *targets = g_slist_append(*targets, target);\n\n /* Because path may already exists in repo (while update) */\n lr_yum_repo_update(repo, record->type, path);\n lr_free(path);\n }\n\n return TRUE;\n}", "func_hash": 295004676042311846082028786867199554891, "file_name": "yum.c", "file_hash": 144181806971203237764937193325619899100, "cwe": ["CWE-22"], "cve": "CVE-2020-14352", "cve_desc": "A flaw was found in librepo in versions before 1.12.1. A directory traversal vulnerability was found where it failed to sanitize paths in remote repository metadata. An attacker controlling a remote repository may be able to copy files outside of the destination directory on the targeted system via path traversal. This flaw could potentially result in system compromise via the overwriting of critical system files. The highest threat from this flaw is to users that make use of untrusted third-party repositories.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14352"} {"idx": 207163, "project": "jasper", "commit_id": "1b1c591306817e46e1e6a3300f714992b32f972b", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/1b1c591306817e46e1e6a3300f714992b32f972b", "commit_message": "jpc_dec: fix another integer overflow in SIZ\n\nValidate the width and height values first, before doing anything\nelse. This prevents integer overflows in the `numhtiles` /\n`numvtiles` calculation below, triggering assertion failures.\n\nFixes CVE-2017-13750\n\nCloses https://github.com/mdadams/jasper/issues/165\nCloses https://github.com/mdadams/jasper/issues/174", "target": 1, "func": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\tsize_t size;\n\tsize_t num_samples;\n\tsize_t num_samples_delta;\n\n\tsize_t tile_samples;\n\tif (!jas_safe_size_mul(siz->tilewidth, siz->tileheight, &tile_samples) ||\n\t (dec->max_samples > 0 && tile_samples > dec->max_samples)) {\n\t\tjas_eprintf(\"tile too large\\n\");\n\t\treturn -1;\n\t}\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tnum_samples = 0;\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\n\t\tif (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (dec->max_samples > 0 && num_samples > dec->max_samples) {\n\t\tjas_eprintf(\"maximum number of samples exceeded (%zu > %zu)\\n\",\n\t\t num_samples, dec->max_samples);\n\t\treturn -1;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tassert(dec->numhtiles >= 0);\n\tassert(dec->numvtiles >= 0);\n\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size) ||\n\t size > INT_MAX) {\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / 16 / 16) {\n\t\t/* avoid Denial of Service by a malicious input file\n\t\t with millions of tiny tiles; if max_samples is\n\t\t configured, then assume the tiles are at least\n\t\t 16x16, and don't allow more than this number of\n\t\t tiles */\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / dec->numcomps / 16) {\n\t\t/* another DoS check: since each tile allocates an\n\t\t array of components, this check attempts to catch\n\t\t excessive tile*component numbers */\n\t\treturn -1;\n\t}\n\tdec->numtiles = size;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\t/* initialize all tiles with JPC_TILE_DONE so\n\t\t jpc_dec_destroy() knows which ones need a\n\t\t jpc_dec_tilefini() call; they are not actually\n\t\t \"done\", of course */\n\t\ttile->state = JPC_TILE_DONE;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno / dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. */\n\tdec->state = JPC_MH;\n\n\treturn 0;\n}", "func_hash": 146070774894853069389254970862603312793, "file_name": "jpc_dec.c", "file_hash": 209203870439462798793289497580636737168, "cwe": ["CWE-617"], "cve": "CVE-2017-13746", "cve_desc": "There is a reachable assertion abort in the function jpc_dec_process_siz() in jpc/jpc_dec.c:1297 in JasPer 2.0.12 that will lead to a remote denial of service attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-13746"} {"idx": 393685, "project": "jasper", "commit_id": "1b1c591306817e46e1e6a3300f714992b32f972b", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/1b1c591306817e46e1e6a3300f714992b32f972b", "commit_message": "jpc_dec: fix another integer overflow in SIZ\n\nValidate the width and height values first, before doing anything\nelse. This prevents integer overflows in the `numhtiles` /\n`numvtiles` calculation below, triggering assertion failures.\n\nFixes CVE-2017-13750\n\nCloses https://github.com/mdadams/jasper/issues/165\nCloses https://github.com/mdadams/jasper/issues/174", "target": 0, "func": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\tsize_t size;\n\tsize_t num_samples;\n\tsize_t num_samples_delta;\n\n\tsize_t total_samples;\n\tif (!jas_safe_size_mul(siz->width, siz->height, &total_samples) ||\n\t (dec->max_samples > 0 && total_samples > dec->max_samples)) {\n\t\tjas_eprintf(\"image too large\\n\");\n\t\treturn -1;\n\t}\n\n\tsize_t tile_samples;\n\tif (!jas_safe_size_mul(siz->tilewidth, siz->tileheight, &tile_samples) ||\n\t (dec->max_samples > 0 && tile_samples > dec->max_samples)) {\n\t\tjas_eprintf(\"tile too large\\n\");\n\t\treturn -1;\n\t}\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tnum_samples = 0;\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\n\t\tif (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (dec->max_samples > 0 && num_samples > dec->max_samples) {\n\t\tjas_eprintf(\"maximum number of samples exceeded (%zu > %zu)\\n\",\n\t\t num_samples, dec->max_samples);\n\t\treturn -1;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tassert(dec->numhtiles >= 0);\n\tassert(dec->numvtiles >= 0);\n\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size) ||\n\t size > INT_MAX) {\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / 16 / 16) {\n\t\t/* avoid Denial of Service by a malicious input file\n\t\t with millions of tiny tiles; if max_samples is\n\t\t configured, then assume the tiles are at least\n\t\t 16x16, and don't allow more than this number of\n\t\t tiles */\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / dec->numcomps / 16) {\n\t\t/* another DoS check: since each tile allocates an\n\t\t array of components, this check attempts to catch\n\t\t excessive tile*component numbers */\n\t\treturn -1;\n\t}\n\tdec->numtiles = size;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\t/* initialize all tiles with JPC_TILE_DONE so\n\t\t jpc_dec_destroy() knows which ones need a\n\t\t jpc_dec_tilefini() call; they are not actually\n\t\t \"done\", of course */\n\t\ttile->state = JPC_TILE_DONE;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno / dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. */\n\tdec->state = JPC_MH;\n\n\treturn 0;\n}", "func_hash": 239423625020272774582569553280358583536, "file_name": "jpc_dec.c", "file_hash": 79416953850871274512335711211765215084, "cwe": ["CWE-617"], "cve": "CVE-2017-13746", "cve_desc": "There is a reachable assertion abort in the function jpc_dec_process_siz() in jpc/jpc_dec.c:1297 in JasPer 2.0.12 that will lead to a remote denial of service attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-13746"} {"idx": 207218, "project": "LibRaw", "commit_id": "c243f4539233053466c1309bde606815351bee81", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/c243f4539233053466c1309bde606815351bee81", "commit_message": "additional checks in parseSonySRF\n\nparseSonySR2: buffer size check", "target": 1, "func": "void LibRaw::parseSonySRF(unsigned len)\n{\n\n if ((len > 0xfffff) || (len == 0))\n return;\n\n INT64 save = ftell(ifp);\n INT64 offset =\n 0x0310c0 - save; /* for non-DNG this value normally is 0x8ddc */\n if (len < offset || offset < 0)\n return;\n INT64 decrypt_len = offset >> 2; /* master key offset value is the next\n un-encrypted metadata field after SRF0 */\n\n unsigned i, nWB;\n unsigned MasterKey, SRF2Key, RawDataKey;\n INT64 srf_offset, tag_offset, tag_data, tag_dataoffset;\n int tag_dataunitlen;\n uchar *srf_buf;\n short entries;\n unsigned tag_id, tag_type, tag_datalen;\n\n srf_buf = (uchar *)malloc(len);\n fread(srf_buf, len, 1, ifp);\n\n offset += srf_buf[offset] << 2;\n\n#define CHECKBUFFER_SGET4(offset) \\\n do \\\n { \\\n if ((((offset) + 4) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n#define CHECKBUFFER_SGET2(offset) \\\n do \\\n { \\\n if ( ((offset + 2) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n CHECKBUFFER_SGET4(offset);\n\n /* master key is stored in big endian */\n MasterKey = ((unsigned)srf_buf[offset] << 24) |\n ((unsigned)srf_buf[offset + 1] << 16) |\n ((unsigned)srf_buf[offset + 2] << 8) |\n (unsigned)srf_buf[offset + 3];\n\n /* skip SRF0 */\n srf_offset = 0;\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n CHECKBUFFER_SGET4(offset);\n CHECKBUFFER_SGET4(offset + 12 * entries);\n srf_offset = sget4(srf_buf + offset + 12 * entries) -\n save; /* SRF0 ends with SRF1 abs. position */\n\n /* get SRF1, it has fixed 40 bytes length and contains keys to decode metadata\n * and raw data */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, MasterKey);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if (tag_id == 0x0000) {\n SRF2Key = sget4(srf_buf + tag_dataoffset);\n } else if (tag_id == 0x0001) {\n RawDataKey = sget4(srf_buf + tag_dataoffset);\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\n /* get SRF2 */\n CHECKBUFFER_SGET4(offset);\n srf_offset =\n sget4(srf_buf + offset) - save; /* SRFn ends with SRFn+1 position */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, SRF2Key);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) {\n i = (tag_id - 0x00c0) % 3;\n nWB = (tag_id - 0x00c0) / 3;\n icWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n icWBC[Sony_SRF_wb_list[nWB]][3] =\n icWBC[Sony_SRF_wb_list[nWB]][i];\n }\n } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) {\n i = (tag_id - 0x00d0) % 3;\n cam_mul[i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n cam_mul[3] = cam_mul[i];\n }\n } else switch (tag_id) {\n /*\n 0x0002 SRF6Offset\n 0x0003 SRFDataOffset (?)\n 0x0004 RawDataOffset\n 0x0005 RawDataLength\n */\n case 0x0043:\n ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0044:\n ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0045:\n ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0046:\n ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\nrestore_after_parseSonySRF:\n free(srf_buf);\n fseek(ifp, save, SEEK_SET);\n#undef CHECKBUFFER_SGET4\n#undef CHECKBUFFER_SGET2\n}", "func_hash": 36003741864693602356425713981018202212, "file_name": "sony.cpp", "file_hash": 174074939945430273263842493873353606645, "cwe": ["CWE-125"], "cve": "CVE-2020-35535", "cve_desc": "In LibRaw, there is an out-of-bounds read vulnerability within the \"LibRaw::parseSonySRF()\" function (libraw\\src\\metadata\\sony.cpp) when processing srf files.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35535"} {"idx": 394100, "project": "LibRaw", "commit_id": "c243f4539233053466c1309bde606815351bee81", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/c243f4539233053466c1309bde606815351bee81", "commit_message": "additional checks in parseSonySRF\n\nparseSonySR2: buffer size check", "target": 0, "func": "void LibRaw::parseSonySRF(unsigned len)\n{\n\n if ((len > 0xfffff) || (len == 0))\n return;\n\n INT64 save = ftell(ifp);\n INT64 offset =\n 0x0310c0 - save; /* for non-DNG this value normally is 0x8ddc */\n if (len < offset || offset < 0)\n return;\n INT64 decrypt_len = offset >> 2; /* master key offset value is the next\n un-encrypted metadata field after SRF0 */\n\n unsigned i, nWB;\n unsigned MasterKey, SRF2Key, RawDataKey;\n INT64 srf_offset, tag_offset, tag_data, tag_dataoffset;\n int tag_dataunitlen;\n uchar *srf_buf;\n ushort entries;\n unsigned tag_id, tag_type, tag_datalen;\n\n srf_buf = (uchar *)malloc(len+64);\n fread(srf_buf, len, 1, ifp);\n\n offset += srf_buf[offset] << 2;\n\n#define CHECKBUFFER_SGET4(offset) \\\n do \\\n { \\\n if ((((offset) + 4) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n#define CHECKBUFFER_SGET2(offset) \\\n do \\\n { \\\n if ( ((offset + 2) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n CHECKBUFFER_SGET4(offset);\n\n /* master key is stored in big endian */\n MasterKey = ((unsigned)srf_buf[offset] << 24) |\n ((unsigned)srf_buf[offset + 1] << 16) |\n ((unsigned)srf_buf[offset + 2] << 8) |\n (unsigned)srf_buf[offset + 3];\n\n /* skip SRF0 */\n srf_offset = 0;\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n CHECKBUFFER_SGET4(offset);\n CHECKBUFFER_SGET4(offset + 12 * entries);\n srf_offset = sget4(srf_buf + offset + 12 * entries) -\n save; /* SRF0 ends with SRF1 abs. position */\n\n /* get SRF1, it has fixed 40 bytes length and contains keys to decode metadata\n * and raw data */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, MasterKey);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if (tag_id == 0x0000) {\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t SRF2Key = sget4(srf_buf + tag_dataoffset);\n } else if (tag_id == 0x0001) {\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t RawDataKey = sget4(srf_buf + tag_dataoffset);\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\n /* get SRF2 */\n CHECKBUFFER_SGET4(offset);\n srf_offset =\n sget4(srf_buf + offset) - save; /* SRFn ends with SRFn+1 position */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, SRF2Key);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n\t if (tiff_sget(save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) {\n i = (tag_id - 0x00c0) % 3;\n nWB = (tag_id - 0x00c0) / 3;\n\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n\t\ticWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n icWBC[Sony_SRF_wb_list[nWB]][3] =\n icWBC[Sony_SRF_wb_list[nWB]][i];\n }\n } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) {\n i = (tag_id - 0x00d0) % 3;\n\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n\t\tcam_mul[i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n cam_mul[3] = cam_mul[i];\n }\n } else switch (tag_id) {\n /*\n 0x0002 SRF6Offset\n 0x0003 SRFDataOffset (?)\n 0x0004 RawDataOffset\n 0x0005 RawDataLength\n */\n case 0x0043:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset); // need to add extra space\n\t\t ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0044:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0045:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0046:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\nrestore_after_parseSonySRF:\n free(srf_buf);\n fseek(ifp, save, SEEK_SET);\n#undef CHECKBUFFER_SGET4\n#undef CHECKBUFFER_SGET2\n}", "func_hash": 226432943973667982996709681506605030397, "file_name": "sony.cpp", "file_hash": 27383436085782232611262328936960721277, "cwe": ["CWE-125"], "cve": "CVE-2020-35535", "cve_desc": "In LibRaw, there is an out-of-bounds read vulnerability within the \"LibRaw::parseSonySRF()\" function (libraw\\src\\metadata\\sony.cpp) when processing srf files.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35535"} {"idx": 207223, "project": "linux", "commit_id": "1cc5ef91d2ff94d2bf2de3b3585423e8a1051cb6", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1cc5ef91d2ff94d2bf2de3b3585423e8a1051cb6", "commit_message": "netfilter: ctnetlink: add a range check for l3/l4 protonum\n\nThe indexes to the nf_nat_l[34]protos arrays come from userspace. So\ncheck the tuple's family, e.g. l3num, when creating the conntrack in\norder to prevent an OOB memory access during setup. Here is an example\nkernel panic on 4.14.180 when userspace passes in an index greater than\nNFPROTO_NUMPROTO.\n\nInternal error: Oops - BUG: 0 [#1] PREEMPT SMP\nModules linked in:...\nProcess poc (pid: 5614, stack limit = 0x00000000a3933121)\nCPU: 4 PID: 5614 Comm: poc Tainted: G S W O 4.14.180-g051355490483\nHardware name: Qualcomm Technologies, Inc. SM8150 V2 PM8150 Google Inc. MSM\ntask: 000000002a3dfffe task.stack: 00000000a3933121\npc : __cfi_check_fail+0x1c/0x24\nlr : __cfi_check_fail+0x1c/0x24\n...\nCall trace:\n__cfi_check_fail+0x1c/0x24\nname_to_dev_t+0x0/0x468\nnfnetlink_parse_nat_setup+0x234/0x258\nctnetlink_parse_nat_setup+0x4c/0x228\nctnetlink_new_conntrack+0x590/0xc40\nnfnetlink_rcv_msg+0x31c/0x4d4\nnetlink_rcv_skb+0x100/0x184\nnfnetlink_rcv+0xf4/0x180\nnetlink_unicast+0x360/0x770\nnetlink_sendmsg+0x5a0/0x6a4\n___sys_sendmsg+0x314/0x46c\nSyS_sendmsg+0xb4/0x108\nel0_svc_naked+0x34/0x38\n\nThis crash is not happening since 5.4+, however, ctnetlink still\nallows for creating entries with unsupported layer 3 protocol number.\n\nFixes: c1d10adb4a521 (\"[NETFILTER]: Add ctnetlink port for nf_conntrack\")\nSigned-off-by: Will McVicker \n[pablo@netfilter.org: rebased original patch on top of nf.git]\nSigned-off-by: Pablo Neira Ayuso ", "target": 1, "func": "ctnetlink_parse_tuple_filter(const struct nlattr * const cda[],\n\t\t\t struct nf_conntrack_tuple *tuple, u32 type,\n\t\t\t u_int8_t l3num, struct nf_conntrack_zone *zone,\n\t\t\t u_int32_t flags)\n{\n\tstruct nlattr *tb[CTA_TUPLE_MAX+1];\n\tint err;\n\n\tmemset(tuple, 0, sizeof(*tuple));\n\n\terr = nla_parse_nested_deprecated(tb, CTA_TUPLE_MAX, cda[type],\n\t\t\t\t\t tuple_nla_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\n\ttuple->src.l3num = l3num;\n\n\tif (flags & CTA_FILTER_FLAG(CTA_IP_DST) ||\n\t flags & CTA_FILTER_FLAG(CTA_IP_SRC)) {\n\t\tif (!tb[CTA_TUPLE_IP])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_ip(tb[CTA_TUPLE_IP], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (flags & CTA_FILTER_FLAG(CTA_PROTO_NUM)) {\n\t\tif (!tb[CTA_TUPLE_PROTO])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_proto(tb[CTA_TUPLE_PROTO], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t} else if (flags & CTA_FILTER_FLAG(ALL_CTA_PROTO)) {\n\t\t/* Can't manage proto flags without a protonum */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((flags & CTA_FILTER_FLAG(CTA_TUPLE_ZONE)) && tb[CTA_TUPLE_ZONE]) {\n\t\tif (!zone)\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_zone(tb[CTA_TUPLE_ZONE],\n\t\t\t\t\t\t type, zone);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\t/* orig and expect tuples get DIR_ORIGINAL */\n\tif (type == CTA_TUPLE_REPLY)\n\t\ttuple->dst.dir = IP_CT_DIR_REPLY;\n\telse\n\t\ttuple->dst.dir = IP_CT_DIR_ORIGINAL;\n\n\treturn 0;\n}", "func_hash": 314881127093139969577963460594228335130, "file_name": "nf_conntrack_netlink.c", "file_hash": 10421906752535821959993867918474039383, "cwe": ["CWE-120"], "cve": "CVE-2020-25211", "cve_desc": "In the Linux kernel through 5.8.7, local attackers able to inject conntrack netlink configuration could overflow a local buffer, causing crashes or triggering use of incorrect protocol numbers in ctnetlink_parse_tuple_filter in net/netfilter/nf_conntrack_netlink.c, aka CID-1cc5ef91d2ff.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25211"} {"idx": 394260, "project": "linux", "commit_id": "1cc5ef91d2ff94d2bf2de3b3585423e8a1051cb6", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1cc5ef91d2ff94d2bf2de3b3585423e8a1051cb6", "commit_message": "netfilter: ctnetlink: add a range check for l3/l4 protonum\n\nThe indexes to the nf_nat_l[34]protos arrays come from userspace. So\ncheck the tuple's family, e.g. l3num, when creating the conntrack in\norder to prevent an OOB memory access during setup. Here is an example\nkernel panic on 4.14.180 when userspace passes in an index greater than\nNFPROTO_NUMPROTO.\n\nInternal error: Oops - BUG: 0 [#1] PREEMPT SMP\nModules linked in:...\nProcess poc (pid: 5614, stack limit = 0x00000000a3933121)\nCPU: 4 PID: 5614 Comm: poc Tainted: G S W O 4.14.180-g051355490483\nHardware name: Qualcomm Technologies, Inc. SM8150 V2 PM8150 Google Inc. MSM\ntask: 000000002a3dfffe task.stack: 00000000a3933121\npc : __cfi_check_fail+0x1c/0x24\nlr : __cfi_check_fail+0x1c/0x24\n...\nCall trace:\n__cfi_check_fail+0x1c/0x24\nname_to_dev_t+0x0/0x468\nnfnetlink_parse_nat_setup+0x234/0x258\nctnetlink_parse_nat_setup+0x4c/0x228\nctnetlink_new_conntrack+0x590/0xc40\nnfnetlink_rcv_msg+0x31c/0x4d4\nnetlink_rcv_skb+0x100/0x184\nnfnetlink_rcv+0xf4/0x180\nnetlink_unicast+0x360/0x770\nnetlink_sendmsg+0x5a0/0x6a4\n___sys_sendmsg+0x314/0x46c\nSyS_sendmsg+0xb4/0x108\nel0_svc_naked+0x34/0x38\n\nThis crash is not happening since 5.4+, however, ctnetlink still\nallows for creating entries with unsupported layer 3 protocol number.\n\nFixes: c1d10adb4a521 (\"[NETFILTER]: Add ctnetlink port for nf_conntrack\")\nSigned-off-by: Will McVicker \n[pablo@netfilter.org: rebased original patch on top of nf.git]\nSigned-off-by: Pablo Neira Ayuso ", "target": 0, "func": "ctnetlink_parse_tuple_filter(const struct nlattr * const cda[],\n\t\t\t struct nf_conntrack_tuple *tuple, u32 type,\n\t\t\t u_int8_t l3num, struct nf_conntrack_zone *zone,\n\t\t\t u_int32_t flags)\n{\n\tstruct nlattr *tb[CTA_TUPLE_MAX+1];\n\tint err;\n\n\tmemset(tuple, 0, sizeof(*tuple));\n\n\terr = nla_parse_nested_deprecated(tb, CTA_TUPLE_MAX, cda[type],\n\t\t\t\t\t tuple_nla_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (l3num != NFPROTO_IPV4 && l3num != NFPROTO_IPV6)\n\t\treturn -EOPNOTSUPP;\n\ttuple->src.l3num = l3num;\n\n\tif (flags & CTA_FILTER_FLAG(CTA_IP_DST) ||\n\t flags & CTA_FILTER_FLAG(CTA_IP_SRC)) {\n\t\tif (!tb[CTA_TUPLE_IP])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_ip(tb[CTA_TUPLE_IP], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (flags & CTA_FILTER_FLAG(CTA_PROTO_NUM)) {\n\t\tif (!tb[CTA_TUPLE_PROTO])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_proto(tb[CTA_TUPLE_PROTO], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t} else if (flags & CTA_FILTER_FLAG(ALL_CTA_PROTO)) {\n\t\t/* Can't manage proto flags without a protonum */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((flags & CTA_FILTER_FLAG(CTA_TUPLE_ZONE)) && tb[CTA_TUPLE_ZONE]) {\n\t\tif (!zone)\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_zone(tb[CTA_TUPLE_ZONE],\n\t\t\t\t\t\t type, zone);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\t/* orig and expect tuples get DIR_ORIGINAL */\n\tif (type == CTA_TUPLE_REPLY)\n\t\ttuple->dst.dir = IP_CT_DIR_REPLY;\n\telse\n\t\ttuple->dst.dir = IP_CT_DIR_ORIGINAL;\n\n\treturn 0;\n}", "func_hash": 297246536019297429739528801155810586688, "file_name": "nf_conntrack_netlink.c", "file_hash": 101744799810334093791081782651175919270, "cwe": ["CWE-120"], "cve": "CVE-2020-25211", "cve_desc": "In the Linux kernel through 5.8.7, local attackers able to inject conntrack netlink configuration could overflow a local buffer, causing crashes or triggering use of incorrect protocol numbers in ctnetlink_parse_tuple_filter in net/netfilter/nf_conntrack_netlink.c, aka CID-1cc5ef91d2ff.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-25211"} {"idx": 207262, "project": "LuaJIT", "commit_id": "e296f56b825c688c3530a981dc6b495d972f3d01", "project_url": "https://github.com/LuaJIT/LuaJIT", "commit_url": "https://github.com/LuaJIT/LuaJIT/commit/e296f56b825c688c3530a981dc6b495d972f3d01", "commit_message": "Call error function on rethrow after trace exit.", "target": 1, "func": "LJ_NOINLINE void lj_err_run(lua_State *L)\n{\n ptrdiff_t ef = finderrfunc(L);\n if (ef) {\n TValue *errfunc = restorestack(L, ef);\n TValue *top = L->top;\n lj_trace_abort(G(L));\n if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {\n setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));\n lj_err_throw(L, LUA_ERRERR);\n }\n L->status = LUA_ERRERR;\n copyTV(L, top, top-1);\n copyTV(L, top-1, errfunc);\n L->top = top+1;\n lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */\n }\n lj_err_throw(L, LUA_ERRRUN);\n}", "func_hash": 10321220320343571354725004127912719521, "file_name": "lj_err.c", "file_hash": 198203473898814036407466574660463075188, "cwe": ["CWE-125"], "cve": "CVE-2020-24372", "cve_desc": "LuaJIT through 2.1.0-beta3 has an out-of-bounds read in lj_err_run in lj_err.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-24372"} {"idx": 394651, "project": "LuaJIT", "commit_id": "e296f56b825c688c3530a981dc6b495d972f3d01", "project_url": "https://github.com/LuaJIT/LuaJIT", "commit_url": "https://github.com/LuaJIT/LuaJIT/commit/e296f56b825c688c3530a981dc6b495d972f3d01", "commit_message": "Call error function on rethrow after trace exit.", "target": 0, "func": "LJ_NOINLINE void LJ_FASTCALL lj_err_run(lua_State *L)\n{\n ptrdiff_t ef = finderrfunc(L);\n if (ef) {\n TValue *errfunc = restorestack(L, ef);\n TValue *top = L->top;\n lj_trace_abort(G(L));\n if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {\n setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));\n lj_err_throw(L, LUA_ERRERR);\n }\n L->status = LUA_ERRERR;\n copyTV(L, top, top-1);\n copyTV(L, top-1, errfunc);\n L->top = top+1;\n lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */\n }\n lj_err_throw(L, LUA_ERRRUN);\n}", "func_hash": 249484905715530894501111987451202547521, "file_name": "lj_err.c", "file_hash": 27116994240096177055314371603152030921, "cwe": ["CWE-125"], "cve": "CVE-2020-24372", "cve_desc": "LuaJIT through 2.1.0-beta3 has an out-of-bounds read in lj_err_run in lj_err.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-24372"} {"idx": 207309, "project": "LibRaw", "commit_id": "55f0a0c08974b8b79ebfa7762b555a1704b25fb2", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/55f0a0c08974b8b79ebfa7762b555a1704b25fb2", "commit_message": "possible buffer underrun in exif parser", "target": 1, "func": "void LibRaw::parse_exif(int base)\n{\n unsigned entries, tag, type, len, save, c;\n double expo, ape;\n\n unsigned kodak = !strncmp(make, \"EASTMAN\", 7) && tiff_nifds < 3;\n\n entries = get2();\n if (!strncmp(make, \"Hasselblad\", 10) && (tiff_nifds > 3) && (entries > 512))\n return;\n INT64 fsize = ifp->size();\n while (entries--)\n {\n tiff_get(base, &tag, &type, &len, &save);\n\n INT64 savepos = ftell(ifp);\n if (len > 8 && savepos + len > fsize * 2)\n {\n fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!\n continue;\n }\n if (callbacks.exif_cb)\n {\n callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp,\n base);\n fseek(ifp, savepos, SEEK_SET);\n }\n\n switch (tag)\n {\n\tcase 0xA005: // Interoperability IFD\n\t\tfseek(ifp, get4() + base, SEEK_SET);\n\t\tparse_exif_interop(base);\n\t\tbreak;\n\tcase 0xA001: // ExifIFD.ColorSpace\n\t\tc = get2();\n\t\tif (c == 1 && imgdata.color.ExifColorSpace == LIBRAW_COLORSPACE_Unknown)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_sRGB;\n\t\telse if (c == 2)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_AdobeRGB;\n\t\tbreak;\n case 0x9400:\n imCommon.exifAmbientTemperature = getreal(type);\n if ((imCommon.CameraTemperature > -273.15f) &&\n ((OlyID == OlyID_TG_5) ||\n (OlyID == OlyID_TG_6))\n )\n imCommon.CameraTemperature += imCommon.exifAmbientTemperature;\n break;\n case 0x9401:\n imCommon.exifHumidity = getreal(type);\n break;\n case 0x9402:\n imCommon.exifPressure = getreal(type);\n break;\n case 0x9403:\n imCommon.exifWaterDepth = getreal(type);\n break;\n case 0x9404:\n imCommon.exifAcceleration = getreal(type);\n break;\n case 0x9405:\n imCommon.exifCameraElevationAngle = getreal(type);\n break;\n\n case 0xa405: // FocalLengthIn35mmFormat\n imgdata.lens.FocalLengthIn35mmFormat = get2();\n break;\n case 0xa431: // BodySerialNumber\n stmread(imgdata.shootinginfo.BodySerial, len, ifp);\n break;\n case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard\n imgdata.lens.MinFocal = getreal(type);\n imgdata.lens.MaxFocal = getreal(type);\n imgdata.lens.MaxAp4MinFocal = getreal(type);\n imgdata.lens.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa435: // LensSerialNumber\n stmread(imgdata.lens.LensSerial, len, ifp);\n if (!strncmp(imgdata.lens.LensSerial, \"----\", 4))\n imgdata.lens.LensSerial[0] = '\\0';\n break;\n case 0xa420: /* 42016, ImageUniqueID */\n stmread(imgdata.color.ImageUniqueID, len, ifp);\n break;\n case 0xc65d: /* 50781, RawDataUniqueID */\n imgdata.color.RawDataUniqueID[16] = 0;\n fread(imgdata.color.RawDataUniqueID, 1, 16, ifp);\n break;\n case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard\n imgdata.lens.dng.MinFocal = getreal(type);\n imgdata.lens.dng.MaxFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MinFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xc68b: /* 50827, OriginalRawFileName */\n stmread(imgdata.color.OriginalRawFileName, len, ifp);\n break;\n case 0xa433: // LensMake\n stmread(imgdata.lens.LensMake, len, ifp);\n break;\n case 0xa434: // LensModel\n stmread(imgdata.lens.Lens, len, ifp);\n if (!strncmp(imgdata.lens.Lens, \"----\", 4))\n imgdata.lens.Lens[0] = '\\0';\n break;\n case 0x9205:\n imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));\n break;\n case 0x829a: // 33434\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type);\n break;\n case 0x829d: // 33437, FNumber\n aperture = getreal(type);\n break;\n case 0x8827: // 34855\n iso_speed = get2();\n break;\n case 0x8831: // 34865\n if (iso_speed == 0xffff && !strncasecmp(make, \"FUJI\", 4))\n iso_speed = getreal(type);\n break;\n case 0x8832: // 34866\n if (iso_speed == 0xffff &&\n (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"CANON\", 5)))\n iso_speed = getreal(type);\n break;\n case 0x9003: // 36867\n case 0x9004: // 36868\n get_timestamp(0);\n break;\n case 0x9201: // 37377\n if ((expo = -getreal(type)) < 128 && shutter == 0.)\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter =\n libraw_powf64l(2.0, expo);\n break;\n case 0x9202: // 37378 ApertureValue\n if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))\n aperture = libraw_powf64l(2.0, ape / 2);\n break;\n case 0x9209: // 37385\n flash_used = getreal(type);\n break;\n case 0x920a: // 37386\n focal_len = getreal(type);\n break;\n case 0x927c: // 37500\n if (((make[0] == '\\0') && !strncmp(model, \"ov5647\", 6)) ||\n (!strncmp(make, \"RaspberryPi\", 11) &&\n (!strncmp(model, \"RP_OV5647\", 9) ||\n !strncmp(model, \"RP_imx219\", 9))))\n {\n char mn_text[512];\n char *pos;\n char ccms[512];\n ushort l;\n float num;\n\n fgets(mn_text, MIN(len, 511), ifp);\n mn_text[511] = 0;\n\n pos = strstr(mn_text, \"gain_r=\");\n if (pos)\n cam_mul[0] = atof(pos + 7);\n pos = strstr(mn_text, \"gain_b=\");\n if (pos)\n cam_mul[2] = atof(pos + 7);\n if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n cam_mul[1] = cam_mul[3] = 1.0f;\n else\n cam_mul[0] = cam_mul[2] = 0.0f;\n\n pos = strstr(mn_text, \"ccm=\");\n if (pos)\n {\n pos += 4;\n char *pos2 = strstr(pos, \" \");\n if (pos2)\n {\n l = pos2 - pos;\n memcpy(ccms, pos, l);\n ccms[l] = '\\0';\n#ifdef LIBRAW_WIN32_CALLS\n // Win32 strtok is already thread-safe\n pos = strtok(ccms, \",\");\n#else\n char *last = 0;\n pos = strtok_r(ccms, \",\", &last);\n#endif\n if (pos)\n {\n for (l = 0; l < 4; l++)\n {\n num = 0.0;\n for (c = 0; c < 3; c++)\n {\n imgdata.color.ccm[l][c] = (float)atoi(pos);\n num += imgdata.color.ccm[l][c];\n#ifdef LIBRAW_WIN32_CALLS\n pos = strtok(NULL, \",\");\n#else\n pos = strtok_r(NULL, \",\", &last);\n#endif\n if (!pos)\n goto end; // broken\n }\n if (num > 0.01)\n FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n }\n }\n }\n }\n end:;\n }\n else if (!strncmp(make, \"SONY\", 4) &&\n (!strncmp(model, \"DSC-V3\", 6) || !strncmp(model, \"DSC-F828\", 8)))\n {\n parseSonySRF(len);\n break;\n }\n else if ((len == 1) && !strncmp(make, \"NIKON\", 5))\n {\n c = get4();\n if (c)\n fseek(ifp, c, SEEK_SET);\n is_NikonTransfer = 1;\n }\n parse_makernote(base, 0);\n break;\n case 0xa002: // 40962\n if (kodak)\n raw_width = get4();\n break;\n case 0xa003: // 40963\n if (kodak)\n raw_height = get4();\n break;\n case 0xa302: // 41730\n if (get4() == 0x20002)\n for (exif_cfa = c = 0; c < 8; c += 2)\n exif_cfa |= fgetc(ifp) * 0x01010101U << c;\n }\n fseek(ifp, save, SEEK_SET);\n }\n}", "func_hash": 249585464397784150523321561794064195071, "file_name": "exif_gps.cpp", "file_hash": 33966377039101004586933357298566684301, "cwe": ["CWE-787"], "cve": "CVE-2020-15365", "cve_desc": "LibRaw before 0.20-Beta3 has an out-of-bounds write in parse_exif() in metadata\\exif_gps.cpp via an unrecognized AtomName and a zero value of tiff_nifds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15365"} {"idx": 395532, "project": "LibRaw", "commit_id": "55f0a0c08974b8b79ebfa7762b555a1704b25fb2", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/55f0a0c08974b8b79ebfa7762b555a1704b25fb2", "commit_message": "possible buffer underrun in exif parser", "target": 0, "func": "void LibRaw::parse_exif(int base)\n{\n unsigned entries, tag, type, len, save, c;\n double expo, ape;\n\n unsigned kodak = !strncmp(make, \"EASTMAN\", 7) && tiff_nifds < 3;\n\n entries = get2();\n if (!strncmp(make, \"Hasselblad\", 10) && (tiff_nifds > 3) && (entries > 512))\n return;\n INT64 fsize = ifp->size();\n while (entries--)\n {\n tiff_get(base, &tag, &type, &len, &save);\n\n INT64 savepos = ftell(ifp);\n if (len > 8 && savepos + len > fsize * 2)\n {\n fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!\n continue;\n }\n if (callbacks.exif_cb)\n {\n callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp,\n base);\n fseek(ifp, savepos, SEEK_SET);\n }\n\n switch (tag)\n {\n\tcase 0xA005: // Interoperability IFD\n\t\tfseek(ifp, get4() + base, SEEK_SET);\n\t\tparse_exif_interop(base);\n\t\tbreak;\n\tcase 0xA001: // ExifIFD.ColorSpace\n\t\tc = get2();\n\t\tif (c == 1 && imgdata.color.ExifColorSpace == LIBRAW_COLORSPACE_Unknown)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_sRGB;\n\t\telse if (c == 2)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_AdobeRGB;\n\t\tbreak;\n case 0x9400:\n imCommon.exifAmbientTemperature = getreal(type);\n if ((imCommon.CameraTemperature > -273.15f) &&\n ((OlyID == OlyID_TG_5) ||\n (OlyID == OlyID_TG_6))\n )\n imCommon.CameraTemperature += imCommon.exifAmbientTemperature;\n break;\n case 0x9401:\n imCommon.exifHumidity = getreal(type);\n break;\n case 0x9402:\n imCommon.exifPressure = getreal(type);\n break;\n case 0x9403:\n imCommon.exifWaterDepth = getreal(type);\n break;\n case 0x9404:\n imCommon.exifAcceleration = getreal(type);\n break;\n case 0x9405:\n imCommon.exifCameraElevationAngle = getreal(type);\n break;\n\n case 0xa405: // FocalLengthIn35mmFormat\n imgdata.lens.FocalLengthIn35mmFormat = get2();\n break;\n case 0xa431: // BodySerialNumber\n stmread(imgdata.shootinginfo.BodySerial, len, ifp);\n break;\n case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard\n imgdata.lens.MinFocal = getreal(type);\n imgdata.lens.MaxFocal = getreal(type);\n imgdata.lens.MaxAp4MinFocal = getreal(type);\n imgdata.lens.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa435: // LensSerialNumber\n stmread(imgdata.lens.LensSerial, len, ifp);\n if (!strncmp(imgdata.lens.LensSerial, \"----\", 4))\n imgdata.lens.LensSerial[0] = '\\0';\n break;\n case 0xa420: /* 42016, ImageUniqueID */\n stmread(imgdata.color.ImageUniqueID, len, ifp);\n break;\n case 0xc65d: /* 50781, RawDataUniqueID */\n imgdata.color.RawDataUniqueID[16] = 0;\n fread(imgdata.color.RawDataUniqueID, 1, 16, ifp);\n break;\n case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard\n imgdata.lens.dng.MinFocal = getreal(type);\n imgdata.lens.dng.MaxFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MinFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xc68b: /* 50827, OriginalRawFileName */\n stmread(imgdata.color.OriginalRawFileName, len, ifp);\n break;\n case 0xa433: // LensMake\n stmread(imgdata.lens.LensMake, len, ifp);\n break;\n case 0xa434: // LensModel\n stmread(imgdata.lens.Lens, len, ifp);\n if (!strncmp(imgdata.lens.Lens, \"----\", 4))\n imgdata.lens.Lens[0] = '\\0';\n break;\n case 0x9205:\n imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));\n break;\n case 0x829a: // 33434\n shutter = getreal(type);\n if (tiff_nifds > 0 && tiff_nifds <= LIBRAW_IFD_MAXCOUNT)\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter;\n break;\n case 0x829d: // 33437, FNumber\n aperture = getreal(type);\n break;\n case 0x8827: // 34855\n iso_speed = get2();\n break;\n case 0x8831: // 34865\n if (iso_speed == 0xffff && !strncasecmp(make, \"FUJI\", 4))\n iso_speed = getreal(type);\n break;\n case 0x8832: // 34866\n if (iso_speed == 0xffff &&\n (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"CANON\", 5)))\n iso_speed = getreal(type);\n break;\n case 0x9003: // 36867\n case 0x9004: // 36868\n get_timestamp(0);\n break;\n case 0x9201: // 37377\n if ((expo = -getreal(type)) < 128 && shutter == 0.)\n {\n shutter = libraw_powf64l(2.0, expo);\n if (tiff_nifds > 0 && tiff_nifds <= LIBRAW_IFD_MAXCOUNT)\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter;\n }\n break;\n case 0x9202: // 37378 ApertureValue\n if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))\n aperture = libraw_powf64l(2.0, ape / 2);\n break;\n case 0x9209: // 37385\n flash_used = getreal(type);\n break;\n case 0x920a: // 37386\n focal_len = getreal(type);\n break;\n case 0x927c: // 37500\n if (((make[0] == '\\0') && !strncmp(model, \"ov5647\", 6)) ||\n (!strncmp(make, \"RaspberryPi\", 11) &&\n (!strncmp(model, \"RP_OV5647\", 9) ||\n !strncmp(model, \"RP_imx219\", 9))))\n {\n char mn_text[512];\n char *pos;\n char ccms[512];\n ushort l;\n float num;\n\n fgets(mn_text, MIN(len, 511), ifp);\n mn_text[511] = 0;\n\n pos = strstr(mn_text, \"gain_r=\");\n if (pos)\n cam_mul[0] = atof(pos + 7);\n pos = strstr(mn_text, \"gain_b=\");\n if (pos)\n cam_mul[2] = atof(pos + 7);\n if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n cam_mul[1] = cam_mul[3] = 1.0f;\n else\n cam_mul[0] = cam_mul[2] = 0.0f;\n\n pos = strstr(mn_text, \"ccm=\");\n if (pos)\n {\n pos += 4;\n char *pos2 = strstr(pos, \" \");\n if (pos2)\n {\n l = pos2 - pos;\n memcpy(ccms, pos, l);\n ccms[l] = '\\0';\n#ifdef LIBRAW_WIN32_CALLS\n // Win32 strtok is already thread-safe\n pos = strtok(ccms, \",\");\n#else\n char *last = 0;\n pos = strtok_r(ccms, \",\", &last);\n#endif\n if (pos)\n {\n for (l = 0; l < 4; l++)\n {\n num = 0.0;\n for (c = 0; c < 3; c++)\n {\n imgdata.color.ccm[l][c] = (float)atoi(pos);\n num += imgdata.color.ccm[l][c];\n#ifdef LIBRAW_WIN32_CALLS\n pos = strtok(NULL, \",\");\n#else\n pos = strtok_r(NULL, \",\", &last);\n#endif\n if (!pos)\n goto end; // broken\n }\n if (num > 0.01)\n FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n }\n }\n }\n }\n end:;\n }\n else if (!strncmp(make, \"SONY\", 4) &&\n (!strncmp(model, \"DSC-V3\", 6) || !strncmp(model, \"DSC-F828\", 8)))\n {\n parseSonySRF(len);\n break;\n }\n else if ((len == 1) && !strncmp(make, \"NIKON\", 5))\n {\n c = get4();\n if (c)\n fseek(ifp, c, SEEK_SET);\n is_NikonTransfer = 1;\n }\n parse_makernote(base, 0);\n break;\n case 0xa002: // 40962\n if (kodak)\n raw_width = get4();\n break;\n case 0xa003: // 40963\n if (kodak)\n raw_height = get4();\n break;\n case 0xa302: // 41730\n if (get4() == 0x20002)\n for (exif_cfa = c = 0; c < 8; c += 2)\n exif_cfa |= fgetc(ifp) * 0x01010101U << c;\n }\n fseek(ifp, save, SEEK_SET);\n }\n}", "func_hash": 88849471279248166228850794810488034142, "file_name": "exif_gps.cpp", "file_hash": 334473202743025901900719414950252527514, "cwe": ["CWE-787"], "cve": "CVE-2020-15365", "cve_desc": "LibRaw before 0.20-Beta3 has an out-of-bounds write in parse_exif() in metadata\\exif_gps.cpp via an unrecognized AtomName and a zero value of tiff_nifds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15365"} {"idx": 207312, "project": "ImageMagick6", "commit_id": "ebe38274941908892c32b7244fa4e0fe7497e528", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/ebe38274941908892c32b7244fa4e0fe7497e528", "commit_message": "...", "target": 1, "func": "static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n const char\n *client_name;\n\n Display\n *display;\n\n float\n pixels_per_point;\n\n Image\n *image;\n\n int\n sans,\n status;\n\n Pixmap\n pixmap;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n i;\n\n register PixelPacket\n *q;\n\n register size_t\n pixel;\n\n Screen\n *screen;\n\n ssize_t\n x,\n y;\n\n XColor\n *colors;\n\n XImage\n *dps_image;\n\n XRectangle\n page,\n bits_per_pixel;\n\n XResourceInfo\n resource_info;\n\n XrmDatabase\n resource_database;\n\n XStandardColormap\n *map_info;\n\n XVisualInfo\n *visual_info;\n\n /*\n Open X server connection.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n display=XOpenDisplay(image_info->server_name);\n if (display == (Display *) NULL)\n return((Image *) NULL);\n /*\n Set our forgiving exception handler.\n */\n (void) XSetErrorHandler(XError);\n /*\n Open image file.\n */\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return((Image *) NULL);\n /*\n Get user defaults from X resource database.\n */\n client_name=GetClientName();\n resource_database=XGetResourceDatabase(display,client_name);\n XGetResourceInfo(image_info,resource_database,client_name,&resource_info);\n /*\n Allocate standard colormap.\n */\n map_info=XAllocStandardColormap();\n visual_info=(XVisualInfo *) NULL;\n if (map_info == (XStandardColormap *) NULL)\n ThrowReaderException(ResourceLimitError,\"UnableToCreateStandardColormap\")\n else\n {\n /*\n Initialize visual info.\n */\n (void) CloneString(&resource_info.visual_type,\"default\");\n visual_info=XBestVisualInfo(display,map_info,&resource_info);\n map_info->colormap=(Colormap) NULL;\n }\n if ((map_info == (XStandardColormap *) NULL) ||\n (visual_info == (XVisualInfo *) NULL))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Create a pixmap the appropriate size for the image.\n */\n screen=ScreenOfDisplay(display,visual_info->screen);\n pixels_per_point=XDPSPixelsPerPoint(screen);\n if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))\n pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/\n DefaultResolution;\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap,\n &bits_per_pixel,&page);\n if ((status == dps_status_failure) || (status == dps_status_no_extension))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Rasterize the file into the pixmap.\n */\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth,\n &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue,\n &sans);\n if (status != dps_status_success)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Initialize DPS X image.\n */\n dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (dps_image == (XImage *) NULL)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Get the colormap colors.\n */\n colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size,\n sizeof(*colors));\n if (colors == (XColor *) NULL)\n {\n image=DestroyImage(image);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor))\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=(size_t) i;\n colors[i].pad=0;\n }\n else\n {\n size_t\n blue,\n blue_bit,\n green,\n green_bit,\n red,\n red_bit;\n\n /*\n DirectColor or TrueColor visual.\n */\n red=0;\n green=0;\n blue=0;\n red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1);\n green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1);\n blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1);\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=red | green | blue;\n colors[i].pad=0;\n red+=red_bit;\n if (red > visual_info->red_mask)\n red=0;\n green+=green_bit;\n if (green > visual_info->green_mask)\n green=0;\n blue+=blue_bit;\n if (blue > visual_info->blue_mask)\n blue=0;\n }\n }\n (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen),\n colors,visual_info->colormap_size);\n /*\n Convert X image to MIFF format.\n */\n if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor))\n image->storage_class=PseudoClass;\n image->columns=(size_t) dps_image->width;\n image->rows=(size_t) dps_image->height;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n switch (image->storage_class)\n {\n case DirectClass:\n default:\n {\n register size_t\n color,\n index;\n\n size_t\n blue_mask,\n blue_shift,\n green_mask,\n green_shift,\n red_mask,\n red_shift;\n\n /*\n Determine shift and mask for red, green, and blue.\n */\n red_mask=visual_info->red_mask;\n red_shift=0;\n while ((red_mask != 0) && ((red_mask & 0x01) == 0))\n {\n red_mask>>=1;\n red_shift++;\n }\n green_mask=visual_info->green_mask;\n green_shift=0;\n while ((green_mask != 0) && ((green_mask & 0x01) == 0))\n {\n green_mask>>=1;\n green_shift++;\n }\n blue_mask=visual_info->blue_mask;\n blue_shift=0;\n while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))\n {\n blue_mask>>=1;\n blue_shift++;\n }\n /*\n Convert X image to DirectClass packets.\n */\n if ((visual_info->colormap_size > 0) &&\n (visual_info->klass == DirectColor))\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n index=(pixel >> red_shift) & red_mask;\n SetPixelRed(q,ScaleShortToQuantum(colors[index].red));\n index=(pixel >> green_shift) & green_mask;\n SetPixelGreen(q,ScaleShortToQuantum(colors[index].green));\n index=(pixel >> blue_shift) & blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n color=(pixel >> red_shift) & red_mask;\n color=(color*65535L)/red_mask;\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> green_shift) & green_mask;\n color=(color*65535L)/green_mask;\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short)\n color));\n color=(pixel >> blue_shift) & blue_mask;\n color=(color*65535L)/blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short)\n color));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n case PseudoClass:\n {\n /*\n Create colormap.\n */\n if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse)\n {\n image=DestroyImage(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red);\n image->colormap[colors[i].pixel].green=\n ScaleShortToQuantum(colors[i].green);\n image->colormap[colors[i].pixel].blue=\n ScaleShortToQuantum(colors[i].blue);\n }\n /*\n Convert X image to PseudoClass packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n SetPixelIndex(indexes+x,(unsigned short)\n XGetPixel(dps_image,x,y));\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n }\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image);\n /*\n Rasterize matte image.\n */\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page);\n if ((status != dps_status_failure) && (status != dps_status_no_extension))\n {\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x,\n -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans);\n if (status == dps_status_success)\n {\n XImage\n *matte_image;\n\n /*\n Initialize image matte.\n */\n matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (matte_image != (XImage *) NULL)\n {\n image->storage_class=DirectClass;\n image->matte=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelOpacity(q,OpaqueOpacity);\n if (XGetPixel(matte_image,x,y) == 0)\n SetPixelOpacity(q,TransparentOpacity);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n XDestroyImage(matte_image);\n }\n }\n }\n /*\n Relinquish resources.\n */\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "func_hash": 338615485000408978863621753864633927694, "file_name": "dps.c", "file_hash": 40985628552609844008350810107369662516, "cwe": ["CWE-401"], "cve": "CVE-2019-16709", "cve_desc": "ImageMagick 7.0.8-35 has a memory leak in coders/dps.c, as demonstrated by XCreateImage.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-16709"} {"idx": 395543, "project": "ImageMagick6", "commit_id": "ebe38274941908892c32b7244fa4e0fe7497e528", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/ebe38274941908892c32b7244fa4e0fe7497e528", "commit_message": "...", "target": 0, "func": "static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n const char\n *client_name;\n\n Display\n *display;\n\n float\n pixels_per_point;\n\n Image\n *image;\n\n int\n sans,\n status;\n\n Pixmap\n pixmap;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n i;\n\n register PixelPacket\n *q;\n\n register size_t\n pixel;\n\n Screen\n *screen;\n\n ssize_t\n x,\n y;\n\n XColor\n *colors;\n\n XImage\n *dps_image;\n\n XRectangle\n page,\n bits_per_pixel;\n\n XResourceInfo\n resource_info;\n\n XrmDatabase\n resource_database;\n\n XStandardColormap\n *map_info;\n\n XVisualInfo\n *visual_info;\n\n /*\n Open X server connection.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n display=XOpenDisplay(image_info->server_name);\n if (display == (Display *) NULL)\n return((Image *) NULL);\n /*\n Set our forgiving exception handler.\n */\n (void) XSetErrorHandler(XError);\n /*\n Open image file.\n */\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Get user defaults from X resource database.\n */\n client_name=GetClientName();\n resource_database=XGetResourceDatabase(display,client_name);\n XGetResourceInfo(image_info,resource_database,client_name,&resource_info);\n /*\n Allocate standard colormap.\n */\n map_info=XAllocStandardColormap();\n visual_info=(XVisualInfo *) NULL;\n if (map_info == (XStandardColormap *) NULL)\n ThrowReaderException(ResourceLimitError,\"UnableToCreateStandardColormap\")\n else\n {\n /*\n Initialize visual info.\n */\n (void) CloneString(&resource_info.visual_type,\"default\");\n visual_info=XBestVisualInfo(display,map_info,&resource_info);\n map_info->colormap=(Colormap) NULL;\n }\n if ((map_info == (XStandardColormap *) NULL) ||\n (visual_info == (XVisualInfo *) NULL))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Create a pixmap the appropriate size for the image.\n */\n screen=ScreenOfDisplay(display,visual_info->screen);\n pixels_per_point=XDPSPixelsPerPoint(screen);\n if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))\n pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/\n DefaultResolution;\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap,\n &bits_per_pixel,&page);\n if ((status == dps_status_failure) || (status == dps_status_no_extension))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Rasterize the file into the pixmap.\n */\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth,\n &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue,\n &sans);\n if (status != dps_status_success)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Initialize DPS X image.\n */\n dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (dps_image == (XImage *) NULL)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Get the colormap colors.\n */\n colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size,\n sizeof(*colors));\n if (colors == (XColor *) NULL)\n {\n image=DestroyImage(image);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor))\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=(size_t) i;\n colors[i].pad=0;\n }\n else\n {\n size_t\n blue,\n blue_bit,\n green,\n green_bit,\n red,\n red_bit;\n\n /*\n DirectColor or TrueColor visual.\n */\n red=0;\n green=0;\n blue=0;\n red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1);\n green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1);\n blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1);\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=red | green | blue;\n colors[i].pad=0;\n red+=red_bit;\n if (red > visual_info->red_mask)\n red=0;\n green+=green_bit;\n if (green > visual_info->green_mask)\n green=0;\n blue+=blue_bit;\n if (blue > visual_info->blue_mask)\n blue=0;\n }\n }\n (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen),\n colors,visual_info->colormap_size);\n /*\n Convert X image to MIFF format.\n */\n if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor))\n image->storage_class=PseudoClass;\n image->columns=(size_t) dps_image->width;\n image->rows=(size_t) dps_image->height;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n switch (image->storage_class)\n {\n case DirectClass:\n default:\n {\n register size_t\n color,\n index;\n\n size_t\n blue_mask,\n blue_shift,\n green_mask,\n green_shift,\n red_mask,\n red_shift;\n\n /*\n Determine shift and mask for red, green, and blue.\n */\n red_mask=visual_info->red_mask;\n red_shift=0;\n while ((red_mask != 0) && ((red_mask & 0x01) == 0))\n {\n red_mask>>=1;\n red_shift++;\n }\n green_mask=visual_info->green_mask;\n green_shift=0;\n while ((green_mask != 0) && ((green_mask & 0x01) == 0))\n {\n green_mask>>=1;\n green_shift++;\n }\n blue_mask=visual_info->blue_mask;\n blue_shift=0;\n while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))\n {\n blue_mask>>=1;\n blue_shift++;\n }\n /*\n Convert X image to DirectClass packets.\n */\n if ((visual_info->colormap_size > 0) &&\n (visual_info->klass == DirectColor))\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n index=(pixel >> red_shift) & red_mask;\n SetPixelRed(q,ScaleShortToQuantum(colors[index].red));\n index=(pixel >> green_shift) & green_mask;\n SetPixelGreen(q,ScaleShortToQuantum(colors[index].green));\n index=(pixel >> blue_shift) & blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n color=(pixel >> red_shift) & red_mask;\n color=(color*65535L)/red_mask;\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> green_shift) & green_mask;\n color=(color*65535L)/green_mask;\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short)\n color));\n color=(pixel >> blue_shift) & blue_mask;\n color=(color*65535L)/blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short)\n color));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n case PseudoClass:\n {\n /*\n Create colormap.\n */\n if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse)\n {\n image=DestroyImage(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red);\n image->colormap[colors[i].pixel].green=\n ScaleShortToQuantum(colors[i].green);\n image->colormap[colors[i].pixel].blue=\n ScaleShortToQuantum(colors[i].blue);\n }\n /*\n Convert X image to PseudoClass packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n SetPixelIndex(indexes+x,(unsigned short)\n XGetPixel(dps_image,x,y));\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n }\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image);\n /*\n Rasterize matte image.\n */\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page);\n if ((status != dps_status_failure) && (status != dps_status_no_extension))\n {\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x,\n -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans);\n if (status == dps_status_success)\n {\n XImage\n *matte_image;\n\n /*\n Initialize image matte.\n */\n matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (matte_image != (XImage *) NULL)\n {\n image->storage_class=DirectClass;\n image->matte=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelOpacity(q,OpaqueOpacity);\n if (XGetPixel(matte_image,x,y) == 0)\n SetPixelOpacity(q,TransparentOpacity);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n XDestroyImage(matte_image);\n }\n }\n }\n /*\n Relinquish resources.\n */\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "func_hash": 213238347015207464512050206272460635004, "file_name": "dps.c", "file_hash": 80834286855148096293283495169865863818, "cwe": ["CWE-401"], "cve": "CVE-2019-16709", "cve_desc": "ImageMagick 7.0.8-35 has a memory leak in coders/dps.c, as demonstrated by XCreateImage.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-16709"} {"idx": 207463, "project": "ipmitool", "commit_id": "41d7026946fafbd4d1ec0bcaca3ea30a6e8eed22", "project_url": "https://github.com/ipmitool/ipmitool", "commit_url": "https://github.com/ipmitool/ipmitool/commit/41d7026946fafbd4d1ec0bcaca3ea30a6e8eed22", "commit_message": "session: Fix buffer overflow in ipmi_get_session_info\n\nPartial fix for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\nThe `ipmi_get_session_info` function does not properly check the\nresponse `data_len`, which is used as a copy size, allowing stack buffer\noverflow.", "target": 1, "func": "ipmi_get_session_info(struct ipmi_intf * intf,\n\t\t\t\t\t Ipmi_Session_Request_Type session_request_type,\n\t\t\t\t\t uint32_t id_or_handle)\n{\n\tint i, retval = 0;\n\n\tstruct ipmi_rs * rsp;\n\tstruct ipmi_rq req;\n\tuint8_t rqdata[5]; // max length of the variable length request\n\tstruct get_session_info_rsp session_info;\n\n\tmemset(&req, 0, sizeof(req));\n\tmemset(&session_info, 0, sizeof(session_info));\n\treq.msg.netfn = IPMI_NETFN_APP; // 0x06\n\treq.msg.cmd = IPMI_GET_SESSION_INFO; // 0x3D\n\treq.msg.data = rqdata;\n\n\tswitch (session_request_type)\n\t{\n\t\t\n\tcase IPMI_SESSION_REQUEST_CURRENT:\n\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\tswitch (session_request_type)\n\t\t{\n\t\tcase IPMI_SESSION_REQUEST_CURRENT:\n\t\t\trqdata[0] = 0x00;\n\t\t\treq.msg.data_len = 1;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\t\t\trqdata[0] = 0xFF;\n\t\t\trqdata[1] = id_or_handle & 0x000000FF;\n\t\t\trqdata[2] = (id_or_handle >> 8) & 0x000000FF;\n\t\t\trqdata[3] = (id_or_handle >> 16) & 0x000000FF;\n\t\t\trqdata[4] = (id_or_handle >> 24) & 0x000000FF;\n\t\t\treq.msg.data_len = 5;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\t\trqdata[0] = 0xFE;\n\t\t\trqdata[1] = (uint8_t)id_or_handle;\n\t\t\treq.msg.data_len = 2;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_ALL:\n\t\t\tbreak;\n\t\t}\n\n\t\trsp = intf->sendrecv(intf, &req);\n\t\tif (!rsp)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\tretval = -1;\n\t\t}\n\t\telse if (rsp->ccode)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\tretval = -1;\n\t\t}\n\n\t\tif (retval < 0)\n\t\t{\n\t\t\tif ((session_request_type == IPMI_SESSION_REQUEST_CURRENT) &&\n\t\t\t (strncmp(intf->name, \"lan\", 3) != 0))\n\t\t\t\tlprintf(LOG_ERR, \"It is likely that the channel in use \"\n\t\t\t\t\t\"does not support sessions\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmemcpy(&session_info, rsp->data, rsp->data_len);\n\t\t\tprint_session_info(&session_info, rsp->data_len);\n\t\t}\n\t\tbreak;\n\t\t\n\tcase IPMI_SESSION_REQUEST_ALL:\n\t\treq.msg.data_len = 1;\n\t\ti = 1;\n\t\tdo\n\t\t{\n\t\t\trqdata[0] = i++;\n\t\t\trsp = intf->sendrecv(intf, &req);\n\t\t\t\n\t\t\tif (!rsp)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->ccode && rsp->ccode != 0xCC && rsp->ccode != 0xCB)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->data_len < 3)\n\t\t\t{\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tmemcpy(&session_info, rsp->data, rsp->data_len);\n\t\t\tprint_session_info(&session_info, rsp->data_len);\n\t\t\t\n\t\t} while (i <= session_info.session_slot_count);\n\t\tbreak;\n\t}\n\n\treturn retval;\n}", "func_hash": 74274373352257519107108638597566380571, "file_name": "ipmi_session.c", "file_hash": 247350272528331558375579916518031961803, "cwe": ["CWE-120"], "cve": "CVE-2020-5208", "cve_desc": "It's been found that multiple functions in ipmitool before 1.8.19 neglect proper checking of the data received from a remote LAN party, which may lead to buffer overflows and potentially to remote code execution on the ipmitool side. This is especially dangerous if ipmitool is run as a privileged user. This problem is fixed in version 1.8.19.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-5208"} {"idx": 398021, "project": "ipmitool", "commit_id": "41d7026946fafbd4d1ec0bcaca3ea30a6e8eed22", "project_url": "https://github.com/ipmitool/ipmitool", "commit_url": "https://github.com/ipmitool/ipmitool/commit/41d7026946fafbd4d1ec0bcaca3ea30a6e8eed22", "commit_message": "session: Fix buffer overflow in ipmi_get_session_info\n\nPartial fix for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\nThe `ipmi_get_session_info` function does not properly check the\nresponse `data_len`, which is used as a copy size, allowing stack buffer\noverflow.", "target": 0, "func": "ipmi_get_session_info(struct ipmi_intf * intf,\n\t\t\t\t\t Ipmi_Session_Request_Type session_request_type,\n\t\t\t\t\t uint32_t id_or_handle)\n{\n\tint i, retval = 0;\n\n\tstruct ipmi_rs * rsp;\n\tstruct ipmi_rq req;\n\tuint8_t rqdata[5]; // max length of the variable length request\n\tstruct get_session_info_rsp session_info;\n\n\tmemset(&req, 0, sizeof(req));\n\tmemset(&session_info, 0, sizeof(session_info));\n\treq.msg.netfn = IPMI_NETFN_APP; // 0x06\n\treq.msg.cmd = IPMI_GET_SESSION_INFO; // 0x3D\n\treq.msg.data = rqdata;\n\n\tswitch (session_request_type)\n\t{\n\t\t\n\tcase IPMI_SESSION_REQUEST_CURRENT:\n\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\tswitch (session_request_type)\n\t\t{\n\t\tcase IPMI_SESSION_REQUEST_CURRENT:\n\t\t\trqdata[0] = 0x00;\n\t\t\treq.msg.data_len = 1;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\t\t\trqdata[0] = 0xFF;\n\t\t\trqdata[1] = id_or_handle & 0x000000FF;\n\t\t\trqdata[2] = (id_or_handle >> 8) & 0x000000FF;\n\t\t\trqdata[3] = (id_or_handle >> 16) & 0x000000FF;\n\t\t\trqdata[4] = (id_or_handle >> 24) & 0x000000FF;\n\t\t\treq.msg.data_len = 5;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\t\trqdata[0] = 0xFE;\n\t\t\trqdata[1] = (uint8_t)id_or_handle;\n\t\t\treq.msg.data_len = 2;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_ALL:\n\t\t\tbreak;\n\t\t}\n\n\t\trsp = intf->sendrecv(intf, &req);\n\t\tif (!rsp)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\tretval = -1;\n\t\t}\n\t\telse if (rsp->ccode)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\tretval = -1;\n\t\t}\n\n\t\tif (retval < 0)\n\t\t{\n\t\t\tif ((session_request_type == IPMI_SESSION_REQUEST_CURRENT) &&\n\t\t\t (strncmp(intf->name, \"lan\", 3) != 0))\n\t\t\t\tlprintf(LOG_ERR, \"It is likely that the channel in use \"\n\t\t\t\t\t\"does not support sessions\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmemcpy(&session_info, rsp->data,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t\tprint_session_info(&session_info,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t}\n\t\tbreak;\n\t\t\n\tcase IPMI_SESSION_REQUEST_ALL:\n\t\treq.msg.data_len = 1;\n\t\ti = 1;\n\t\tdo\n\t\t{\n\t\t\trqdata[0] = i++;\n\t\t\trsp = intf->sendrecv(intf, &req);\n\t\t\t\n\t\t\tif (!rsp)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->ccode && rsp->ccode != 0xCC && rsp->ccode != 0xCB)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->data_len < 3)\n\t\t\t{\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tmemcpy(&session_info, rsp->data,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t\tprint_session_info(&session_info,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t\t\n\t\t} while (i <= session_info.session_slot_count);\n\t\tbreak;\n\t}\n\n\treturn retval;\n}", "func_hash": 199469369287121058887061968857902324953, "file_name": "ipmi_session.c", "file_hash": 267703300933254104634065913717330228812, "cwe": ["CWE-120"], "cve": "CVE-2020-5208", "cve_desc": "It's been found that multiple functions in ipmitool before 1.8.19 neglect proper checking of the data received from a remote LAN party, which may lead to buffer overflows and potentially to remote code execution on the ipmitool side. This is especially dangerous if ipmitool is run as a privileged user. This problem is fixed in version 1.8.19.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-5208"} {"idx": 207478, "project": "linux", "commit_id": "b166a20b07382b8bc1dcee2a448715c9c2c81b5b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=b166a20b07382b8bc1dcee2a448715c9c2c81b5b", "commit_message": "net/sctp: fix race condition in sctp_destroy_sock\n\nIf sctp_destroy_sock is called without sock_net(sk)->sctp.addr_wq_lock\nheld and sp->do_auto_asconf is true, then an element is removed\nfrom the auto_asconf_splist without any proper locking.\n\nThis can happen in the following functions:\n1. In sctp_accept, if sctp_sock_migrate fails.\n2. In inet_create or inet6_create, if there is a bpf program\n attached to BPF_CGROUP_INET_SOCK_CREATE which denies\n creation of the sctp socket.\n\nThe bug is fixed by acquiring addr_wq_lock in sctp_destroy_sock\ninstead of sctp_close.\n\nThis addresses CVE-2021-23133.\n\nReported-by: Or Cohen \nReviewed-by: Xin Long \nFixes: 610236587600 (\"bpf: Add new cgroup attach type to enable sock modifications\")\nSigned-off-by: Or Cohen \nAcked-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller ", "target": 1, "func": "static void sctp_destroy_sock(struct sock *sk)\n{\n\tstruct sctp_sock *sp;\n\n\tpr_debug(\"%s: sk:%p\\n\", __func__, sk);\n\n\t/* Release our hold on the endpoint. */\n\tsp = sctp_sk(sk);\n\t/* This could happen during socket init, thus we bail out\n\t * early, since the rest of the below is not setup either.\n\t */\n\tif (sp->ep == NULL)\n\t\treturn;\n\n\tif (sp->do_auto_asconf) {\n\t\tsp->do_auto_asconf = 0;\n\t\tlist_del(&sp->auto_asconf_list);\n\t}\n\tsctp_endpoint_free(sp->ep);\n\tlocal_bh_disable();\n\tsk_sockets_allocated_dec(sk);\n\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n\tlocal_bh_enable();\n}", "func_hash": 101888975784216426905323708378071777831, "file_name": "socket.c", "file_hash": 259867879448567869242511888039904254317, "cwe": ["CWE-362"], "cve": "CVE-2021-23133", "cve_desc": "A race condition in Linux kernel SCTP sockets (net/sctp/socket.c) before 5.12-rc8 can lead to kernel privilege escalation from the context of a network service or an unprivileged process. If sctp_destroy_sock is called without sock_net(sk)->sctp.addr_wq_lock then an element is removed from the auto_asconf_splist list without any proper locking. This can be exploited by an attacker with network service privileges to escalate to root or from the context of an unprivileged user directly if a BPF_CGROUP_INET_SOCK_CREATE is attached which denies creation of some SCTP socket.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23133"} {"idx": 398128, "project": "linux", "commit_id": "b166a20b07382b8bc1dcee2a448715c9c2c81b5b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=b166a20b07382b8bc1dcee2a448715c9c2c81b5b", "commit_message": "net/sctp: fix race condition in sctp_destroy_sock\n\nIf sctp_destroy_sock is called without sock_net(sk)->sctp.addr_wq_lock\nheld and sp->do_auto_asconf is true, then an element is removed\nfrom the auto_asconf_splist without any proper locking.\n\nThis can happen in the following functions:\n1. In sctp_accept, if sctp_sock_migrate fails.\n2. In inet_create or inet6_create, if there is a bpf program\n attached to BPF_CGROUP_INET_SOCK_CREATE which denies\n creation of the sctp socket.\n\nThe bug is fixed by acquiring addr_wq_lock in sctp_destroy_sock\ninstead of sctp_close.\n\nThis addresses CVE-2021-23133.\n\nReported-by: Or Cohen \nReviewed-by: Xin Long \nFixes: 610236587600 (\"bpf: Add new cgroup attach type to enable sock modifications\")\nSigned-off-by: Or Cohen \nAcked-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller ", "target": 0, "func": "static void sctp_destroy_sock(struct sock *sk)\n{\n\tstruct sctp_sock *sp;\n\n\tpr_debug(\"%s: sk:%p\\n\", __func__, sk);\n\n\t/* Release our hold on the endpoint. */\n\tsp = sctp_sk(sk);\n\t/* This could happen during socket init, thus we bail out\n\t * early, since the rest of the below is not setup either.\n\t */\n\tif (sp->ep == NULL)\n\t\treturn;\n\n\tif (sp->do_auto_asconf) {\n\t\tsp->do_auto_asconf = 0;\n\t\tspin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);\n\t\tlist_del(&sp->auto_asconf_list);\n\t\tspin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);\n\t}\n\tsctp_endpoint_free(sp->ep);\n\tlocal_bh_disable();\n\tsk_sockets_allocated_dec(sk);\n\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n\tlocal_bh_enable();\n}", "func_hash": 46478563144325225575228492490622030956, "file_name": "socket.c", "file_hash": 178833899936531764627469356293020305361, "cwe": ["CWE-362"], "cve": "CVE-2021-23133", "cve_desc": "A race condition in Linux kernel SCTP sockets (net/sctp/socket.c) before 5.12-rc8 can lead to kernel privilege escalation from the context of a network service or an unprivileged process. If sctp_destroy_sock is called without sock_net(sk)->sctp.addr_wq_lock then an element is removed from the auto_asconf_splist list without any proper locking. This can be exploited by an attacker with network service privileges to escalate to root or from the context of an unprivileged user directly if a BPF_CGROUP_INET_SOCK_CREATE is attached which denies creation of some SCTP socket.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23133"} {"idx": 207488, "project": "linux", "commit_id": "4d6636498c41891d0482a914dd570343a838ad79", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=4d6636498c41891d0482a914dd570343a838ad79", "commit_message": "can: mcba_usb: fix use-after-free on disconnect\n\nThe driver was accessing its driver data after having freed it.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nCc: stable # 4.12\nCc: Remigiusz Ko\u0142\u0142\u0105taj \nReported-by: syzbot+e29b17e5042bbc56fae9@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nSigned-off-by: Marc Kleine-Budde ", "target": 1, "func": "static void mcba_usb_disconnect(struct usb_interface *intf)\n{\n\tstruct mcba_priv *priv = usb_get_intfdata(intf);\n\n\tusb_set_intfdata(intf, NULL);\n\n\tnetdev_info(priv->netdev, \"device disconnected\\n\");\n\n\tunregister_candev(priv->netdev);\n\tfree_candev(priv->netdev);\n\n\tmcba_urb_unlink(priv);\n}", "func_hash": 299041107675112775746202953247181403214, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2019-19529", "cve_desc": "In the Linux kernel before 5.3.11, there is a use-after-free bug that can be caused by a malicious USB device in the drivers/net/can/usb/mcba_usb.c driver, aka CID-4d6636498c41.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19529"} {"idx": 398308, "project": "linux", "commit_id": "4d6636498c41891d0482a914dd570343a838ad79", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=4d6636498c41891d0482a914dd570343a838ad79", "commit_message": "can: mcba_usb: fix use-after-free on disconnect\n\nThe driver was accessing its driver data after having freed it.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nCc: stable # 4.12\nCc: Remigiusz Ko\u0142\u0142\u0105taj \nReported-by: syzbot+e29b17e5042bbc56fae9@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nSigned-off-by: Marc Kleine-Budde ", "target": 0, "func": "static void mcba_usb_disconnect(struct usb_interface *intf)\n{\n\tstruct mcba_priv *priv = usb_get_intfdata(intf);\n\n\tusb_set_intfdata(intf, NULL);\n\n\tnetdev_info(priv->netdev, \"device disconnected\\n\");\n\n\tunregister_candev(priv->netdev);\n\tmcba_urb_unlink(priv);\n\tfree_candev(priv->netdev);\n}", "func_hash": 37910976496708887492798010851532616183, "file_name": "mcba_usb.c", "file_hash": 278357705682492618477693192859299956324, "cwe": ["CWE-416"], "cve": "CVE-2019-19529", "cve_desc": "In the Linux kernel before 5.3.11, there is a use-after-free bug that can be caused by a malicious USB device in the drivers/net/can/usb/mcba_usb.c driver, aka CID-4d6636498c41.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19529"} {"idx": 207567, "project": "FreeRDP", "commit_id": "6ade7b4cbfd71c54b3d724e8f2d6ac76a58e879a", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6ade7b4cbfd71c54b3d724e8f2d6ac76a58e879a", "commit_message": "Fixed OOB Read in license_read_new_or_upgrade_license_packet\n\nCVE-2020-11099 thanks to @antonio-morales for finding this.", "target": 1, "func": "BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n{\n\tUINT32 os_major;\n\tUINT32 os_minor;\n\tUINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;\n\twStream* licenseStream = NULL;\n\tBOOL ret = FALSE;\n\tBYTE computedMac[16];\n\tLICENSE_BLOB* calBlob;\n\n\tDEBUG_LICENSE(\"Receiving Server New/Upgrade License Packet\");\n\n\tcalBlob = license_new_binary_blob(BB_DATA_BLOB);\n\tif (!calBlob)\n\t\treturn FALSE;\n\n\t/* EncryptedLicenseInfo */\n\tif (!license_read_encrypted_blob(license, s, calBlob))\n\t\tgoto out_free_blob;\n\n\t/* compute MAC and check it */\n\tif (Stream_GetRemainingLength(s) < 16)\n\t\tgoto out_free_blob;\n\n\tif (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))\n\t\tgoto out_free_blob;\n\n\tif (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)\n\t{\n\t\tWLog_ERR(TAG, \"new or upgrade license MAC mismatch\");\n\t\tgoto out_free_blob;\n\t}\n\n\tif (!Stream_SafeSeek(s, 16))\n\t\tgoto out_free_blob;\n\n\tlicenseStream = Stream_New(calBlob->data, calBlob->length);\n\tif (!licenseStream)\n\t\tgoto out_free_blob;\n\n\tStream_Read_UINT16(licenseStream, os_minor);\n\tStream_Read_UINT16(licenseStream, os_major);\n\n\t/* Scope */\n\tStream_Read_UINT32(licenseStream, cbScope);\n\tif (Stream_GetRemainingLength(licenseStream) < cbScope)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Scope:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);\n#endif\n\tStream_Seek(licenseStream, cbScope);\n\n\t/* CompanyName */\n\tStream_Read_UINT32(licenseStream, cbCompanyName);\n\tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Company name:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);\n#endif\n\tStream_Seek(licenseStream, cbCompanyName);\n\n\t/* productId */\n\tStream_Read_UINT32(licenseStream, cbProductId);\n\tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Product id:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);\n#endif\n\tStream_Seek(licenseStream, cbProductId);\n\n\t/* licenseInfo */\n\tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n\tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n\t\tgoto out_free_stream;\n\n\tlicense->state = LICENSE_STATE_COMPLETED;\n\n\tret = TRUE;\n\tif (!license->rdp->settings->OldLicenseBehaviour)\n\t\tret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,\n\t\t license->rdp->settings->ClientHostname);\n\nout_free_stream:\n\tStream_Free(licenseStream, FALSE);\nout_free_blob:\n\tlicense_free_binary_blob(calBlob);\n\treturn ret;\n}", "func_hash": 134542836492059404727348638541733942617, "file_name": "license.c", "file_hash": 41805382834640061372439312241604164558, "cwe": ["CWE-125"], "cve": "CVE-2020-11099", "cve_desc": "In FreeRDP before version 2.1.2, there is an out of bounds read in license_read_new_or_upgrade_license_packet. A manipulated license packet can lead to out of bound reads to an internal buffer. This is fixed in version 2.1.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11099"} {"idx": 399253, "project": "FreeRDP", "commit_id": "6ade7b4cbfd71c54b3d724e8f2d6ac76a58e879a", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6ade7b4cbfd71c54b3d724e8f2d6ac76a58e879a", "commit_message": "Fixed OOB Read in license_read_new_or_upgrade_license_packet\n\nCVE-2020-11099 thanks to @antonio-morales for finding this.", "target": 0, "func": "BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n{\n\tUINT32 os_major;\n\tUINT32 os_minor;\n\tUINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;\n\twStream* licenseStream = NULL;\n\tBOOL ret = FALSE;\n\tBYTE computedMac[16];\n\tLICENSE_BLOB* calBlob;\n\n\tDEBUG_LICENSE(\"Receiving Server New/Upgrade License Packet\");\n\n\tcalBlob = license_new_binary_blob(BB_DATA_BLOB);\n\tif (!calBlob)\n\t\treturn FALSE;\n\n\t/* EncryptedLicenseInfo */\n\tif (!license_read_encrypted_blob(license, s, calBlob))\n\t\tgoto out_free_blob;\n\n\t/* compute MAC and check it */\n\tif (Stream_GetRemainingLength(s) < 16)\n\t\tgoto out_free_blob;\n\n\tif (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))\n\t\tgoto out_free_blob;\n\n\tif (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)\n\t{\n\t\tWLog_ERR(TAG, \"new or upgrade license MAC mismatch\");\n\t\tgoto out_free_blob;\n\t}\n\n\tif (!Stream_SafeSeek(s, 16))\n\t\tgoto out_free_blob;\n\n\tlicenseStream = Stream_New(calBlob->data, calBlob->length);\n\tif (!licenseStream)\n\t\tgoto out_free_blob;\n\n\tif (Stream_GetRemainingLength(licenseStream) < 8)\n\t\tgoto out_free_stream;\n\n\tStream_Read_UINT16(licenseStream, os_minor);\n\tStream_Read_UINT16(licenseStream, os_major);\n\n\t/* Scope */\n\tStream_Read_UINT32(licenseStream, cbScope);\n\tif (Stream_GetRemainingLength(licenseStream) < cbScope)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Scope:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);\n#endif\n\tStream_Seek(licenseStream, cbScope);\n\n\t/* CompanyName */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbCompanyName);\n\tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Company name:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);\n#endif\n\tStream_Seek(licenseStream, cbCompanyName);\n\n\t/* productId */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbProductId);\n\tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Product id:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);\n#endif\n\tStream_Seek(licenseStream, cbProductId);\n\n\t/* licenseInfo */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n\tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n\t\tgoto out_free_stream;\n\n\tlicense->state = LICENSE_STATE_COMPLETED;\n\n\tret = TRUE;\n\tif (!license->rdp->settings->OldLicenseBehaviour)\n\t\tret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,\n\t\t license->rdp->settings->ClientHostname);\n\nout_free_stream:\n\tStream_Free(licenseStream, FALSE);\nout_free_blob:\n\tlicense_free_binary_blob(calBlob);\n\treturn ret;\n}", "func_hash": 6142177492251916498402563365630944846, "file_name": "license.c", "file_hash": 277374306214112301716369894769697860260, "cwe": ["CWE-125"], "cve": "CVE-2020-11099", "cve_desc": "In FreeRDP before version 2.1.2, there is an out of bounds read in license_read_new_or_upgrade_license_packet. A manipulated license packet can lead to out of bound reads to an internal buffer. This is fixed in version 2.1.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11099"} {"idx": 207568, "project": "neomutt", "commit_id": "fa1db5785e5cfd9d3cd27b7571b9fe268d2ec2dc", "project_url": "https://github.com/neomutt/neomutt", "commit_url": "https://github.com/neomutt/neomutt/commit/fa1db5785e5cfd9d3cd27b7571b9fe268d2ec2dc", "commit_message": "Fix seqset iterator when it ends in a comma\n\nIf the seqset ended with a comma, the substr_end marker would be just\nbefore the trailing nul. In the next call, the loop to skip the\nmarker would iterate right past the end of string too.\n\nThe fix is simple: place the substr_end marker and skip past it\nimmediately.", "target": 1, "func": "int mutt_seqset_iterator_next(struct SeqsetIterator *iter, unsigned int *next)\n{\n if (!iter || !next)\n return -1;\n\n if (iter->in_range)\n {\n if ((iter->down && (iter->range_cur == (iter->range_end - 1))) ||\n (!iter->down && (iter->range_cur == (iter->range_end + 1))))\n {\n iter->in_range = 0;\n }\n }\n\n if (!iter->in_range)\n {\n iter->substr_cur = iter->substr_end;\n if (iter->substr_cur == iter->eostr)\n return 1;\n\n while (!*(iter->substr_cur))\n iter->substr_cur++;\n iter->substr_end = strchr(iter->substr_cur, ',');\n if (!iter->substr_end)\n iter->substr_end = iter->eostr;\n else\n *(iter->substr_end) = '\\0';\n\n char *range_sep = strchr(iter->substr_cur, ':');\n if (range_sep)\n *range_sep++ = '\\0';\n\n if (mutt_str_atoui(iter->substr_cur, &iter->range_cur) != 0)\n return -1;\n if (range_sep)\n {\n if (mutt_str_atoui(range_sep, &iter->range_end) != 0)\n return -1;\n }\n else\n iter->range_end = iter->range_cur;\n\n iter->down = (iter->range_end < iter->range_cur);\n iter->in_range = 1;\n }\n\n *next = iter->range_cur;\n if (iter->down)\n iter->range_cur--;\n else\n iter->range_cur++;\n\n return 0;\n}", "func_hash": 257112514707438087045881839725941902548, "file_name": "util.c", "file_hash": 182862442973424291478090835977217355147, "cwe": ["CWE-125"], "cve": "CVE-2021-32055", "cve_desc": "Mutt 1.11.0 through 2.0.x before 2.0.7 (and NeoMutt 2019-10-25 through 2021-05-04) has a $imap_qresync issue in which imap/util.c has an out-of-bounds read in situations where an IMAP sequence set ends with a comma. NOTE: the $imap_qresync setting for QRESYNC is not enabled by default.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32055"} {"idx": 399279, "project": "neomutt", "commit_id": "fa1db5785e5cfd9d3cd27b7571b9fe268d2ec2dc", "project_url": "https://github.com/neomutt/neomutt", "commit_url": "https://github.com/neomutt/neomutt/commit/fa1db5785e5cfd9d3cd27b7571b9fe268d2ec2dc", "commit_message": "Fix seqset iterator when it ends in a comma\n\nIf the seqset ended with a comma, the substr_end marker would be just\nbefore the trailing nul. In the next call, the loop to skip the\nmarker would iterate right past the end of string too.\n\nThe fix is simple: place the substr_end marker and skip past it\nimmediately.", "target": 0, "func": "int mutt_seqset_iterator_next(struct SeqsetIterator *iter, unsigned int *next)\n{\n if (!iter || !next)\n return -1;\n\n if (iter->in_range)\n {\n if ((iter->down && (iter->range_cur == (iter->range_end - 1))) ||\n (!iter->down && (iter->range_cur == (iter->range_end + 1))))\n {\n iter->in_range = 0;\n }\n }\n\n if (!iter->in_range)\n {\n iter->substr_cur = iter->substr_end;\n if (iter->substr_cur == iter->eostr)\n return 1;\n\n iter->substr_end = strchr(iter->substr_cur, ',');\n if (!iter->substr_end)\n iter->substr_end = iter->eostr;\n else\n *(iter->substr_end++) = '\\0';\n\n char *range_sep = strchr(iter->substr_cur, ':');\n if (range_sep)\n *range_sep++ = '\\0';\n\n if (mutt_str_atoui(iter->substr_cur, &iter->range_cur) != 0)\n return -1;\n if (range_sep)\n {\n if (mutt_str_atoui(range_sep, &iter->range_end) != 0)\n return -1;\n }\n else\n iter->range_end = iter->range_cur;\n\n iter->down = (iter->range_end < iter->range_cur);\n iter->in_range = 1;\n }\n\n *next = iter->range_cur;\n if (iter->down)\n iter->range_cur--;\n else\n iter->range_cur++;\n\n return 0;\n}", "func_hash": 115544312171455919770050433822536511211, "file_name": "util.c", "file_hash": 291250013394246044813495982803953252555, "cwe": ["CWE-125"], "cve": "CVE-2021-32055", "cve_desc": "Mutt 1.11.0 through 2.0.x before 2.0.7 (and NeoMutt 2019-10-25 through 2021-05-04) has a $imap_qresync issue in which imap/util.c has an out-of-bounds read in situations where an IMAP sequence set ends with a comma. NOTE: the $imap_qresync setting for QRESYNC is not enabled by default.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32055"} {"idx": 207646, "project": "dpdk", "commit_id": "97ecc1c85c95c13bc66a87435758e93406c35c48", "project_url": "https://github.com/DPDK/dpdk", "commit_url": "https://git.dpdk.org/dpdk/commit/?id=97ecc1c85c95c13bc66a87435758e93406c35c48", "commit_message": "vhost: fix translated address not checked\n\nMalicious guest can construct desc with invalid address and zero buffer\nlength. That will request vhost to check both translated address and\ntranslated data length. This patch will add missed address check.\n\nCVE-2020-10725\nFixes: 75ed51697820 (\"vhost: add packed ring batch dequeue\")\nFixes: ef861692c398 (\"vhost: add packed ring batch enqueue\")\nCc: stable@dpdk.org\n\nSigned-off-by: Marvin Liu \nReviewed-by: Maxime Coquelin ", "target": 1, "func": "virtio_dev_rx_batch_packed(struct virtio_net *dev,\n\t\t\t struct vhost_virtqueue *vq,\n\t\t\t struct rte_mbuf **pkts)\n{\n\tbool wrap_counter = vq->avail_wrap_counter;\n\tstruct vring_packed_desc *descs = vq->desc_packed;\n\tuint16_t avail_idx = vq->last_avail_idx;\n\tuint64_t desc_addrs[PACKED_BATCH_SIZE];\n\tstruct virtio_net_hdr_mrg_rxbuf *hdrs[PACKED_BATCH_SIZE];\n\tuint32_t buf_offset = dev->vhost_hlen;\n\tuint64_t lens[PACKED_BATCH_SIZE];\n\tuint16_t ids[PACKED_BATCH_SIZE];\n\tuint16_t i;\n\n\tif (unlikely(avail_idx & PACKED_BATCH_MASK))\n\t\treturn -1;\n\n\tif (unlikely((avail_idx + PACKED_BATCH_SIZE) > vq->size))\n\t\treturn -1;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->next != NULL))\n\t\t\treturn -1;\n\t\tif (unlikely(!desc_is_avail(&descs[avail_idx + i],\n\t\t\t\t\t wrap_counter)))\n\t\t\treturn -1;\n\t}\n\n\trte_smp_rmb();\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tlens[i] = descs[avail_idx + i].len;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->pkt_len > (lens[i] - buf_offset)))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tdesc_addrs[i] = vhost_iova_to_vva(dev, vq,\n\t\t\t\t\t\t descs[avail_idx + i].addr,\n\t\t\t\t\t\t &lens[i],\n\t\t\t\t\t\t VHOST_ACCESS_RW);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(lens[i] != descs[avail_idx + i].len))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_prefetch0((void *)(uintptr_t)desc_addrs[i]);\n\t\thdrs[i] = (struct virtio_net_hdr_mrg_rxbuf *)\n\t\t\t\t\t(uintptr_t)desc_addrs[i];\n\t\tlens[i] = pkts[i]->pkt_len + dev->vhost_hlen;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvirtio_enqueue_offload(pkts[i], &hdrs[i]->hdr);\n\n\tvq_inc_last_avail_packed(vq, PACKED_BATCH_SIZE);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_memcpy((void *)(uintptr_t)(desc_addrs[i] + buf_offset),\n\t\t\t rte_pktmbuf_mtod_offset(pkts[i], void *, 0),\n\t\t\t pkts[i]->pkt_len);\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvhost_log_cache_write_iova(dev, vq, descs[avail_idx + i].addr,\n\t\t\t\t\t lens[i]);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tids[i] = descs[avail_idx + i].id;\n\n\tvhost_flush_enqueue_batch_packed(dev, vq, lens, ids);\n\n\treturn 0;\n}", "func_hash": 102453748518051213474151730781275698968, "file_name": "virtio_net.c", "file_hash": 334799408988785600589913806266401918539, "cwe": ["CWE-665"], "cve": "CVE-2020-10725", "cve_desc": "A flaw was found in DPDK version 19.11 and above that allows a malicious guest to cause a segmentation fault of the vhost-user backend application running on the host, which could result in a loss of connectivity for the other guests running on that host. This is caused by a missing validity check of the descriptor address in the function `virtio_dev_rx_batch_packed()`.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10725"} {"idx": 399931, "project": "dpdk", "commit_id": "97ecc1c85c95c13bc66a87435758e93406c35c48", "project_url": "https://github.com/DPDK/dpdk", "commit_url": "https://git.dpdk.org/dpdk/commit/?id=97ecc1c85c95c13bc66a87435758e93406c35c48", "commit_message": "vhost: fix translated address not checked\n\nMalicious guest can construct desc with invalid address and zero buffer\nlength. That will request vhost to check both translated address and\ntranslated data length. This patch will add missed address check.\n\nCVE-2020-10725\nFixes: 75ed51697820 (\"vhost: add packed ring batch dequeue\")\nFixes: ef861692c398 (\"vhost: add packed ring batch enqueue\")\nCc: stable@dpdk.org\n\nSigned-off-by: Marvin Liu \nReviewed-by: Maxime Coquelin ", "target": 0, "func": "virtio_dev_rx_batch_packed(struct virtio_net *dev,\n\t\t\t struct vhost_virtqueue *vq,\n\t\t\t struct rte_mbuf **pkts)\n{\n\tbool wrap_counter = vq->avail_wrap_counter;\n\tstruct vring_packed_desc *descs = vq->desc_packed;\n\tuint16_t avail_idx = vq->last_avail_idx;\n\tuint64_t desc_addrs[PACKED_BATCH_SIZE];\n\tstruct virtio_net_hdr_mrg_rxbuf *hdrs[PACKED_BATCH_SIZE];\n\tuint32_t buf_offset = dev->vhost_hlen;\n\tuint64_t lens[PACKED_BATCH_SIZE];\n\tuint16_t ids[PACKED_BATCH_SIZE];\n\tuint16_t i;\n\n\tif (unlikely(avail_idx & PACKED_BATCH_MASK))\n\t\treturn -1;\n\n\tif (unlikely((avail_idx + PACKED_BATCH_SIZE) > vq->size))\n\t\treturn -1;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->next != NULL))\n\t\t\treturn -1;\n\t\tif (unlikely(!desc_is_avail(&descs[avail_idx + i],\n\t\t\t\t\t wrap_counter)))\n\t\t\treturn -1;\n\t}\n\n\trte_smp_rmb();\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tlens[i] = descs[avail_idx + i].len;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->pkt_len > (lens[i] - buf_offset)))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tdesc_addrs[i] = vhost_iova_to_vva(dev, vq,\n\t\t\t\t\t\t descs[avail_idx + i].addr,\n\t\t\t\t\t\t &lens[i],\n\t\t\t\t\t\t VHOST_ACCESS_RW);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(!desc_addrs[i]))\n\t\t\treturn -1;\n\t\tif (unlikely(lens[i] != descs[avail_idx + i].len))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_prefetch0((void *)(uintptr_t)desc_addrs[i]);\n\t\thdrs[i] = (struct virtio_net_hdr_mrg_rxbuf *)\n\t\t\t\t\t(uintptr_t)desc_addrs[i];\n\t\tlens[i] = pkts[i]->pkt_len + dev->vhost_hlen;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvirtio_enqueue_offload(pkts[i], &hdrs[i]->hdr);\n\n\tvq_inc_last_avail_packed(vq, PACKED_BATCH_SIZE);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_memcpy((void *)(uintptr_t)(desc_addrs[i] + buf_offset),\n\t\t\t rte_pktmbuf_mtod_offset(pkts[i], void *, 0),\n\t\t\t pkts[i]->pkt_len);\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvhost_log_cache_write_iova(dev, vq, descs[avail_idx + i].addr,\n\t\t\t\t\t lens[i]);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tids[i] = descs[avail_idx + i].id;\n\n\tvhost_flush_enqueue_batch_packed(dev, vq, lens, ids);\n\n\treturn 0;\n}", "func_hash": 188928422674607432358756721051108139422, "file_name": "virtio_net.c", "file_hash": 85025136489883593128814721133827467594, "cwe": ["CWE-665"], "cve": "CVE-2020-10725", "cve_desc": "A flaw was found in DPDK version 19.11 and above that allows a malicious guest to cause a segmentation fault of the vhost-user backend application running on the host, which could result in a loss of connectivity for the other guests running on that host. This is caused by a missing validity check of the descriptor address in the function `virtio_dev_rx_batch_packed()`.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-10725"} {"idx": 207709, "project": "openssh-portable", "commit_id": "e04fd6dde16de1cdc5a4d9946397ff60d96568db", "project_url": "https://github.com/openssh/openssh-portable", "commit_url": "https://github.com/openssh/openssh-portable/commit/e04fd6dde16de1cdc5a4d9946397ff60d96568db", "commit_message": "upstream: factor SSH_AGENT_CONSTRAIN_EXTENSION parsing into its own\n\nfunction and remove an unused variable; ok dtucker@\n\nOpenBSD-Commit-ID: e1a938657fbf7ef0ba5e73b30365734a0cc96559", "target": 1, "func": "parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,\n u_int *secondsp, int *confirmp, char **sk_providerp)\n{\n\tu_char ctype;\n\tint r;\n\tu_int seconds, maxsign = 0;\n\tchar *ext_name = NULL;\n\tstruct sshbuf *b = NULL;\n\n\twhile (sshbuf_len(m)) {\n\t\tif ((r = sshbuf_get_u8(m, &ctype)) != 0) {\n\t\t\terror_fr(r, \"parse constraint type\");\n\t\t\tgoto err;\n\t\t}\n\t\tswitch (ctype) {\n\t\tcase SSH_AGENT_CONSTRAIN_LIFETIME:\n\t\t\tif (*deathp != 0) {\n\t\t\t\terror_f(\"lifetime already set\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &seconds)) != 0) {\n\t\t\t\terror_fr(r, \"parse lifetime constraint\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\t*deathp = monotime() + seconds;\n\t\t\t*secondsp = seconds;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_CONFIRM:\n\t\t\tif (*confirmp != 0) {\n\t\t\t\terror_f(\"confirm already set\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\t*confirmp = 1;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_MAXSIGN:\n\t\t\tif (k == NULL) {\n\t\t\t\terror_f(\"maxsign not valid here\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif (maxsign != 0) {\n\t\t\t\terror_f(\"maxsign already set\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"parse maxsign constraint\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"enable maxsign\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_EXTENSION:\n\t\t\tif ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {\n\t\t\t\terror_fr(r, \"parse constraint extension\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tdebug_f(\"constraint ext %s\", ext_name);\n\t\t\tif (strcmp(ext_name, \"sk-provider@openssh.com\") == 0) {\n\t\t\t\tif (sk_providerp == NULL) {\n\t\t\t\t\terror_f(\"%s not valid here\", ext_name);\n\t\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t\tif (*sk_providerp != NULL) {\n\t\t\t\t\terror_f(\"%s already set\", ext_name);\n\t\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t\tif ((r = sshbuf_get_cstring(m,\n\t\t\t\t sk_providerp, NULL)) != 0) {\n\t\t\t\t\terror_fr(r, \"parse %s\", ext_name);\n\t\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terror_f(\"unsupported constraint \\\"%s\\\"\",\n\t\t\t\t ext_name);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tfree(ext_name);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terror_f(\"Unknown constraint %d\", ctype);\n err:\n\t\t\tfree(ext_name);\n\t\t\tsshbuf_free(b);\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* success */\n\treturn 0;\n}", "func_hash": 290388599994091021538832116997941391254, "file_name": "ssh-agent.c", "file_hash": 87779332367907809549758324037987574976, "cwe": ["CWE-399"], "cve": "CVE-2021-28041", "cve_desc": "ssh-agent in OpenSSH before 8.5 has a double free that may be relevant in a few less-common scenarios, such as unconstrained agent-socket access on a legacy operating system, or the forwarding of an agent to an attacker-controlled host.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28041"} {"idx": 400219, "project": "openssh-portable", "commit_id": "e04fd6dde16de1cdc5a4d9946397ff60d96568db", "project_url": "https://github.com/openssh/openssh-portable", "commit_url": "https://github.com/openssh/openssh-portable/commit/e04fd6dde16de1cdc5a4d9946397ff60d96568db", "commit_message": "upstream: factor SSH_AGENT_CONSTRAIN_EXTENSION parsing into its own\n\nfunction and remove an unused variable; ok dtucker@\n\nOpenBSD-Commit-ID: e1a938657fbf7ef0ba5e73b30365734a0cc96559", "target": 0, "func": "parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,\n u_int *secondsp, int *confirmp, char **sk_providerp)\n{\n\tu_char ctype;\n\tint r;\n\tu_int seconds, maxsign = 0;\n\n\twhile (sshbuf_len(m)) {\n\t\tif ((r = sshbuf_get_u8(m, &ctype)) != 0) {\n\t\t\terror_fr(r, \"parse constraint type\");\n\t\t\tgoto out;\n\t\t}\n\t\tswitch (ctype) {\n\t\tcase SSH_AGENT_CONSTRAIN_LIFETIME:\n\t\t\tif (*deathp != 0) {\n\t\t\t\terror_f(\"lifetime already set\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &seconds)) != 0) {\n\t\t\t\terror_fr(r, \"parse lifetime constraint\");\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\t*deathp = monotime() + seconds;\n\t\t\t*secondsp = seconds;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_CONFIRM:\n\t\t\tif (*confirmp != 0) {\n\t\t\t\terror_f(\"confirm already set\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\t*confirmp = 1;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_MAXSIGN:\n\t\t\tif (k == NULL) {\n\t\t\t\terror_f(\"maxsign not valid here\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif (maxsign != 0) {\n\t\t\t\terror_f(\"maxsign already set\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"parse maxsign constraint\");\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"enable maxsign\");\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_EXTENSION:\n\t\t\tif ((r = parse_key_constraint_extension(m,\n\t\t\t sk_providerp)) != 0)\n\t\t\t\tgoto out; /* error already logged */\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terror_f(\"Unknown constraint %d\", ctype);\n\t\t\tr = SSH_ERR_FEATURE_UNSUPPORTED;\n\t\t\tgoto out;\n\t\t}\n\t}\n\t/* success */\n\tr = 0;\n out:\n\treturn r;\n}", "func_hash": 232574937102401113671684513760495292728, "file_name": "ssh-agent.c", "file_hash": 18065453139461798727973638100015895964, "cwe": ["CWE-399"], "cve": "CVE-2021-28041", "cve_desc": "ssh-agent in OpenSSH before 8.5 has a double free that may be relevant in a few less-common scenarios, such as unconstrained agent-socket access on a legacy operating system, or the forwarding of an agent to an attacker-controlled host.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28041"} {"idx": 207760, "project": "ghostpdl", "commit_id": "ef252e7dc214bcbd9a2539216aab9202848602bb", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=ef252e7dc214bcbd9a2539216aab9202848602bb", "commit_message": "Bug #700168 - add a type check\n\nBug #700168 \"Type confusion in JBIG2Decode\"\n\nThe code was assuming that .jbig2globalctx was a structure allocated\nby the graphics library, without checking.\n\nAdd a check to see that it is a structure and that its the correct\ntype of structure.", "target": 1, "func": "z_jbig2decode(i_ctx_t * i_ctx_p)\n{\n os_ptr op = osp;\n ref *sop = NULL;\n s_jbig2_global_data_t *gref;\n stream_jbig2decode_state state;\n\n /* Extract the global context reference, if any, from the parameter\n dictionary and embed it in our stream state. The original object\n ref is under the JBIG2Globals key.\n We expect the postscript code to resolve this and call\n z_jbig2makeglobalctx() below to create an astruct wrapping the\n global decoder data and store it under the .jbig2globalctx key\n */\n s_jbig2decode_set_global_data((stream_state*)&state, NULL);\n if (r_has_type(op, t_dictionary)) {\n check_dict_read(*op);\n if ( dict_find_string(op, \".jbig2globalctx\", &sop) > 0) {\n gref = r_ptr(sop, s_jbig2_global_data_t);\n s_jbig2decode_set_global_data((stream_state*)&state, gref);\n }\n }\n\n /* we pass npop=0, since we've no arguments left to consume */\n return filter_read(i_ctx_p, 0, &s_jbig2decode_template,\n (stream_state *) & state, (sop ? r_space(sop) : 0));\n}", "func_hash": 97329561179419003333279755223789841109, "file_name": "zfjbig2.c", "file_hash": 229460632376071204775166887684116270011, "cwe": ["CWE-704"], "cve": "CVE-2018-19477", "cve_desc": "psi/zfjbig2.c in Artifex Ghostscript before 9.26 allows remote attackers to bypass intended access restrictions because of a JBIG2Decode type confusion.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-19477"} {"idx": 400829, "project": "ghostpdl", "commit_id": "ef252e7dc214bcbd9a2539216aab9202848602bb", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=ef252e7dc214bcbd9a2539216aab9202848602bb", "commit_message": "Bug #700168 - add a type check\n\nBug #700168 \"Type confusion in JBIG2Decode\"\n\nThe code was assuming that .jbig2globalctx was a structure allocated\nby the graphics library, without checking.\n\nAdd a check to see that it is a structure and that its the correct\ntype of structure.", "target": 0, "func": "z_jbig2decode(i_ctx_t * i_ctx_p)\n{\n os_ptr op = osp;\n ref *sop = NULL;\n s_jbig2_global_data_t *gref;\n stream_jbig2decode_state state;\n\n /* Extract the global context reference, if any, from the parameter\n dictionary and embed it in our stream state. The original object\n ref is under the JBIG2Globals key.\n We expect the postscript code to resolve this and call\n z_jbig2makeglobalctx() below to create an astruct wrapping the\n global decoder data and store it under the .jbig2globalctx key\n */\n s_jbig2decode_set_global_data((stream_state*)&state, NULL);\n if (r_has_type(op, t_dictionary)) {\n check_dict_read(*op);\n if ( dict_find_string(op, \".jbig2globalctx\", &sop) > 0) {\n if (!r_is_struct(sop) || !r_has_stype(sop, imemory, st_jbig2_global_data_t))\n return_error(gs_error_typecheck);\n gref = r_ptr(sop, s_jbig2_global_data_t);\n s_jbig2decode_set_global_data((stream_state*)&state, gref);\n }\n }\n\n /* we pass npop=0, since we've no arguments left to consume */\n return filter_read(i_ctx_p, 0, &s_jbig2decode_template,\n (stream_state *) & state, (sop ? r_space(sop) : 0));\n}", "func_hash": 86435150776279333063814177787900349530, "file_name": "zfjbig2.c", "file_hash": 63233810997322384568647606475846249915, "cwe": ["CWE-704"], "cve": "CVE-2018-19477", "cve_desc": "psi/zfjbig2.c in Artifex Ghostscript before 9.26 allows remote attackers to bypass intended access restrictions because of a JBIG2Decode type confusion.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-19477"} {"idx": 207769, "project": "libvncserver", "commit_id": "57433015f856cc12753378254ce4f1c78f5d9c7b", "project_url": "https://github.com/LibVNC/libvncserver", "commit_url": "https://github.com/LibVNC/libvncserver/commit/57433015f856cc12753378254ce4f1c78f5d9c7b", "commit_message": "libvncclient: handle half-open TCP connections\n\nWhen a connection is not reset properly at the TCP level (e.g. sudden\npower loss or process crash) the TCP connection becomes half-open and\nread() always returns -1 with errno = EAGAIN while select() always\nreturns 0. This leads to an infinite loop and can be fixed by closing\nthe connection after a certain number of retries (based on a timeout)\nhas been exceeded.", "target": 1, "func": "ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)\n{\n#undef DEBUG_READ_EXACT\n#ifdef DEBUG_READ_EXACT\n\tchar* oout=out;\n\tunsigned int nn=n;\n\trfbClientLog(\"ReadFromRFBServer %d bytes\\n\",n);\n#endif\n\n /* Handle attempts to write to NULL out buffer that might occur\n when an outside malloc() fails. For instance, memcpy() to NULL\n results in undefined behaviour and probably memory corruption.*/\n if(!out)\n return FALSE;\n\n if (client->serverPort==-1) {\n /* vncrec playing */\n rfbVNCRec* rec = client->vncRec;\n struct timeval tv;\n\n if (rec->readTimestamp) {\n rec->readTimestamp = FALSE;\n if (!fread(&tv,sizeof(struct timeval),1,rec->file))\n return FALSE;\n\n tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);\n tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);\n\n if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {\n struct timeval diff;\n diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;\n diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;\n if(diff.tv_usec<0) {\n\t diff.tv_sec--;\n\t diff.tv_usec+=1000000;\n }\n#ifndef WIN32\n sleep (diff.tv_sec);\n usleep (diff.tv_usec);\n#else\n\tSleep (diff.tv_sec * 1000 + diff.tv_usec/1000);\n#endif\n }\n\n rec->tv=tv;\n }\n \n return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);\n }\n \n if (n <= client->buffered) {\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n#ifdef DEBUG_READ_EXACT\n goto hexdump;\n#endif\n return TRUE;\n }\n\n memcpy(out, client->bufoutptr, client->buffered);\n\n out += client->buffered;\n n -= client->buffered;\n\n client->bufoutptr = client->buf;\n client->buffered = 0;\n\n if (n <= RFB_BUF_SIZE) {\n\n while (client->buffered < n) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else {\n#endif /* LIBVNCSERVER_HAVE_SASL */\n i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n#ifdef WIN32\n\tif (i < 0) errno=WSAGetLastError();\n#endif\n#ifdef LIBVNCSERVER_HAVE_SASL\n }\n#endif\n \n if (i <= 0) {\n\tif (i < 0) {\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, 100000);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%d: %s)\\n\",errno,strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n client->buffered += i;\n }\n\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n\n } else {\n\n while (n > 0) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, out, n);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, out, n);\n else\n#endif\n i = read(client->sock, out, n);\n\n if (i <= 0) {\n\tif (i < 0) {\n#ifdef WIN32\n\t errno=WSAGetLastError();\n#endif\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, 100000);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%s)\\n\",strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n out += i;\n n -= i;\n }\n }\n\n#ifdef DEBUG_READ_EXACT\nhexdump:\n { unsigned int ii;\n for(ii=0;iiserverPort==-1) {\n /* vncrec playing */\n rfbVNCRec* rec = client->vncRec;\n struct timeval tv;\n\n if (rec->readTimestamp) {\n rec->readTimestamp = FALSE;\n if (!fread(&tv,sizeof(struct timeval),1,rec->file))\n return FALSE;\n\n tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);\n tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);\n\n if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {\n struct timeval diff;\n diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;\n diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;\n if(diff.tv_usec<0) {\n\t diff.tv_sec--;\n\t diff.tv_usec+=1000000;\n }\n#ifndef WIN32\n sleep (diff.tv_sec);\n usleep (diff.tv_usec);\n#else\n\tSleep (diff.tv_sec * 1000 + diff.tv_usec/1000);\n#endif\n }\n\n rec->tv=tv;\n }\n \n return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);\n }\n \n if (n <= client->buffered) {\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n#ifdef DEBUG_READ_EXACT\n goto hexdump;\n#endif\n return TRUE;\n }\n\n memcpy(out, client->bufoutptr, client->buffered);\n\n out += client->buffered;\n n -= client->buffered;\n\n client->bufoutptr = client->buf;\n client->buffered = 0;\n\n if (n <= RFB_BUF_SIZE) {\n\n while (client->buffered < n) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else {\n#endif /* LIBVNCSERVER_HAVE_SASL */\n i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n#ifdef WIN32\n\tif (i < 0) errno=WSAGetLastError();\n#endif\n#ifdef LIBVNCSERVER_HAVE_SASL\n }\n#endif\n \n if (i <= 0) {\n\tif (i < 0) {\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t if (client->readTimeout > 0 &&\n\t\t++retries > (client->readTimeout * 1000 * 1000 / USECS_WAIT_PER_RETRY))\n\t {\n\t rfbClientLog(\"Connection timed out\\n\");\n\t return FALSE;\n\t }\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, USECS_WAIT_PER_RETRY);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%d: %s)\\n\",errno,strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n client->buffered += i;\n }\n\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n\n } else {\n\n while (n > 0) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, out, n);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, out, n);\n else\n#endif\n i = read(client->sock, out, n);\n\n if (i <= 0) {\n\tif (i < 0) {\n#ifdef WIN32\n\t errno=WSAGetLastError();\n#endif\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t if (client->readTimeout > 0 &&\n\t\t++retries > (client->readTimeout * 1000 * 1000 / USECS_WAIT_PER_RETRY))\n\t {\n\t\trfbClientLog(\"Connection timed out\\n\");\n\t\treturn FALSE;\n\t }\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, USECS_WAIT_PER_RETRY);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%s)\\n\",strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n out += i;\n n -= i;\n }\n }\n\n#ifdef DEBUG_READ_EXACT\nhexdump:\n { unsigned int ii;\n for(ii=0;ii= rowDelta)\n\t\t\t{\n\t\t\t\tfFirstLine = FALSE;\n\t\t\t\tfInsertFgPel = FALSE;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t Extract the compression order code ID from the compression\n\t\t order header.\n\t\t*/\n\t\tcode = ExtractCodeId(*pbSrc);\n\n\t\t/* Handle Background Run Orders. */\n\t\tif (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN)\n\t\t{\n\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\tif (fFirstLine)\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength = runLength - 1;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength--;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t/* A follow-on background run order will need a foreground pel inserted. */\n\t\t\tfInsertFgPel = TRUE;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* For any of the other run-types a follow-on background run\n\t\t order does not need a foreground pel inserted. */\n\t\tfInsertFgPel = FALSE;\n\n\t\tswitch (code)\n\t\t{\n\t\t\t/* Handle Foreground Run Orders. */\n\t\t\tcase REGULAR_FG_RUN:\n\t\t\tcase MEGA_MEGA_FG_RUN:\n\t\t\tcase LITE_SET_FG_FG_RUN:\n\t\t\tcase MEGA_MEGA_SET_FG_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN)\n\t\t\t\t{\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Dithered Run Orders. */\n\t\t\tcase LITE_DITHERED_RUN:\n\t\t\tcase MEGA_MEGA_DITHERED_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\tSRCREADPIXEL(pixelB, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelB);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Run Orders. */\n\t\t\tcase REGULAR_COLOR_RUN:\n\t\t\tcase MEGA_MEGA_COLOR_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Foreground/Background Image Orders. */\n\t\t\tcase REGULAR_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_FGBG_IMAGE:\n\t\t\tcase LITE_SET_FG_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_SET_FGBG_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE)\n\t\t\t\t{\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (runLength > 0)\n\t\t\t\t{\n\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\t\tif (fFirstLine)\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Image Orders. */\n\t\t\tcase REGULAR_COLOR_IMAGE:\n\t\t\tcase MEGA_MEGA_COLOR_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tSRCREADPIXEL(temp, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 1. */\n\t\t\tcase SPECIAL_FGBG_1:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 2. */\n\t\t\tcase SPECIAL_FGBG_2:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle White Order. */\n\t\t\tcase SPECIAL_WHITE:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, WHITE_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Black Order. */\n\t\t\tcase SPECIAL_BLACK:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}", "func_hash": 331442662922212710095771286967091287297, "file_name": "bitmap.c", "file_hash": 240388249285142606906928254622016487642, "cwe": ["CWE-125"], "cve": "CVE-2020-4033", "cve_desc": "In FreeRDP before version 2.1.2, there is an out of bounds read in RLEDECOMPRESS. All FreeRDP based clients with sessions with color depth < 32 are affected. This is fixed in version 2.1.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-4033"} {"idx": 402135, "project": "FreeRDP", "commit_id": "0a98c450c58ec150e44781c89aa6f8e7e0f571f5", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/0a98c450c58ec150e44781c89aa6f8e7e0f571f5", "commit_message": "Fixed out of bound read in RLEDECOMPRESS\n\nCVE-2020-4033 thanks to @antonio-morales for finding this.", "target": 0, "func": "static INLINE BOOL RLEDECOMPRESS(const BYTE* pbSrcBuffer, UINT32 cbSrcBuffer, BYTE* pbDestBuffer,\n UINT32 rowDelta, UINT32 width, UINT32 height)\n{\n\tconst BYTE* pbSrc = pbSrcBuffer;\n\tconst BYTE* pbEnd;\n\tconst BYTE* pbDestEnd;\n\tBYTE* pbDest = pbDestBuffer;\n\tPIXEL temp;\n\tPIXEL fgPel = WHITE_PIXEL;\n\tBOOL fInsertFgPel = FALSE;\n\tBOOL fFirstLine = TRUE;\n\tBYTE bitmask;\n\tPIXEL pixelA, pixelB;\n\tUINT32 runLength;\n\tUINT32 code;\n\tUINT32 advance;\n\tRLEEXTRA\n\n\tif ((rowDelta == 0) || (rowDelta < width))\n\t\treturn FALSE;\n\n\tif (!pbSrcBuffer || !pbDestBuffer)\n\t\treturn FALSE;\n\n\tpbEnd = pbSrcBuffer + cbSrcBuffer;\n\tpbDestEnd = pbDestBuffer + rowDelta * height;\n\n\twhile (pbSrc < pbEnd)\n\t{\n\t\t/* Watch out for the end of the first scanline. */\n\t\tif (fFirstLine)\n\t\t{\n\t\t\tif ((UINT32)(pbDest - pbDestBuffer) >= rowDelta)\n\t\t\t{\n\t\t\t\tfFirstLine = FALSE;\n\t\t\t\tfInsertFgPel = FALSE;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t Extract the compression order code ID from the compression\n\t\t order header.\n\t\t*/\n\t\tcode = ExtractCodeId(*pbSrc);\n\n\t\t/* Handle Background Run Orders. */\n\t\tif (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN)\n\t\t{\n\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\tif (fFirstLine)\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength = runLength - 1;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength--;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t/* A follow-on background run order will need a foreground pel inserted. */\n\t\t\tfInsertFgPel = TRUE;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* For any of the other run-types a follow-on background run\n\t\t order does not need a foreground pel inserted. */\n\t\tfInsertFgPel = FALSE;\n\n\t\tswitch (code)\n\t\t{\n\t\t\t/* Handle Foreground Run Orders. */\n\t\t\tcase REGULAR_FG_RUN:\n\t\t\tcase MEGA_MEGA_FG_RUN:\n\t\t\tcase LITE_SET_FG_FG_RUN:\n\t\t\tcase MEGA_MEGA_SET_FG_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN)\n\t\t\t\t{\n\t\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Dithered Run Orders. */\n\t\t\tcase LITE_DITHERED_RUN:\n\t\t\tcase MEGA_MEGA_DITHERED_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tSRCREADPIXEL(pixelB, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelB);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Run Orders. */\n\t\t\tcase REGULAR_COLOR_RUN:\n\t\t\tcase MEGA_MEGA_COLOR_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Foreground/Background Image Orders. */\n\t\t\tcase REGULAR_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_FGBG_IMAGE:\n\t\t\tcase LITE_SET_FG_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_SET_FGBG_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tif (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE)\n\t\t\t\t{\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (runLength > 0)\n\t\t\t\t{\n\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\t\tif (fFirstLine)\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Image Orders. */\n\t\t\tcase REGULAR_COLOR_IMAGE:\n\t\t\tcase MEGA_MEGA_COLOR_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\tSRCREADPIXEL(temp, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 1. */\n\t\t\tcase SPECIAL_FGBG_1:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 2. */\n\t\t\tcase SPECIAL_FGBG_2:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle White Order. */\n\t\t\tcase SPECIAL_WHITE:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, WHITE_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Black Order. */\n\t\t\tcase SPECIAL_BLACK:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}", "func_hash": 330868354547923912162511443116069597288, "file_name": "bitmap.c", "file_hash": 143788789463402519338648204370894043846, "cwe": ["CWE-125"], "cve": "CVE-2020-4033", "cve_desc": "In FreeRDP before version 2.1.2, there is an out of bounds read in RLEDECOMPRESS. All FreeRDP based clients with sessions with color depth < 32 are affected. This is fixed in version 2.1.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-4033"} {"idx": 207837, "project": "htslib", "commit_id": "dcd4b7304941a8832fba2d0fc4c1e716e7a4e72c", "project_url": "https://github.com/samtools/htslib", "commit_url": "https://github.com/samtools/htslib/commit/dcd4b7304941a8832fba2d0fc4c1e716e7a4e72c", "commit_message": "Fix check for VCF record size\n\nThe check for excessive record size in vcf_parse_format() only\nlooked at individual fields. It was therefore possible to\nexceed the limit and overflow fmt_aux_t::offset by having\nmultiple fields with a combined size that went over INT_MAX.\nFix by including the amount of memory used so far in the check.\n\nCredit to OSS-Fuzz\nFixes oss-fuzz 24097", "target": 1, "func": "static int vcf_parse_format(kstring_t *s, const bcf_hdr_t *h, bcf1_t *v, char *p, char *q)\n{\n if ( !bcf_hdr_nsamples(h) ) return 0;\n\n static int extreme_val_warned = 0;\n char *r, *t;\n int j, l, m, g, overflow = 0;\n khint_t k;\n ks_tokaux_t aux1;\n vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID];\n kstring_t *mem = (kstring_t*)&h->mem;\n fmt_aux_t fmt[MAX_N_FMT];\n mem->l = 0;\n\n char *end = s->s + s->l;\n if ( q>=end )\n {\n hts_log_error(\"FORMAT column with no sample columns starting at %s:%\"PRIhts_pos\"\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n\n v->n_fmt = 0;\n if ( p[0]=='.' && p[1]==0 ) // FORMAT field is empty \".\"\n {\n v->n_sample = bcf_hdr_nsamples(h);\n return 0;\n }\n\n // get format information from the dictionary\n for (j = 0, t = kstrtok(p, \":\", &aux1); t; t = kstrtok(0, 0, &aux1), ++j) {\n if (j >= MAX_N_FMT) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"FORMAT column at %s:%\"PRIhts_pos\" lists more identifiers than htslib can handle\",\n bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n\n *(char*)aux1.p = 0;\n k = kh_get(vdict, d, t);\n if (k == kh_end(d) || kh_val(d, k).info[BCF_HL_FMT] == 15) {\n if ( t[0]=='.' && t[1]==0 )\n {\n hts_log_error(\"Invalid FORMAT tag name '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n hts_log_warning(\"FORMAT '%s' at %s:%\"PRIhts_pos\" is not defined in the header, assuming Type=String\", t, bcf_seqname_safe(h,v), v->pos+1);\n kstring_t tmp = {0,0,0};\n int l;\n ksprintf(&tmp, \"##FORMAT=\", t);\n bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);\n free(tmp.s);\n int res = hrec ? bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) : -1;\n if (res < 0) bcf_hrec_destroy(hrec);\n if (res > 0) res = bcf_hdr_sync((bcf_hdr_t*)h);\n\n k = kh_get(vdict, d, t);\n v->errcode = BCF_ERR_TAG_UNDEF;\n if (res || k == kh_end(d)) {\n hts_log_error(\"Could not add dummy header for FORMAT '%s' at %s:%\"PRIhts_pos, t, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n }\n fmt[j].max_l = fmt[j].max_m = fmt[j].max_g = 0;\n fmt[j].key = kh_val(d, k).id;\n fmt[j].is_gt = !strcmp(t, \"GT\");\n fmt[j].y = h->id[0][fmt[j].key].val->info[BCF_HL_FMT];\n v->n_fmt++;\n }\n // compute max\n int n_sample_ori = -1;\n r = q + 1; // r: position in the format string\n l = 0, m = g = 1, v->n_sample = 0; // m: max vector size, l: max field len, g: max number of alleles\n while ( rkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *r!='\\t' && ris_gt) g++;\n break;\n\n case '\\t':\n *r = 0; // fall through\n\n case '\\0':\n case ':':\n if (f->max_m < m) f->max_m = m;\n if (f->max_l < l) f->max_l = l;\n if (f->is_gt && f->max_g < g) f->max_g = g;\n l = 0, m = g = 1;\n if ( *r==':' ) {\n j++; f++;\n if ( j>=v->n_fmt ) {\n hts_log_error(\"Incorrect number of FORMAT fields at %s:%\"PRIhts_pos\"\",\n h->id[BCF_DT_CTG][v->rid].key, v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n } else goto end_for;\n break;\n }\n if ( r>=end ) break;\n r++; l++;\n }\n end_for:\n v->n_sample++;\n if ( v->n_sample == bcf_hdr_nsamples(h) ) break;\n r++;\n }\n\n // allocate memory for arrays\n for (j = 0; j < v->n_fmt; ++j) {\n fmt_aux_t *f = &fmt[j];\n if ( !f->max_m ) f->max_m = 1; // omitted trailing format field\n if ((f->y>>4&0xf) == BCF_HT_STR) {\n f->size = f->is_gt? f->max_g << 2 : f->max_l;\n } else if ((f->y>>4&0xf) == BCF_HT_REAL || (f->y>>4&0xf) == BCF_HT_INT) {\n f->size = f->max_m << 2;\n } else\n {\n hts_log_error(\"The format type %d at %s:%\"PRIhts_pos\" is currently not supported\", f->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n if (align_mem(mem) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n f->offset = mem->l;\n\n // Limit the total memory to ~2Gb per VCF row. This should mean\n // malformed VCF data is less likely to take excessive memory and/or\n // time.\n if (v->n_sample * (uint64_t)f->size > INT_MAX) {\n hts_log_error(\"Excessive memory required by FORMAT fields at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n if (ks_resize(mem, mem->l + v->n_sample * (size_t)f->size) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n mem->l += v->n_sample * f->size;\n }\n for (j = 0; j < v->n_fmt; ++j)\n fmt[j].buf = (uint8_t*)mem->s + fmt[j].offset;\n // fill the sample fields; at beginning of the loop, t points to the first char of a format\n n_sample_ori = -1;\n t = q + 1; m = 0; // m: sample id\n while ( tkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *t && tbuf) {\n hts_log_error(\"Memory allocation failure for FORMAT field type %d at %s:%\"PRIhts_pos,\n z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) { // genotypes\n int32_t is_phased = 0;\n uint32_t *x = (uint32_t*)(z->buf + z->size * (size_t)m);\n uint32_t unreadable = 0;\n uint32_t max = 0;\n overflow = 0;\n for (l = 0;; ++t) {\n if (*t == '.') {\n ++t, x[l++] = is_phased;\n } else {\n char *tt = t;\n uint32_t val = hts_str2uint(t, &t, sizeof(val) * CHAR_MAX - 2, &overflow);\n unreadable |= tt == t;\n if (max < val) max = val;\n x[l++] = (val + 1) << 1 | is_phased;\n }\n is_phased = (*t == '|');\n if (*t != '|' && *t != '/') break;\n }\n // Possibly check max against v->n_allele instead?\n if (overflow || max > (INT32_MAX >> 1) - 1) {\n hts_log_error(\"Couldn't read GT data: value too large at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if (unreadable) {\n hts_log_error(\"Couldn't read GT data: value not a number or '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if ( !l ) x[l++] = 0; // An empty field, insert missing value\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n for (r = t, l = 0; *t != ':' && *t; ++t) x[l++] = *t;\n for (; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.') {\n x[l++] = bcf_int32_missing, ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n long int tmp_val = hts_str2int(t, &te, sizeof(tmp_val)*CHAR_BIT, &overflow);\n if ( te==t || overflow || tmp_valBCF_MAX_BT_INT32 )\n {\n if ( !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered and set to missing at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname_safe(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n tmp_val = bcf_int32_missing;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) x[l++] = bcf_int32_missing;\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.' && !isdigit_c(t[1])) {\n bcf_float_set_missing(x[l++]), ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n float tmp_val = hts_str2dbl(t, &te, &overflow);\n if ( (te==t || overflow) && !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) bcf_float_set_missing(x[l++]); // An empty field, insert missing value\n for (; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n } else {\n hts_log_error(\"Unknown FORMAT field type %d at %s:%\"PRIhts_pos, z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n\n if (*t == '\\0') {\n break;\n }\n else if (*t == ':') {\n t++;\n }\n else {\n char buffer[8];\n hts_log_error(\"Invalid character %s in '%s' FORMAT field at %s:%\"PRIhts_pos\"\",\n hts_strprint(buffer, sizeof buffer, '\\'', t, 1),\n h->id[BCF_DT_ID][z->key].key, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_CHAR;\n return -1;\n }\n }\n\n for (; j < v->n_fmt; ++j) { // fill end-of-vector values\n fmt_aux_t *z = &fmt[j];\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n if (z->size) x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n if ( z->size ) x[0] = '.';\n for (l = 1; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n bcf_float_set_missing(x[0]);\n for (l = 1; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n }\n }\n\n m++; t++;\n }\n\n // write individual genotype information\n kstring_t *str = &v->indiv;\n int i;\n if (v->n_sample > 0) {\n for (i = 0; i < v->n_fmt; ++i) {\n fmt_aux_t *z = &fmt[i];\n bcf_enc_int1(str, z->key);\n if ((z->y>>4&0xf) == BCF_HT_STR && !z->is_gt) {\n bcf_enc_size(str, z->size, BCF_BT_CHAR);\n kputsn((char*)z->buf, z->size * (size_t)v->n_sample, str);\n } else if ((z->y>>4&0xf) == BCF_HT_INT || z->is_gt) {\n bcf_enc_vint(str, (z->size>>2) * v->n_sample, (int32_t*)z->buf, z->size>>2);\n } else {\n bcf_enc_size(str, z->size>>2, BCF_BT_FLOAT);\n if (serialize_float_array(str, (z->size>>2) * (size_t)v->n_sample,\n (float *) z->buf) != 0) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"Out of memory at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n }\n }\n }\n\n if ( v->n_sample!=bcf_hdr_nsamples(h) )\n {\n hts_log_error(\"Number of columns at %s:%\"PRIhts_pos\" does not match the number of samples (%d vs %d)\",\n bcf_seqname_safe(h,v), v->pos+1, v->n_sample, bcf_hdr_nsamples(h));\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n if ( v->indiv.l > 0xffffffff )\n {\n hts_log_error(\"The FORMAT at %s:%\"PRIhts_pos\" is too long\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n\n // Error recovery: return -1 if this is a critical error or 0 if we want to ignore the FORMAT and proceed\n v->n_fmt = 0;\n return -1;\n }\n\n return 0;\n}", "func_hash": 96050944124671021810367137301841765076, "file_name": "vcf.c", "file_hash": 216202403731898608128777271004350100032, "cwe": ["CWE-787"], "cve": "CVE-2020-36403", "cve_desc": "HTSlib through 1.10.2 allows out-of-bounds write access in vcf_parse_format (called from vcf_parse and vcf_read).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36403"} {"idx": 402146, "project": "htslib", "commit_id": "dcd4b7304941a8832fba2d0fc4c1e716e7a4e72c", "project_url": "https://github.com/samtools/htslib", "commit_url": "https://github.com/samtools/htslib/commit/dcd4b7304941a8832fba2d0fc4c1e716e7a4e72c", "commit_message": "Fix check for VCF record size\n\nThe check for excessive record size in vcf_parse_format() only\nlooked at individual fields. It was therefore possible to\nexceed the limit and overflow fmt_aux_t::offset by having\nmultiple fields with a combined size that went over INT_MAX.\nFix by including the amount of memory used so far in the check.\n\nCredit to OSS-Fuzz\nFixes oss-fuzz 24097", "target": 0, "func": "static int vcf_parse_format(kstring_t *s, const bcf_hdr_t *h, bcf1_t *v, char *p, char *q)\n{\n if ( !bcf_hdr_nsamples(h) ) return 0;\n\n static int extreme_val_warned = 0;\n char *r, *t;\n int j, l, m, g, overflow = 0;\n khint_t k;\n ks_tokaux_t aux1;\n vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID];\n kstring_t *mem = (kstring_t*)&h->mem;\n fmt_aux_t fmt[MAX_N_FMT];\n mem->l = 0;\n\n char *end = s->s + s->l;\n if ( q>=end )\n {\n hts_log_error(\"FORMAT column with no sample columns starting at %s:%\"PRIhts_pos\"\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n\n v->n_fmt = 0;\n if ( p[0]=='.' && p[1]==0 ) // FORMAT field is empty \".\"\n {\n v->n_sample = bcf_hdr_nsamples(h);\n return 0;\n }\n\n // get format information from the dictionary\n for (j = 0, t = kstrtok(p, \":\", &aux1); t; t = kstrtok(0, 0, &aux1), ++j) {\n if (j >= MAX_N_FMT) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"FORMAT column at %s:%\"PRIhts_pos\" lists more identifiers than htslib can handle\",\n bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n\n *(char*)aux1.p = 0;\n k = kh_get(vdict, d, t);\n if (k == kh_end(d) || kh_val(d, k).info[BCF_HL_FMT] == 15) {\n if ( t[0]=='.' && t[1]==0 )\n {\n hts_log_error(\"Invalid FORMAT tag name '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n hts_log_warning(\"FORMAT '%s' at %s:%\"PRIhts_pos\" is not defined in the header, assuming Type=String\", t, bcf_seqname_safe(h,v), v->pos+1);\n kstring_t tmp = {0,0,0};\n int l;\n ksprintf(&tmp, \"##FORMAT=\", t);\n bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);\n free(tmp.s);\n int res = hrec ? bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) : -1;\n if (res < 0) bcf_hrec_destroy(hrec);\n if (res > 0) res = bcf_hdr_sync((bcf_hdr_t*)h);\n\n k = kh_get(vdict, d, t);\n v->errcode = BCF_ERR_TAG_UNDEF;\n if (res || k == kh_end(d)) {\n hts_log_error(\"Could not add dummy header for FORMAT '%s' at %s:%\"PRIhts_pos, t, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n }\n fmt[j].max_l = fmt[j].max_m = fmt[j].max_g = 0;\n fmt[j].key = kh_val(d, k).id;\n fmt[j].is_gt = !strcmp(t, \"GT\");\n fmt[j].y = h->id[0][fmt[j].key].val->info[BCF_HL_FMT];\n v->n_fmt++;\n }\n // compute max\n int n_sample_ori = -1;\n r = q + 1; // r: position in the format string\n l = 0, m = g = 1, v->n_sample = 0; // m: max vector size, l: max field len, g: max number of alleles\n while ( rkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *r!='\\t' && ris_gt) g++;\n break;\n\n case '\\t':\n *r = 0; // fall through\n\n case '\\0':\n case ':':\n if (f->max_m < m) f->max_m = m;\n if (f->max_l < l) f->max_l = l;\n if (f->is_gt && f->max_g < g) f->max_g = g;\n l = 0, m = g = 1;\n if ( *r==':' ) {\n j++; f++;\n if ( j>=v->n_fmt ) {\n hts_log_error(\"Incorrect number of FORMAT fields at %s:%\"PRIhts_pos\"\",\n h->id[BCF_DT_CTG][v->rid].key, v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n } else goto end_for;\n break;\n }\n if ( r>=end ) break;\n r++; l++;\n }\n end_for:\n v->n_sample++;\n if ( v->n_sample == bcf_hdr_nsamples(h) ) break;\n r++;\n }\n\n // allocate memory for arrays\n for (j = 0; j < v->n_fmt; ++j) {\n fmt_aux_t *f = &fmt[j];\n if ( !f->max_m ) f->max_m = 1; // omitted trailing format field\n if ((f->y>>4&0xf) == BCF_HT_STR) {\n f->size = f->is_gt? f->max_g << 2 : f->max_l;\n } else if ((f->y>>4&0xf) == BCF_HT_REAL || (f->y>>4&0xf) == BCF_HT_INT) {\n f->size = f->max_m << 2;\n } else\n {\n hts_log_error(\"The format type %d at %s:%\"PRIhts_pos\" is currently not supported\", f->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n if (align_mem(mem) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n\n // Limit the total memory to ~2Gb per VCF row. This should mean\n // malformed VCF data is less likely to take excessive memory and/or\n // time.\n if ((uint64_t) mem->l + v->n_sample * (uint64_t)f->size > INT_MAX) {\n hts_log_error(\"Excessive memory required by FORMAT fields at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n\n f->offset = mem->l;\n if (ks_resize(mem, mem->l + v->n_sample * (size_t)f->size) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n mem->l += v->n_sample * f->size;\n }\n for (j = 0; j < v->n_fmt; ++j)\n fmt[j].buf = (uint8_t*)mem->s + fmt[j].offset;\n // fill the sample fields; at beginning of the loop, t points to the first char of a format\n n_sample_ori = -1;\n t = q + 1; m = 0; // m: sample id\n while ( tkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *t && tbuf) {\n hts_log_error(\"Memory allocation failure for FORMAT field type %d at %s:%\"PRIhts_pos,\n z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) { // genotypes\n int32_t is_phased = 0;\n uint32_t *x = (uint32_t*)(z->buf + z->size * (size_t)m);\n uint32_t unreadable = 0;\n uint32_t max = 0;\n overflow = 0;\n for (l = 0;; ++t) {\n if (*t == '.') {\n ++t, x[l++] = is_phased;\n } else {\n char *tt = t;\n uint32_t val = hts_str2uint(t, &t, sizeof(val) * CHAR_MAX - 2, &overflow);\n unreadable |= tt == t;\n if (max < val) max = val;\n x[l++] = (val + 1) << 1 | is_phased;\n }\n is_phased = (*t == '|');\n if (*t != '|' && *t != '/') break;\n }\n // Possibly check max against v->n_allele instead?\n if (overflow || max > (INT32_MAX >> 1) - 1) {\n hts_log_error(\"Couldn't read GT data: value too large at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if (unreadable) {\n hts_log_error(\"Couldn't read GT data: value not a number or '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if ( !l ) x[l++] = 0; // An empty field, insert missing value\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n for (r = t, l = 0; *t != ':' && *t; ++t) x[l++] = *t;\n for (; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.') {\n x[l++] = bcf_int32_missing, ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n long int tmp_val = hts_str2int(t, &te, sizeof(tmp_val)*CHAR_BIT, &overflow);\n if ( te==t || overflow || tmp_valBCF_MAX_BT_INT32 )\n {\n if ( !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered and set to missing at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname_safe(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n tmp_val = bcf_int32_missing;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) x[l++] = bcf_int32_missing;\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.' && !isdigit_c(t[1])) {\n bcf_float_set_missing(x[l++]), ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n float tmp_val = hts_str2dbl(t, &te, &overflow);\n if ( (te==t || overflow) && !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) bcf_float_set_missing(x[l++]); // An empty field, insert missing value\n for (; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n } else {\n hts_log_error(\"Unknown FORMAT field type %d at %s:%\"PRIhts_pos, z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n\n if (*t == '\\0') {\n break;\n }\n else if (*t == ':') {\n t++;\n }\n else {\n char buffer[8];\n hts_log_error(\"Invalid character %s in '%s' FORMAT field at %s:%\"PRIhts_pos\"\",\n hts_strprint(buffer, sizeof buffer, '\\'', t, 1),\n h->id[BCF_DT_ID][z->key].key, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_CHAR;\n return -1;\n }\n }\n\n for (; j < v->n_fmt; ++j) { // fill end-of-vector values\n fmt_aux_t *z = &fmt[j];\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n if (z->size) x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n if ( z->size ) x[0] = '.';\n for (l = 1; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n bcf_float_set_missing(x[0]);\n for (l = 1; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n }\n }\n\n m++; t++;\n }\n\n // write individual genotype information\n kstring_t *str = &v->indiv;\n int i;\n if (v->n_sample > 0) {\n for (i = 0; i < v->n_fmt; ++i) {\n fmt_aux_t *z = &fmt[i];\n bcf_enc_int1(str, z->key);\n if ((z->y>>4&0xf) == BCF_HT_STR && !z->is_gt) {\n bcf_enc_size(str, z->size, BCF_BT_CHAR);\n kputsn((char*)z->buf, z->size * (size_t)v->n_sample, str);\n } else if ((z->y>>4&0xf) == BCF_HT_INT || z->is_gt) {\n bcf_enc_vint(str, (z->size>>2) * v->n_sample, (int32_t*)z->buf, z->size>>2);\n } else {\n bcf_enc_size(str, z->size>>2, BCF_BT_FLOAT);\n if (serialize_float_array(str, (z->size>>2) * (size_t)v->n_sample,\n (float *) z->buf) != 0) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"Out of memory at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n }\n }\n }\n\n if ( v->n_sample!=bcf_hdr_nsamples(h) )\n {\n hts_log_error(\"Number of columns at %s:%\"PRIhts_pos\" does not match the number of samples (%d vs %d)\",\n bcf_seqname_safe(h,v), v->pos+1, v->n_sample, bcf_hdr_nsamples(h));\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n if ( v->indiv.l > 0xffffffff )\n {\n hts_log_error(\"The FORMAT at %s:%\"PRIhts_pos\" is too long\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n\n // Error recovery: return -1 if this is a critical error or 0 if we want to ignore the FORMAT and proceed\n v->n_fmt = 0;\n return -1;\n }\n\n return 0;\n}", "func_hash": 247118421720785064406404220065020270945, "file_name": "vcf.c", "file_hash": 301587879802561524090485814007478108088, "cwe": ["CWE-787"], "cve": "CVE-2020-36403", "cve_desc": "HTSlib through 1.10.2 allows out-of-bounds write access in vcf_parse_format (called from vcf_parse and vcf_read).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36403"} {"idx": 207859, "project": "linux", "commit_id": "e2cb6b891ad2b8caa9131e3be70f45243df82a80", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e2cb6b891ad2b8caa9131e3be70f45243df82a80", "commit_message": "bluetooth: eliminate the potential race condition when removing the HCI controller\n\nThere is a possible race condition vulnerability between issuing a HCI\ncommand and removing the cont. Specifically, functions hci_req_sync()\nand hci_dev_do_close() can race each other like below:\n\nthread-A in hci_req_sync() | thread-B in hci_dev_do_close()\n | hci_req_sync_lock(hdev);\ntest_bit(HCI_UP, &hdev->flags); |\n... | test_and_clear_bit(HCI_UP, &hdev->flags)\nhci_req_sync_lock(hdev); |\n |\nIn this commit we alter the sequence in function hci_req_sync(). Hence,\nthe thread-A cannot issue th.\n\nSigned-off-by: Lin Ma \nCc: Marcel Holtmann \nFixes: 7c6a329e4447 (\"[Bluetooth] Fix regression from using default link policy\")\nSigned-off-by: Greg Kroah-Hartman ", "target": 1, "func": "int hci_req_sync(struct hci_dev *hdev, int (*req)(struct hci_request *req,\n\t\t\t\t\t\t unsigned long opt),\n\t\t unsigned long opt, u32 timeout, u8 *hci_status)\n{\n\tint ret;\n\n\tif (!test_bit(HCI_UP, &hdev->flags))\n\t\treturn -ENETDOWN;\n\n\t/* Serialize all requests */\n\thci_req_sync_lock(hdev);\n\tret = __hci_req_sync(hdev, req, opt, timeout, hci_status);\n\thci_req_sync_unlock(hdev);\n\n\treturn ret;\n}", "func_hash": 313619269789088565138626382025894609870, "file_name": "None", "file_hash": null, "cwe": ["CWE-362"], "cve": "CVE-2021-32399", "cve_desc": "net/bluetooth/hci_request.c in the Linux kernel through 5.12.2 has a race condition for removal of the HCI controller.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32399"} {"idx": 402494, "project": "linux", "commit_id": "e2cb6b891ad2b8caa9131e3be70f45243df82a80", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e2cb6b891ad2b8caa9131e3be70f45243df82a80", "commit_message": "bluetooth: eliminate the potential race condition when removing the HCI controller\n\nThere is a possible race condition vulnerability between issuing a HCI\ncommand and removing the cont. Specifically, functions hci_req_sync()\nand hci_dev_do_close() can race each other like below:\n\nthread-A in hci_req_sync() | thread-B in hci_dev_do_close()\n | hci_req_sync_lock(hdev);\ntest_bit(HCI_UP, &hdev->flags); |\n... | test_and_clear_bit(HCI_UP, &hdev->flags)\nhci_req_sync_lock(hdev); |\n |\nIn this commit we alter the sequence in function hci_req_sync(). Hence,\nthe thread-A cannot issue th.\n\nSigned-off-by: Lin Ma \nCc: Marcel Holtmann \nFixes: 7c6a329e4447 (\"[Bluetooth] Fix regression from using default link policy\")\nSigned-off-by: Greg Kroah-Hartman ", "target": 0, "func": "int hci_req_sync(struct hci_dev *hdev, int (*req)(struct hci_request *req,\n\t\t\t\t\t\t unsigned long opt),\n\t\t unsigned long opt, u32 timeout, u8 *hci_status)\n{\n\tint ret;\n\n\t/* Serialize all requests */\n\thci_req_sync_lock(hdev);\n\t/* check the state after obtaing the lock to protect the HCI_UP\n\t * against any races from hci_dev_do_close when the controller\n\t * gets removed.\n\t */\n\tif (test_bit(HCI_UP, &hdev->flags))\n\t\tret = __hci_req_sync(hdev, req, opt, timeout, hci_status);\n\telse\n\t\tret = -ENETDOWN;\n\thci_req_sync_unlock(hdev);\n\n\treturn ret;\n}", "func_hash": 65250631543124665223010700168908885277, "file_name": "None", "file_hash": null, "cwe": ["CWE-362"], "cve": "CVE-2021-32399", "cve_desc": "net/bluetooth/hci_request.c in the Linux kernel through 5.12.2 has a race condition for removal of the HCI controller.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32399"} {"idx": 207960, "project": "FreeRDP", "commit_id": "795842f4096501fcefc1a7f535ccc8132feb31d7", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7", "commit_message": "Fixed oob read in parallel_process_irp_create", "target": 1, "func": "static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tUINT32 PathLength;\n\tStream_Seek(irp->input, 28);\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tStream_Read_UINT32(irp->input, PathLength);\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,\n\t &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}", "func_hash": 127263676841252997656617566838178046082, "file_name": "parallel_main.c", "file_hash": 150131992737153330341191657107456179815, "cwe": ["CWE-415"], "cve": "CVE-2020-11089", "cve_desc": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11089"} {"idx": 403469, "project": "FreeRDP", "commit_id": "795842f4096501fcefc1a7f535ccc8132feb31d7", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7", "commit_message": "Fixed oob read in parallel_process_irp_create", "target": 0, "func": "static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tWCHAR* ptr;\n\tUINT32 PathLength;\n\tif (!Stream_SafeSeek(irp->input, 28))\n\t\treturn ERROR_INVALID_DATA;\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;\n\tStream_Read_UINT32(irp->input, PathLength);\n\tptr = (WCHAR*)Stream_Pointer(irp->input);\n\tif (!Stream_SafeSeek(irp->input, PathLength))\n\t\treturn ERROR_INVALID_DATA;\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}", "func_hash": 173725646042313254408613769161886647442, "file_name": "parallel_main.c", "file_hash": 263240355701783249294409262318371873632, "cwe": ["CWE-415"], "cve": "CVE-2020-11089", "cve_desc": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11089"} {"idx": 207982, "project": "libexif", "commit_id": "ce03ad7ef4e8aeefce79192bf5b6f69fae396f0c", "project_url": "https://github.com/libexif/libexif", "commit_url": "https://github.com/libexif/libexif/commit/ce03ad7ef4e8aeefce79192bf5b6f69fae396f0c", "commit_message": "fixed another unsigned integer overflow\n\nfirst fixed by google in android fork,\nhttps://android.googlesource.com/platform/external/libexif/+/1e187b62682ffab5003c702657d6d725b4278f16%5E%21/#F0\n\n(use a more generic overflow check method, also check second overflow instance.)\n\nhttps://security-tracker.debian.org/tracker/CVE-2020-0198", "target": 1, "func": "exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,\n\t\t\t unsigned int ds, ExifLong o, ExifLong s)\n{\n\t/* Sanity checks */\n\tif (o >= ds) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail offset (%u).\", o);\n\t\treturn;\n\t}\n\tif (s > ds - o) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail size (%u), max would be %u.\", s, ds-o);\n\t\treturn;\n\t}\n\tif (data->data) \n\t\texif_mem_free (data->priv->mem, data->data);\n\tif (!(data->data = exif_data_alloc (data, s))) {\n\t\tEXIF_LOG_NO_MEMORY (data->priv->log, \"ExifData\", s);\n\t\tdata->size = 0;\n\t\treturn;\n\t}\n\tdata->size = s;\n\tmemcpy (data->data, d + o, s);\n}", "func_hash": 143086974873000951812314655532197973162, "file_name": "exif-data.c", "file_hash": 75155830072442549044493540308366255699, "cwe": ["CWE-190"], "cve": "CVE-2020-0181", "cve_desc": "In exif_data_load_data_thumbnail of exif-data.c, there is a possible denial of service due to an integer overflow. This could lead to remote denial of service with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android-10Android ID: A-145075076", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0181"} {"idx": 404043, "project": "libexif", "commit_id": "ce03ad7ef4e8aeefce79192bf5b6f69fae396f0c", "project_url": "https://github.com/libexif/libexif", "commit_url": "https://github.com/libexif/libexif/commit/ce03ad7ef4e8aeefce79192bf5b6f69fae396f0c", "commit_message": "fixed another unsigned integer overflow\n\nfirst fixed by google in android fork,\nhttps://android.googlesource.com/platform/external/libexif/+/1e187b62682ffab5003c702657d6d725b4278f16%5E%21/#F0\n\n(use a more generic overflow check method, also check second overflow instance.)\n\nhttps://security-tracker.debian.org/tracker/CVE-2020-0198", "target": 0, "func": "exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,\n\t\t\t unsigned int ds, ExifLong o, ExifLong s)\n{\n\t/* Sanity checks */\n\tif (o >= ds) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail offset (%u).\", o);\n\t\treturn;\n\t}\n\tif (CHECKOVERFLOW(o,ds,s)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail size (%u), max would be %u.\", s, ds-o);\n\t\treturn;\n\t}\n\tif (data->data) \n\t\texif_mem_free (data->priv->mem, data->data);\n\tif (!(data->data = exif_data_alloc (data, s))) {\n\t\tEXIF_LOG_NO_MEMORY (data->priv->log, \"ExifData\", s);\n\t\tdata->size = 0;\n\t\treturn;\n\t}\n\tdata->size = s;\n\tmemcpy (data->data, d + o, s);\n}", "func_hash": 217247801021027427726736078179338745762, "file_name": "exif-data.c", "file_hash": 177959717377158849064240208010970158967, "cwe": ["CWE-190"], "cve": "CVE-2020-0181", "cve_desc": "In exif_data_load_data_thumbnail of exif-data.c, there is a possible denial of service due to an integer overflow. This could lead to remote denial of service with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android-10Android ID: A-145075076", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0181"} {"idx": 207984, "project": "linux", "commit_id": "f8be156be163a052a067306417cd0ff679068c97", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f8be156be163a052a067306417cd0ff679068c97", "commit_message": "KVM: do not allow mapping valid but non-reference-counted pages\n\nIt's possible to create a region which maps valid but non-refcounted\npages (e.g., tail pages of non-compound higher order allocations). These\nhost pages can then be returned by gfn_to_page, gfn_to_pfn, etc., family\nof APIs, which take a reference to the page, which takes it from 0 to 1.\nWhen the reference is dropped, this will free the page incorrectly.\n\nFix this by only taking a reference on valid pages if it was non-zero,\nwhich indicates it is participating in normal refcounting (and can be\nreleased with put_page).\n\nThis addresses CVE-2021-22543.\n\nSigned-off-by: Nicholas Piggin \nTested-by: Paolo Bonzini \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini ", "target": 1, "func": "static int hva_to_pfn_remapped(struct vm_area_struct *vma,\n\t\t\t unsigned long addr, bool *async,\n\t\t\t bool write_fault, bool *writable,\n\t\t\t kvm_pfn_t *p_pfn)\n{\n\tkvm_pfn_t pfn;\n\tpte_t *ptep;\n\tspinlock_t *ptl;\n\tint r;\n\n\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\tif (r) {\n\t\t/*\n\t\t * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does\n\t\t * not call the fault handler, so do it here.\n\t\t */\n\t\tbool unlocked = false;\n\t\tr = fixup_user_fault(current->mm, addr,\n\t\t\t\t (write_fault ? FAULT_FLAG_WRITE : 0),\n\t\t\t\t &unlocked);\n\t\tif (unlocked)\n\t\t\treturn -EAGAIN;\n\t\tif (r)\n\t\t\treturn r;\n\n\t\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\t\tif (r)\n\t\t\treturn r;\n\t}\n\n\tif (write_fault && !pte_write(*ptep)) {\n\t\tpfn = KVM_PFN_ERR_RO_FAULT;\n\t\tgoto out;\n\t}\n\n\tif (writable)\n\t\t*writable = pte_write(*ptep);\n\tpfn = pte_pfn(*ptep);\n\n\t/*\n\t * Get a reference here because callers of *hva_to_pfn* and\n\t * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the\n\t * returned pfn. This is only needed if the VMA has VM_MIXEDMAP\n\t * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will\n\t * simply do nothing for reserved pfns.\n\t *\n\t * Whoever called remap_pfn_range is also going to call e.g.\n\t * unmap_mapping_range before the underlying pages are freed,\n\t * causing a call to our MMU notifier.\n\t */ \n\tkvm_get_pfn(pfn);\n\nout:\n\tpte_unmap_unlock(ptep, ptl);\n\t*p_pfn = pfn;\n\treturn 0;\n}", "func_hash": 34637737820996662550739674284396157244, "file_name": "kvm_main.c", "file_hash": 46031908884113883543971253940531128308, "cwe": ["CWE-119"], "cve": "CVE-2021-22543", "cve_desc": "An issue was discovered in Linux: KVM through Improper handling of VM_IO|VM_PFNMAP vmas in KVM can bypass RO checks and can lead to pages being freed while still accessible by the VMM and guest. This allows users with the ability to start and control a VM to read/write random pages of memory and can result in local privilege escalation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22543"} {"idx": 404071, "project": "linux", "commit_id": "f8be156be163a052a067306417cd0ff679068c97", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f8be156be163a052a067306417cd0ff679068c97", "commit_message": "KVM: do not allow mapping valid but non-reference-counted pages\n\nIt's possible to create a region which maps valid but non-refcounted\npages (e.g., tail pages of non-compound higher order allocations). These\nhost pages can then be returned by gfn_to_page, gfn_to_pfn, etc., family\nof APIs, which take a reference to the page, which takes it from 0 to 1.\nWhen the reference is dropped, this will free the page incorrectly.\n\nFix this by only taking a reference on valid pages if it was non-zero,\nwhich indicates it is participating in normal refcounting (and can be\nreleased with put_page).\n\nThis addresses CVE-2021-22543.\n\nSigned-off-by: Nicholas Piggin \nTested-by: Paolo Bonzini \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini ", "target": 0, "func": "static int hva_to_pfn_remapped(struct vm_area_struct *vma,\n\t\t\t unsigned long addr, bool *async,\n\t\t\t bool write_fault, bool *writable,\n\t\t\t kvm_pfn_t *p_pfn)\n{\n\tkvm_pfn_t pfn;\n\tpte_t *ptep;\n\tspinlock_t *ptl;\n\tint r;\n\n\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\tif (r) {\n\t\t/*\n\t\t * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does\n\t\t * not call the fault handler, so do it here.\n\t\t */\n\t\tbool unlocked = false;\n\t\tr = fixup_user_fault(current->mm, addr,\n\t\t\t\t (write_fault ? FAULT_FLAG_WRITE : 0),\n\t\t\t\t &unlocked);\n\t\tif (unlocked)\n\t\t\treturn -EAGAIN;\n\t\tif (r)\n\t\t\treturn r;\n\n\t\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\t\tif (r)\n\t\t\treturn r;\n\t}\n\n\tif (write_fault && !pte_write(*ptep)) {\n\t\tpfn = KVM_PFN_ERR_RO_FAULT;\n\t\tgoto out;\n\t}\n\n\tif (writable)\n\t\t*writable = pte_write(*ptep);\n\tpfn = pte_pfn(*ptep);\n\n\t/*\n\t * Get a reference here because callers of *hva_to_pfn* and\n\t * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the\n\t * returned pfn. This is only needed if the VMA has VM_MIXEDMAP\n\t * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will\n\t * simply do nothing for reserved pfns.\n\t *\n\t * Whoever called remap_pfn_range is also going to call e.g.\n\t * unmap_mapping_range before the underlying pages are freed,\n\t * causing a call to our MMU notifier.\n\t *\n\t * Certain IO or PFNMAP mappings can be backed with valid\n\t * struct pages, but be allocated without refcounting e.g.,\n\t * tail pages of non-compound higher order allocations, which\n\t * would then underflow the refcount when the caller does the\n\t * required put_page. Don't allow those pages here.\n\t */ \n\tif (!kvm_try_get_pfn(pfn))\n\t\tr = -EFAULT;\n\nout:\n\tpte_unmap_unlock(ptep, ptl);\n\t*p_pfn = pfn;\n\n\treturn r;\n}", "func_hash": 235303097832170728328463052478034776462, "file_name": "kvm_main.c", "file_hash": 128604129557357206239644885946299920019, "cwe": ["CWE-119"], "cve": "CVE-2021-22543", "cve_desc": "An issue was discovered in Linux: KVM through Improper handling of VM_IO|VM_PFNMAP vmas in KVM can bypass RO checks and can lead to pages being freed while still accessible by the VMM and guest. This allows users with the ability to start and control a VM to read/write random pages of memory and can result in local privilege escalation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-22543"} {"idx": 207988, "project": "htmldoc", "commit_id": "369b2ea1fd0d0537ba707f20a2f047b6afd2fbdc", "project_url": "https://github.com/michaelrsweet/htmldoc", "commit_url": "https://github.com/michaelrsweet/htmldoc/commit/369b2ea1fd0d0537ba707f20a2f047b6afd2fbdc", "commit_message": "Fix JPEG error handling (Issue #415)", "target": 1, "func": "file_rlookup(const char *filename)\t/* I - Filename */\n{\n int\t\ti;\t\t\t/* Looping var */\n cache_t\t*wc;\t\t\t/* Current cache file */\n\n\n for (i = web_files, wc = web_cache; i > 0; i --, wc ++)\n if (!strcmp(wc->name, filename))\n return (wc->url);\n\n return (filename);\n}", "func_hash": 247926750040439863252034643481156274624, "file_name": "file.c", "file_hash": 112372106302515576988443220036361552035, "cwe": ["CWE-415"], "cve": "CVE-2021-23191", "cve_desc": "A security issue was found in htmldoc v1.9.12 and before. A NULL pointer dereference in the function image_load_jpeg() in image.cxx may result in denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23191"} {"idx": 404189, "project": "htmldoc", "commit_id": "369b2ea1fd0d0537ba707f20a2f047b6afd2fbdc", "project_url": "https://github.com/michaelrsweet/htmldoc", "commit_url": "https://github.com/michaelrsweet/htmldoc/commit/369b2ea1fd0d0537ba707f20a2f047b6afd2fbdc", "commit_message": "Fix JPEG error handling (Issue #415)", "target": 0, "func": "file_rlookup(const char *filename)\t/* I - Filename */\n{\n int\t\ti;\t\t\t/* Looping var */\n cache_t\t*wc;\t\t\t/* Current cache file */\n\n\n for (i = web_files, wc = web_cache; i > 0; i --, wc ++)\n {\n if (!strcmp(wc->name, filename))\n {\n if (!strncmp(wc->url, \"data:\", 5))\n return (\"data URL\");\n else\n return (wc->url);\n }\n }\n\n return (filename);\n}", "func_hash": 160640686191433638773312545807992809931, "file_name": "file.c", "file_hash": 45330877591208647018443475508993917061, "cwe": ["CWE-415"], "cve": "CVE-2021-23191", "cve_desc": "A security issue was found in htmldoc v1.9.12 and before. A NULL pointer dereference in the function image_load_jpeg() in image.cxx may result in denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23191"} {"idx": 208034, "project": "ImageMagick", "commit_id": "43dfb1894761c4929d5d5c98dc80ba4e59a0d114", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/43dfb1894761c4929d5d5c98dc80ba4e59a0d114", "commit_message": "Handle null pointer return from call to xmlCreatePushParserCtxt (#2624).", "target": 1, "func": "static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n const char\n *option;\n\n FILE\n *file;\n\n Image\n *image,\n *next;\n\n int\n status,\n unique_file;\n\n ssize_t\n n;\n\n SVGInfo\n *svg_info;\n\n unsigned char\n message[MagickPathExtent];\n\n xmlSAXHandler\n sax_modules;\n\n xmlSAXHandlerPtr\n sax_handler;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if ((fabs(image->resolution.x) < MagickEpsilon) ||\n (fabs(image->resolution.y) < MagickEpsilon))\n {\n GeometryInfo\n geometry_info;\n\n int\n flags;\n\n flags=ParseGeometry(SVGDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n if (LocaleCompare(image_info->magick,\"MSVG\") != 0)\n {\n Image\n *svg_image;\n\n svg_image=RenderSVGImage(image_info,image,exception);\n if (svg_image != (Image *) NULL)\n {\n image=DestroyImageList(image);\n return(svg_image);\n }\n {\n#if defined(MAGICKCORE_RSVG_DELEGATE)\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface_t\n *cairo_surface;\n\n cairo_t\n *cairo_image;\n\n MagickBooleanType\n apply_density;\n\n MemoryInfo\n *pixel_info;\n\n register unsigned char\n *p;\n\n RsvgDimensionData\n dimension_info;\n\n unsigned char\n *pixels;\n\n#else\n GdkPixbuf\n *pixel_buffer;\n\n register const guchar\n *p;\n#endif\n\n GError\n *error;\n\n PixelInfo\n fill_color;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n RsvgHandle\n *svg_handle;\n\n ssize_t\n y;\n\n unsigned char\n *buffer;\n\n buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,\n sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n#if LIBRSVG_CHECK_VERSION(2,40,3)\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n svg_handle=rsvg_handle_new_with_flags(RSVG_HANDLE_FLAG_UNLIMITED);\n else\n#endif\n svg_handle=rsvg_handle_new();\n if (svg_handle == (RsvgHandle *) NULL)\n {\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n rsvg_handle_set_base_uri(svg_handle,image_info->filename);\n if ((fabs(image->resolution.x) > MagickEpsilon) &&\n (fabs(image->resolution.y) > MagickEpsilon))\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n while ((n=ReadBlob(image,MagickMaxBufferExtent-1,buffer)) != 0)\n {\n buffer[n]='\\0';\n error=(GError *) NULL;\n (void) rsvg_handle_write(svg_handle,buffer,n,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n }\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n error=(GError *) NULL;\n rsvg_handle_close(svg_handle,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n apply_density=MagickTrue;\n rsvg_handle_get_dimensions(svg_handle,&dimension_info);\n if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0))\n {\n RsvgDimensionData\n dpi_dimension_info;\n\n /*\n We should not apply the density when the internal 'factor' is 'i'.\n This can be checked by using the trick below.\n */\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x*256,\n image->resolution.y*256);\n rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info);\n if ((dpi_dimension_info.width != dimension_info.width) ||\n (dpi_dimension_info.height != dimension_info.height))\n apply_density=MagickFalse;\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n }\n if (image_info->size != (char *) NULL)\n {\n (void) GetGeometry(image_info->size,(ssize_t *) NULL,\n (ssize_t *) NULL,&image->columns,&image->rows);\n if ((image->columns != 0) || (image->rows != 0))\n {\n image->resolution.x=DefaultSVGDensity*image->columns/\n dimension_info.width;\n image->resolution.y=DefaultSVGDensity*image->rows/\n dimension_info.height;\n if (fabs(image->resolution.x) < MagickEpsilon)\n image->resolution.x=image->resolution.y;\n else\n if (fabs(image->resolution.y) < MagickEpsilon)\n image->resolution.y=image->resolution.x;\n else\n image->resolution.x=image->resolution.y=MagickMin(\n image->resolution.x,image->resolution.y);\n apply_density=MagickTrue;\n }\n }\n if (apply_density != MagickFalse)\n {\n image->columns=image->resolution.x*dimension_info.width/\n DefaultSVGDensity;\n image->rows=image->resolution.y*dimension_info.height/\n DefaultSVGDensity;\n }\n else\n {\n image->columns=dimension_info.width;\n image->rows=dimension_info.height;\n }\n pixel_info=(MemoryInfo *) NULL;\n#else\n pixel_buffer=rsvg_handle_get_pixbuf(svg_handle);\n rsvg_handle_free(svg_handle);\n image->columns=gdk_pixbuf_get_width(pixel_buffer);\n image->rows=gdk_pixbuf_get_height(pixel_buffer);\n#endif\n image->alpha_trait=BlendPixelTrait;\n if (image_info->ping == MagickFalse)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n size_t\n stride;\n#endif\n\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n#if !defined(MAGICKCORE_CAIRO_DELEGATE)\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n g_object_unref(svg_handle);\n ThrowReaderException(MissingDelegateError,\n \"NoDecodeDelegateForThisImageFormat\");\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n stride=4*image->columns;\n#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)\n stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,\n (int) image->columns);\n#endif\n pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n#endif\n (void) SetImageBackgroundColor(image,exception);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface=cairo_image_surface_create_for_data(pixels,\n CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int)\n stride);\n if ((cairo_surface == (cairo_surface_t *) NULL) ||\n (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS))\n {\n if (cairo_surface != (cairo_surface_t *) NULL)\n cairo_surface_destroy(cairo_surface);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n cairo_image=cairo_create(cairo_surface);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);\n cairo_paint(cairo_image);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);\n if (apply_density != MagickFalse)\n cairo_scale(cairo_image,image->resolution.x/DefaultSVGDensity,\n image->resolution.y/DefaultSVGDensity);\n rsvg_handle_render_cairo(svg_handle,cairo_image);\n cairo_destroy(cairo_image);\n cairo_surface_destroy(cairo_surface);\n g_object_unref(svg_handle);\n p=pixels;\n#else\n p=gdk_pixbuf_get_pixels(pixel_buffer);\n#endif\n GetPixelInfo(image,&fill_color);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n fill_color.blue=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.red=ScaleCharToQuantum(*p++);\n#else\n fill_color.red=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.blue=ScaleCharToQuantum(*p++);\n#endif\n fill_color.alpha=ScaleCharToQuantum(*p++);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n {\n double\n gamma;\n\n gamma=QuantumScale*fill_color.alpha;\n gamma=PerceptibleReciprocal(gamma);\n fill_color.blue*=gamma;\n fill_color.green*=gamma;\n fill_color.red*=gamma;\n }\n#endif\n CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double)\n GetPixelAlpha(image,q),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n if (pixel_info != (MemoryInfo *) NULL)\n pixel_info=RelinquishVirtualMemory(pixel_info);\n#else\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n (void) CloseBlob(image);\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n return(GetFirstImageInList(image));\n#endif\n }\n }\n /*\n Open draw file.\n */\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"w\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) CopyMagickString(image->filename,filename,MagickPathExtent);\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Parse SVG file.\n */\n svg_info=AcquireSVGInfo();\n if (svg_info == (SVGInfo *) NULL)\n {\n (void) fclose(file);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n svg_info->file=file;\n svg_info->exception=exception;\n svg_info->image=image;\n svg_info->image_info=image_info;\n svg_info->bounds.width=image->columns;\n svg_info->bounds.height=image->rows;\n svg_info->svgDepth=0;\n if (image_info->size != (char *) NULL)\n (void) CloneString(&svg_info->size,image_info->size);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"begin SAX\");\n xmlInitParser();\n (void) xmlSubstituteEntitiesDefault(1);\n (void) memset(&sax_modules,0,sizeof(sax_modules));\n sax_modules.internalSubset=SVGInternalSubset;\n sax_modules.isStandalone=SVGIsStandalone;\n sax_modules.hasInternalSubset=SVGHasInternalSubset;\n sax_modules.hasExternalSubset=SVGHasExternalSubset;\n sax_modules.resolveEntity=SVGResolveEntity;\n sax_modules.getEntity=SVGGetEntity;\n sax_modules.entityDecl=SVGEntityDeclaration;\n sax_modules.notationDecl=SVGNotationDeclaration;\n sax_modules.attributeDecl=SVGAttributeDeclaration;\n sax_modules.elementDecl=SVGElementDeclaration;\n sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration;\n sax_modules.setDocumentLocator=SVGSetDocumentLocator;\n sax_modules.startDocument=SVGStartDocument;\n sax_modules.endDocument=SVGEndDocument;\n sax_modules.startElement=SVGStartElement;\n sax_modules.endElement=SVGEndElement;\n sax_modules.reference=SVGReference;\n sax_modules.characters=SVGCharacters;\n sax_modules.ignorableWhitespace=SVGIgnorableWhitespace;\n sax_modules.processingInstruction=SVGProcessingInstructions;\n sax_modules.comment=SVGComment;\n sax_modules.warning=SVGWarning;\n sax_modules.error=SVGError;\n sax_modules.fatalError=SVGError;\n sax_modules.getParameterEntity=SVGGetParameterEntity;\n sax_modules.cdataBlock=SVGCDataBlock;\n sax_modules.externalSubset=SVGExternalSubset;\n sax_handler=(&sax_modules);\n n=ReadBlob(image,MagickPathExtent-1,message);\n message[n]='\\0';\n if (n > 0)\n {\n svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *)\n message,n,image->filename);\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE);\n while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0)\n {\n message[n]='\\0';\n status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0);\n if (status != 0)\n break;\n }\n }\n (void) xmlParseChunk(svg_info->parser,(char *) message,0,1);\n SVGEndDocument(svg_info);\n if (svg_info->parser->myDoc != (xmlDocPtr) NULL)\n xmlFreeDoc(svg_info->parser->myDoc);\n xmlFreeParserCtxt(svg_info->parser);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"end SAX\");\n (void) fclose(file);\n (void) CloseBlob(image);\n image->columns=svg_info->width;\n image->rows=svg_info->height;\n if (exception->severity >= ErrorException)\n {\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (image_info->ping == MagickFalse)\n {\n ImageInfo\n *read_info;\n\n /*\n Draw image.\n */\n image=DestroyImage(image);\n image=(Image *) NULL;\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"mvg:%s\",\n filename);\n image=ReadImage(read_info,exception);\n read_info=DestroyImageInfo(read_info);\n if (image != (Image *) NULL)\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n }\n /*\n Relinquish resources.\n */\n if (image != (Image *) NULL)\n {\n if (svg_info->title != (char *) NULL)\n (void) SetImageProperty(image,\"svg:title\",svg_info->title,exception);\n if (svg_info->comment != (char *) NULL)\n (void) SetImageProperty(image,\"svg:comment\",svg_info->comment,\n exception);\n }\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n return(GetFirstImageInList(image));\n}", "func_hash": 180037334584447297470863175563104318601, "file_name": "svg.c", "file_hash": 51472336918671537401593740120665504703, "cwe": ["CWE-476"], "cve": "CVE-2021-3596", "cve_desc": "A NULL pointer dereference flaw was found in ImageMagick in versions prior to 7.0.10-31 in ReadSVGImage() in coders/svg.c. This issue is due to not checking the return value from libxml2's xmlCreatePushParserCtxt() and uses the value directly, which leads to a crash and segmentation fault.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3596"} {"idx": 404419, "project": "ImageMagick", "commit_id": "43dfb1894761c4929d5d5c98dc80ba4e59a0d114", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/43dfb1894761c4929d5d5c98dc80ba4e59a0d114", "commit_message": "Handle null pointer return from call to xmlCreatePushParserCtxt (#2624).", "target": 0, "func": "static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n const char\n *option;\n\n FILE\n *file;\n\n Image\n *image,\n *next;\n\n int\n status,\n unique_file;\n\n ssize_t\n n;\n\n SVGInfo\n *svg_info;\n\n unsigned char\n message[MagickPathExtent];\n\n xmlSAXHandler\n sax_modules;\n\n xmlSAXHandlerPtr\n sax_handler;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if ((fabs(image->resolution.x) < MagickEpsilon) ||\n (fabs(image->resolution.y) < MagickEpsilon))\n {\n GeometryInfo\n geometry_info;\n\n int\n flags;\n\n flags=ParseGeometry(SVGDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n if (LocaleCompare(image_info->magick,\"MSVG\") != 0)\n {\n Image\n *svg_image;\n\n svg_image=RenderSVGImage(image_info,image,exception);\n if (svg_image != (Image *) NULL)\n {\n image=DestroyImageList(image);\n return(svg_image);\n }\n {\n#if defined(MAGICKCORE_RSVG_DELEGATE)\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface_t\n *cairo_surface;\n\n cairo_t\n *cairo_image;\n\n MagickBooleanType\n apply_density;\n\n MemoryInfo\n *pixel_info;\n\n register unsigned char\n *p;\n\n RsvgDimensionData\n dimension_info;\n\n unsigned char\n *pixels;\n\n#else\n GdkPixbuf\n *pixel_buffer;\n\n register const guchar\n *p;\n#endif\n\n GError\n *error;\n\n PixelInfo\n fill_color;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n RsvgHandle\n *svg_handle;\n\n ssize_t\n y;\n\n unsigned char\n *buffer;\n\n buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,\n sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n#if LIBRSVG_CHECK_VERSION(2,40,3)\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n svg_handle=rsvg_handle_new_with_flags(RSVG_HANDLE_FLAG_UNLIMITED);\n else\n#endif\n svg_handle=rsvg_handle_new();\n if (svg_handle == (RsvgHandle *) NULL)\n {\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n rsvg_handle_set_base_uri(svg_handle,image_info->filename);\n if ((fabs(image->resolution.x) > MagickEpsilon) &&\n (fabs(image->resolution.y) > MagickEpsilon))\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n while ((n=ReadBlob(image,MagickMaxBufferExtent-1,buffer)) != 0)\n {\n buffer[n]='\\0';\n error=(GError *) NULL;\n (void) rsvg_handle_write(svg_handle,buffer,n,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n }\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n error=(GError *) NULL;\n rsvg_handle_close(svg_handle,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n apply_density=MagickTrue;\n rsvg_handle_get_dimensions(svg_handle,&dimension_info);\n if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0))\n {\n RsvgDimensionData\n dpi_dimension_info;\n\n /*\n We should not apply the density when the internal 'factor' is 'i'.\n This can be checked by using the trick below.\n */\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x*256,\n image->resolution.y*256);\n rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info);\n if ((dpi_dimension_info.width != dimension_info.width) ||\n (dpi_dimension_info.height != dimension_info.height))\n apply_density=MagickFalse;\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n }\n if (image_info->size != (char *) NULL)\n {\n (void) GetGeometry(image_info->size,(ssize_t *) NULL,\n (ssize_t *) NULL,&image->columns,&image->rows);\n if ((image->columns != 0) || (image->rows != 0))\n {\n image->resolution.x=DefaultSVGDensity*image->columns/\n dimension_info.width;\n image->resolution.y=DefaultSVGDensity*image->rows/\n dimension_info.height;\n if (fabs(image->resolution.x) < MagickEpsilon)\n image->resolution.x=image->resolution.y;\n else\n if (fabs(image->resolution.y) < MagickEpsilon)\n image->resolution.y=image->resolution.x;\n else\n image->resolution.x=image->resolution.y=MagickMin(\n image->resolution.x,image->resolution.y);\n apply_density=MagickTrue;\n }\n }\n if (apply_density != MagickFalse)\n {\n image->columns=image->resolution.x*dimension_info.width/\n DefaultSVGDensity;\n image->rows=image->resolution.y*dimension_info.height/\n DefaultSVGDensity;\n }\n else\n {\n image->columns=dimension_info.width;\n image->rows=dimension_info.height;\n }\n pixel_info=(MemoryInfo *) NULL;\n#else\n pixel_buffer=rsvg_handle_get_pixbuf(svg_handle);\n rsvg_handle_free(svg_handle);\n image->columns=gdk_pixbuf_get_width(pixel_buffer);\n image->rows=gdk_pixbuf_get_height(pixel_buffer);\n#endif\n image->alpha_trait=BlendPixelTrait;\n if (image_info->ping == MagickFalse)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n size_t\n stride;\n#endif\n\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n#if !defined(MAGICKCORE_CAIRO_DELEGATE)\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n g_object_unref(svg_handle);\n ThrowReaderException(MissingDelegateError,\n \"NoDecodeDelegateForThisImageFormat\");\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n stride=4*image->columns;\n#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)\n stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,\n (int) image->columns);\n#endif\n pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n#endif\n (void) SetImageBackgroundColor(image,exception);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface=cairo_image_surface_create_for_data(pixels,\n CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int)\n stride);\n if ((cairo_surface == (cairo_surface_t *) NULL) ||\n (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS))\n {\n if (cairo_surface != (cairo_surface_t *) NULL)\n cairo_surface_destroy(cairo_surface);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n cairo_image=cairo_create(cairo_surface);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);\n cairo_paint(cairo_image);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);\n if (apply_density != MagickFalse)\n cairo_scale(cairo_image,image->resolution.x/DefaultSVGDensity,\n image->resolution.y/DefaultSVGDensity);\n rsvg_handle_render_cairo(svg_handle,cairo_image);\n cairo_destroy(cairo_image);\n cairo_surface_destroy(cairo_surface);\n g_object_unref(svg_handle);\n p=pixels;\n#else\n p=gdk_pixbuf_get_pixels(pixel_buffer);\n#endif\n GetPixelInfo(image,&fill_color);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n fill_color.blue=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.red=ScaleCharToQuantum(*p++);\n#else\n fill_color.red=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.blue=ScaleCharToQuantum(*p++);\n#endif\n fill_color.alpha=ScaleCharToQuantum(*p++);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n {\n double\n gamma;\n\n gamma=QuantumScale*fill_color.alpha;\n gamma=PerceptibleReciprocal(gamma);\n fill_color.blue*=gamma;\n fill_color.green*=gamma;\n fill_color.red*=gamma;\n }\n#endif\n CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double)\n GetPixelAlpha(image,q),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n if (pixel_info != (MemoryInfo *) NULL)\n pixel_info=RelinquishVirtualMemory(pixel_info);\n#else\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n (void) CloseBlob(image);\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n return(GetFirstImageInList(image));\n#endif\n }\n }\n /*\n Open draw file.\n */\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"w\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) CopyMagickString(image->filename,filename,MagickPathExtent);\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Parse SVG file.\n */\n svg_info=AcquireSVGInfo();\n if (svg_info == (SVGInfo *) NULL)\n {\n (void) fclose(file);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n svg_info->file=file;\n svg_info->exception=exception;\n svg_info->image=image;\n svg_info->image_info=image_info;\n svg_info->bounds.width=image->columns;\n svg_info->bounds.height=image->rows;\n svg_info->svgDepth=0;\n if (image_info->size != (char *) NULL)\n (void) CloneString(&svg_info->size,image_info->size);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"begin SAX\");\n xmlInitParser();\n (void) xmlSubstituteEntitiesDefault(1);\n (void) memset(&sax_modules,0,sizeof(sax_modules));\n sax_modules.internalSubset=SVGInternalSubset;\n sax_modules.isStandalone=SVGIsStandalone;\n sax_modules.hasInternalSubset=SVGHasInternalSubset;\n sax_modules.hasExternalSubset=SVGHasExternalSubset;\n sax_modules.resolveEntity=SVGResolveEntity;\n sax_modules.getEntity=SVGGetEntity;\n sax_modules.entityDecl=SVGEntityDeclaration;\n sax_modules.notationDecl=SVGNotationDeclaration;\n sax_modules.attributeDecl=SVGAttributeDeclaration;\n sax_modules.elementDecl=SVGElementDeclaration;\n sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration;\n sax_modules.setDocumentLocator=SVGSetDocumentLocator;\n sax_modules.startDocument=SVGStartDocument;\n sax_modules.endDocument=SVGEndDocument;\n sax_modules.startElement=SVGStartElement;\n sax_modules.endElement=SVGEndElement;\n sax_modules.reference=SVGReference;\n sax_modules.characters=SVGCharacters;\n sax_modules.ignorableWhitespace=SVGIgnorableWhitespace;\n sax_modules.processingInstruction=SVGProcessingInstructions;\n sax_modules.comment=SVGComment;\n sax_modules.warning=SVGWarning;\n sax_modules.error=SVGError;\n sax_modules.fatalError=SVGError;\n sax_modules.getParameterEntity=SVGGetParameterEntity;\n sax_modules.cdataBlock=SVGCDataBlock;\n sax_modules.externalSubset=SVGExternalSubset;\n sax_handler=(&sax_modules);\n n=ReadBlob(image,MagickPathExtent-1,message);\n message[n]='\\0';\n if (n > 0)\n {\n svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *)\n message,n,image->filename);\n if (svg_info->parser != (xmlParserCtxtPtr) NULL)\n {\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE);\n while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0)\n {\n message[n]='\\0';\n status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0);\n if (status != 0)\n break;\n }\n }\n }\n if (svg_info->parser == (xmlParserCtxtPtr) NULL)\n {\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n (void) xmlParseChunk(svg_info->parser,(char *) message,0,1);\n SVGEndDocument(svg_info);\n if (svg_info->parser->myDoc != (xmlDocPtr) NULL)\n xmlFreeDoc(svg_info->parser->myDoc);\n xmlFreeParserCtxt(svg_info->parser);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"end SAX\");\n (void) fclose(file);\n (void) CloseBlob(image);\n image->columns=svg_info->width;\n image->rows=svg_info->height;\n if (exception->severity >= ErrorException)\n {\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (image_info->ping == MagickFalse)\n {\n ImageInfo\n *read_info;\n\n /*\n Draw image.\n */\n image=DestroyImage(image);\n image=(Image *) NULL;\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"mvg:%s\",\n filename);\n image=ReadImage(read_info,exception);\n read_info=DestroyImageInfo(read_info);\n if (image != (Image *) NULL)\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n }\n /*\n Relinquish resources.\n */\n if (image != (Image *) NULL)\n {\n if (svg_info->title != (char *) NULL)\n (void) SetImageProperty(image,\"svg:title\",svg_info->title,exception);\n if (svg_info->comment != (char *) NULL)\n (void) SetImageProperty(image,\"svg:comment\",svg_info->comment,\n exception);\n }\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n return(GetFirstImageInList(image));\n}", "func_hash": 3887413949017567445987346552453913759, "file_name": "svg.c", "file_hash": 337096097169576095069518738824638795411, "cwe": ["CWE-476"], "cve": "CVE-2021-3596", "cve_desc": "A NULL pointer dereference flaw was found in ImageMagick in versions prior to 7.0.10-31 in ReadSVGImage() in coders/svg.c. This issue is due to not checking the return value from libxml2's xmlCreatePushParserCtxt() and uses the value directly, which leads to a crash and segmentation fault.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3596"} {"idx": 208176, "project": "Pillow", "commit_id": "518ee3722a99d7f7d890db82a20bd81c1c0327fb", "project_url": "https://github.com/python-pillow/Pillow", "commit_url": "https://github.com/python-pillow/Pillow/commit/518ee3722a99d7f7d890db82a20bd81c1c0327fb", "commit_message": "Use snprintf instead of sprintf", "target": 1, "func": "convert(\n Imaging imOut, Imaging imIn, const char *mode, ImagingPalette palette, int dither) {\n ImagingSectionCookie cookie;\n ImagingShuffler convert;\n int y;\n\n if (!imIn) {\n return (Imaging)ImagingError_ModeError();\n }\n\n if (!mode) {\n /* Map palette image to full depth */\n if (!imIn->palette) {\n return (Imaging)ImagingError_ModeError();\n }\n mode = imIn->palette->mode;\n } else {\n /* Same mode? */\n if (!strcmp(imIn->mode, mode)) {\n return ImagingCopy2(imOut, imIn);\n }\n }\n\n /* test for special conversions */\n\n if (strcmp(imIn->mode, \"P\") == 0 || strcmp(imIn->mode, \"PA\") == 0) {\n return frompalette(imOut, imIn, mode);\n }\n\n if (strcmp(mode, \"P\") == 0 || strcmp(mode, \"PA\") == 0) {\n return topalette(imOut, imIn, mode, palette, dither);\n }\n\n if (dither && strcmp(mode, \"1\") == 0) {\n return tobilevel(imOut, imIn, dither);\n }\n\n /* standard conversion machinery */\n\n convert = NULL;\n\n for (y = 0; converters[y].from; y++) {\n if (!strcmp(imIn->mode, converters[y].from) &&\n !strcmp(mode, converters[y].to)) {\n convert = converters[y].convert;\n break;\n }\n }\n\n if (!convert) {\n#ifdef notdef\n return (Imaging)ImagingError_ValueError(\"conversion not supported\");\n#else\n static char buf[100];\n sprintf(buf, \"conversion from %.10s to %.10s not supported\", imIn->mode, mode);\n return (Imaging)ImagingError_ValueError(buf);\n#endif\n }\n\n imOut = ImagingNew2Dirty(mode, imOut, imIn);\n if (!imOut) {\n return NULL;\n }\n\n ImagingSectionEnter(&cookie);\n for (y = 0; y < imIn->ysize; y++) {\n (*convert)((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize);\n }\n ImagingSectionLeave(&cookie);\n\n return imOut;\n}", "func_hash": 153563211180652837046563908236284072940, "file_name": "Convert.c", "file_hash": 102304181524469502669923065985601381042, "cwe": ["CWE-120"], "cve": "CVE-2021-34552", "cve_desc": "Pillow through 8.2.0 and PIL (aka Python Imaging Library) through 1.1.7 allow an attacker to pass controlled parameters directly into a convert function to trigger a buffer overflow in Convert.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-34552"} {"idx": 406417, "project": "Pillow", "commit_id": "518ee3722a99d7f7d890db82a20bd81c1c0327fb", "project_url": "https://github.com/python-pillow/Pillow", "commit_url": "https://github.com/python-pillow/Pillow/commit/518ee3722a99d7f7d890db82a20bd81c1c0327fb", "commit_message": "Use snprintf instead of sprintf", "target": 0, "func": "convert(\n Imaging imOut, Imaging imIn, const char *mode, ImagingPalette palette, int dither) {\n ImagingSectionCookie cookie;\n ImagingShuffler convert;\n int y;\n\n if (!imIn) {\n return (Imaging)ImagingError_ModeError();\n }\n\n if (!mode) {\n /* Map palette image to full depth */\n if (!imIn->palette) {\n return (Imaging)ImagingError_ModeError();\n }\n mode = imIn->palette->mode;\n } else {\n /* Same mode? */\n if (!strcmp(imIn->mode, mode)) {\n return ImagingCopy2(imOut, imIn);\n }\n }\n\n /* test for special conversions */\n\n if (strcmp(imIn->mode, \"P\") == 0 || strcmp(imIn->mode, \"PA\") == 0) {\n return frompalette(imOut, imIn, mode);\n }\n\n if (strcmp(mode, \"P\") == 0 || strcmp(mode, \"PA\") == 0) {\n return topalette(imOut, imIn, mode, palette, dither);\n }\n\n if (dither && strcmp(mode, \"1\") == 0) {\n return tobilevel(imOut, imIn, dither);\n }\n\n /* standard conversion machinery */\n\n convert = NULL;\n\n for (y = 0; converters[y].from; y++) {\n if (!strcmp(imIn->mode, converters[y].from) &&\n !strcmp(mode, converters[y].to)) {\n convert = converters[y].convert;\n break;\n }\n }\n\n if (!convert) {\n#ifdef notdef\n return (Imaging)ImagingError_ValueError(\"conversion not supported\");\n#else\n static char buf[100];\n snprintf(buf, 100, \"conversion from %.10s to %.10s not supported\", imIn->mode, mode);\n return (Imaging)ImagingError_ValueError(buf);\n#endif\n }\n\n imOut = ImagingNew2Dirty(mode, imOut, imIn);\n if (!imOut) {\n return NULL;\n }\n\n ImagingSectionEnter(&cookie);\n for (y = 0; y < imIn->ysize; y++) {\n (*convert)((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize);\n }\n ImagingSectionLeave(&cookie);\n\n return imOut;\n}", "func_hash": 49408685075221960114435384484180174065, "file_name": "Convert.c", "file_hash": 191354307007992806151056045081601061264, "cwe": ["CWE-120"], "cve": "CVE-2021-34552", "cve_desc": "Pillow through 8.2.0 and PIL (aka Python Imaging Library) through 1.1.7 allow an attacker to pass controlled parameters directly into a convert function to trigger a buffer overflow in Convert.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-34552"} {"idx": 208186, "project": "ImageMagick", "commit_id": "8d25d94a363b104acd6ff23df7470aeedb806c51", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/8d25d94a363b104acd6ff23df7470aeedb806c51", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3195", "target": 1, "func": "MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,\n const double dux,const double duy,const double dvx,const double dvy)\n{\n double A,B,C,F;\n\n assert(resample_filter != (ResampleFilter *) NULL);\n assert(resample_filter->signature == MagickCoreSignature);\n\n resample_filter->limit_reached = MagickFalse;\n\n /* A 'point' filter forces use of interpolation instead of area sampling */\n if ( resample_filter->filter == PointFilter )\n return; /* EWA turned off - nothing to do */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"# -----\\n\" );\n (void) FormatLocaleFile(stderr, \"dux=%lf; dvx=%lf; duy=%lf; dvy=%lf;\\n\",\n dux, dvx, duy, dvy);\n#endif\n\n /* Find Ellipse Coefficents such that\n A*u^2 + B*u*v + C*v^2 = F\n With u,v relative to point around which we are resampling.\n And the given scaling dx,dy vectors in u,v space\n du/dx,dv/dx and du/dy,dv/dy\n */\n#if EWA\n /* Direct conversion of derivatives into elliptical coefficients\n However when magnifying images, the scaling vectors will be small\n resulting in a ellipse that is too small to sample properly.\n As such we need to clamp the major/minor axis to a minumum of 1.0\n to prevent it getting too small.\n */\n#if EWA_CLAMP\n { double major_mag,\n minor_mag,\n major_x,\n major_y,\n minor_x,\n minor_y;\n\n ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag,\n &major_x, &major_y, &minor_x, &minor_y);\n major_x *= major_mag; major_y *= major_mag;\n minor_x *= minor_mag; minor_y *= minor_mag;\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"major_x=%lf; major_y=%lf; minor_x=%lf; minor_y=%lf;\\n\",\n major_x, major_y, minor_x, minor_y);\n#endif\n A = major_y*major_y+minor_y*minor_y;\n B = -2.0*(major_x*major_y+minor_x*minor_y);\n C = major_x*major_x+minor_x*minor_x;\n F = major_mag*minor_mag;\n F *= F; /* square it */\n }\n#else /* raw unclamped EWA */\n A = dvx*dvx+dvy*dvy;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy;\n F = dux*dvy-duy*dvx;\n F *= F; /* square it */\n#endif /* EWA_CLAMP */\n\n#else /* HQ_EWA */\n /*\n This Paul Heckbert's \"Higher Quality EWA\" formula, from page 60 in his\n thesis, which adds a unit circle to the elliptical area so as to do both\n Reconstruction and Prefiltering of the pixels in the resampling. It also\n means it is always likely to have at least 4 pixels within the area of the\n ellipse, for weighted averaging. No scaling will result with F == 4.0 and\n a circle of radius 2.0, and F smaller than this means magnification is\n being used.\n\n NOTE: This method produces a very blury result at near unity scale while\n producing perfect results for strong minitification and magnifications.\n\n However filter support is fixed to 2.0 (no good for Windowed Sinc filters)\n */\n A = dvx*dvx+dvy*dvy+1;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy+1;\n F = A*C - B*B/4;\n#endif\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"A=%lf; B=%lf; C=%lf; F=%lf\\n\", A,B,C,F);\n\n /* Figure out the various information directly about the ellipse.\n This information currently not needed at this time, but may be\n needed later for better limit determination.\n\n It is also good to have as a record for future debugging\n */\n { double alpha, beta, gamma, Major, Minor;\n double Eccentricity, Ellipse_Area, Ellipse_Angle;\n\n alpha = A+C;\n beta = A-C;\n gamma = sqrt(beta*beta + B*B );\n\n if ( alpha - gamma <= MagickEpsilon )\n Major=MagickMaximumValue;\n else\n Major=sqrt(2*F/(alpha - gamma));\n Minor = sqrt(2*F/(alpha + gamma));\n\n (void) FormatLocaleFile(stderr, \"# Major=%lf; Minor=%lf\\n\", Major, Minor );\n\n /* other information about ellipse include... */\n Eccentricity = Major/Minor;\n Ellipse_Area = MagickPI*Major*Minor;\n Ellipse_Angle = atan2(B, A-C);\n\n (void) FormatLocaleFile(stderr, \"# Angle=%lf Area=%lf\\n\",\n (double) RadiansToDegrees(Ellipse_Angle), Ellipse_Area);\n }\n#endif\n\n /* If one or both of the scaling vectors is impossibly large\n (producing a very large raw F value), we may as well not bother\n doing any form of resampling since resampled area is very large.\n In this case some alternative means of pixel sampling, such as\n the average of the whole image is needed to get a reasonable\n result. Calculate only as needed.\n */\n if ( (4*A*C - B*B) > MagickMaximumValue ) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse to match the filters support\n (that is, multiply F by the square of the support)\n Simplier to just multiply it by the support twice!\n */\n F *= resample_filter->support;\n F *= resample_filter->support;\n\n /* Orthogonal bounds of the ellipse */\n resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B));\n resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B));\n\n /* Horizontally aligned parallelogram fitted to Ellipse */\n resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */\n resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\\n\",\n resample_filter->Ulimit, resample_filter->Vlimit,\n resample_filter->Uwidth, resample_filter->slope );\n#endif\n\n /* Check the absolute area of the parallelogram involved.\n * This limit needs more work, as it is too slow for larger images\n * with tiled views of the horizon.\n */\n if ( (resample_filter->Uwidth * resample_filter->Vlimit)\n > (4.0*resample_filter->image_area)) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse formula to directly index the Filter Lookup Table */\n { double scale;\n#if FILTER_LUT\n /* scale so that F = WLUT_WIDTH; -- hardcoded */\n scale = (double)WLUT_WIDTH/F;\n#else\n /* scale so that F = resample_filter->F (support^2) */\n scale = resample_filter->F/F;\n#endif\n resample_filter->A = A*scale;\n resample_filter->B = B*scale;\n resample_filter->C = C*scale;\n }\n}", "func_hash": 45641212703278469189293880191561977341, "file_name": "resample.c", "file_hash": 188410894561754941220365305515407560718, "cwe": ["CWE-369"], "cve": "CVE-2021-20246", "cve_desc": "A flaw was found in ImageMagick in MagickCore/resample.c. An attacker who submits a crafted file that is processed by ImageMagick could trigger undefined behavior in the form of math division by zero. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20246"} {"idx": 406508, "project": "ImageMagick", "commit_id": "8d25d94a363b104acd6ff23df7470aeedb806c51", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/8d25d94a363b104acd6ff23df7470aeedb806c51", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/3195", "target": 0, "func": "MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,\n const double dux,const double duy,const double dvx,const double dvy)\n{\n double A,B,C,F;\n\n assert(resample_filter != (ResampleFilter *) NULL);\n assert(resample_filter->signature == MagickCoreSignature);\n\n resample_filter->limit_reached = MagickFalse;\n\n /* A 'point' filter forces use of interpolation instead of area sampling */\n if ( resample_filter->filter == PointFilter )\n return; /* EWA turned off - nothing to do */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"# -----\\n\" );\n (void) FormatLocaleFile(stderr, \"dux=%lf; dvx=%lf; duy=%lf; dvy=%lf;\\n\",\n dux, dvx, duy, dvy);\n#endif\n\n /* Find Ellipse Coefficents such that\n A*u^2 + B*u*v + C*v^2 = F\n With u,v relative to point around which we are resampling.\n And the given scaling dx,dy vectors in u,v space\n du/dx,dv/dx and du/dy,dv/dy\n */\n#if EWA\n /* Direct conversion of derivatives into elliptical coefficients\n However when magnifying images, the scaling vectors will be small\n resulting in a ellipse that is too small to sample properly.\n As such we need to clamp the major/minor axis to a minumum of 1.0\n to prevent it getting too small.\n */\n#if EWA_CLAMP\n { double major_mag,\n minor_mag,\n major_x,\n major_y,\n minor_x,\n minor_y;\n\n ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag,\n &major_x, &major_y, &minor_x, &minor_y);\n major_x *= major_mag; major_y *= major_mag;\n minor_x *= minor_mag; minor_y *= minor_mag;\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"major_x=%lf; major_y=%lf; minor_x=%lf; minor_y=%lf;\\n\",\n major_x, major_y, minor_x, minor_y);\n#endif\n A = major_y*major_y+minor_y*minor_y;\n B = -2.0*(major_x*major_y+minor_x*minor_y);\n C = major_x*major_x+minor_x*minor_x;\n F = major_mag*minor_mag;\n F *= F; /* square it */\n }\n#else /* raw unclamped EWA */\n A = dvx*dvx+dvy*dvy;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy;\n F = dux*dvy-duy*dvx;\n F *= F; /* square it */\n#endif /* EWA_CLAMP */\n\n#else /* HQ_EWA */\n /*\n This Paul Heckbert's \"Higher Quality EWA\" formula, from page 60 in his\n thesis, which adds a unit circle to the elliptical area so as to do both\n Reconstruction and Prefiltering of the pixels in the resampling. It also\n means it is always likely to have at least 4 pixels within the area of the\n ellipse, for weighted averaging. No scaling will result with F == 4.0 and\n a circle of radius 2.0, and F smaller than this means magnification is\n being used.\n\n NOTE: This method produces a very blury result at near unity scale while\n producing perfect results for strong minitification and magnifications.\n\n However filter support is fixed to 2.0 (no good for Windowed Sinc filters)\n */\n A = dvx*dvx+dvy*dvy+1;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy+1;\n F = A*C - B*B/4;\n#endif\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"A=%lf; B=%lf; C=%lf; F=%lf\\n\", A,B,C,F);\n\n /* Figure out the various information directly about the ellipse.\n This information currently not needed at this time, but may be\n needed later for better limit determination.\n\n It is also good to have as a record for future debugging\n */\n { double alpha, beta, gamma, Major, Minor;\n double Eccentricity, Ellipse_Area, Ellipse_Angle;\n\n alpha = A+C;\n beta = A-C;\n gamma = sqrt(beta*beta + B*B );\n\n if ( alpha - gamma <= MagickEpsilon )\n Major=MagickMaximumValue;\n else\n Major=sqrt(2*F/(alpha - gamma));\n Minor = sqrt(2*F/(alpha + gamma));\n\n (void) FormatLocaleFile(stderr, \"# Major=%lf; Minor=%lf\\n\", Major, Minor );\n\n /* other information about ellipse include... */\n Eccentricity = Major/Minor;\n Ellipse_Area = MagickPI*Major*Minor;\n Ellipse_Angle = atan2(B, A-C);\n\n (void) FormatLocaleFile(stderr, \"# Angle=%lf Area=%lf\\n\",\n (double) RadiansToDegrees(Ellipse_Angle), Ellipse_Area);\n }\n#endif\n\n /* If one or both of the scaling vectors is impossibly large\n (producing a very large raw F value), we may as well not bother\n doing any form of resampling since resampled area is very large.\n In this case some alternative means of pixel sampling, such as\n the average of the whole image is needed to get a reasonable\n result. Calculate only as needed.\n */\n if ( (4*A*C - B*B) > MagickMaximumValue ) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse to match the filters support\n (that is, multiply F by the square of the support)\n Simplier to just multiply it by the support twice!\n */\n F *= resample_filter->support;\n F *= resample_filter->support;\n\n /* Orthogonal bounds of the ellipse */\n resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B));\n resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B));\n\n /* Horizontally aligned parallelogram fitted to Ellipse */\n resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */\n resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\\n\",\n resample_filter->Ulimit, resample_filter->Vlimit,\n resample_filter->Uwidth, resample_filter->slope );\n#endif\n\n /* Check the absolute area of the parallelogram involved.\n * This limit needs more work, as it is too slow for larger images\n * with tiled views of the horizon.\n */\n if ( (resample_filter->Uwidth * resample_filter->Vlimit)\n > (4.0*resample_filter->image_area)) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse formula to directly index the Filter Lookup Table */\n { double scale;\n#if FILTER_LUT\n /* scale so that F = WLUT_WIDTH; -- hardcoded */\n scale=(double) WLUT_WIDTH*PerceptibleReciprocal(F);\n#else\n /* scale so that F = resample_filter->F (support^2) */\n scale=resample_filter->F*PerceptibleReciprocal(F);\n#endif\n resample_filter->A = A*scale;\n resample_filter->B = B*scale;\n resample_filter->C = C*scale;\n }\n}", "func_hash": 158269641881363729632824535538673253824, "file_name": "resample.c", "file_hash": 190008070469448764190102768697922738255, "cwe": ["CWE-369"], "cve": "CVE-2021-20246", "cve_desc": "A flaw was found in ImageMagick in MagickCore/resample.c. An attacker who submits a crafted file that is processed by ImageMagick could trigger undefined behavior in the form of math division by zero. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20246"} {"idx": 208226, "project": "flatpak", "commit_id": "cc1401043c075268ecc652eac557ef8076b5eaba", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba", "commit_message": "portal: Do not use caller-supplied variables in environment\n\nIf the caller specifies a variable that can be used to inject arbitrary\ncode into processes, we must not allow it to enter the environment\nblock used to run `flatpak run`, which runs unsandboxed.\n\nThis change requires the previous commit \"context: Add --env-fd option\",\nwhich adds infrastructure used here.\n\nTo be secure, this change also requires the previous commit\n\"run: Convert all environment variables into bwrap arguments\", which\nprotects a non-setuid bwrap(1) from the same attack.\n\nSigned-off-by: Simon McVittie \nPart-of: https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2", "target": 1, "func": "handle_spawn (PortalFlatpak *object,\n GDBusMethodInvocation *invocation,\n GUnixFDList *fd_list,\n const gchar *arg_cwd_path,\n const gchar *const *arg_argv,\n GVariant *arg_fds,\n GVariant *arg_envs,\n guint arg_flags,\n GVariant *arg_options)\n{\n g_autoptr(GError) error = NULL;\n ChildSetupData child_setup_data = { NULL };\n GPid pid;\n PidData *pid_data;\n InstanceIdReadData *instance_id_read_data = NULL;\n gsize i, j, n_fds, n_envs;\n const gint *fds = NULL;\n gint fds_len = 0;\n g_autofree FdMapEntry *fd_map = NULL;\n gchar **env;\n gint32 max_fd;\n GKeyFile *app_info;\n g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);\n g_autofree char *app_id = NULL;\n g_autofree char *branch = NULL;\n g_autofree char *arch = NULL;\n g_autofree char *app_commit = NULL;\n g_autofree char *runtime_ref = NULL;\n g_auto(GStrv) runtime_parts = NULL;\n g_autofree char *runtime_commit = NULL;\n g_autofree char *instance_path = NULL;\n g_auto(GStrv) extra_args = NULL;\n g_auto(GStrv) shares = NULL;\n g_auto(GStrv) sockets = NULL;\n g_auto(GStrv) devices = NULL;\n g_auto(GStrv) sandbox_expose = NULL;\n g_auto(GStrv) sandbox_expose_ro = NULL;\n g_autoptr(GVariant) sandbox_expose_fd = NULL;\n g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;\n g_autoptr(GOutputStream) instance_id_out_stream = NULL;\n guint sandbox_flags = 0;\n gboolean sandboxed;\n gboolean expose_pids;\n gboolean share_pids;\n gboolean notify_start;\n gboolean devel;\n g_autoptr(GString) env_string = g_string_new (\"\");\n\n child_setup_data.instance_id_fd = -1;\n child_setup_data.env_fd = -1;\n\n if (fd_list != NULL)\n fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);\n\n app_info = g_object_get_data (G_OBJECT (invocation), \"app-info\");\n g_assert (app_info != NULL);\n\n app_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_NAME, NULL);\n g_assert (app_id != NULL);\n\n g_debug (\"spawn() called from app: '%s'\", app_id);\n if (*app_id == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (*arg_cwd_path == 0)\n arg_cwd_path = NULL;\n\n if (arg_argv == NULL || *arg_argv == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No command given\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_ref = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_RUNTIME, NULL);\n if (runtime_ref == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"No runtime found\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_parts = g_strsplit (runtime_ref, \"/\", -1);\n\n branch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BRANCH, NULL);\n instance_path = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);\n arch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_ARCH, NULL);\n extra_args = g_key_file_get_string_list (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);\n app_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_COMMIT, NULL);\n runtime_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);\n shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SHARED, NULL, NULL);\n sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);\n devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);\n\n devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_DEVEL, NULL);\n\n g_variant_lookup (arg_options, \"sandbox-expose\", \"^as\", &sandbox_expose);\n g_variant_lookup (arg_options, \"sandbox-expose-ro\", \"^as\", &sandbox_expose_ro);\n g_variant_lookup (arg_options, \"sandbox-flags\", \"u\", &sandbox_flags);\n sandbox_expose_fd = g_variant_lookup_value (arg_options, \"sandbox-expose-fd\", G_VARIANT_TYPE (\"ah\"));\n sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, \"sandbox-expose-fd-ro\", G_VARIANT_TYPE (\"ah\"));\n\n if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported sandbox flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_path == NULL &&\n ((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||\n (sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Invalid sandbox expose, caller has no instance path\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n {\n const char *expose = sandbox_expose[i];\n\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n g_debug (\"Running spawn command %s\", arg_argv[0]);\n\n n_fds = 0;\n if (fds != NULL)\n n_fds = g_variant_n_children (arg_fds);\n fd_map = g_new0 (FdMapEntry, n_fds);\n\n child_setup_data.fd_map = fd_map;\n child_setup_data.fd_map_len = n_fds;\n\n max_fd = -1;\n for (i = 0; i < n_fds; i++)\n {\n gint32 handle, dest_fd;\n int handle_fd;\n\n g_variant_get_child (arg_fds, i, \"{uh}\", &dest_fd, &handle);\n\n if (handle >= fds_len || handle < 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n handle_fd = fds[handle];\n\n fd_map[i].to = dest_fd;\n fd_map[i].from = handle_fd;\n fd_map[i].final = fd_map[i].to;\n\n /* If stdin/out/err is a tty we try to set it as the controlling\n tty for the app, this way we can use this to run in a terminal. */\n if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&\n !child_setup_data.set_tty &&\n isatty (handle_fd))\n {\n child_setup_data.set_tty = TRUE;\n child_setup_data.tty = handle_fd;\n }\n\n max_fd = MAX (max_fd, fd_map[i].to);\n max_fd = MAX (max_fd, fd_map[i].from);\n }\n\n /* We make a second pass over the fds to find if any \"to\" fd index\n overlaps an already in use fd (i.e. one in the \"from\" category\n that are allocated randomly). If a fd overlaps \"to\" fd then its\n a caller issue and not our fault, so we ignore that. */\n for (i = 0; i < n_fds; i++)\n {\n int to_fd = fd_map[i].to;\n gboolean conflict = FALSE;\n\n /* At this point we're fine with using \"from\" values for this\n value (because we handle to==from in the code), or values\n that are before \"i\" in the fd_map (because those will be\n closed at this point when dup:ing). However, we can't\n reuse a fd that is in \"from\" for j > i. */\n for (j = i + 1; j < n_fds; j++)\n {\n int from_fd = fd_map[j].from;\n if (from_fd == to_fd)\n {\n conflict = TRUE;\n break;\n }\n }\n\n if (conflict)\n fd_map[i].to = ++max_fd;\n }\n\n if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)\n {\n char *empty[] = { NULL };\n env = g_strdupv (empty);\n }\n else\n env = g_get_environ ();\n\n n_envs = g_variant_n_children (arg_envs);\n for (i = 0; i < n_envs; i++)\n {\n const char *var = NULL;\n const char *val = NULL;\n g_variant_get_child (arg_envs, i, \"{&s&s}\", &var, &val);\n\n env = g_environ_setenv (env, var, val, TRUE);\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup (\"flatpak\"));\n g_ptr_array_add (flatpak_argv, g_strdup (\"run\"));\n\n sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;\n\n if (sandboxed)\n {\n g_ptr_array_add (flatpak_argv, g_strdup (\"--sandbox\"));\n\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"wayland\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=wayland\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"fallback-x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=fallback-x11\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=x11\"));\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"ipc\") &&\n sockets != NULL && (g_strv_contains ((const char * const *) sockets, \"fallback-x11\") ||\n g_strv_contains ((const char * const *) sockets, \"x11\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=ipc\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"pulseaudio\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=pulseaudio\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)\n {\n if (devices != NULL &&\n (g_strv_contains ((const char * const *) devices, \"dri\") ||\n g_strv_contains ((const char * const *) devices, \"all\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--device=dri\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--session-bus\"));\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--a11y-bus\"));\n }\n else\n {\n for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)\n {\n if (g_str_has_prefix (extra_args[i], \"--env=\"))\n {\n const char *var_val = extra_args[i] + strlen (\"--env=\");\n\n if (var_val[0] == '\\0' || var_val[0] == '=')\n {\n g_warning (\"Environment variable in extra-args has empty name\");\n continue;\n }\n\n if (strchr (var_val, '=') == NULL)\n {\n g_warning (\"Environment variable in extra-args has no value\");\n continue;\n }\n\n g_string_append (env_string, var_val);\n g_string_append_c (env_string, '\\0');\n }\n else\n {\n g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));\n }\n }\n }\n\n if (env_string->len > 0)\n {\n g_auto(GLnxTmpfile) env_tmpf = { 0, };\n\n if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&env_tmpf, \"environ\",\n env_string->str,\n env_string->len, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n child_setup_data.env_fd = glnx_steal_fd (&env_tmpf.fd);\n g_ptr_array_add (flatpak_argv,\n g_strdup_printf (\"--env-fd=%d\",\n child_setup_data.env_fd));\n }\n\n expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;\n share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;\n\n if (expose_pids || share_pids)\n {\n g_autofree char *instance_id = NULL;\n int sender_pid1 = 0;\n\n if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_NOT_SUPPORTED,\n \"Expose pids not supported with setuid bwrap\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n instance_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);\n\n if (instance_id)\n {\n g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);\n sender_pid1 = flatpak_instance_get_child_pid (instance);\n }\n\n if (sender_pid1 == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Could not find requesting pid\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--parent-pid=%d\", sender_pid1));\n\n if (share_pids)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-share-pids\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-expose-pids\"));\n }\n\n notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;\n if (notify_start)\n {\n int pipe_fds[2];\n if (pipe (pipe_fds) == -1)\n {\n int errsv = errno;\n g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,\n g_io_error_from_errno (errsv),\n \"Failed to create instance ID pipe: %s\",\n g_strerror (errsv));\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));\n /* This is saved to ensure the portal's end gets closed after the exec. */\n instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));\n\n instance_id_read_data = g_new0 (InstanceIdReadData, 1);\n\n g_input_stream_read_async (in_stream, instance_id_read_data->buffer,\n INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,\n instance_id_read_finish, instance_id_read_data);\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--instance-id-fd=%d\", pipe_fds[1]));\n child_setup_data.instance_id_fd = pipe_fds[1];\n }\n\n if (devel)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--devel\"));\n\n /* Inherit launcher network access from launcher, unless\n NO_NETWORK set. */\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"network\") &&\n !(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=network\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--unshare=network\"));\n\n\n if (instance_path)\n {\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n }\n\n if (sandbox_expose_fd != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n if (sandbox_expose_fd_ro != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd_ro);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd_ro, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime=%s\", runtime_parts[1]));\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-version=%s\", runtime_parts[3]));\n\n if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)\n {\n if (app_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--commit=%s\", app_commit));\n if (runtime_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-commit=%s\", runtime_commit));\n }\n\n if (arg_cwd_path != NULL)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--cwd=%s\", arg_cwd_path));\n\n if (arg_argv[0][0] != 0)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--command=%s\", arg_argv[0]));\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"%s/%s/%s\", app_id, arch ? arch : \"\", branch ? branch : \"\"));\n for (i = 1; arg_argv[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));\n g_ptr_array_add (flatpak_argv, NULL);\n\n if (opt_verbose)\n {\n g_autoptr(GString) cmd = g_string_new (\"\");\n\n for (i = 0; flatpak_argv->pdata[i] != NULL; i++)\n {\n if (i > 0)\n g_string_append (cmd, \" \");\n g_string_append (cmd, flatpak_argv->pdata[i]);\n }\n\n g_debug (\"Starting: %s\\n\", cmd->str);\n }\n\n /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_async_with_pipes (NULL,\n (char **) flatpak_argv->pdata,\n env,\n G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n child_setup_func, &child_setup_data,\n &pid,\n NULL,\n NULL,\n NULL,\n &error))\n {\n gint code = G_DBUS_ERROR_FAILED;\n if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))\n code = G_DBUS_ERROR_ACCESS_DENIED;\n else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))\n code = G_DBUS_ERROR_FILE_NOT_FOUND;\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,\n \"Failed to start command: %s\",\n error->message);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_id_read_data)\n instance_id_read_data->pid = pid;\n\n pid_data = g_new0 (PidData, 1);\n pid_data->pid = pid;\n pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));\n pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;\n pid_data->expose_or_share_pids = (expose_pids || share_pids);\n pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,\n pid,\n child_watch_died,\n pid_data,\n NULL);\n\n g_debug (\"Client Pid is %d\", pid_data->pid);\n\n g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),\n pid_data);\n\n portal_flatpak_complete_spawn (object, invocation, NULL, pid);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n}", "func_hash": 144494882491907388223070867045165262676, "file_name": "flatpak-portal.c", "file_hash": 19219990768444523006760710939168862358, "cwe": ["CWE-74"], "cve": "CVE-2021-21261", "cve_desc": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21261"} {"idx": 406983, "project": "flatpak", "commit_id": "cc1401043c075268ecc652eac557ef8076b5eaba", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba", "commit_message": "portal: Do not use caller-supplied variables in environment\n\nIf the caller specifies a variable that can be used to inject arbitrary\ncode into processes, we must not allow it to enter the environment\nblock used to run `flatpak run`, which runs unsandboxed.\n\nThis change requires the previous commit \"context: Add --env-fd option\",\nwhich adds infrastructure used here.\n\nTo be secure, this change also requires the previous commit\n\"run: Convert all environment variables into bwrap arguments\", which\nprotects a non-setuid bwrap(1) from the same attack.\n\nSigned-off-by: Simon McVittie \nPart-of: https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2", "target": 0, "func": "handle_spawn (PortalFlatpak *object,\n GDBusMethodInvocation *invocation,\n GUnixFDList *fd_list,\n const gchar *arg_cwd_path,\n const gchar *const *arg_argv,\n GVariant *arg_fds,\n GVariant *arg_envs,\n guint arg_flags,\n GVariant *arg_options)\n{\n g_autoptr(GError) error = NULL;\n ChildSetupData child_setup_data = { NULL };\n GPid pid;\n PidData *pid_data;\n InstanceIdReadData *instance_id_read_data = NULL;\n gsize i, j, n_fds, n_envs;\n const gint *fds = NULL;\n gint fds_len = 0;\n g_autofree FdMapEntry *fd_map = NULL;\n gchar **env;\n gint32 max_fd;\n GKeyFile *app_info;\n g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);\n g_autofree char *app_id = NULL;\n g_autofree char *branch = NULL;\n g_autofree char *arch = NULL;\n g_autofree char *app_commit = NULL;\n g_autofree char *runtime_ref = NULL;\n g_auto(GStrv) runtime_parts = NULL;\n g_autofree char *runtime_commit = NULL;\n g_autofree char *instance_path = NULL;\n g_auto(GStrv) extra_args = NULL;\n g_auto(GStrv) shares = NULL;\n g_auto(GStrv) sockets = NULL;\n g_auto(GStrv) devices = NULL;\n g_auto(GStrv) sandbox_expose = NULL;\n g_auto(GStrv) sandbox_expose_ro = NULL;\n g_autoptr(GVariant) sandbox_expose_fd = NULL;\n g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;\n g_autoptr(GOutputStream) instance_id_out_stream = NULL;\n guint sandbox_flags = 0;\n gboolean sandboxed;\n gboolean expose_pids;\n gboolean share_pids;\n gboolean notify_start;\n gboolean devel;\n g_autoptr(GString) env_string = g_string_new (\"\");\n\n child_setup_data.instance_id_fd = -1;\n child_setup_data.env_fd = -1;\n\n if (fd_list != NULL)\n fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);\n\n app_info = g_object_get_data (G_OBJECT (invocation), \"app-info\");\n g_assert (app_info != NULL);\n\n app_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_NAME, NULL);\n g_assert (app_id != NULL);\n\n g_debug (\"spawn() called from app: '%s'\", app_id);\n if (*app_id == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (*arg_cwd_path == 0)\n arg_cwd_path = NULL;\n\n if (arg_argv == NULL || *arg_argv == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No command given\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_ref = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_RUNTIME, NULL);\n if (runtime_ref == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"No runtime found\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_parts = g_strsplit (runtime_ref, \"/\", -1);\n\n branch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BRANCH, NULL);\n instance_path = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);\n arch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_ARCH, NULL);\n extra_args = g_key_file_get_string_list (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);\n app_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_COMMIT, NULL);\n runtime_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);\n shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SHARED, NULL, NULL);\n sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);\n devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);\n\n devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_DEVEL, NULL);\n\n g_variant_lookup (arg_options, \"sandbox-expose\", \"^as\", &sandbox_expose);\n g_variant_lookup (arg_options, \"sandbox-expose-ro\", \"^as\", &sandbox_expose_ro);\n g_variant_lookup (arg_options, \"sandbox-flags\", \"u\", &sandbox_flags);\n sandbox_expose_fd = g_variant_lookup_value (arg_options, \"sandbox-expose-fd\", G_VARIANT_TYPE (\"ah\"));\n sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, \"sandbox-expose-fd-ro\", G_VARIANT_TYPE (\"ah\"));\n\n if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported sandbox flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_path == NULL &&\n ((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||\n (sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Invalid sandbox expose, caller has no instance path\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n {\n const char *expose = sandbox_expose[i];\n\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n g_debug (\"Running spawn command %s\", arg_argv[0]);\n\n n_fds = 0;\n if (fds != NULL)\n n_fds = g_variant_n_children (arg_fds);\n fd_map = g_new0 (FdMapEntry, n_fds);\n\n child_setup_data.fd_map = fd_map;\n child_setup_data.fd_map_len = n_fds;\n\n max_fd = -1;\n for (i = 0; i < n_fds; i++)\n {\n gint32 handle, dest_fd;\n int handle_fd;\n\n g_variant_get_child (arg_fds, i, \"{uh}\", &dest_fd, &handle);\n\n if (handle >= fds_len || handle < 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n handle_fd = fds[handle];\n\n fd_map[i].to = dest_fd;\n fd_map[i].from = handle_fd;\n fd_map[i].final = fd_map[i].to;\n\n /* If stdin/out/err is a tty we try to set it as the controlling\n tty for the app, this way we can use this to run in a terminal. */\n if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&\n !child_setup_data.set_tty &&\n isatty (handle_fd))\n {\n child_setup_data.set_tty = TRUE;\n child_setup_data.tty = handle_fd;\n }\n\n max_fd = MAX (max_fd, fd_map[i].to);\n max_fd = MAX (max_fd, fd_map[i].from);\n }\n\n /* We make a second pass over the fds to find if any \"to\" fd index\n overlaps an already in use fd (i.e. one in the \"from\" category\n that are allocated randomly). If a fd overlaps \"to\" fd then its\n a caller issue and not our fault, so we ignore that. */\n for (i = 0; i < n_fds; i++)\n {\n int to_fd = fd_map[i].to;\n gboolean conflict = FALSE;\n\n /* At this point we're fine with using \"from\" values for this\n value (because we handle to==from in the code), or values\n that are before \"i\" in the fd_map (because those will be\n closed at this point when dup:ing). However, we can't\n reuse a fd that is in \"from\" for j > i. */\n for (j = i + 1; j < n_fds; j++)\n {\n int from_fd = fd_map[j].from;\n if (from_fd == to_fd)\n {\n conflict = TRUE;\n break;\n }\n }\n\n if (conflict)\n fd_map[i].to = ++max_fd;\n }\n\n if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)\n {\n char *empty[] = { NULL };\n env = g_strdupv (empty);\n }\n else\n env = g_get_environ ();\n\n /* Let the environment variables given by the caller override the ones\n * from extra_args. Don't add them to @env, because they are controlled\n * by our caller, which might be trying to use them to inject code into\n * flatpak(1); add them to the environment block instead.\n *\n * We don't use --env= here, so that if the values are something that\n * should not be exposed to other uids, they can remain confidential. */\n n_envs = g_variant_n_children (arg_envs);\n for (i = 0; i < n_envs; i++)\n {\n const char *var = NULL;\n const char *val = NULL;\n g_variant_get_child (arg_envs, i, \"{&s&s}\", &var, &val);\n\n if (var[0] == '\\0')\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Environment variable cannot have empty name\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (strchr (var, '=') != NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Environment variable name cannot contain '='\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n g_string_append (env_string, var);\n g_string_append_c (env_string, '=');\n g_string_append (env_string, val);\n g_string_append_c (env_string, '\\0');\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup (\"flatpak\"));\n g_ptr_array_add (flatpak_argv, g_strdup (\"run\"));\n\n sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;\n\n if (sandboxed)\n {\n g_ptr_array_add (flatpak_argv, g_strdup (\"--sandbox\"));\n\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"wayland\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=wayland\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"fallback-x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=fallback-x11\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=x11\"));\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"ipc\") &&\n sockets != NULL && (g_strv_contains ((const char * const *) sockets, \"fallback-x11\") ||\n g_strv_contains ((const char * const *) sockets, \"x11\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=ipc\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"pulseaudio\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=pulseaudio\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)\n {\n if (devices != NULL &&\n (g_strv_contains ((const char * const *) devices, \"dri\") ||\n g_strv_contains ((const char * const *) devices, \"all\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--device=dri\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--session-bus\"));\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--a11y-bus\"));\n }\n else\n {\n for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)\n {\n if (g_str_has_prefix (extra_args[i], \"--env=\"))\n {\n const char *var_val = extra_args[i] + strlen (\"--env=\");\n\n if (var_val[0] == '\\0' || var_val[0] == '=')\n {\n g_warning (\"Environment variable in extra-args has empty name\");\n continue;\n }\n\n if (strchr (var_val, '=') == NULL)\n {\n g_warning (\"Environment variable in extra-args has no value\");\n continue;\n }\n\n g_string_append (env_string, var_val);\n g_string_append_c (env_string, '\\0');\n }\n else\n {\n g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));\n }\n }\n }\n\n if (env_string->len > 0)\n {\n g_auto(GLnxTmpfile) env_tmpf = { 0, };\n\n if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&env_tmpf, \"environ\",\n env_string->str,\n env_string->len, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n child_setup_data.env_fd = glnx_steal_fd (&env_tmpf.fd);\n g_ptr_array_add (flatpak_argv,\n g_strdup_printf (\"--env-fd=%d\",\n child_setup_data.env_fd));\n }\n\n expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;\n share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;\n\n if (expose_pids || share_pids)\n {\n g_autofree char *instance_id = NULL;\n int sender_pid1 = 0;\n\n if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_NOT_SUPPORTED,\n \"Expose pids not supported with setuid bwrap\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n instance_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);\n\n if (instance_id)\n {\n g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);\n sender_pid1 = flatpak_instance_get_child_pid (instance);\n }\n\n if (sender_pid1 == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Could not find requesting pid\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--parent-pid=%d\", sender_pid1));\n\n if (share_pids)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-share-pids\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-expose-pids\"));\n }\n\n notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;\n if (notify_start)\n {\n int pipe_fds[2];\n if (pipe (pipe_fds) == -1)\n {\n int errsv = errno;\n g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,\n g_io_error_from_errno (errsv),\n \"Failed to create instance ID pipe: %s\",\n g_strerror (errsv));\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));\n /* This is saved to ensure the portal's end gets closed after the exec. */\n instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));\n\n instance_id_read_data = g_new0 (InstanceIdReadData, 1);\n\n g_input_stream_read_async (in_stream, instance_id_read_data->buffer,\n INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,\n instance_id_read_finish, instance_id_read_data);\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--instance-id-fd=%d\", pipe_fds[1]));\n child_setup_data.instance_id_fd = pipe_fds[1];\n }\n\n if (devel)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--devel\"));\n\n /* Inherit launcher network access from launcher, unless\n NO_NETWORK set. */\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"network\") &&\n !(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=network\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--unshare=network\"));\n\n\n if (instance_path)\n {\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n }\n\n if (sandbox_expose_fd != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n if (sandbox_expose_fd_ro != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd_ro);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd_ro, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime=%s\", runtime_parts[1]));\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-version=%s\", runtime_parts[3]));\n\n if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)\n {\n if (app_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--commit=%s\", app_commit));\n if (runtime_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-commit=%s\", runtime_commit));\n }\n\n if (arg_cwd_path != NULL)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--cwd=%s\", arg_cwd_path));\n\n if (arg_argv[0][0] != 0)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--command=%s\", arg_argv[0]));\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"%s/%s/%s\", app_id, arch ? arch : \"\", branch ? branch : \"\"));\n for (i = 1; arg_argv[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));\n g_ptr_array_add (flatpak_argv, NULL);\n\n if (opt_verbose)\n {\n g_autoptr(GString) cmd = g_string_new (\"\");\n\n for (i = 0; flatpak_argv->pdata[i] != NULL; i++)\n {\n if (i > 0)\n g_string_append (cmd, \" \");\n g_string_append (cmd, flatpak_argv->pdata[i]);\n }\n\n g_debug (\"Starting: %s\\n\", cmd->str);\n }\n\n /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_async_with_pipes (NULL,\n (char **) flatpak_argv->pdata,\n env,\n G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n child_setup_func, &child_setup_data,\n &pid,\n NULL,\n NULL,\n NULL,\n &error))\n {\n gint code = G_DBUS_ERROR_FAILED;\n if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))\n code = G_DBUS_ERROR_ACCESS_DENIED;\n else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))\n code = G_DBUS_ERROR_FILE_NOT_FOUND;\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,\n \"Failed to start command: %s\",\n error->message);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_id_read_data)\n instance_id_read_data->pid = pid;\n\n pid_data = g_new0 (PidData, 1);\n pid_data->pid = pid;\n pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));\n pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;\n pid_data->expose_or_share_pids = (expose_pids || share_pids);\n pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,\n pid,\n child_watch_died,\n pid_data,\n NULL);\n\n g_debug (\"Client Pid is %d\", pid_data->pid);\n\n g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),\n pid_data);\n\n portal_flatpak_complete_spawn (object, invocation, NULL, pid);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n}", "func_hash": 169249480714805025705831341619325652058, "file_name": "flatpak-portal.c", "file_hash": 19898678342647791512450826224505270858, "cwe": ["CWE-74"], "cve": "CVE-2021-21261", "cve_desc": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21261"} {"idx": 208328, "project": "qemu", "commit_id": "26194a58f4eb83c5bdf4061a1628508084450ba1", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=26194a58f4eb83c5bdf4061a1628508084450ba1", "commit_message": "msf2-mac: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang ", "target": 1, "func": "static void msf2_dma_tx(MSF2EmacState *s)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n hwaddr desc = s->regs[R_DMA_TX_DESC];\n uint8_t buf[MAX_PKT_SIZE];\n EmacDesc d;\n int size;\n uint8_t pktcnt;\n uint32_t status;\n\n if (!(s->regs[R_CFG1] & R_CFG1_TX_EN_MASK)) {\n return;\n }\n\n while (1) {\n emac_load_desc(s, &d, desc);\n if (d.pktsize & EMPTY_MASK) {\n break;\n }\n size = d.pktsize & PKT_SIZE;\n address_space_read(&s->dma_as, d.pktaddr, MEMTXATTRS_UNSPECIFIED,\n buf, size);\n /*\n * This is very basic way to send packets. Ideally there should be\n * a FIFO and packets should be sent out from FIFO only when\n * R_CFG1 bit 0 is set.\n */\n if (s->regs[R_CFG1] & R_CFG1_LB_EN_MASK) {\n nc->info->receive(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }\n d.pktsize |= EMPTY_MASK;\n emac_store_desc(s, &d, desc);\n /* update sent packets count */\n status = s->regs[R_DMA_TX_STATUS];\n pktcnt = FIELD_EX32(status, DMA_TX_STATUS, PKTCNT);\n pktcnt++;\n s->regs[R_DMA_TX_STATUS] = FIELD_DP32(status, DMA_TX_STATUS,\n PKTCNT, pktcnt);\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_PKT_SENT_MASK;\n desc = d.next;\n }\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_UNDERRUN_MASK;\n s->regs[R_DMA_TX_CTL] &= ~R_DMA_TX_CTL_EN_MASK;\n}", "func_hash": 210460850867257661112339256476991113885, "file_name": "msf2-emac.c", "file_hash": 2953274522012196769230291457426786188, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"} {"idx": 408536, "project": "qemu", "commit_id": "26194a58f4eb83c5bdf4061a1628508084450ba1", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=26194a58f4eb83c5bdf4061a1628508084450ba1", "commit_message": "msf2-mac: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang ", "target": 0, "func": "static void msf2_dma_tx(MSF2EmacState *s)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n hwaddr desc = s->regs[R_DMA_TX_DESC];\n uint8_t buf[MAX_PKT_SIZE];\n EmacDesc d;\n int size;\n uint8_t pktcnt;\n uint32_t status;\n\n if (!(s->regs[R_CFG1] & R_CFG1_TX_EN_MASK)) {\n return;\n }\n\n while (1) {\n emac_load_desc(s, &d, desc);\n if (d.pktsize & EMPTY_MASK) {\n break;\n }\n size = d.pktsize & PKT_SIZE;\n address_space_read(&s->dma_as, d.pktaddr, MEMTXATTRS_UNSPECIFIED,\n buf, size);\n /*\n * This is very basic way to send packets. Ideally there should be\n * a FIFO and packets should be sent out from FIFO only when\n * R_CFG1 bit 0 is set.\n */\n if (s->regs[R_CFG1] & R_CFG1_LB_EN_MASK) {\n qemu_receive_packet(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }\n d.pktsize |= EMPTY_MASK;\n emac_store_desc(s, &d, desc);\n /* update sent packets count */\n status = s->regs[R_DMA_TX_STATUS];\n pktcnt = FIELD_EX32(status, DMA_TX_STATUS, PKTCNT);\n pktcnt++;\n s->regs[R_DMA_TX_STATUS] = FIELD_DP32(status, DMA_TX_STATUS,\n PKTCNT, pktcnt);\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_PKT_SENT_MASK;\n desc = d.next;\n }\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_UNDERRUN_MASK;\n s->regs[R_DMA_TX_CTL] &= ~R_DMA_TX_CTL_EN_MASK;\n}", "func_hash": 284876204590805725700414354925392506313, "file_name": "msf2-emac.c", "file_hash": 337380191442365190569965145383120579518, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"} {"idx": 208360, "project": "linux", "commit_id": "6402939ec86eaf226c8b8ae00ed983936b164908", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/6402939ec86eaf226c8b8ae00ed983936b164908", "commit_message": "ieee802154: ca8210: prevent memory leak\n\nIn ca8210_probe the allocated pdata needs to be assigned to\nspi_device->dev.platform_data before calling ca8210_get_platform_data.\nOthrwise when ca8210_get_platform_data fails pdata cannot be released.\n\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20190917224713.26371-1-navid.emamdoost@gmail.com\nSigned-off-by: Stefan Schmidt ", "target": 1, "func": "static int ca8210_probe(struct spi_device *spi_device)\n{\n\tstruct ca8210_priv *priv;\n\tstruct ieee802154_hw *hw;\n\tstruct ca8210_platform_data *pdata;\n\tint ret;\n\n\tdev_info(&spi_device->dev, \"Inserting ca8210\\n\");\n\n\t/* allocate ieee802154_hw and private data */\n\thw = ieee802154_alloc_hw(sizeof(struct ca8210_priv), &ca8210_phy_ops);\n\tif (!hw) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_alloc_hw failed\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tpriv = hw->priv;\n\tpriv->hw = hw;\n\tpriv->spi = spi_device;\n\thw->parent = &spi_device->dev;\n\tspin_lock_init(&priv->lock);\n\tpriv->async_tx_pending = false;\n\tpriv->hw_registered = false;\n\tpriv->sync_up = 0;\n\tpriv->sync_down = 0;\n\tpriv->promiscuous = false;\n\tpriv->retries = 0;\n\tinit_completion(&priv->ca8210_is_awake);\n\tinit_completion(&priv->spi_transfer_complete);\n\tinit_completion(&priv->sync_exchange_complete);\n\tspi_set_drvdata(priv->spi, priv);\n\tif (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS)) {\n\t\tcascoda_api_upstream = ca8210_test_int_driver_write;\n\t\tca8210_test_interface_init(priv);\n\t} else {\n\t\tcascoda_api_upstream = NULL;\n\t}\n\tca8210_hw_setup(hw);\n\tieee802154_random_extended_addr(&hw->phy->perm_extended_addr);\n\n\tpdata = kmalloc(sizeof(*pdata), GFP_KERNEL);\n\tif (!pdata) {\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tret = ca8210_get_platform_data(priv->spi, pdata);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_get_platform_data failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->spi->dev.platform_data = pdata;\n\n\tret = ca8210_dev_com_init(priv);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_dev_com_init failed\\n\");\n\t\tgoto error;\n\t}\n\tret = ca8210_reset_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_reset_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tret = ca8210_interrupt_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_interrupt_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tmsleep(100);\n\n\tca8210_reset_send(priv->spi, 1);\n\n\tret = tdme_chipinit(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"tdme_chipinit failed\\n\");\n\t\tgoto error;\n\t}\n\n\tif (pdata->extclockenable) {\n\t\tret = ca8210_config_extern_clk(pdata, priv->spi, 1);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_config_extern_clk failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t\tret = ca8210_register_ext_clock(priv->spi);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_register_ext_clock failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tret = ieee802154_register_hw(hw);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_register_hw failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->hw_registered = true;\n\n\treturn 0;\nerror:\n\tmsleep(100); /* wait for pending spi transfers to complete */\n\tca8210_remove(spi_device);\n\treturn link_to_linux_err(ret);\n}", "func_hash": 61533142784419522390913351661196993599, "file_name": "ca8210.c", "file_hash": 208279676983551182817731397984369769438, "cwe": ["CWE-401"], "cve": "CVE-2019-19075", "cve_desc": "A memory leak in the ca8210_probe() function in drivers/net/ieee802154/ca8210.c in the Linux kernel before 5.3.8 allows attackers to cause a denial of service (memory consumption) by triggering ca8210_get_platform_data() failures, aka CID-6402939ec86e.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19075"} {"idx": 408790, "project": "linux", "commit_id": "6402939ec86eaf226c8b8ae00ed983936b164908", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/6402939ec86eaf226c8b8ae00ed983936b164908", "commit_message": "ieee802154: ca8210: prevent memory leak\n\nIn ca8210_probe the allocated pdata needs to be assigned to\nspi_device->dev.platform_data before calling ca8210_get_platform_data.\nOthrwise when ca8210_get_platform_data fails pdata cannot be released.\n\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20190917224713.26371-1-navid.emamdoost@gmail.com\nSigned-off-by: Stefan Schmidt ", "target": 0, "func": "static int ca8210_probe(struct spi_device *spi_device)\n{\n\tstruct ca8210_priv *priv;\n\tstruct ieee802154_hw *hw;\n\tstruct ca8210_platform_data *pdata;\n\tint ret;\n\n\tdev_info(&spi_device->dev, \"Inserting ca8210\\n\");\n\n\t/* allocate ieee802154_hw and private data */\n\thw = ieee802154_alloc_hw(sizeof(struct ca8210_priv), &ca8210_phy_ops);\n\tif (!hw) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_alloc_hw failed\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tpriv = hw->priv;\n\tpriv->hw = hw;\n\tpriv->spi = spi_device;\n\thw->parent = &spi_device->dev;\n\tspin_lock_init(&priv->lock);\n\tpriv->async_tx_pending = false;\n\tpriv->hw_registered = false;\n\tpriv->sync_up = 0;\n\tpriv->sync_down = 0;\n\tpriv->promiscuous = false;\n\tpriv->retries = 0;\n\tinit_completion(&priv->ca8210_is_awake);\n\tinit_completion(&priv->spi_transfer_complete);\n\tinit_completion(&priv->sync_exchange_complete);\n\tspi_set_drvdata(priv->spi, priv);\n\tif (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS)) {\n\t\tcascoda_api_upstream = ca8210_test_int_driver_write;\n\t\tca8210_test_interface_init(priv);\n\t} else {\n\t\tcascoda_api_upstream = NULL;\n\t}\n\tca8210_hw_setup(hw);\n\tieee802154_random_extended_addr(&hw->phy->perm_extended_addr);\n\n\tpdata = kmalloc(sizeof(*pdata), GFP_KERNEL);\n\tif (!pdata) {\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tpriv->spi->dev.platform_data = pdata;\n\tret = ca8210_get_platform_data(priv->spi, pdata);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_get_platform_data failed\\n\");\n\t\tgoto error;\n\t}\n\n\tret = ca8210_dev_com_init(priv);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_dev_com_init failed\\n\");\n\t\tgoto error;\n\t}\n\tret = ca8210_reset_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_reset_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tret = ca8210_interrupt_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_interrupt_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tmsleep(100);\n\n\tca8210_reset_send(priv->spi, 1);\n\n\tret = tdme_chipinit(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"tdme_chipinit failed\\n\");\n\t\tgoto error;\n\t}\n\n\tif (pdata->extclockenable) {\n\t\tret = ca8210_config_extern_clk(pdata, priv->spi, 1);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_config_extern_clk failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t\tret = ca8210_register_ext_clock(priv->spi);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_register_ext_clock failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tret = ieee802154_register_hw(hw);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_register_hw failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->hw_registered = true;\n\n\treturn 0;\nerror:\n\tmsleep(100); /* wait for pending spi transfers to complete */\n\tca8210_remove(spi_device);\n\treturn link_to_linux_err(ret);\n}", "func_hash": 336626202028729989886532464410611533075, "file_name": "ca8210.c", "file_hash": 319543798324660429477790651307351184355, "cwe": ["CWE-401"], "cve": "CVE-2019-19075", "cve_desc": "A memory leak in the ca8210_probe() function in drivers/net/ieee802154/ca8210.c in the Linux kernel before 5.3.8 allows attackers to cause a denial of service (memory consumption) by triggering ca8210_get_platform_data() failures, aka CID-6402939ec86e.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19075"} {"idx": 208379, "project": "exiv2", "commit_id": "f9308839198aca5e68a65194f151a1de92398f54", "project_url": "https://github.com/Exiv2/exiv2", "commit_url": "https://github.com/Exiv2/exiv2/commit/f9308839198aca5e68a65194f151a1de92398f54", "commit_message": "Better bounds checking in Jp2Image::encodeJp2Header()", "target": 1, "func": " void Jp2Image::encodeJp2Header(const DataBuf& boxBuf,DataBuf& outBuf)\n {\n DataBuf output(boxBuf.size_ + iccProfile_.size_ + 100); // allocate sufficient space\n int outlen = sizeof(Jp2BoxHeader) ; // now many bytes have we written to output?\n int inlen = sizeof(Jp2BoxHeader) ; // how many bytes have we read from boxBuf?\n Jp2BoxHeader* pBox = (Jp2BoxHeader*) boxBuf.pData_;\n int32_t length = getLong((byte*)&pBox->length, bigEndian);\n int32_t count = sizeof (Jp2BoxHeader);\n char* p = (char*) boxBuf.pData_;\n bool bWroteColor = false ;\n\n while ( count < length || !bWroteColor ) {\n Jp2BoxHeader* pSubBox = (Jp2BoxHeader*) (p+count) ;\n\n // copy data. pointer could be into a memory mapped file which we will decode!\n Jp2BoxHeader subBox ; memcpy(&subBox,pSubBox,sizeof(subBox));\n Jp2BoxHeader newBox = subBox;\n\n if ( count < length ) {\n subBox.length = getLong((byte*)&subBox.length, bigEndian);\n subBox.type = getLong((byte*)&subBox.type , bigEndian);\n#ifdef EXIV2_DEBUG_MESSAGES\n std::cout << \"Jp2Image::encodeJp2Header subbox: \"<< toAscii(subBox.type) << \" length = \" << subBox.length << std::endl;\n#endif\n count += subBox.length;\n newBox.type = subBox.type;\n } else {\n subBox.length=0;\n newBox.type = kJp2BoxTypeColorHeader;\n count = length;\n }\n\n int32_t newlen = subBox.length;\n if ( newBox.type == kJp2BoxTypeColorHeader ) {\n bWroteColor = true ;\n if ( ! iccProfileDefined() ) {\n const char* pad = \"\\x01\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x05\\x1cuuid\";\n uint32_t psize = 15;\n newlen = sizeof(newBox) + psize ;\n ul2Data((byte*)&newBox.length,psize ,bigEndian);\n ul2Data((byte*)&newBox.type ,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox));\n ::memcpy(output.pData_+outlen+sizeof(newBox) ,pad ,psize );\n } else {\n const char* pad = \"\\x02\\x00\\x00\";\n uint32_t psize = 3;\n newlen = sizeof(newBox) + psize + iccProfile_.size_;\n ul2Data((byte*)&newBox.length,newlen,bigEndian);\n ul2Data((byte*)&newBox.type,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox) );\n ::memcpy(output.pData_+outlen+sizeof(newBox) , pad ,psize );\n ::memcpy(output.pData_+outlen+sizeof(newBox)+psize,iccProfile_.pData_,iccProfile_.size_);\n }\n } else {\n ::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);\n }\n\n outlen += newlen;\n inlen += subBox.length;\n }\n\n // allocate the correct number of bytes, copy the data and update the box header\n outBuf.alloc(outlen);\n ::memcpy(outBuf.pData_,output.pData_,outlen);\n pBox = (Jp2BoxHeader*) outBuf.pData_;\n ul2Data((byte*)&pBox->type,kJp2BoxTypeJp2Header,bigEndian);\n ul2Data((byte*)&pBox->length,outlen,bigEndian);\n } // Jp2Image::encodeJp2Header", "func_hash": 283238054270063515231631540450683386105, "file_name": "jp2image.cpp", "file_hash": 259416280230579713604619027373688496310, "cwe": ["CWE-703"], "cve": "CVE-2021-29464", "cve_desc": "Exiv2 is a command-line utility and C++ library for reading, writing, deleting, and modifying the metadata of image files. A heap buffer overflow was found in Exiv2 versions v0.27.3 and earlier. The heap overflow is triggered when Exiv2 is used to write metadata into a crafted image file. An attacker could potentially exploit the vulnerability to gain code execution, if they can trick the victim into running Exiv2 on a crafted image file. Note that this bug is only triggered when writing the metadata, which is a less frequently used Exiv2 operation than reading the metadata. For example, to trigger the bug in the Exiv2 command-line application, you need to add an extra command-line argument such as `insert`. The bug is fixed in version v0.27.4.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29464"} {"idx": 409137, "project": "exiv2", "commit_id": "f9308839198aca5e68a65194f151a1de92398f54", "project_url": "https://github.com/Exiv2/exiv2", "commit_url": "https://github.com/Exiv2/exiv2/commit/f9308839198aca5e68a65194f151a1de92398f54", "commit_message": "Better bounds checking in Jp2Image::encodeJp2Header()", "target": 0, "func": " void Jp2Image::encodeJp2Header(const DataBuf& boxBuf,DataBuf& outBuf)\n {\n DataBuf output(boxBuf.size_ + iccProfile_.size_ + 100); // allocate sufficient space\n long outlen = sizeof(Jp2BoxHeader) ; // now many bytes have we written to output?\n long inlen = sizeof(Jp2BoxHeader) ; // how many bytes have we read from boxBuf?\n Jp2BoxHeader* pBox = (Jp2BoxHeader*) boxBuf.pData_;\n uint32_t length = getLong((byte*)&pBox->length, bigEndian);\n uint32_t count = sizeof (Jp2BoxHeader);\n char* p = (char*) boxBuf.pData_;\n bool bWroteColor = false ;\n\n while ( count < length || !bWroteColor ) {\n Jp2BoxHeader* pSubBox = (Jp2BoxHeader*) (p+count) ;\n\n // copy data. pointer could be into a memory mapped file which we will decode!\n Jp2BoxHeader subBox ; memcpy(&subBox,pSubBox,sizeof(subBox));\n Jp2BoxHeader newBox = subBox;\n\n if ( count < length ) {\n subBox.length = getLong((byte*)&subBox.length, bigEndian);\n subBox.type = getLong((byte*)&subBox.type , bigEndian);\n#ifdef EXIV2_DEBUG_MESSAGES\n std::cout << \"Jp2Image::encodeJp2Header subbox: \"<< toAscii(subBox.type) << \" length = \" << subBox.length << std::endl;\n#endif\n enforce(subBox.length <= length - count, Exiv2::kerCorruptedMetadata);\n count += subBox.length;\n newBox.type = subBox.type;\n } else {\n subBox.length=0;\n newBox.type = kJp2BoxTypeColorHeader;\n count = length;\n }\n\n uint32_t newlen = subBox.length;\n if ( newBox.type == kJp2BoxTypeColorHeader ) {\n bWroteColor = true ;\n if ( ! iccProfileDefined() ) {\n const char* pad = \"\\x01\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x05\\x1cuuid\";\n uint32_t psize = 15;\n newlen = sizeof(newBox) + psize ;\n enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);\n ul2Data((byte*)&newBox.length,psize ,bigEndian);\n ul2Data((byte*)&newBox.type ,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox));\n ::memcpy(output.pData_+outlen+sizeof(newBox) ,pad ,psize );\n } else {\n const char* pad = \"\\x02\\x00\\x00\";\n uint32_t psize = 3;\n newlen = sizeof(newBox) + psize + iccProfile_.size_;\n enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);\n ul2Data((byte*)&newBox.length,newlen,bigEndian);\n ul2Data((byte*)&newBox.type,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox) );\n ::memcpy(output.pData_+outlen+sizeof(newBox) , pad ,psize );\n ::memcpy(output.pData_+outlen+sizeof(newBox)+psize,iccProfile_.pData_,iccProfile_.size_);\n }\n } else {\n enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);\n ::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);\n }\n\n outlen += newlen;\n inlen += subBox.length;\n }\n\n // allocate the correct number of bytes, copy the data and update the box header\n outBuf.alloc(outlen);\n ::memcpy(outBuf.pData_,output.pData_,outlen);\n pBox = (Jp2BoxHeader*) outBuf.pData_;\n ul2Data((byte*)&pBox->type,kJp2BoxTypeJp2Header,bigEndian);\n ul2Data((byte*)&pBox->length,outlen,bigEndian);\n } // Jp2Image::encodeJp2Header", "func_hash": 254424797715317318255069396936422095555, "file_name": "jp2image.cpp", "file_hash": 257548072802610556157913826586057789339, "cwe": ["CWE-703"], "cve": "CVE-2021-29464", "cve_desc": "Exiv2 is a command-line utility and C++ library for reading, writing, deleting, and modifying the metadata of image files. A heap buffer overflow was found in Exiv2 versions v0.27.3 and earlier. The heap overflow is triggered when Exiv2 is used to write metadata into a crafted image file. An attacker could potentially exploit the vulnerability to gain code execution, if they can trick the victim into running Exiv2 on a crafted image file. Note that this bug is only triggered when writing the metadata, which is a less frequently used Exiv2 operation than reading the metadata. For example, to trigger the bug in the Exiv2 command-line application, you need to add an extra command-line argument such as `insert`. The bug is fixed in version v0.27.4.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29464"} {"idx": 208385, "project": "libexif", "commit_id": "e6a38a1a23ba94d139b1fa2cd4519fdcfe3c9bab", "project_url": "https://github.com/libexif/libexif", "commit_url": "https://github.com/libexif/libexif/commit/e6a38a1a23ba94d139b1fa2cd4519fdcfe3c9bab", "commit_message": "Add a failsafe on the maximum number of Canon MakerNote subtags.\n\nA malicious file could be crafted to cause extremely large values in some\ntags without tripping any buffer range checks. This is bad with the libexif\nrepresentation of Canon MakerNotes because some arrays are turned into\nindividual tags that the application must loop around.\n\nThe largest value I've seen for failsafe_size in a (very small) sample of valid\nCanon files is <5000. The limit is set two orders of magnitude larger to avoid\ntripping up falsely in case some models use much larger values.\n\nPatch from Google.\n\nCVE-2020-13114", "target": 1, "func": "exif_mnote_data_canon_load (ExifMnoteData *ne,\n\tconst unsigned char *buf, unsigned int buf_size)\n{\n\tExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne;\n\tExifShort c;\n\tsize_t i, tcount, o, datao;\n\n\tif (!n || !buf || !buf_size) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\tdatao = 6 + n->offset;\n\tif (CHECKOVERFLOW(datao, buf_size, 2)) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\n\t/* Read the number of tags */\n\tc = exif_get_short (buf + datao, n->order);\n\tdatao += 2;\n\n\t/* Remove any old entries */\n\texif_mnote_data_canon_clear (n);\n\n\t/* Reserve enough space for all the possible MakerNote tags */\n\tn->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c);\n\tif (!n->entries) {\n\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", sizeof (MnoteCanonEntry) * c);\n\t\treturn;\n\t}\n\n\t/* Parse the entries */\n\ttcount = 0;\n\tfor (i = c, o = datao; i; --i, o += 12) {\n\t\tsize_t s;\n\n\t\tmemset(&n->entries[tcount], 0, sizeof(MnoteCanonEntry));\n\t\tif (CHECKOVERFLOW(o,buf_size,12)) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\"ExifMnoteCanon\", \"Short MakerNote\");\n\t\t\tbreak;\n\t\t}\n\n\t\tn->entries[tcount].tag = exif_get_short (buf + o, n->order);\n\t\tn->entries[tcount].format = exif_get_short (buf + o + 2, n->order);\n\t\tn->entries[tcount].components = exif_get_long (buf + o + 4, n->order);\n\t\tn->entries[tcount].order = n->order;\n\n\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG, \"ExifMnoteCanon\",\n\t\t\t\"Loading entry 0x%x ('%s')...\", n->entries[tcount].tag,\n\t\t\t mnote_canon_tag_get_name (n->entries[tcount].tag));\n\n\t\t/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,\n\t\t * we will check the buffer sizes closer later. */\n\t\tif (\texif_format_get_size (n->entries[tcount].format) &&\n\t\t\tbuf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components\n\t\t) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\", \"Tag size overflow detected (%u * %lu)\", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Size? If bigger than 4 bytes, the actual data is not\n\t\t * in the entry but somewhere else (offset).\n\t\t */\n\t\ts = exif_format_get_size (n->entries[tcount].format) * \n\t\t\t\t\t\t\t\t n->entries[tcount].components;\n\t\tn->entries[tcount].size = s;\n\t\tif (!s) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\",\n\t\t\t\t \"Invalid zero-length tag size\");\n\t\t\tcontinue;\n\n\t\t} else {\n\t\t\tsize_t dataofs = o + 8;\n\t\t\tif (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6;\n\n\t\t\tif (CHECKOVERFLOW(dataofs, buf_size, s)) {\n\t\t\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t\t\"ExifMnoteCanon\",\n\t\t\t\t\t\"Tag data past end of buffer (%u > %u)\",\n\t\t\t\t\t(unsigned)(dataofs + s), buf_size);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tn->entries[tcount].data = exif_mem_alloc (ne->mem, s);\n\t\t\tif (!n->entries[tcount].data) {\n\t\t\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", s);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmemcpy (n->entries[tcount].data, buf + dataofs, s);\n\t\t}\n\n\t\t/* Tag was successfully parsed */\n\t\t++tcount;\n\t}\n\t/* Store the count of successfully parsed tags */\n\tn->count = tcount;\n}", "func_hash": 109413947811139194834711999466987635352, "file_name": "exif-mnote-data-canon.c", "file_hash": 50854914328871916179051173676790229612, "cwe": ["CWE-703"], "cve": "CVE-2020-13114", "cve_desc": "An issue was discovered in libexif before 0.6.22. An unrestricted size in handling Canon EXIF MakerNote data could lead to consumption of large amounts of compute time for decoding EXIF data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13114"} {"idx": 409181, "project": "libexif", "commit_id": "e6a38a1a23ba94d139b1fa2cd4519fdcfe3c9bab", "project_url": "https://github.com/libexif/libexif", "commit_url": "https://github.com/libexif/libexif/commit/e6a38a1a23ba94d139b1fa2cd4519fdcfe3c9bab", "commit_message": "Add a failsafe on the maximum number of Canon MakerNote subtags.\n\nA malicious file could be crafted to cause extremely large values in some\ntags without tripping any buffer range checks. This is bad with the libexif\nrepresentation of Canon MakerNotes because some arrays are turned into\nindividual tags that the application must loop around.\n\nThe largest value I've seen for failsafe_size in a (very small) sample of valid\nCanon files is <5000. The limit is set two orders of magnitude larger to avoid\ntripping up falsely in case some models use much larger values.\n\nPatch from Google.\n\nCVE-2020-13114", "target": 0, "func": "exif_mnote_data_canon_load (ExifMnoteData *ne,\n\tconst unsigned char *buf, unsigned int buf_size)\n{\n\tExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne;\n\tExifShort c;\n\tsize_t i, tcount, o, datao;\n\tlong failsafe_size = 0;\n\n\tif (!n || !buf || !buf_size) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\tdatao = 6 + n->offset;\n\tif (CHECKOVERFLOW(datao, buf_size, 2)) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\n\t/* Read the number of tags */\n\tc = exif_get_short (buf + datao, n->order);\n\tdatao += 2;\n\n\t/* Remove any old entries */\n\texif_mnote_data_canon_clear (n);\n\n\t/* Reserve enough space for all the possible MakerNote tags */\n\tn->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c);\n\tif (!n->entries) {\n\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", sizeof (MnoteCanonEntry) * c);\n\t\treturn;\n\t}\n\n\t/* Parse the entries */\n\ttcount = 0;\n\tfor (i = c, o = datao; i; --i, o += 12) {\n\t\tsize_t s;\n\n\t\tmemset(&n->entries[tcount], 0, sizeof(MnoteCanonEntry));\n\t\tif (CHECKOVERFLOW(o,buf_size,12)) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\"ExifMnoteCanon\", \"Short MakerNote\");\n\t\t\tbreak;\n\t\t}\n\n\t\tn->entries[tcount].tag = exif_get_short (buf + o, n->order);\n\t\tn->entries[tcount].format = exif_get_short (buf + o + 2, n->order);\n\t\tn->entries[tcount].components = exif_get_long (buf + o + 4, n->order);\n\t\tn->entries[tcount].order = n->order;\n\n\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG, \"ExifMnoteCanon\",\n\t\t\t\"Loading entry 0x%x ('%s')...\", n->entries[tcount].tag,\n\t\t\t mnote_canon_tag_get_name (n->entries[tcount].tag));\n\n\t\t/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,\n\t\t * we will check the buffer sizes closer later. */\n\t\tif (\texif_format_get_size (n->entries[tcount].format) &&\n\t\t\tbuf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components\n\t\t) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\", \"Tag size overflow detected (%u * %lu)\", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Size? If bigger than 4 bytes, the actual data is not\n\t\t * in the entry but somewhere else (offset).\n\t\t */\n\t\ts = exif_format_get_size (n->entries[tcount].format) * \n\t\t\t\t\t\t\t\t n->entries[tcount].components;\n\t\tn->entries[tcount].size = s;\n\t\tif (!s) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\",\n\t\t\t\t \"Invalid zero-length tag size\");\n\t\t\tcontinue;\n\n\t\t} else {\n\t\t\tsize_t dataofs = o + 8;\n\t\t\tif (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6;\n\n\t\t\tif (CHECKOVERFLOW(dataofs, buf_size, s)) {\n\t\t\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t\t\"ExifMnoteCanon\",\n\t\t\t\t\t\"Tag data past end of buffer (%u > %u)\",\n\t\t\t\t\t(unsigned)(dataofs + s), buf_size);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tn->entries[tcount].data = exif_mem_alloc (ne->mem, s);\n\t\t\tif (!n->entries[tcount].data) {\n\t\t\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", s);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmemcpy (n->entries[tcount].data, buf + dataofs, s);\n\t\t}\n\n\t\t/* Track the size of decoded tag data. A malicious file could\n\t\t * be crafted to cause extremely large values here without\n\t\t * tripping any buffer range checks. This is especially bad\n\t\t * with the libexif representation of Canon MakerNotes because\n\t\t * some arrays are turned into individual tags that the\n\t\t * application must loop around. */\n\t\tfailsafe_size += mnote_canon_entry_count_values(&n->entries[tcount]);\n\n\t\tif (failsafe_size > FAILSAFE_SIZE_MAX) {\n\t\t\t/* Abort if the total size of the data in the tags extraordinarily large, */\n\t\t\texif_mem_free (ne->mem, n->entries[tcount].data);\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\t \"ExifMnoteCanon\", \"Failsafe tag size overflow (%lu > %ld)\",\n\t\t\t\t\t failsafe_size, FAILSAFE_SIZE_MAX);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Tag was successfully parsed */\n\t\t++tcount;\n\t}\n\t/* Store the count of successfully parsed tags */\n\tn->count = tcount;\n}", "func_hash": 243101963042935684342369089106960421342, "file_name": "exif-mnote-data-canon.c", "file_hash": 9011600979219090703503738886747625810, "cwe": ["CWE-703"], "cve": "CVE-2020-13114", "cve_desc": "An issue was discovered in libexif before 0.6.22. An unrestricted size in handling Canon EXIF MakerNote data could lead to consumption of large amounts of compute time for decoding EXIF data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-13114"} {"idx": 208386, "project": "bzip2", "commit_id": "74de1e2e6ffc9d51ef9824db71a8ffee5962cdbc", "project_url": "https://gitlab.com/federicomenaquintero/bzip2", "commit_url": "https://gitlab.com/federicomenaquintero/bzip2/commit/74de1e2e6ffc9d51ef9824db71a8ffee5962cdbc", "commit_message": "Make sure nSelectors is not out of range\n\nnSelectors is used in a loop from 0 to nSelectors to access selectorMtf\nwhich is\n\tUChar selectorMtf[BZ_MAX_SELECTORS];\nso if nSelectors is bigger than BZ_MAX_SELECTORS it'll do an invalid memory\naccess\n\nFixes out of bounds access discovered while fuzzying karchive", "target": 1, "func": "Int32 BZ2_decompress ( DState* s )\n{\n UChar uc;\n Int32 retVal;\n Int32 minLen, maxLen;\n bz_stream* strm = s->strm;\n\n /* stuff that needs to be saved/restored */\n Int32 i;\n Int32 j;\n Int32 t;\n Int32 alphaSize;\n Int32 nGroups;\n Int32 nSelectors;\n Int32 EOB;\n Int32 groupNo;\n Int32 groupPos;\n Int32 nextSym;\n Int32 nblockMAX;\n Int32 nblock;\n Int32 es;\n Int32 N;\n Int32 curr;\n Int32 zt;\n Int32 zn; \n Int32 zvec;\n Int32 zj;\n Int32 gSel;\n Int32 gMinlen;\n Int32* gLimit;\n Int32* gBase;\n Int32* gPerm;\n\n if (s->state == BZ_X_MAGIC_1) {\n /*initialise the save area*/\n s->save_i = 0;\n s->save_j = 0;\n s->save_t = 0;\n s->save_alphaSize = 0;\n s->save_nGroups = 0;\n s->save_nSelectors = 0;\n s->save_EOB = 0;\n s->save_groupNo = 0;\n s->save_groupPos = 0;\n s->save_nextSym = 0;\n s->save_nblockMAX = 0;\n s->save_nblock = 0;\n s->save_es = 0;\n s->save_N = 0;\n s->save_curr = 0;\n s->save_zt = 0;\n s->save_zn = 0;\n s->save_zvec = 0;\n s->save_zj = 0;\n s->save_gSel = 0;\n s->save_gMinlen = 0;\n s->save_gLimit = NULL;\n s->save_gBase = NULL;\n s->save_gPerm = NULL;\n }\n\n /*restore from the save area*/\n i = s->save_i;\n j = s->save_j;\n t = s->save_t;\n alphaSize = s->save_alphaSize;\n nGroups = s->save_nGroups;\n nSelectors = s->save_nSelectors;\n EOB = s->save_EOB;\n groupNo = s->save_groupNo;\n groupPos = s->save_groupPos;\n nextSym = s->save_nextSym;\n nblockMAX = s->save_nblockMAX;\n nblock = s->save_nblock;\n es = s->save_es;\n N = s->save_N;\n curr = s->save_curr;\n zt = s->save_zt;\n zn = s->save_zn; \n zvec = s->save_zvec;\n zj = s->save_zj;\n gSel = s->save_gSel;\n gMinlen = s->save_gMinlen;\n gLimit = s->save_gLimit;\n gBase = s->save_gBase;\n gPerm = s->save_gPerm;\n\n retVal = BZ_OK;\n\n switch (s->state) {\n\n GET_UCHAR(BZ_X_MAGIC_1, uc);\n if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_2, uc);\n if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_3, uc)\n if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)\n if (s->blockSize100k < (BZ_HDR_0 + 1) || \n s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);\n s->blockSize100k -= BZ_HDR_0;\n\n if (s->smallDecompress) {\n s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );\n s->ll4 = BZALLOC( \n ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) \n );\n if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);\n } else {\n s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );\n if (s->tt == NULL) RETURN(BZ_MEM_ERROR);\n }\n\n GET_UCHAR(BZ_X_BLKHDR_1, uc);\n\n if (uc == 0x17) goto endhdr_2;\n if (uc != 0x31) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_2, uc);\n if (uc != 0x41) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_3, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_4, uc);\n if (uc != 0x26) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_5, uc);\n if (uc != 0x53) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_6, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n\n s->currBlockNo++;\n if (s->verbosity >= 2)\n VPrintf1 ( \"\\n [%d: huff+mtf \", s->currBlockNo );\n \n s->storedBlockCRC = 0;\n GET_UCHAR(BZ_X_BCRC_1, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_2, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_3, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_4, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n\n GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);\n\n s->origPtr = 0;\n GET_UCHAR(BZ_X_ORIGPTR_1, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_2, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_3, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n\n if (s->origPtr < 0)\n RETURN(BZ_DATA_ERROR);\n if (s->origPtr > 10 + 100000*s->blockSize100k) \n RETURN(BZ_DATA_ERROR);\n\n /*--- Receive the mapping table ---*/\n for (i = 0; i < 16; i++) {\n GET_BIT(BZ_X_MAPPING_1, uc);\n if (uc == 1) \n s->inUse16[i] = True; else \n s->inUse16[i] = False;\n }\n\n for (i = 0; i < 256; i++) s->inUse[i] = False;\n\n for (i = 0; i < 16; i++)\n if (s->inUse16[i])\n for (j = 0; j < 16; j++) {\n GET_BIT(BZ_X_MAPPING_2, uc);\n if (uc == 1) s->inUse[i * 16 + j] = True;\n }\n makeMaps_d ( s );\n if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);\n alphaSize = s->nInUse+2;\n\n /*--- Now the selectors ---*/\n GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);\n if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);\n GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);\n if (nSelectors < 1) RETURN(BZ_DATA_ERROR);\n for (i = 0; i < nSelectors; i++) {\n j = 0;\n while (True) {\n GET_BIT(BZ_X_SELECTOR_3, uc);\n if (uc == 0) break;\n j++;\n if (j >= nGroups) RETURN(BZ_DATA_ERROR);\n }\n s->selectorMtf[i] = j;\n }\n\n /*--- Undo the MTF values for the selectors. ---*/\n {\n UChar pos[BZ_N_GROUPS], tmp, v;\n for (v = 0; v < nGroups; v++) pos[v] = v;\n \n for (i = 0; i < nSelectors; i++) {\n v = s->selectorMtf[i];\n tmp = pos[v];\n while (v > 0) { pos[v] = pos[v-1]; v--; }\n pos[0] = tmp;\n s->selector[i] = tmp;\n }\n }\n\n /*--- Now the coding tables ---*/\n for (t = 0; t < nGroups; t++) {\n GET_BITS(BZ_X_CODING_1, curr, 5);\n for (i = 0; i < alphaSize; i++) {\n while (True) {\n if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);\n GET_BIT(BZ_X_CODING_2, uc);\n if (uc == 0) break;\n GET_BIT(BZ_X_CODING_3, uc);\n if (uc == 0) curr++; else curr--;\n }\n s->len[t][i] = curr;\n }\n }\n\n /*--- Create the Huffman decoding tables ---*/\n for (t = 0; t < nGroups; t++) {\n minLen = 32;\n maxLen = 0;\n for (i = 0; i < alphaSize; i++) {\n if (s->len[t][i] > maxLen) maxLen = s->len[t][i];\n if (s->len[t][i] < minLen) minLen = s->len[t][i];\n }\n BZ2_hbCreateDecodeTables ( \n &(s->limit[t][0]), \n &(s->base[t][0]), \n &(s->perm[t][0]), \n &(s->len[t][0]),\n minLen, maxLen, alphaSize\n );\n s->minLens[t] = minLen;\n }\n\n /*--- Now the MTF values ---*/\n\n EOB = s->nInUse+1;\n nblockMAX = 100000 * s->blockSize100k;\n groupNo = -1;\n groupPos = 0;\n\n for (i = 0; i <= 255; i++) s->unzftab[i] = 0;\n\n /*-- MTF init --*/\n {\n Int32 ii, jj, kk;\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n /*-- end MTF init --*/\n\n nblock = 0;\n GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);\n\n while (True) {\n\n if (nextSym == EOB) break;\n\n if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {\n\n es = -1;\n N = 1;\n do {\n /* Check that N doesn't get too big, so that es doesn't\n go negative. The maximum value that can be\n RUNA/RUNB encoded is equal to the block size (post\n the initial RLE), viz, 900k, so bounding N at 2\n million should guard against overflow without\n rejecting any legitimate inputs. */\n if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);\n if (nextSym == BZ_RUNA) es = es + (0+1) * N; else\n if (nextSym == BZ_RUNB) es = es + (1+1) * N;\n N = N * 2;\n GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);\n }\n while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);\n\n es++;\n uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];\n s->unzftab[uc] += es;\n\n if (s->smallDecompress)\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->ll16[nblock] = (UInt16)uc;\n nblock++;\n es--;\n }\n else\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->tt[nblock] = (UInt32)uc;\n nblock++;\n es--;\n };\n\n continue;\n\n } else {\n\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n\n /*-- uc = MTF ( nextSym-1 ) --*/\n {\n Int32 ii, jj, kk, pp, lno, off;\n UInt32 nn;\n nn = (UInt32)(nextSym - 1);\n\n if (nn < MTFL_SIZE) {\n /* avoid general-case expense */\n pp = s->mtfbase[0];\n uc = s->mtfa[pp+nn];\n while (nn > 3) {\n Int32 z = pp+nn;\n s->mtfa[(z) ] = s->mtfa[(z)-1];\n s->mtfa[(z)-1] = s->mtfa[(z)-2];\n s->mtfa[(z)-2] = s->mtfa[(z)-3];\n s->mtfa[(z)-3] = s->mtfa[(z)-4];\n nn -= 4;\n }\n while (nn > 0) { \n s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; \n };\n s->mtfa[pp] = uc;\n } else { \n /* general case */\n lno = nn / MTFL_SIZE;\n off = nn % MTFL_SIZE;\n pp = s->mtfbase[lno] + off;\n uc = s->mtfa[pp];\n while (pp > s->mtfbase[lno]) { \n s->mtfa[pp] = s->mtfa[pp-1]; pp--; \n };\n s->mtfbase[lno]++;\n while (lno > 0) {\n s->mtfbase[lno]--;\n s->mtfa[s->mtfbase[lno]] \n = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];\n lno--;\n }\n s->mtfbase[0]--;\n s->mtfa[s->mtfbase[0]] = uc;\n if (s->mtfbase[0] == 0) {\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n }\n }\n /*-- end uc = MTF ( nextSym-1 ) --*/\n\n s->unzftab[s->seqToUnseq[uc]]++;\n if (s->smallDecompress)\n s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else\n s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);\n nblock++;\n\n GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);\n continue;\n }\n }\n\n /* Now we know what nblock is, we can do a better sanity\n check on s->origPtr.\n */\n if (s->origPtr < 0 || s->origPtr >= nblock)\n RETURN(BZ_DATA_ERROR);\n\n /*-- Set up cftab to facilitate generation of T^(-1) --*/\n /* Check: unzftab entries in range. */\n for (i = 0; i <= 255; i++) {\n if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)\n RETURN(BZ_DATA_ERROR);\n }\n /* Actually generate cftab. */\n s->cftab[0] = 0;\n for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];\n for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];\n /* Check: cftab entries in range. */\n for (i = 0; i <= 256; i++) {\n if (s->cftab[i] < 0 || s->cftab[i] > nblock) {\n /* s->cftab[i] can legitimately be == nblock */\n RETURN(BZ_DATA_ERROR);\n }\n }\n /* Check: cftab entries non-descending. */\n for (i = 1; i <= 256; i++) {\n if (s->cftab[i-1] > s->cftab[i]) {\n RETURN(BZ_DATA_ERROR);\n }\n }\n\n s->state_out_len = 0;\n s->state_out_ch = 0;\n BZ_INITIALISE_CRC ( s->calculatedBlockCRC );\n s->state = BZ_X_OUTPUT;\n if (s->verbosity >= 2) VPrintf0 ( \"rt+rld\" );\n\n if (s->smallDecompress) {\n\n /*-- Make a copy of cftab, used in generation of T --*/\n for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];\n\n /*-- compute the T vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->ll16[i]);\n SET_LL(i, s->cftabCopy[uc]);\n s->cftabCopy[uc]++;\n }\n\n /*-- Compute T^(-1) by pointer reversal on T --*/\n i = s->origPtr;\n j = GET_LL(i);\n do {\n Int32 tmp = GET_LL(j);\n SET_LL(j, i);\n i = j;\n j = tmp;\n }\n while (i != s->origPtr);\n\n s->tPos = s->origPtr;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n }\n\n } else {\n\n /*-- compute the T^(-1) vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->tt[i] & 0xff);\n s->tt[s->cftab[uc]] |= (i << 8);\n s->cftab[uc]++;\n }\n\n s->tPos = s->tt[s->origPtr] >> 8;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_FAST(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_FAST(s->k0); s->nblock_used++;\n }\n\n }\n\n RETURN(BZ_OK);\n\n\n\n endhdr_2:\n\n GET_UCHAR(BZ_X_ENDHDR_2, uc);\n if (uc != 0x72) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_3, uc);\n if (uc != 0x45) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_4, uc);\n if (uc != 0x38) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_5, uc);\n if (uc != 0x50) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_6, uc);\n if (uc != 0x90) RETURN(BZ_DATA_ERROR);\n\n s->storedCombinedCRC = 0;\n GET_UCHAR(BZ_X_CCRC_1, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_2, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_3, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_4, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n\n s->state = BZ_X_IDLE;\n RETURN(BZ_STREAM_END);\n\n default: AssertH ( False, 4001 );\n }\n\n AssertH ( False, 4002 );\n\n save_state_and_return:\n\n s->save_i = i;\n s->save_j = j;\n s->save_t = t;\n s->save_alphaSize = alphaSize;\n s->save_nGroups = nGroups;\n s->save_nSelectors = nSelectors;\n s->save_EOB = EOB;\n s->save_groupNo = groupNo;\n s->save_groupPos = groupPos;\n s->save_nextSym = nextSym;\n s->save_nblockMAX = nblockMAX;\n s->save_nblock = nblock;\n s->save_es = es;\n s->save_N = N;\n s->save_curr = curr;\n s->save_zt = zt;\n s->save_zn = zn;\n s->save_zvec = zvec;\n s->save_zj = zj;\n s->save_gSel = gSel;\n s->save_gMinlen = gMinlen;\n s->save_gLimit = gLimit;\n s->save_gBase = gBase;\n s->save_gPerm = gPerm;\n\n return retVal; \n}", "func_hash": 120674854973715065353694327928800513153, "file_name": "decompress.c", "file_hash": 72033256175143443316855579923429908170, "cwe": ["CWE-787"], "cve": "CVE-2019-12900", "cve_desc": "BZ2_decompress in decompress.c in bzip2 through 1.0.6 has an out-of-bounds write when there are many selectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-12900"} {"idx": 409183, "project": "bzip2", "commit_id": "74de1e2e6ffc9d51ef9824db71a8ffee5962cdbc", "project_url": "https://gitlab.com/federicomenaquintero/bzip2", "commit_url": "https://gitlab.com/federicomenaquintero/bzip2/commit/74de1e2e6ffc9d51ef9824db71a8ffee5962cdbc", "commit_message": "Make sure nSelectors is not out of range\n\nnSelectors is used in a loop from 0 to nSelectors to access selectorMtf\nwhich is\n\tUChar selectorMtf[BZ_MAX_SELECTORS];\nso if nSelectors is bigger than BZ_MAX_SELECTORS it'll do an invalid memory\naccess\n\nFixes out of bounds access discovered while fuzzying karchive", "target": 0, "func": "Int32 BZ2_decompress ( DState* s )\n{\n UChar uc;\n Int32 retVal;\n Int32 minLen, maxLen;\n bz_stream* strm = s->strm;\n\n /* stuff that needs to be saved/restored */\n Int32 i;\n Int32 j;\n Int32 t;\n Int32 alphaSize;\n Int32 nGroups;\n Int32 nSelectors;\n Int32 EOB;\n Int32 groupNo;\n Int32 groupPos;\n Int32 nextSym;\n Int32 nblockMAX;\n Int32 nblock;\n Int32 es;\n Int32 N;\n Int32 curr;\n Int32 zt;\n Int32 zn; \n Int32 zvec;\n Int32 zj;\n Int32 gSel;\n Int32 gMinlen;\n Int32* gLimit;\n Int32* gBase;\n Int32* gPerm;\n\n if (s->state == BZ_X_MAGIC_1) {\n /*initialise the save area*/\n s->save_i = 0;\n s->save_j = 0;\n s->save_t = 0;\n s->save_alphaSize = 0;\n s->save_nGroups = 0;\n s->save_nSelectors = 0;\n s->save_EOB = 0;\n s->save_groupNo = 0;\n s->save_groupPos = 0;\n s->save_nextSym = 0;\n s->save_nblockMAX = 0;\n s->save_nblock = 0;\n s->save_es = 0;\n s->save_N = 0;\n s->save_curr = 0;\n s->save_zt = 0;\n s->save_zn = 0;\n s->save_zvec = 0;\n s->save_zj = 0;\n s->save_gSel = 0;\n s->save_gMinlen = 0;\n s->save_gLimit = NULL;\n s->save_gBase = NULL;\n s->save_gPerm = NULL;\n }\n\n /*restore from the save area*/\n i = s->save_i;\n j = s->save_j;\n t = s->save_t;\n alphaSize = s->save_alphaSize;\n nGroups = s->save_nGroups;\n nSelectors = s->save_nSelectors;\n EOB = s->save_EOB;\n groupNo = s->save_groupNo;\n groupPos = s->save_groupPos;\n nextSym = s->save_nextSym;\n nblockMAX = s->save_nblockMAX;\n nblock = s->save_nblock;\n es = s->save_es;\n N = s->save_N;\n curr = s->save_curr;\n zt = s->save_zt;\n zn = s->save_zn; \n zvec = s->save_zvec;\n zj = s->save_zj;\n gSel = s->save_gSel;\n gMinlen = s->save_gMinlen;\n gLimit = s->save_gLimit;\n gBase = s->save_gBase;\n gPerm = s->save_gPerm;\n\n retVal = BZ_OK;\n\n switch (s->state) {\n\n GET_UCHAR(BZ_X_MAGIC_1, uc);\n if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_2, uc);\n if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_3, uc)\n if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)\n if (s->blockSize100k < (BZ_HDR_0 + 1) || \n s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);\n s->blockSize100k -= BZ_HDR_0;\n\n if (s->smallDecompress) {\n s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );\n s->ll4 = BZALLOC( \n ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) \n );\n if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);\n } else {\n s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );\n if (s->tt == NULL) RETURN(BZ_MEM_ERROR);\n }\n\n GET_UCHAR(BZ_X_BLKHDR_1, uc);\n\n if (uc == 0x17) goto endhdr_2;\n if (uc != 0x31) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_2, uc);\n if (uc != 0x41) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_3, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_4, uc);\n if (uc != 0x26) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_5, uc);\n if (uc != 0x53) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_6, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n\n s->currBlockNo++;\n if (s->verbosity >= 2)\n VPrintf1 ( \"\\n [%d: huff+mtf \", s->currBlockNo );\n \n s->storedBlockCRC = 0;\n GET_UCHAR(BZ_X_BCRC_1, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_2, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_3, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_4, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n\n GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);\n\n s->origPtr = 0;\n GET_UCHAR(BZ_X_ORIGPTR_1, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_2, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_3, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n\n if (s->origPtr < 0)\n RETURN(BZ_DATA_ERROR);\n if (s->origPtr > 10 + 100000*s->blockSize100k) \n RETURN(BZ_DATA_ERROR);\n\n /*--- Receive the mapping table ---*/\n for (i = 0; i < 16; i++) {\n GET_BIT(BZ_X_MAPPING_1, uc);\n if (uc == 1) \n s->inUse16[i] = True; else \n s->inUse16[i] = False;\n }\n\n for (i = 0; i < 256; i++) s->inUse[i] = False;\n\n for (i = 0; i < 16; i++)\n if (s->inUse16[i])\n for (j = 0; j < 16; j++) {\n GET_BIT(BZ_X_MAPPING_2, uc);\n if (uc == 1) s->inUse[i * 16 + j] = True;\n }\n makeMaps_d ( s );\n if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);\n alphaSize = s->nInUse+2;\n\n /*--- Now the selectors ---*/\n GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);\n if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);\n GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);\n if (nSelectors < 1 || nSelectors > BZ_MAX_SELECTORS) RETURN(BZ_DATA_ERROR);\n for (i = 0; i < nSelectors; i++) {\n j = 0;\n while (True) {\n GET_BIT(BZ_X_SELECTOR_3, uc);\n if (uc == 0) break;\n j++;\n if (j >= nGroups) RETURN(BZ_DATA_ERROR);\n }\n s->selectorMtf[i] = j;\n }\n\n /*--- Undo the MTF values for the selectors. ---*/\n {\n UChar pos[BZ_N_GROUPS], tmp, v;\n for (v = 0; v < nGroups; v++) pos[v] = v;\n \n for (i = 0; i < nSelectors; i++) {\n v = s->selectorMtf[i];\n tmp = pos[v];\n while (v > 0) { pos[v] = pos[v-1]; v--; }\n pos[0] = tmp;\n s->selector[i] = tmp;\n }\n }\n\n /*--- Now the coding tables ---*/\n for (t = 0; t < nGroups; t++) {\n GET_BITS(BZ_X_CODING_1, curr, 5);\n for (i = 0; i < alphaSize; i++) {\n while (True) {\n if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);\n GET_BIT(BZ_X_CODING_2, uc);\n if (uc == 0) break;\n GET_BIT(BZ_X_CODING_3, uc);\n if (uc == 0) curr++; else curr--;\n }\n s->len[t][i] = curr;\n }\n }\n\n /*--- Create the Huffman decoding tables ---*/\n for (t = 0; t < nGroups; t++) {\n minLen = 32;\n maxLen = 0;\n for (i = 0; i < alphaSize; i++) {\n if (s->len[t][i] > maxLen) maxLen = s->len[t][i];\n if (s->len[t][i] < minLen) minLen = s->len[t][i];\n }\n BZ2_hbCreateDecodeTables ( \n &(s->limit[t][0]), \n &(s->base[t][0]), \n &(s->perm[t][0]), \n &(s->len[t][0]),\n minLen, maxLen, alphaSize\n );\n s->minLens[t] = minLen;\n }\n\n /*--- Now the MTF values ---*/\n\n EOB = s->nInUse+1;\n nblockMAX = 100000 * s->blockSize100k;\n groupNo = -1;\n groupPos = 0;\n\n for (i = 0; i <= 255; i++) s->unzftab[i] = 0;\n\n /*-- MTF init --*/\n {\n Int32 ii, jj, kk;\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n /*-- end MTF init --*/\n\n nblock = 0;\n GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);\n\n while (True) {\n\n if (nextSym == EOB) break;\n\n if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {\n\n es = -1;\n N = 1;\n do {\n /* Check that N doesn't get too big, so that es doesn't\n go negative. The maximum value that can be\n RUNA/RUNB encoded is equal to the block size (post\n the initial RLE), viz, 900k, so bounding N at 2\n million should guard against overflow without\n rejecting any legitimate inputs. */\n if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);\n if (nextSym == BZ_RUNA) es = es + (0+1) * N; else\n if (nextSym == BZ_RUNB) es = es + (1+1) * N;\n N = N * 2;\n GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);\n }\n while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);\n\n es++;\n uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];\n s->unzftab[uc] += es;\n\n if (s->smallDecompress)\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->ll16[nblock] = (UInt16)uc;\n nblock++;\n es--;\n }\n else\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->tt[nblock] = (UInt32)uc;\n nblock++;\n es--;\n };\n\n continue;\n\n } else {\n\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n\n /*-- uc = MTF ( nextSym-1 ) --*/\n {\n Int32 ii, jj, kk, pp, lno, off;\n UInt32 nn;\n nn = (UInt32)(nextSym - 1);\n\n if (nn < MTFL_SIZE) {\n /* avoid general-case expense */\n pp = s->mtfbase[0];\n uc = s->mtfa[pp+nn];\n while (nn > 3) {\n Int32 z = pp+nn;\n s->mtfa[(z) ] = s->mtfa[(z)-1];\n s->mtfa[(z)-1] = s->mtfa[(z)-2];\n s->mtfa[(z)-2] = s->mtfa[(z)-3];\n s->mtfa[(z)-3] = s->mtfa[(z)-4];\n nn -= 4;\n }\n while (nn > 0) { \n s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; \n };\n s->mtfa[pp] = uc;\n } else { \n /* general case */\n lno = nn / MTFL_SIZE;\n off = nn % MTFL_SIZE;\n pp = s->mtfbase[lno] + off;\n uc = s->mtfa[pp];\n while (pp > s->mtfbase[lno]) { \n s->mtfa[pp] = s->mtfa[pp-1]; pp--; \n };\n s->mtfbase[lno]++;\n while (lno > 0) {\n s->mtfbase[lno]--;\n s->mtfa[s->mtfbase[lno]] \n = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];\n lno--;\n }\n s->mtfbase[0]--;\n s->mtfa[s->mtfbase[0]] = uc;\n if (s->mtfbase[0] == 0) {\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n }\n }\n /*-- end uc = MTF ( nextSym-1 ) --*/\n\n s->unzftab[s->seqToUnseq[uc]]++;\n if (s->smallDecompress)\n s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else\n s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);\n nblock++;\n\n GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);\n continue;\n }\n }\n\n /* Now we know what nblock is, we can do a better sanity\n check on s->origPtr.\n */\n if (s->origPtr < 0 || s->origPtr >= nblock)\n RETURN(BZ_DATA_ERROR);\n\n /*-- Set up cftab to facilitate generation of T^(-1) --*/\n /* Check: unzftab entries in range. */\n for (i = 0; i <= 255; i++) {\n if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)\n RETURN(BZ_DATA_ERROR);\n }\n /* Actually generate cftab. */\n s->cftab[0] = 0;\n for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];\n for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];\n /* Check: cftab entries in range. */\n for (i = 0; i <= 256; i++) {\n if (s->cftab[i] < 0 || s->cftab[i] > nblock) {\n /* s->cftab[i] can legitimately be == nblock */\n RETURN(BZ_DATA_ERROR);\n }\n }\n /* Check: cftab entries non-descending. */\n for (i = 1; i <= 256; i++) {\n if (s->cftab[i-1] > s->cftab[i]) {\n RETURN(BZ_DATA_ERROR);\n }\n }\n\n s->state_out_len = 0;\n s->state_out_ch = 0;\n BZ_INITIALISE_CRC ( s->calculatedBlockCRC );\n s->state = BZ_X_OUTPUT;\n if (s->verbosity >= 2) VPrintf0 ( \"rt+rld\" );\n\n if (s->smallDecompress) {\n\n /*-- Make a copy of cftab, used in generation of T --*/\n for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];\n\n /*-- compute the T vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->ll16[i]);\n SET_LL(i, s->cftabCopy[uc]);\n s->cftabCopy[uc]++;\n }\n\n /*-- Compute T^(-1) by pointer reversal on T --*/\n i = s->origPtr;\n j = GET_LL(i);\n do {\n Int32 tmp = GET_LL(j);\n SET_LL(j, i);\n i = j;\n j = tmp;\n }\n while (i != s->origPtr);\n\n s->tPos = s->origPtr;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n }\n\n } else {\n\n /*-- compute the T^(-1) vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->tt[i] & 0xff);\n s->tt[s->cftab[uc]] |= (i << 8);\n s->cftab[uc]++;\n }\n\n s->tPos = s->tt[s->origPtr] >> 8;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_FAST(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_FAST(s->k0); s->nblock_used++;\n }\n\n }\n\n RETURN(BZ_OK);\n\n\n\n endhdr_2:\n\n GET_UCHAR(BZ_X_ENDHDR_2, uc);\n if (uc != 0x72) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_3, uc);\n if (uc != 0x45) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_4, uc);\n if (uc != 0x38) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_5, uc);\n if (uc != 0x50) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_6, uc);\n if (uc != 0x90) RETURN(BZ_DATA_ERROR);\n\n s->storedCombinedCRC = 0;\n GET_UCHAR(BZ_X_CCRC_1, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_2, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_3, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_4, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n\n s->state = BZ_X_IDLE;\n RETURN(BZ_STREAM_END);\n\n default: AssertH ( False, 4001 );\n }\n\n AssertH ( False, 4002 );\n\n save_state_and_return:\n\n s->save_i = i;\n s->save_j = j;\n s->save_t = t;\n s->save_alphaSize = alphaSize;\n s->save_nGroups = nGroups;\n s->save_nSelectors = nSelectors;\n s->save_EOB = EOB;\n s->save_groupNo = groupNo;\n s->save_groupPos = groupPos;\n s->save_nextSym = nextSym;\n s->save_nblockMAX = nblockMAX;\n s->save_nblock = nblock;\n s->save_es = es;\n s->save_N = N;\n s->save_curr = curr;\n s->save_zt = zt;\n s->save_zn = zn;\n s->save_zvec = zvec;\n s->save_zj = zj;\n s->save_gSel = gSel;\n s->save_gMinlen = gMinlen;\n s->save_gLimit = gLimit;\n s->save_gBase = gBase;\n s->save_gPerm = gPerm;\n\n return retVal; \n}", "func_hash": 50256333025586074658313400952120769070, "file_name": "decompress.c", "file_hash": 136748043173234766740927134335279737239, "cwe": ["CWE-787"], "cve": "CVE-2019-12900", "cve_desc": "BZ2_decompress in decompress.c in bzip2 through 1.0.6 has an out-of-bounds write when there are many selectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-12900"} {"idx": 208387, "project": "linux", "commit_id": "68035c80e129c4cfec659aac4180354530b26527", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=68035c80e129c4cfec659aac4180354530b26527", "commit_message": "media: uvcvideo: Avoid cyclic entity chains due to malformed USB descriptors\n\nWay back in 2017, fuzzing the 4.14-rc2 USB stack with syzkaller kicked\nup the following WARNING from the UVC chain scanning code:\n\n | list_add double add: new=ffff880069084010, prev=ffff880069084010,\n | next=ffff880067d22298.\n | ------------[ cut here ]------------\n | WARNING: CPU: 1 PID: 1846 at lib/list_debug.c:31 __list_add_valid+0xbd/0xf0\n | Modules linked in:\n | CPU: 1 PID: 1846 Comm: kworker/1:2 Not tainted\n | 4.14.0-rc2-42613-g1488251d1a98 #238\n | Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n | Workqueue: usb_hub_wq hub_event\n | task: ffff88006b01ca40 task.stack: ffff880064358000\n | RIP: 0010:__list_add_valid+0xbd/0xf0 lib/list_debug.c:29\n | RSP: 0018:ffff88006435ddd0 EFLAGS: 00010286\n | RAX: 0000000000000058 RBX: ffff880067d22298 RCX: 0000000000000000\n | RDX: 0000000000000058 RSI: ffffffff85a58800 RDI: ffffed000c86bbac\n | RBP: ffff88006435dde8 R08: 1ffff1000c86ba52 R09: 0000000000000000\n | R10: 0000000000000002 R11: 0000000000000000 R12: ffff880069084010\n | R13: ffff880067d22298 R14: ffff880069084010 R15: ffff880067d222a0\n | FS: 0000000000000000(0000) GS:ffff88006c900000(0000) knlGS:0000000000000000\n | CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n | CR2: 0000000020004ff2 CR3: 000000006b447000 CR4: 00000000000006e0\n | Call Trace:\n | __list_add ./include/linux/list.h:59\n | list_add_tail+0x8c/0x1b0 ./include/linux/list.h:92\n | uvc_scan_chain_forward.isra.8+0x373/0x416\n | drivers/media/usb/uvc/uvc_driver.c:1471\n | uvc_scan_chain drivers/media/usb/uvc/uvc_driver.c:1585\n | uvc_scan_device drivers/media/usb/uvc/uvc_driver.c:1769\n | uvc_probe+0x77f2/0x8f00 drivers/media/usb/uvc/uvc_driver.c:2104\n\nLooking into the output from usbmon, the interesting part is the\nfollowing data packet:\n\n ffff880069c63e00 30710169 C Ci:1:002:0 0 143 = 09028f00 01030080\n 00090403 00000e01 00000924 03000103 7c003328 010204db\n\nIf we drop the lead configuration and interface descriptors, we're left\nwith an output terminal descriptor describing a generic display:\n\n /* Output terminal descriptor */\n buf[0]\t09\n buf[1]\t24\n buf[2]\t03\t/* UVC_VC_OUTPUT_TERMINAL */\n buf[3]\t00\t/* ID */\n buf[4]\t01\t/* type == 0x0301 (UVC_OTT_DISPLAY) */\n buf[5]\t03\n buf[6]\t7c\n buf[7]\t00\t/* source ID refers to self! */\n buf[8]\t33\n\nThe problem with this descriptor is that it is self-referential: the\nsource ID of 0 matches itself! This causes the 'struct uvc_entity'\nrepresenting the display to be added to its chain list twice during\n'uvc_scan_chain()': once via 'uvc_scan_chain_entity()' when it is\nprocessed directly from the 'dev->entities' list and then again\nimmediately afterwards when trying to follow the source ID in\n'uvc_scan_chain_forward()'\n\nAdd a check before adding an entity to a chain list to ensure that the\nentity is not already part of a chain.\n\nLink: https://lore.kernel.org/linux-media/CAAeHK+z+Si69jUR+N-SjN9q4O+o5KFiNManqEa-PjUta7EOb7A@mail.gmail.com/\n\nCc: \nFixes: c0efd232929c (\"V4L/DVB (8145a): USB Video Class driver\")\nReported-by: Andrey Konovalov \nSigned-off-by: Will Deacon \nSigned-off-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "func": "static int uvc_scan_chain_forward(struct uvc_video_chain *chain,\n\tstruct uvc_entity *entity, struct uvc_entity *prev)\n{\n\tstruct uvc_entity *forward;\n\tint found;\n\n\t/* Forward scan */\n\tforward = NULL;\n\tfound = 0;\n\n\twhile (1) {\n\t\tforward = uvc_entity_by_reference(chain->dev, entity->id,\n\t\t\tforward);\n\t\tif (forward == NULL)\n\t\t\tbreak;\n\t\tif (forward == prev)\n\t\t\tcontinue;\n\n\t\tswitch (UVC_ENTITY_TYPE(forward)) {\n\t\tcase UVC_VC_EXTENSION_UNIT:\n\t\t\tif (forward->bNrInPins != 1) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Extension unit %d \"\n\t\t\t\t\t \"has more than 1 input pin.\\n\",\n\t\t\t\t\t entity->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" XU %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase UVC_OTT_VENDOR_SPECIFIC:\n\t\tcase UVC_OTT_DISPLAY:\n\t\tcase UVC_OTT_MEDIA_TRANSPORT_OUTPUT:\n\t\tcase UVC_TT_STREAMING:\n\t\t\tif (UVC_ENTITY_IS_ITERM(forward)) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Unsupported input \"\n\t\t\t\t\t\"terminal %u.\\n\", forward->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" OT %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found)\n\t\tprintk(KERN_CONT \")\");\n\n\treturn 0;\n}", "func_hash": 123653754294464916552649451582011619031, "file_name": "uvc_driver.c", "file_hash": 191132273763227891984157864046404633494, "cwe": ["CWE-269"], "cve": "CVE-2020-0404", "cve_desc": "In uvc_scan_chain_forward of uvc_driver.c, there is a possible linked list corruption due to an unusual root cause. This could lead to local escalation of privilege in the kernel with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android kernelAndroid ID: A-111893654References: Upstream kernel", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0404"} {"idx": 409209, "project": "linux", "commit_id": "68035c80e129c4cfec659aac4180354530b26527", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=68035c80e129c4cfec659aac4180354530b26527", "commit_message": "media: uvcvideo: Avoid cyclic entity chains due to malformed USB descriptors\n\nWay back in 2017, fuzzing the 4.14-rc2 USB stack with syzkaller kicked\nup the following WARNING from the UVC chain scanning code:\n\n | list_add double add: new=ffff880069084010, prev=ffff880069084010,\n | next=ffff880067d22298.\n | ------------[ cut here ]------------\n | WARNING: CPU: 1 PID: 1846 at lib/list_debug.c:31 __list_add_valid+0xbd/0xf0\n | Modules linked in:\n | CPU: 1 PID: 1846 Comm: kworker/1:2 Not tainted\n | 4.14.0-rc2-42613-g1488251d1a98 #238\n | Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n | Workqueue: usb_hub_wq hub_event\n | task: ffff88006b01ca40 task.stack: ffff880064358000\n | RIP: 0010:__list_add_valid+0xbd/0xf0 lib/list_debug.c:29\n | RSP: 0018:ffff88006435ddd0 EFLAGS: 00010286\n | RAX: 0000000000000058 RBX: ffff880067d22298 RCX: 0000000000000000\n | RDX: 0000000000000058 RSI: ffffffff85a58800 RDI: ffffed000c86bbac\n | RBP: ffff88006435dde8 R08: 1ffff1000c86ba52 R09: 0000000000000000\n | R10: 0000000000000002 R11: 0000000000000000 R12: ffff880069084010\n | R13: ffff880067d22298 R14: ffff880069084010 R15: ffff880067d222a0\n | FS: 0000000000000000(0000) GS:ffff88006c900000(0000) knlGS:0000000000000000\n | CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n | CR2: 0000000020004ff2 CR3: 000000006b447000 CR4: 00000000000006e0\n | Call Trace:\n | __list_add ./include/linux/list.h:59\n | list_add_tail+0x8c/0x1b0 ./include/linux/list.h:92\n | uvc_scan_chain_forward.isra.8+0x373/0x416\n | drivers/media/usb/uvc/uvc_driver.c:1471\n | uvc_scan_chain drivers/media/usb/uvc/uvc_driver.c:1585\n | uvc_scan_device drivers/media/usb/uvc/uvc_driver.c:1769\n | uvc_probe+0x77f2/0x8f00 drivers/media/usb/uvc/uvc_driver.c:2104\n\nLooking into the output from usbmon, the interesting part is the\nfollowing data packet:\n\n ffff880069c63e00 30710169 C Ci:1:002:0 0 143 = 09028f00 01030080\n 00090403 00000e01 00000924 03000103 7c003328 010204db\n\nIf we drop the lead configuration and interface descriptors, we're left\nwith an output terminal descriptor describing a generic display:\n\n /* Output terminal descriptor */\n buf[0]\t09\n buf[1]\t24\n buf[2]\t03\t/* UVC_VC_OUTPUT_TERMINAL */\n buf[3]\t00\t/* ID */\n buf[4]\t01\t/* type == 0x0301 (UVC_OTT_DISPLAY) */\n buf[5]\t03\n buf[6]\t7c\n buf[7]\t00\t/* source ID refers to self! */\n buf[8]\t33\n\nThe problem with this descriptor is that it is self-referential: the\nsource ID of 0 matches itself! This causes the 'struct uvc_entity'\nrepresenting the display to be added to its chain list twice during\n'uvc_scan_chain()': once via 'uvc_scan_chain_entity()' when it is\nprocessed directly from the 'dev->entities' list and then again\nimmediately afterwards when trying to follow the source ID in\n'uvc_scan_chain_forward()'\n\nAdd a check before adding an entity to a chain list to ensure that the\nentity is not already part of a chain.\n\nLink: https://lore.kernel.org/linux-media/CAAeHK+z+Si69jUR+N-SjN9q4O+o5KFiNManqEa-PjUta7EOb7A@mail.gmail.com/\n\nCc: \nFixes: c0efd232929c (\"V4L/DVB (8145a): USB Video Class driver\")\nReported-by: Andrey Konovalov \nSigned-off-by: Will Deacon \nSigned-off-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "func": "static int uvc_scan_chain_forward(struct uvc_video_chain *chain,\n\tstruct uvc_entity *entity, struct uvc_entity *prev)\n{\n\tstruct uvc_entity *forward;\n\tint found;\n\n\t/* Forward scan */\n\tforward = NULL;\n\tfound = 0;\n\n\twhile (1) {\n\t\tforward = uvc_entity_by_reference(chain->dev, entity->id,\n\t\t\tforward);\n\t\tif (forward == NULL)\n\t\t\tbreak;\n\t\tif (forward == prev)\n\t\t\tcontinue;\n\t\tif (forward->chain.next || forward->chain.prev) {\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Found reference to \"\n\t\t\t\t\"entity %d already in chain.\\n\", forward->id);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tswitch (UVC_ENTITY_TYPE(forward)) {\n\t\tcase UVC_VC_EXTENSION_UNIT:\n\t\t\tif (forward->bNrInPins != 1) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Extension unit %d \"\n\t\t\t\t\t \"has more than 1 input pin.\\n\",\n\t\t\t\t\t entity->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" XU %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase UVC_OTT_VENDOR_SPECIFIC:\n\t\tcase UVC_OTT_DISPLAY:\n\t\tcase UVC_OTT_MEDIA_TRANSPORT_OUTPUT:\n\t\tcase UVC_TT_STREAMING:\n\t\t\tif (UVC_ENTITY_IS_ITERM(forward)) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Unsupported input \"\n\t\t\t\t\t\"terminal %u.\\n\", forward->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" OT %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found)\n\t\tprintk(KERN_CONT \")\");\n\n\treturn 0;\n}", "func_hash": 322996038616249136159214385992788112120, "file_name": "uvc_driver.c", "file_hash": 4268898927496496530877874928351244974, "cwe": ["CWE-269"], "cve": "CVE-2020-0404", "cve_desc": "In uvc_scan_chain_forward of uvc_driver.c, there is a possible linked list corruption due to an unusual root cause. This could lead to local escalation of privilege in the kernel with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android kernelAndroid ID: A-111893654References: Upstream kernel", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-0404"} {"idx": 208417, "project": "FreeRDP", "commit_id": "3627aaf7d289315b614a584afb388f04abfb5bbf", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/3627aaf7d289315b614a584afb388f04abfb5bbf", "commit_message": "Fixed #6011: Bounds check in rdp_read_font_capability_set", "target": 1, "func": "static BOOL rdp_read_font_capability_set(wStream* s, UINT16 length, rdpSettings* settings)\n{\n\tWINPR_UNUSED(settings);\n\tif (length > 4)\n\t\tStream_Seek_UINT16(s); /* fontSupportFlags (2 bytes) */\n\n\tif (length > 6)\n\t\tStream_Seek_UINT16(s); /* pad2Octets (2 bytes) */\n\n\treturn TRUE;\n}", "func_hash": 96775287308094683173081923312272464161, "file_name": "capabilities.c", "file_hash": 220178181907002554481670918981962007546, "cwe": ["CWE-125"], "cve": "CVE-2020-11058", "cve_desc": "In FreeRDP after 1.1 and before 2.0.0, a stream out-of-bounds seek in rdp_read_font_capability_set could lead to a later out-of-bounds read. As a result, a manipulated client or server might force a disconnect due to an invalid data read. This has been fixed in 2.0.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11058"} {"idx": 409646, "project": "FreeRDP", "commit_id": "3627aaf7d289315b614a584afb388f04abfb5bbf", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/3627aaf7d289315b614a584afb388f04abfb5bbf", "commit_message": "Fixed #6011: Bounds check in rdp_read_font_capability_set", "target": 0, "func": "static BOOL rdp_read_font_capability_set(wStream* s, UINT16 length, rdpSettings* settings)\n{\n\tWINPR_UNUSED(settings);\n\tif (length > 5)\n\t\tStream_Seek_UINT16(s); /* fontSupportFlags (2 bytes) */\n\n\tif (length > 7)\n\t\tStream_Seek_UINT16(s); /* pad2Octets (2 bytes) */\n\n\treturn TRUE;\n}", "func_hash": 240631951564620109845124398816934997661, "file_name": "capabilities.c", "file_hash": 293392751886149045407526050872086295032, "cwe": ["CWE-125"], "cve": "CVE-2020-11058", "cve_desc": "In FreeRDP after 1.1 and before 2.0.0, a stream out-of-bounds seek in rdp_read_font_capability_set could lead to a later out-of-bounds read. As a result, a manipulated client or server might force a disconnect due to an invalid data read. This has been fixed in 2.0.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11058"} {"idx": 208442, "project": "vim", "commit_id": "a4bc2dd7cccf5a4a9f78b58b6f35a45d17164323", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/a4bc2dd7cccf5a4a9f78b58b6f35a45d17164323", "commit_message": "patch 8.2.4233: crash when recording and using Select mode\n\nProblem: Crash when recording and using Select mode.\nSolution: When deleting the last recorded character check there is something\n to delete.", "target": 1, "func": "delete_buff_tail(buffheader_T *buf, int slen)\n{\n int len = (int)STRLEN(buf->bh_curr->b_str);\n\n if (len >= slen)\n {\n\tbuf->bh_curr->b_str[len - slen] = NUL;\n\tbuf->bh_space += slen;\n }\n}", "func_hash": 90835994948559295819813488897108093946, "file_name": "getchar.c", "file_hash": 76721105757079965904241533445828839417, "cwe": ["CWE-125"], "cve": "CVE-2022-0393", "cve_desc": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0393"} {"idx": 410380, "project": "vim", "commit_id": "a4bc2dd7cccf5a4a9f78b58b6f35a45d17164323", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/a4bc2dd7cccf5a4a9f78b58b6f35a45d17164323", "commit_message": "patch 8.2.4233: crash when recording and using Select mode\n\nProblem: Crash when recording and using Select mode.\nSolution: When deleting the last recorded character check there is something\n to delete.", "target": 0, "func": "delete_buff_tail(buffheader_T *buf, int slen)\n{\n int len;\n\n if (buf->bh_curr == NULL || buf->bh_curr->b_str == NULL)\n\treturn; // nothing to delete\n len = (int)STRLEN(buf->bh_curr->b_str);\n if (len >= slen)\n {\n\tbuf->bh_curr->b_str[len - slen] = NUL;\n\tbuf->bh_space += slen;\n }\n}", "func_hash": 336788785576301235020342001615874018140, "file_name": "getchar.c", "file_hash": 84112372745004655192629545398640829449, "cwe": ["CWE-125"], "cve": "CVE-2022-0393", "cve_desc": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0393"} {"idx": 208443, "project": "util-linux", "commit_id": "57202f5713afa2af20ffbb6ab5331481d0396f8d", "project_url": "https://github.com/karelzak/util-linux", "commit_url": "https://github.com/util-linux/util-linux/commit/57202f5713afa2af20ffbb6ab5331481d0396f8d", "commit_message": "libmount: fix UID check for FUSE umount [CVE-2021-3995]\n\nImproper UID check allows an unprivileged user to unmount FUSE\nfilesystems of users with similar UID.\n\nSigned-off-by: Karel Zak ", "target": 1, "func": "static int is_fuse_usermount(struct libmnt_context *cxt, int *errsv)\n{\n\tstruct libmnt_ns *ns_old;\n\tconst char *type = mnt_fs_get_fstype(cxt->fs);\n\tconst char *optstr;\n\tchar *user_id = NULL;\n\tsize_t sz;\n\tuid_t uid;\n\tchar uidstr[sizeof(stringify_value(ULONG_MAX))];\n\n\t*errsv = 0;\n\n\tif (!type)\n\t\treturn 0;\n\n\tif (strcmp(type, \"fuse\") != 0 &&\n\t strcmp(type, \"fuseblk\") != 0 &&\n\t strncmp(type, \"fuse.\", 5) != 0 &&\n\t strncmp(type, \"fuseblk.\", 8) != 0)\n\t\treturn 0;\n\n\t/* get user_id= from mount table */\n\toptstr = mnt_fs_get_fs_options(cxt->fs);\n\tif (!optstr)\n\t\treturn 0;\n\n\tif (mnt_optstr_get_option(optstr, \"user_id\", &user_id, &sz) != 0)\n\t\treturn 0;\n\n\tif (sz == 0 || user_id == NULL)\n\t\treturn 0;\n\n\t/* get current user */\n\tns_old = mnt_context_switch_origin_ns(cxt);\n\tif (!ns_old) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tuid = getuid();\n\n\tif (!mnt_context_switch_ns(cxt, ns_old)) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tsnprintf(uidstr, sizeof(uidstr), \"%lu\", (unsigned long) uid);\n\treturn strncmp(user_id, uidstr, sz) == 0;\n}", "func_hash": 250996731534461132714192643189189574637, "file_name": "context_umount.c", "file_hash": 125812784703718397556754016630697265498, "cwe": ["CWE-703"], "cve": "CVE-2021-3995", "cve_desc": "A logic error was found in the libmount library of util-linux in the function that allows an unprivileged user to unmount a FUSE filesystem. This flaw allows an unprivileged local attacker to unmount FUSE filesystems that belong to certain other users who have a UID that is a prefix of the UID of the attacker in its string form. An attacker may use this flaw to cause a denial of service to applications that use the affected filesystems.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3995"} {"idx": 410433, "project": "util-linux", "commit_id": "57202f5713afa2af20ffbb6ab5331481d0396f8d", "project_url": "https://github.com/karelzak/util-linux", "commit_url": "https://github.com/util-linux/util-linux/commit/57202f5713afa2af20ffbb6ab5331481d0396f8d", "commit_message": "libmount: fix UID check for FUSE umount [CVE-2021-3995]\n\nImproper UID check allows an unprivileged user to unmount FUSE\nfilesystems of users with similar UID.\n\nSigned-off-by: Karel Zak ", "target": 0, "func": "static int is_fuse_usermount(struct libmnt_context *cxt, int *errsv)\n{\n\tstruct libmnt_ns *ns_old;\n\tconst char *type = mnt_fs_get_fstype(cxt->fs);\n\tconst char *optstr;\n\tuid_t uid, entry_uid;\n\n\t*errsv = 0;\n\n\tif (!type)\n\t\treturn 0;\n\n\tif (strcmp(type, \"fuse\") != 0 &&\n\t strcmp(type, \"fuseblk\") != 0 &&\n\t strncmp(type, \"fuse.\", 5) != 0 &&\n\t strncmp(type, \"fuseblk.\", 8) != 0)\n\t\treturn 0;\n\n\t/* get user_id= from mount table */\n\toptstr = mnt_fs_get_fs_options(cxt->fs);\n\tif (!optstr)\n\t\treturn 0;\n\tif (mnt_optstr_get_uid(optstr, \"user_id\", &entry_uid) != 0)\n\t\treturn 0;\n\n\t/* get current user */\n\tns_old = mnt_context_switch_origin_ns(cxt);\n\tif (!ns_old) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tuid = getuid();\n\n\tif (!mnt_context_switch_ns(cxt, ns_old)) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\treturn uid == entry_uid;\n}", "func_hash": 213903412718009870541850988614145209310, "file_name": "context_umount.c", "file_hash": 146021313466954642962075102520904761419, "cwe": ["CWE-703"], "cve": "CVE-2021-3995", "cve_desc": "A logic error was found in the libmount library of util-linux in the function that allows an unprivileged user to unmount a FUSE filesystem. This flaw allows an unprivileged local attacker to unmount FUSE filesystems that belong to certain other users who have a UID that is a prefix of the UID of the attacker in its string form. An attacker may use this flaw to cause a denial of service to applications that use the affected filesystems.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3995"} {"idx": 208465, "project": "linux", "commit_id": "bb1fceca22492109be12640d49f5ea5a544c6bb4", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/bb1fceca22492109be12640d49f5ea5a544c6bb4", "commit_message": "tcp: fix use after free in tcp_xmit_retransmit_queue()\n\nWhen tcp_sendmsg() allocates a fresh and empty skb, it puts it at the\ntail of the write queue using tcp_add_write_queue_tail()\n\nThen it attempts to copy user data into this fresh skb.\n\nIf the copy fails, we undo the work and remove the fresh skb.\n\nUnfortunately, this undo lacks the change done to tp->highest_sack and\nwe can leave a dangling pointer (to a freed skb)\n\nLater, tcp_xmit_retransmit_queue() can dereference this pointer and\naccess freed memory. For regular kernels where memory is not unmapped,\nthis might cause SACK bugs because tcp_highest_sack_seq() is buggy,\nreturning garbage instead of tp->snd_nxt, but with various debug\nfeatures like CONFIG_DEBUG_PAGEALLOC, this can crash the kernel.\n\nThis bug was found by Marco Grassi thanks to syzkaller.\n\nFixes: 6859d49475d4 (\"[TCP]: Abstract tp->highest_sack accessing & point to next skb\")\nReported-by: Marco Grassi \nSigned-off-by: Eric Dumazet \nCc: Ilpo J\u00e4rvinen \nCc: Yuchung Cheng \nCc: Neal Cardwell \nAcked-by: Neal Cardwell \nReviewed-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 1, "func": "static inline void tcp_check_send_head(struct sock *sk, struct sk_buff *skb_unlinked)\n{\n\tif (sk->sk_send_head == skb_unlinked)\n\t\tsk->sk_send_head = NULL;\n}", "func_hash": 286319380038378703927252822840010754897, "file_name": "tcp.h", "file_hash": 236491050258006963296337743903046036385, "cwe": ["CWE-269"], "cve": "CVE-2016-6828", "cve_desc": "The tcp_check_send_head function in include/net/tcp.h in the Linux kernel before 4.7.5 does not properly maintain certain SACK state after a failed data copy, which allows local users to cause a denial of service (tcp_xmit_retransmit_queue use-after-free and system crash) via a crafted SACK option.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6828"} {"idx": 410730, "project": "linux", "commit_id": "bb1fceca22492109be12640d49f5ea5a544c6bb4", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/bb1fceca22492109be12640d49f5ea5a544c6bb4", "commit_message": "tcp: fix use after free in tcp_xmit_retransmit_queue()\n\nWhen tcp_sendmsg() allocates a fresh and empty skb, it puts it at the\ntail of the write queue using tcp_add_write_queue_tail()\n\nThen it attempts to copy user data into this fresh skb.\n\nIf the copy fails, we undo the work and remove the fresh skb.\n\nUnfortunately, this undo lacks the change done to tp->highest_sack and\nwe can leave a dangling pointer (to a freed skb)\n\nLater, tcp_xmit_retransmit_queue() can dereference this pointer and\naccess freed memory. For regular kernels where memory is not unmapped,\nthis might cause SACK bugs because tcp_highest_sack_seq() is buggy,\nreturning garbage instead of tp->snd_nxt, but with various debug\nfeatures like CONFIG_DEBUG_PAGEALLOC, this can crash the kernel.\n\nThis bug was found by Marco Grassi thanks to syzkaller.\n\nFixes: 6859d49475d4 (\"[TCP]: Abstract tp->highest_sack accessing & point to next skb\")\nReported-by: Marco Grassi \nSigned-off-by: Eric Dumazet \nCc: Ilpo J\u00e4rvinen \nCc: Yuchung Cheng \nCc: Neal Cardwell \nAcked-by: Neal Cardwell \nReviewed-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 0, "func": "static inline void tcp_check_send_head(struct sock *sk, struct sk_buff *skb_unlinked)\n{\n\tif (sk->sk_send_head == skb_unlinked)\n\t\tsk->sk_send_head = NULL;\n\tif (tcp_sk(sk)->highest_sack == skb_unlinked)\n\t\ttcp_sk(sk)->highest_sack = NULL;\n}", "func_hash": 13960346507511537841086746551000480722, "file_name": "tcp.h", "file_hash": 190793441312101944732099470746697518158, "cwe": ["CWE-269"], "cve": "CVE-2016-6828", "cve_desc": "The tcp_check_send_head function in include/net/tcp.h in the Linux kernel before 4.7.5 does not properly maintain certain SACK state after a failed data copy, which allows local users to cause a denial of service (tcp_xmit_retransmit_queue use-after-free and system crash) via a crafted SACK option.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6828"} {"idx": 208486, "project": "FreeRDP", "commit_id": "7b1d4b49391b4512402840431757703a96946820", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/7b1d4b49391b4512402840431757703a96946820", "commit_message": "Fix CVE-2020-11524: out of bounds access in interleaved\n\nThanks to Sunglin and HuanGMz from Knownsec 404", "target": 1, "func": "static INLINE BOOL ensure_capacity(const BYTE* start, const BYTE* end, size_t size, size_t base)\n{\n\tconst size_t available = (uintptr_t)end - (uintptr_t)start;\n\tconst BOOL rc = available >= size * base;\n\treturn rc;\n}", "func_hash": 273800597882029893841433748498836516890, "file_name": "interleaved.c", "file_hash": 53310291745985367888052005529616339629, "cwe": ["CWE-787"], "cve": "CVE-2020-11524", "cve_desc": "libfreerdp/codec/interleaved.c in FreeRDP versions > 1.0 through 2.0.0-rc4 has an Out-of-bounds Write.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11524"} {"idx": 411767, "project": "FreeRDP", "commit_id": "7b1d4b49391b4512402840431757703a96946820", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/7b1d4b49391b4512402840431757703a96946820", "commit_message": "Fix CVE-2020-11524: out of bounds access in interleaved\n\nThanks to Sunglin and HuanGMz from Knownsec 404", "target": 0, "func": "static INLINE BOOL ensure_capacity(const BYTE* start, const BYTE* end, size_t size, size_t base)\n{\n\tconst size_t available = (uintptr_t)end - (uintptr_t)start;\n\tconst BOOL rc = available >= size * base;\n\treturn rc && (start <= end);\n}", "func_hash": 62009639525486969112218650651107079035, "file_name": "interleaved.c", "file_hash": 59823618162798519600546635910344459304, "cwe": ["CWE-787"], "cve": "CVE-2020-11524", "cve_desc": "libfreerdp/codec/interleaved.c in FreeRDP versions > 1.0 through 2.0.0-rc4 has an Out-of-bounds Write.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11524"} {"idx": 208509, "project": "samurai", "commit_id": "d2af3bc375e2a77139c3a28d6128c60cd8d08655", "project_url": "https://github.com/michaelforney/samurai", "commit_url": "https://github.com/michaelforney/samurai/commit/d2af3bc375e2a77139c3a28d6128c60cd8d08655", "commit_message": "parse: Check for non-empty command/rspfile/rspfile_content\n\nThis matches ninja behavior and prevents the possibility of a rule\nwith an empty (NULL) command string.\n\nFixes #68.", "target": 1, "func": "parserule(struct scanner *s, struct environment *env)\n{\n\tstruct rule *r;\n\tchar *var;\n\tstruct evalstring *val;\n\tbool hascommand = false, hasrspfile = false, hasrspcontent = false;\n\n\tr = mkrule(scanname(s));\n\tscannewline(s);\n\twhile (scanindent(s)) {\n\t\tvar = scanname(s);\n\t\tparselet(s, &val);\n\t\truleaddvar(r, var, val);\n\t\tif (strcmp(var, \"command\") == 0)\n\t\t\thascommand = true;\n\t\telse if (strcmp(var, \"rspfile\") == 0)\n\t\t\thasrspfile = true;\n\t\telse if (strcmp(var, \"rspfile_content\") == 0)\n\t\t\thasrspcontent = true;\n\t}\n\tif (!hascommand)\n\t\tfatal(\"rule '%s' has no command\", r->name);\n\tif (hasrspfile != hasrspcontent)\n\t\tfatal(\"rule '%s' has rspfile and no rspfile_content or vice versa\", r->name);\n\tenvaddrule(env, r);\n}", "func_hash": 158772877754883417055259391720915509761, "file_name": "parse.c", "file_hash": 134786963503081241350175386942272896983, "cwe": ["CWE-284"], "cve": "CVE-2021-30219", "cve_desc": "samurai 1.2 has a NULL pointer dereference in printstatus() function in build.c via a crafted build file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30219"} {"idx": 411968, "project": "samurai", "commit_id": "d2af3bc375e2a77139c3a28d6128c60cd8d08655", "project_url": "https://github.com/michaelforney/samurai", "commit_url": "https://github.com/michaelforney/samurai/commit/d2af3bc375e2a77139c3a28d6128c60cd8d08655", "commit_message": "parse: Check for non-empty command/rspfile/rspfile_content\n\nThis matches ninja behavior and prevents the possibility of a rule\nwith an empty (NULL) command string.\n\nFixes #68.", "target": 0, "func": "parserule(struct scanner *s, struct environment *env)\n{\n\tstruct rule *r;\n\tchar *var;\n\tstruct evalstring *val;\n\tbool hascommand = false, hasrspfile = false, hasrspcontent = false;\n\n\tr = mkrule(scanname(s));\n\tscannewline(s);\n\twhile (scanindent(s)) {\n\t\tvar = scanname(s);\n\t\tparselet(s, &val);\n\t\truleaddvar(r, var, val);\n\t\tif (!val)\n\t\t\tcontinue;\n\t\tif (strcmp(var, \"command\") == 0)\n\t\t\thascommand = true;\n\t\telse if (strcmp(var, \"rspfile\") == 0)\n\t\t\thasrspfile = true;\n\t\telse if (strcmp(var, \"rspfile_content\") == 0)\n\t\t\thasrspcontent = true;\n\t}\n\tif (!hascommand)\n\t\tfatal(\"rule '%s' has no command\", r->name);\n\tif (hasrspfile != hasrspcontent)\n\t\tfatal(\"rule '%s' has rspfile and no rspfile_content or vice versa\", r->name);\n\tenvaddrule(env, r);\n}", "func_hash": 157838789206844278726643478332342942198, "file_name": "parse.c", "file_hash": 119357443556476309285433377996843330247, "cwe": ["CWE-284"], "cve": "CVE-2021-30219", "cve_desc": "samurai 1.2 has a NULL pointer dereference in printstatus() function in build.c via a crafted build file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30219"} {"idx": 208514, "project": "kitty", "commit_id": "82c137878c2b99100a3cdc1c0f0efea069313901", "project_url": "https://github.com/kovidgoyal/kitty", "commit_url": "https://github.com/kovidgoyal/kitty/commit/82c137878c2b99100a3cdc1c0f0efea069313901", "commit_message": "Graphics protocol: Dont return filename in the error message when opening file fails, since filenames can contain control characters\n\nFixes #3128", "target": 1, "func": "handle_add_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, bool *is_dirty, uint32_t iid) {\n#define ABRT(code, ...) { set_add_response(#code, __VA_ARGS__); self->loading_image = 0; if (img) img->data_loaded = false; return NULL; }\n#define MAX_DATA_SZ (4u * 100000000u)\n has_add_respose = false;\n bool existing, init_img = true;\n Image *img = NULL;\n unsigned char tt = g->transmission_type ? g->transmission_type : 'd';\n enum FORMATS { RGB=24, RGBA=32, PNG=100 };\n uint32_t fmt = g->format ? g->format : RGBA;\n if (tt == 'd' && self->loading_image) init_img = false;\n if (init_img) {\n self->last_init_graphics_command = *g;\n self->last_init_graphics_command.id = iid;\n self->loading_image = 0;\n if (g->data_width > 10000 || g->data_height > 10000) ABRT(EINVAL, \"Image too large\");\n remove_images(self, add_trim_predicate, 0);\n img = find_or_create_image(self, iid, &existing);\n if (existing) {\n free_load_data(&img->load_data);\n img->data_loaded = false;\n free_refs_data(img);\n *is_dirty = true;\n self->layers_dirty = true;\n } else {\n img->internal_id = internal_id_counter++;\n img->client_id = iid;\n }\n img->atime = monotonic(); img->used_storage = 0;\n img->width = g->data_width; img->height = g->data_height;\n switch(fmt) {\n case PNG:\n if (g->data_sz > MAX_DATA_SZ) ABRT(EINVAL, \"PNG data size too large\");\n img->load_data.is_4byte_aligned = true;\n img->load_data.is_opaque = false;\n img->load_data.data_sz = g->data_sz ? g->data_sz : 1024 * 100;\n break;\n case RGB:\n case RGBA:\n img->load_data.data_sz = (size_t)g->data_width * g->data_height * (fmt / 8);\n if (!img->load_data.data_sz) ABRT(EINVAL, \"Zero width/height not allowed\");\n img->load_data.is_4byte_aligned = fmt == RGBA || (img->width % 4 == 0);\n img->load_data.is_opaque = fmt == RGB;\n break;\n default:\n ABRT(EINVAL, \"Unknown image format: %u\", fmt);\n }\n if (tt == 'd') {\n if (g->more) self->loading_image = img->internal_id;\n img->load_data.buf_capacity = img->load_data.data_sz + (g->compressed ? 1024 : 10); // compression header\n img->load_data.buf = malloc(img->load_data.buf_capacity);\n img->load_data.buf_used = 0;\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n } else {\n self->last_init_graphics_command.more = g->more;\n self->last_init_graphics_command.payload_sz = g->payload_sz;\n g = &self->last_init_graphics_command;\n tt = g->transmission_type ? g->transmission_type : 'd';\n fmt = g->format ? g->format : RGBA;\n img = img_by_internal_id(self, self->loading_image);\n if (img == NULL) {\n self->loading_image = 0;\n ABRT(EILSEQ, \"More payload loading refers to non-existent image\");\n }\n }\n int fd;\n static char fname[2056] = {0};\n switch(tt) {\n case 'd': // direct\n if (img->load_data.buf_capacity - img->load_data.buf_used < g->payload_sz) {\n if (img->load_data.buf_used + g->payload_sz > MAX_DATA_SZ || fmt != PNG) ABRT(EFBIG, \"Too much data\");\n img->load_data.buf_capacity = MIN(2 * img->load_data.buf_capacity, MAX_DATA_SZ);\n img->load_data.buf = realloc(img->load_data.buf, img->load_data.buf_capacity);\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n memcpy(img->load_data.buf + img->load_data.buf_used, payload, g->payload_sz);\n img->load_data.buf_used += g->payload_sz;\n if (!g->more) { img->data_loaded = true; self->loading_image = 0; }\n break;\n case 'f': // file\n case 't': // temporary file\n case 's': // POSIX shared memory\n if (g->payload_sz > 2048) ABRT(EINVAL, \"Filename too long\");\n snprintf(fname, sizeof(fname)/sizeof(fname[0]), \"%.*s\", (int)g->payload_sz, payload);\n if (tt == 's') fd = shm_open(fname, O_RDONLY, 0);\n else fd = open(fname, O_CLOEXEC | O_RDONLY);\n if (fd == -1) ABRT(EBADF, \"Failed to open file %s for graphics transmission with error: [%d] %s\", fname, errno, strerror(errno));\n img->data_loaded = mmap_img_file(self, img, fd, g->data_sz, g->data_offset);\n safe_close(fd, __FILE__, __LINE__);\n if (tt == 't') {\n if (global_state.boss) { call_boss(safe_delete_temp_file, \"s\", fname); }\n else unlink(fname);\n }\n else if (tt == 's') shm_unlink(fname);\n break;\n default:\n ABRT(EINVAL, \"Unknown transmission type: %c\", g->transmission_type);\n }\n if (!img->data_loaded) return NULL;\n self->loading_image = 0;\n bool needs_processing = g->compressed || fmt == PNG;\n if (needs_processing) {\n uint8_t *buf; size_t bufsz;\n#define IB { if (img->load_data.buf) { buf = img->load_data.buf; bufsz = img->load_data.buf_used; } else { buf = img->load_data.mapped_file; bufsz = img->load_data.mapped_file_sz; } }\n switch(g->compressed) {\n case 'z':\n IB;\n if (!inflate_zlib(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n case 0:\n break;\n default:\n ABRT(EINVAL, \"Unknown image compression: %c\", g->compressed);\n }\n switch(fmt) {\n case PNG:\n IB;\n if (!inflate_png(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n default: break;\n }\n#undef IB\n img->load_data.data = img->load_data.buf;\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n }\n if (img->load_data.mapped_file) {\n munmap(img->load_data.mapped_file, img->load_data.mapped_file_sz);\n img->load_data.mapped_file = NULL; img->load_data.mapped_file_sz = 0;\n }\n } else {\n if (tt == 'd') {\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.buf;\n } else {\n if (img->load_data.mapped_file_sz < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.mapped_file_sz, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.mapped_file;\n }\n }\n size_t required_sz = (size_t)(img->load_data.is_opaque ? 3 : 4) * img->width * img->height;\n if (img->load_data.data_sz != required_sz) ABRT(EINVAL, \"Image dimensions: %ux%u do not match data size: %zu, expected size: %zu\", img->width, img->height, img->load_data.data_sz, required_sz);\n if (LIKELY(img->data_loaded && send_to_gpu)) {\n send_image_to_gpu(&img->texture_id, img->load_data.data, img->width, img->height, img->load_data.is_opaque, img->load_data.is_4byte_aligned, false, REPEAT_CLAMP);\n free_load_data(&img->load_data);\n self->used_storage += required_sz;\n img->used_storage = required_sz;\n }\n return img;\n#undef MAX_DATA_SZ\n#undef ABRT\n}", "func_hash": 190291358908045897044593526849423587818, "file_name": "graphics.c", "file_hash": 218259155304673927751800930612074736524, "cwe": ["CWE-787"], "cve": "CVE-2020-35605", "cve_desc": "The Graphics Protocol feature in graphics.c in kitty before 0.19.3 allows remote attackers to execute arbitrary code because a filename containing special characters can be included in an error message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35605"} {"idx": 412024, "project": "kitty", "commit_id": "82c137878c2b99100a3cdc1c0f0efea069313901", "project_url": "https://github.com/kovidgoyal/kitty", "commit_url": "https://github.com/kovidgoyal/kitty/commit/82c137878c2b99100a3cdc1c0f0efea069313901", "commit_message": "Graphics protocol: Dont return filename in the error message when opening file fails, since filenames can contain control characters\n\nFixes #3128", "target": 0, "func": "handle_add_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, bool *is_dirty, uint32_t iid) {\n#define ABRT(code, ...) { set_add_response(#code, __VA_ARGS__); self->loading_image = 0; if (img) img->data_loaded = false; return NULL; }\n#define MAX_DATA_SZ (4u * 100000000u)\n has_add_respose = false;\n bool existing, init_img = true;\n Image *img = NULL;\n unsigned char tt = g->transmission_type ? g->transmission_type : 'd';\n enum FORMATS { RGB=24, RGBA=32, PNG=100 };\n uint32_t fmt = g->format ? g->format : RGBA;\n if (tt == 'd' && self->loading_image) init_img = false;\n if (init_img) {\n self->last_init_graphics_command = *g;\n self->last_init_graphics_command.id = iid;\n self->loading_image = 0;\n if (g->data_width > 10000 || g->data_height > 10000) ABRT(EINVAL, \"Image too large\");\n remove_images(self, add_trim_predicate, 0);\n img = find_or_create_image(self, iid, &existing);\n if (existing) {\n free_load_data(&img->load_data);\n img->data_loaded = false;\n free_refs_data(img);\n *is_dirty = true;\n self->layers_dirty = true;\n } else {\n img->internal_id = internal_id_counter++;\n img->client_id = iid;\n }\n img->atime = monotonic(); img->used_storage = 0;\n img->width = g->data_width; img->height = g->data_height;\n switch(fmt) {\n case PNG:\n if (g->data_sz > MAX_DATA_SZ) ABRT(EINVAL, \"PNG data size too large\");\n img->load_data.is_4byte_aligned = true;\n img->load_data.is_opaque = false;\n img->load_data.data_sz = g->data_sz ? g->data_sz : 1024 * 100;\n break;\n case RGB:\n case RGBA:\n img->load_data.data_sz = (size_t)g->data_width * g->data_height * (fmt / 8);\n if (!img->load_data.data_sz) ABRT(EINVAL, \"Zero width/height not allowed\");\n img->load_data.is_4byte_aligned = fmt == RGBA || (img->width % 4 == 0);\n img->load_data.is_opaque = fmt == RGB;\n break;\n default:\n ABRT(EINVAL, \"Unknown image format: %u\", fmt);\n }\n if (tt == 'd') {\n if (g->more) self->loading_image = img->internal_id;\n img->load_data.buf_capacity = img->load_data.data_sz + (g->compressed ? 1024 : 10); // compression header\n img->load_data.buf = malloc(img->load_data.buf_capacity);\n img->load_data.buf_used = 0;\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n } else {\n self->last_init_graphics_command.more = g->more;\n self->last_init_graphics_command.payload_sz = g->payload_sz;\n g = &self->last_init_graphics_command;\n tt = g->transmission_type ? g->transmission_type : 'd';\n fmt = g->format ? g->format : RGBA;\n img = img_by_internal_id(self, self->loading_image);\n if (img == NULL) {\n self->loading_image = 0;\n ABRT(EILSEQ, \"More payload loading refers to non-existent image\");\n }\n }\n int fd;\n static char fname[2056] = {0};\n switch(tt) {\n case 'd': // direct\n if (img->load_data.buf_capacity - img->load_data.buf_used < g->payload_sz) {\n if (img->load_data.buf_used + g->payload_sz > MAX_DATA_SZ || fmt != PNG) ABRT(EFBIG, \"Too much data\");\n img->load_data.buf_capacity = MIN(2 * img->load_data.buf_capacity, MAX_DATA_SZ);\n img->load_data.buf = realloc(img->load_data.buf, img->load_data.buf_capacity);\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n memcpy(img->load_data.buf + img->load_data.buf_used, payload, g->payload_sz);\n img->load_data.buf_used += g->payload_sz;\n if (!g->more) { img->data_loaded = true; self->loading_image = 0; }\n break;\n case 'f': // file\n case 't': // temporary file\n case 's': // POSIX shared memory\n if (g->payload_sz > 2048) ABRT(EINVAL, \"Filename too long\");\n snprintf(fname, sizeof(fname)/sizeof(fname[0]), \"%.*s\", (int)g->payload_sz, payload);\n if (tt == 's') fd = shm_open(fname, O_RDONLY, 0);\n else fd = open(fname, O_CLOEXEC | O_RDONLY);\n if (fd == -1) ABRT(EBADF, \"Failed to open file for graphics transmission with error: [%d] %s\", errno, strerror(errno));\n img->data_loaded = mmap_img_file(self, img, fd, g->data_sz, g->data_offset);\n safe_close(fd, __FILE__, __LINE__);\n if (tt == 't') {\n if (global_state.boss) { call_boss(safe_delete_temp_file, \"s\", fname); }\n else unlink(fname);\n }\n else if (tt == 's') shm_unlink(fname);\n break;\n default:\n ABRT(EINVAL, \"Unknown transmission type: %c\", g->transmission_type);\n }\n if (!img->data_loaded) return NULL;\n self->loading_image = 0;\n bool needs_processing = g->compressed || fmt == PNG;\n if (needs_processing) {\n uint8_t *buf; size_t bufsz;\n#define IB { if (img->load_data.buf) { buf = img->load_data.buf; bufsz = img->load_data.buf_used; } else { buf = img->load_data.mapped_file; bufsz = img->load_data.mapped_file_sz; } }\n switch(g->compressed) {\n case 'z':\n IB;\n if (!inflate_zlib(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n case 0:\n break;\n default:\n ABRT(EINVAL, \"Unknown image compression: %c\", g->compressed);\n }\n switch(fmt) {\n case PNG:\n IB;\n if (!inflate_png(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n default: break;\n }\n#undef IB\n img->load_data.data = img->load_data.buf;\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n }\n if (img->load_data.mapped_file) {\n munmap(img->load_data.mapped_file, img->load_data.mapped_file_sz);\n img->load_data.mapped_file = NULL; img->load_data.mapped_file_sz = 0;\n }\n } else {\n if (tt == 'd') {\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.buf;\n } else {\n if (img->load_data.mapped_file_sz < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.mapped_file_sz, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.mapped_file;\n }\n }\n size_t required_sz = (size_t)(img->load_data.is_opaque ? 3 : 4) * img->width * img->height;\n if (img->load_data.data_sz != required_sz) ABRT(EINVAL, \"Image dimensions: %ux%u do not match data size: %zu, expected size: %zu\", img->width, img->height, img->load_data.data_sz, required_sz);\n if (LIKELY(img->data_loaded && send_to_gpu)) {\n send_image_to_gpu(&img->texture_id, img->load_data.data, img->width, img->height, img->load_data.is_opaque, img->load_data.is_4byte_aligned, false, REPEAT_CLAMP);\n free_load_data(&img->load_data);\n self->used_storage += required_sz;\n img->used_storage = required_sz;\n }\n return img;\n#undef MAX_DATA_SZ\n#undef ABRT\n}", "func_hash": 193680568271064946316026012683564581506, "file_name": "graphics.c", "file_hash": 214029482599077989103196340419005151504, "cwe": ["CWE-787"], "cve": "CVE-2020-35605", "cve_desc": "The Graphics Protocol feature in graphics.c in kitty before 0.19.3 allows remote attackers to execute arbitrary code because a filename containing special characters can be included in an error message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35605"} {"idx": 208547, "project": "kopano-core", "commit_id": "512457466b87039c6a8d25887fdaca6173619546", "project_url": "https://github.com/Kopano-dev/kopano-core", "commit_url": "https://github.com/Kopano-dev/kopano-core/commit/512457466b87039c6a8d25887fdaca6173619546", "commit_message": "Set limit on header size to prevent bad alloc\n\nThis sets a hard limit of 64 KiB to the header to prevent a memory\nallocation exception from being thrown during the parsing of the request\nheaders.", "target": 1, "func": "HRESULT Http::HrReadHeaders()\n{\n\tHRESULT hr;\n\tstd::string strBuffer;\n\tULONG n = 0;\n\tstd::map::iterator iHeader = mapHeaders.end();\n\n\tec_log_debug(\"Receiving headers:\");\n\tdo\n\t{\n\t\thr = m_lpChannel->HrReadLine(strBuffer);\n\t\tif (hr != hrSuccess)\n\t\t\treturn hr;\n\t\tif (strBuffer.empty())\n\t\t\tbreak;\n\n\t\tif (n == 0) {\n\t\t\tm_strAction = strBuffer;\n\t\t} else {\n\t\t\tauto pos = strBuffer.find(':');\n\t\t\tsize_t start = 0;\n\n\t\t\tif (strBuffer[0] == ' ' || strBuffer[0] == '\\t') {\n\t\t\t\tif (iHeader == mapHeaders.end())\n\t\t\t\t\tcontinue;\n\t\t\t\t// continue header\n\t\t\t\twhile (strBuffer[start] == ' ' || strBuffer[start] == '\\t')\n\t\t\t\t\t++start;\n\t\t\t\tiHeader->second += strBuffer.substr(start);\n\t\t\t} else {\n\t\t\t\t// new header\n\t\t\t\tauto r = mapHeaders.emplace(strBuffer.substr(0, pos), strBuffer.substr(pos + 2));\n\t\t\t\tiHeader = r.first;\n\t\t\t}\n\t\t}\n\n\t\tif (strBuffer.find(\"Authorization\") != std::string::npos)\n\t\t\tec_log_debug(\"< Authorization: