idx
int64
project
string
commit_id
string
project_url
string
commit_url
string
commit_message
string
target
int64
func
string
func_hash
string
file_name
string
file_hash
string
cwe
string
cve
string
cve_desc
string
nvd_url
string
211,563
vim
a062006b9de0b2947ab5fb376c6e67ef92a8cd69
https://github.com/vim/vim
https://github.com/vim/vim/commit/a062006b9de0b2947ab5fb376c6e67ef92a8cd69
patch 8.2.3610: crash when ModeChanged triggered too early Problem: Crash when ModeChanged triggered too early. Solution: Trigger ModeChanged after setting VIsual.
1
n_start_visual_mode(int c) { #ifdef FEAT_CONCEAL int cursor_line_was_concealed = curwin->w_p_cole > 0 && conceal_cursor_line(curwin); #endif VIsual_mode = c; VIsual_active = TRUE; VIsual_reselect = TRUE; trigger_modechanged(); // Corner case: the 0 position in a tab may change when going into // virtualedit. Recalculate curwin->w_cursor to avoid bad highlighting. if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB) { validate_virtcol(); coladvance(curwin->w_virtcol); } VIsual = curwin->w_cursor; #ifdef FEAT_FOLDING foldAdjustVisual(); #endif setmouse(); #ifdef FEAT_CONCEAL // Check if redraw is needed after changing the state. conceal_check_cursor_line(cursor_line_was_concealed); #endif if (p_smd && msg_silent == 0) redraw_cmdline = TRUE; // show visual mode later #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end may still be the same, and the selection needs to be owned clip_star.vmode = NUL; #endif // Only need to redraw this line, unless still need to redraw an old // Visual area (when 'lazyredraw' is set). if (curwin->w_redr_type < INVERTED) { curwin->w_old_cursor_lnum = curwin->w_cursor.lnum; curwin->w_old_visual_lnum = curwin->w_cursor.lnum; } }
184740522957607059139984101996502665794
None
CWE-122
CVE-2021-3968
vim is vulnerable to Heap-based Buffer Overflow
https://nvd.nist.gov/vuln/detail/CVE-2021-3968
449,294
vim
a062006b9de0b2947ab5fb376c6e67ef92a8cd69
https://github.com/vim/vim
https://github.com/vim/vim/commit/a062006b9de0b2947ab5fb376c6e67ef92a8cd69
patch 8.2.3610: crash when ModeChanged triggered too early Problem: Crash when ModeChanged triggered too early. Solution: Trigger ModeChanged after setting VIsual.
0
n_start_visual_mode(int c) { #ifdef FEAT_CONCEAL int cursor_line_was_concealed = curwin->w_p_cole > 0 && conceal_cursor_line(curwin); #endif VIsual_mode = c; VIsual_active = TRUE; VIsual_reselect = TRUE; // Corner case: the 0 position in a tab may change when going into // virtualedit. Recalculate curwin->w_cursor to avoid bad highlighting. if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB) { validate_virtcol(); coladvance(curwin->w_virtcol); } VIsual = curwin->w_cursor; #ifdef FEAT_FOLDING foldAdjustVisual(); #endif trigger_modechanged(); setmouse(); #ifdef FEAT_CONCEAL // Check if redraw is needed after changing the state. conceal_check_cursor_line(cursor_line_was_concealed); #endif if (p_smd && msg_silent == 0) redraw_cmdline = TRUE; // show visual mode later #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end may still be the same, and the selection needs to be owned clip_star.vmode = NUL; #endif // Only need to redraw this line, unless still need to redraw an old // Visual area (when 'lazyredraw' is set). if (curwin->w_redr_type < INVERTED) { curwin->w_old_cursor_lnum = curwin->w_cursor.lnum; curwin->w_old_visual_lnum = curwin->w_cursor.lnum; } }
18013964164383096631914378209665418022
None
CWE-122
CVE-2021-3968
vim is vulnerable to Heap-based Buffer Overflow
https://nvd.nist.gov/vuln/detail/CVE-2021-3968
211,567
clamav-devel
c6870a6c857dd722dffaf6d37ae52ec259d12492
https://github.com/vrtadmin/clamav-devel
https://github.com/vrtadmin/clamav-devel/commit/c6870a6c857dd722dffaf6d37ae52ec259d12492
bb #6808
1
static char *getsistring(FILE *f, uint32_t ptr, uint32_t len) { char *name; uint32_t i; if (!len) return NULL; if (len>400) len=400; name = cli_malloc(len); if (!name) { cli_dbgmsg("SIS: OOM\n"); return NULL; } fseek(f, ptr, SEEK_SET); if (fread(name, len, 1, f)!=1) { cli_dbgmsg("SIS: Unable to read string\n"); free(name); return NULL; } for (i = 0 ; i < len; i+=2) name[i/2] = name[i]; name[i/2]='\0'; return name; }
249475827060217450801946160071587171974
sis.c
74416937580759661752528557759080505362
CWE-189
CVE-2013-2020
Integer underflow in the cli_scanpe function in pe.c in ClamAV before 0.97.8 allows remote attackers to cause a denial of service (crash) via a skewed offset larger than the size of the PE section in a UPX packed executable, which triggers an out-of-bounds read.
https://nvd.nist.gov/vuln/detail/CVE-2013-2020
449,321
clamav-devel
c6870a6c857dd722dffaf6d37ae52ec259d12492
https://github.com/vrtadmin/clamav-devel
https://github.com/vrtadmin/clamav-devel/commit/c6870a6c857dd722dffaf6d37ae52ec259d12492
bb #6808
0
static char *getsistring(FILE *f, uint32_t ptr, uint32_t len) { char *name; uint32_t i; if (!len) return NULL; if (len>400) len=400; name = cli_malloc(len+1); if (!name) { cli_dbgmsg("SIS: OOM\n"); return NULL; } fseek(f, ptr, SEEK_SET); if (fread(name, len, 1, f)!=1) { cli_dbgmsg("SIS: Unable to read string\n"); free(name); return NULL; } for (i = 0 ; i < len; i+=2) name[i/2] = name[i]; name[i/2]='\0'; return name; }
103287413099842266713052785251008739113
sis.c
220725720240675887606122374077538393241
CWE-189
CVE-2013-2020
Integer underflow in the cli_scanpe function in pe.c in ClamAV before 0.97.8 allows remote attackers to cause a denial of service (crash) via a skewed offset larger than the size of the PE section in a UPX packed executable, which triggers an out-of-bounds read.
https://nvd.nist.gov/vuln/detail/CVE-2013-2020
211,695
vim
4c13e5e6763c6eb36a343a2b8235ea227202e952
https://github.com/vim/vim
https://github.com/vim/vim/commit/4c13e5e6763c6eb36a343a2b8235ea227202e952
patch 8.2.3949: using freed memory with /\%V Problem: Using freed memory with /\%V. Solution: Get the line again after getvvcol().
1
reg_match_visual(void) { pos_T top, bot; linenr_T lnum; colnr_T col; win_T *wp = rex.reg_win == NULL ? curwin : rex.reg_win; int mode; colnr_T start, end; colnr_T start2, end2; colnr_T cols; colnr_T curswant; // Check if the buffer is the current buffer. if (rex.reg_buf != curbuf || VIsual.lnum == 0) return FALSE; if (VIsual_active) { if (LT_POS(VIsual, wp->w_cursor)) { top = VIsual; bot = wp->w_cursor; } else { top = wp->w_cursor; bot = VIsual; } mode = VIsual_mode; curswant = wp->w_curswant; } else { if (LT_POS(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end)) { top = curbuf->b_visual.vi_start; bot = curbuf->b_visual.vi_end; } else { top = curbuf->b_visual.vi_end; bot = curbuf->b_visual.vi_start; } mode = curbuf->b_visual.vi_mode; curswant = curbuf->b_visual.vi_curswant; } lnum = rex.lnum + rex.reg_firstlnum; if (lnum < top.lnum || lnum > bot.lnum) return FALSE; if (mode == 'v') { col = (colnr_T)(rex.input - rex.line); if ((lnum == top.lnum && col < top.col) || (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e'))) return FALSE; } else if (mode == Ctrl_V) { getvvcol(wp, &top, &start, NULL, &end); getvvcol(wp, &bot, &start2, NULL, &end2); if (start2 < start) start = start2; if (end2 > end) end = end2; if (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL) end = MAXCOL; cols = win_linetabsize(wp, rex.line, (colnr_T)(rex.input - rex.line)); if (cols < start || cols > end - (*p_sel == 'e')) return FALSE; } return TRUE; }
213127434587581742033304075177767787021
regexp.c
154178765544405999260732501141990227321
CWE-416
CVE-2021-4192
vim is vulnerable to Use After Free
https://nvd.nist.gov/vuln/detail/CVE-2021-4192
450,764
vim
4c13e5e6763c6eb36a343a2b8235ea227202e952
https://github.com/vim/vim
https://github.com/vim/vim/commit/4c13e5e6763c6eb36a343a2b8235ea227202e952
patch 8.2.3949: using freed memory with /\%V Problem: Using freed memory with /\%V. Solution: Get the line again after getvvcol().
0
reg_match_visual(void) { pos_T top, bot; linenr_T lnum; colnr_T col; win_T *wp = rex.reg_win == NULL ? curwin : rex.reg_win; int mode; colnr_T start, end; colnr_T start2, end2; colnr_T cols; colnr_T curswant; // Check if the buffer is the current buffer. if (rex.reg_buf != curbuf || VIsual.lnum == 0) return FALSE; if (VIsual_active) { if (LT_POS(VIsual, wp->w_cursor)) { top = VIsual; bot = wp->w_cursor; } else { top = wp->w_cursor; bot = VIsual; } mode = VIsual_mode; curswant = wp->w_curswant; } else { if (LT_POS(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end)) { top = curbuf->b_visual.vi_start; bot = curbuf->b_visual.vi_end; } else { top = curbuf->b_visual.vi_end; bot = curbuf->b_visual.vi_start; } mode = curbuf->b_visual.vi_mode; curswant = curbuf->b_visual.vi_curswant; } lnum = rex.lnum + rex.reg_firstlnum; if (lnum < top.lnum || lnum > bot.lnum) return FALSE; col = (colnr_T)(rex.input - rex.line); if (mode == 'v') { if ((lnum == top.lnum && col < top.col) || (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e'))) return FALSE; } else if (mode == Ctrl_V) { getvvcol(wp, &top, &start, NULL, &end); getvvcol(wp, &bot, &start2, NULL, &end2); if (start2 < start) start = start2; if (end2 > end) end = end2; if (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL) end = MAXCOL; // getvvcol() flushes rex.line, need to get it again rex.line = reg_getline(rex.lnum); rex.input = rex.line + col; cols = win_linetabsize(wp, rex.line, col); if (cols < start || cols > end - (*p_sel == 'e')) return FALSE; } return TRUE; }
273404837920170490390239404652231965596
regexp.c
323022444375597496724509829879656182542
CWE-416
CVE-2021-4192
vim is vulnerable to Use After Free
https://nvd.nist.gov/vuln/detail/CVE-2021-4192
211,699
gnulib
2d1bd71ec70a31b01d01b734faa66bb1ed28961f
https://github.com/coreutils/gnulib
http://git.savannah.gnu.org/cgit/gnulib.git/commit/?id=2d1bd71ec70a31b01d01b734faa66bb1ed28961f
glob: fix heap buffer overflow * lib/glob.c (glob): Fix off-by-one error introduced into glibc in commit dd7d45e838a42b0ed470c44b55901ea98d0c2bab dated 1997-10-29 20:33:40. Problem reported by Tim Rühsen in: https://sourceware.org/bugzilla/show_bug.cgi?id=22320 Fix suggested by Bruno Haible.
1
glob (const char *pattern, int flags, int (*errfunc) (const char *, int), glob_t *pglob) { const char *filename; char *dirname = NULL; size_t dirlen; int status; size_t oldcount; int meta; int dirname_modified; int malloc_dirname = 0; glob_t dirs; int retval = 0; size_t alloca_used = 0; if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0) { __set_errno (EINVAL); return -1; } /* POSIX requires all slashes to be matched. This means that with a trailing slash we must match only directories. */ if (pattern[0] && pattern[strlen (pattern) - 1] == '/') flags |= GLOB_ONLYDIR; if (!(flags & GLOB_DOOFFS)) /* Have to do this so 'globfree' knows where to start freeing. It also makes all the code that uses gl_offs simpler. */ pglob->gl_offs = 0; if (!(flags & GLOB_APPEND)) { pglob->gl_pathc = 0; if (!(flags & GLOB_DOOFFS)) pglob->gl_pathv = NULL; else { size_t i; if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *)) return GLOB_NOSPACE; pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1) * sizeof (char *)); if (pglob->gl_pathv == NULL) return GLOB_NOSPACE; for (i = 0; i <= pglob->gl_offs; ++i) pglob->gl_pathv[i] = NULL; } } if (flags & GLOB_BRACE) { const char *begin; if (flags & GLOB_NOESCAPE) begin = strchr (pattern, '{'); else { begin = pattern; while (1) { if (*begin == '\0') { begin = NULL; break; } if (*begin == '\\' && begin[1] != '\0') ++begin; else if (*begin == '{') break; ++begin; } } if (begin != NULL) { /* Allocate working buffer large enough for our work. Note that we have at least an opening and closing brace. */ size_t firstc; char *alt_start; const char *p; const char *next; const char *rest; size_t rest_len; char *onealt; size_t pattern_len = strlen (pattern) - 1; int alloca_onealt = glob_use_alloca (alloca_used, pattern_len); if (alloca_onealt) onealt = alloca_account (pattern_len, alloca_used); else { onealt = malloc (pattern_len); if (onealt == NULL) return GLOB_NOSPACE; } /* We know the prefix for all sub-patterns. */ alt_start = mempcpy (onealt, pattern, begin - pattern); /* Find the first sub-pattern and at the same time find the rest after the closing brace. */ next = next_brace_sub (begin + 1, flags); if (next == NULL) { /* It is an invalid expression. */ illegal_brace: if (__glibc_unlikely (!alloca_onealt)) free (onealt); flags &= ~GLOB_BRACE; goto no_brace; } /* Now find the end of the whole brace expression. */ rest = next; while (*rest != '}') { rest = next_brace_sub (rest + 1, flags); if (rest == NULL) /* It is an illegal expression. */ goto illegal_brace; } /* Please note that we now can be sure the brace expression is well-formed. */ rest_len = strlen (++rest) + 1; /* We have a brace expression. BEGIN points to the opening {, NEXT points past the terminator of the first element, and END points past the final }. We will accumulate result names from recursive runs for each brace alternative in the buffer using GLOB_APPEND. */ firstc = pglob->gl_pathc; p = begin + 1; while (1) { int result; /* Construct the new glob expression. */ mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len); result = glob (onealt, ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC)) | GLOB_APPEND), errfunc, pglob); /* If we got an error, return it. */ if (result && result != GLOB_NOMATCH) { if (__glibc_unlikely (!alloca_onealt)) free (onealt); if (!(flags & GLOB_APPEND)) { globfree (pglob); pglob->gl_pathc = 0; } return result; } if (*next == '}') /* We saw the last entry. */ break; p = next + 1; next = next_brace_sub (p, flags); assert (next != NULL); } if (__glibc_unlikely (!alloca_onealt)) free (onealt); if (pglob->gl_pathc != firstc) /* We found some entries. */ return 0; else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC))) return GLOB_NOMATCH; } } no_brace: oldcount = pglob->gl_pathc + pglob->gl_offs; /* Find the filename. */ filename = strrchr (pattern, '/'); #if defined __MSDOS__ || defined WINDOWS32 /* The case of "d:pattern". Since ':' is not allowed in file names, we can safely assume that wherever it happens in pattern, it signals the filename part. This is so we could some day support patterns like "[a-z]:foo". */ if (filename == NULL) filename = strchr (pattern, ':'); #endif /* __MSDOS__ || WINDOWS32 */ dirname_modified = 0; if (filename == NULL) { /* This can mean two things: a simple name or "~name". The latter case is nothing but a notation for a directory. */ if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~') { dirname = (char *) pattern; dirlen = strlen (pattern); /* Set FILENAME to NULL as a special flag. This is ugly but other solutions would require much more code. We test for this special case below. */ filename = NULL; } else { if (__glibc_unlikely (pattern[0] == '\0')) { dirs.gl_pathv = NULL; goto no_matches; } filename = pattern; dirname = (char *) "."; dirlen = 0; } } else if (filename == pattern || (filename == pattern + 1 && pattern[0] == '\\' && (flags & GLOB_NOESCAPE) == 0)) { /* "/pattern" or "\\/pattern". */ dirname = (char *) "/"; dirlen = 1; ++filename; } else { char *newp; dirlen = filename - pattern; #if defined __MSDOS__ || defined WINDOWS32 if (*filename == ':' || (filename > pattern + 1 && filename[-1] == ':')) { char *drive_spec; ++dirlen; drive_spec = __alloca (dirlen + 1); *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0'; /* For now, disallow wildcards in the drive spec, to prevent infinite recursion in glob. */ if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE))) return GLOB_NOMATCH; /* If this is "d:pattern", we need to copy ':' to DIRNAME as well. If it's "d:/pattern", don't remove the slash from "d:/", since "d:" and "d:/" are not the same.*/ } #endif if (glob_use_alloca (alloca_used, dirlen + 1)) newp = alloca_account (dirlen + 1, alloca_used); else { newp = malloc (dirlen + 1); if (newp == NULL) return GLOB_NOSPACE; malloc_dirname = 1; } *((char *) mempcpy (newp, pattern, dirlen)) = '\0'; dirname = newp; ++filename; #if defined __MSDOS__ || defined WINDOWS32 bool drive_root = (dirlen > 1 && (dirname[dirlen - 1] == ':' || (dirlen > 2 && dirname[dirlen - 2] == ':' && dirname[dirlen - 1] == '/'))); #else bool drive_root = false; #endif if (filename[0] == '\0' && dirlen > 1 && !drive_root) /* "pattern/". Expand "pattern", appending slashes. */ { int orig_flags = flags; if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\') { /* "pattern\\/". Remove the final backslash if it hasn't been quoted. */ char *p = (char *) &dirname[dirlen - 1]; while (p > dirname && p[-1] == '\\') --p; if ((&dirname[dirlen] - p) & 1) { *(char *) &dirname[--dirlen] = '\0'; flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC); } } int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob); if (val == 0) pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK)); else if (val == GLOB_NOMATCH && flags != orig_flags) { /* Make sure globfree (&dirs); is a nop. */ dirs.gl_pathv = NULL; flags = orig_flags; oldcount = pglob->gl_pathc + pglob->gl_offs; goto no_matches; } retval = val; goto out; } } if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~') { if (dirname[1] == '\0' || dirname[1] == '/' || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\' && (dirname[2] == '\0' || dirname[2] == '/'))) { /* Look up home directory. */ char *home_dir = getenv ("HOME"); int malloc_home_dir = 0; if (home_dir == NULL || home_dir[0] == '\0') { #ifdef WINDOWS32 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference to HOME, because the user can change HOME. */ const char *home_drive = getenv ("HOMEDRIVE"); const char *home_path = getenv ("HOMEPATH"); if (home_drive != NULL && home_path != NULL) { size_t home_drive_len = strlen (home_drive); size_t home_path_len = strlen (home_path); char *mem = alloca (home_drive_len + home_path_len + 1); memcpy (mem, home_drive, home_drive_len); memcpy (mem + home_drive_len, home_path, home_path_len + 1); home_dir = mem; } else home_dir = "c:/users/default"; /* poor default */ #else int err; struct passwd *p; struct passwd pwbuf; struct scratch_buffer s; scratch_buffer_init (&s); while (true) { p = NULL; err = __getlogin_r (s.data, s.length); if (err == 0) { # if defined HAVE_GETPWNAM_R || defined _LIBC size_t ssize = strlen (s.data) + 1; err = getpwnam_r (s.data, &pwbuf, s.data + ssize, s.length - ssize, &p); # else p = getpwnam (s.data); if (p == NULL) err = errno; # endif } if (err != ERANGE) break; if (!scratch_buffer_grow (&s)) { retval = GLOB_NOSPACE; goto out; } } if (err == 0) { home_dir = strdup (p->pw_dir); malloc_home_dir = 1; } scratch_buffer_free (&s); if (err == 0 && home_dir == NULL) { retval = GLOB_NOSPACE; goto out; } #endif /* WINDOWS32 */ } if (home_dir == NULL || home_dir[0] == '\0') { if (__glibc_unlikely (malloc_home_dir)) free (home_dir); if (flags & GLOB_TILDE_CHECK) { retval = GLOB_NOMATCH; goto out; } else { home_dir = (char *) "~"; /* No luck. */ malloc_home_dir = 0; } } /* Now construct the full directory. */ if (dirname[1] == '\0') { if (__glibc_unlikely (malloc_dirname)) free (dirname); dirname = home_dir; dirlen = strlen (dirname); malloc_dirname = malloc_home_dir; } else { char *newp; size_t home_len = strlen (home_dir); int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen); if (use_alloca) newp = alloca_account (home_len + dirlen, alloca_used); else { newp = malloc (home_len + dirlen); if (newp == NULL) { if (__glibc_unlikely (malloc_home_dir)) free (home_dir); retval = GLOB_NOSPACE; goto out; } } mempcpy (mempcpy (newp, home_dir, home_len), &dirname[1], dirlen); if (__glibc_unlikely (malloc_dirname)) free (dirname); dirname = newp; dirlen += home_len - 1; malloc_dirname = !use_alloca; if (__glibc_unlikely (malloc_home_dir)) free (home_dir); } dirname_modified = 1; } else { #ifndef WINDOWS32 char *end_name = strchr (dirname, '/'); char *user_name; int malloc_user_name = 0; char *unescape = NULL; if (!(flags & GLOB_NOESCAPE)) { if (end_name == NULL) { unescape = strchr (dirname, '\\'); if (unescape) end_name = strchr (unescape, '\0'); } else unescape = memchr (dirname, '\\', end_name - dirname); } if (end_name == NULL) user_name = dirname + 1; else { char *newp; if (glob_use_alloca (alloca_used, end_name - dirname)) newp = alloca_account (end_name - dirname, alloca_used); else { newp = malloc (end_name - dirname); if (newp == NULL) { retval = GLOB_NOSPACE; goto out; } malloc_user_name = 1; } if (unescape != NULL) { char *p = mempcpy (newp, dirname + 1, unescape - dirname - 1); char *q = unescape; while (*q != '\0') { if (*q == '\\') { if (q[1] == '\0') { /* "~fo\\o\\" unescape to user_name "foo\\", but "~fo\\o\\/" unescape to user_name "foo". */ if (filename == NULL) *p++ = '\\'; break; } ++q; } *p++ = *q++; } *p = '\0'; } else *((char *) mempcpy (newp, dirname + 1, end_name - dirname)) = '\0'; user_name = newp; } /* Look up specific user's home directory. */ { struct passwd *p; struct scratch_buffer pwtmpbuf; scratch_buffer_init (&pwtmpbuf); # if defined HAVE_GETPWNAM_R || defined _LIBC struct passwd pwbuf; while (getpwnam_r (user_name, &pwbuf, pwtmpbuf.data, pwtmpbuf.length, &p) == ERANGE) { if (!scratch_buffer_grow (&pwtmpbuf)) { retval = GLOB_NOSPACE; goto out; } } # else p = getpwnam (user_name); # endif if (__glibc_unlikely (malloc_user_name)) free (user_name); /* If we found a home directory use this. */ if (p != NULL) { size_t home_len = strlen (p->pw_dir); size_t rest_len = end_name == NULL ? 0 : strlen (end_name); char *d; if (__glibc_unlikely (malloc_dirname)) free (dirname); malloc_dirname = 0; if (glob_use_alloca (alloca_used, home_len + rest_len + 1)) dirname = alloca_account (home_len + rest_len + 1, alloca_used); else { dirname = malloc (home_len + rest_len + 1); if (dirname == NULL) { scratch_buffer_free (&pwtmpbuf); retval = GLOB_NOSPACE; goto out; } malloc_dirname = 1; } d = mempcpy (dirname, p->pw_dir, home_len); if (end_name != NULL) d = mempcpy (d, end_name, rest_len); *d = '\0'; dirlen = home_len + rest_len; dirname_modified = 1; } else { if (flags & GLOB_TILDE_CHECK) { /* We have to regard it as an error if we cannot find the home directory. */ retval = GLOB_NOMATCH; goto out; } } scratch_buffer_free (&pwtmpbuf); } #endif /* !WINDOWS32 */ } } /* Now test whether we looked for "~" or "~NAME". In this case we can give the answer now. */ if (filename == NULL) { size_t newcount = pglob->gl_pathc + pglob->gl_offs; char **new_gl_pathv; if (newcount > SIZE_MAX / sizeof (char *) - 2) { nospace: free (pglob->gl_pathv); pglob->gl_pathv = NULL; pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } new_gl_pathv = realloc (pglob->gl_pathv, (newcount + 2) * sizeof (char *)); if (new_gl_pathv == NULL) goto nospace; pglob->gl_pathv = new_gl_pathv; if (flags & GLOB_MARK && is_dir (dirname, flags, pglob)) { char *p; pglob->gl_pathv[newcount] = malloc (dirlen + 2); if (pglob->gl_pathv[newcount] == NULL) goto nospace; p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen); p[0] = '/'; p[1] = '\0'; if (__glibc_unlikely (malloc_dirname)) free (dirname); } else { if (__glibc_unlikely (malloc_dirname)) pglob->gl_pathv[newcount] = dirname; else { pglob->gl_pathv[newcount] = strdup (dirname); if (pglob->gl_pathv[newcount] == NULL) goto nospace; } } pglob->gl_pathv[++newcount] = NULL; ++pglob->gl_pathc; pglob->gl_flags = flags; return 0; } meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE)); /* meta is 1 if correct glob pattern containing metacharacters. If meta has bit (1 << 2) set, it means there was an unterminated [ which we handle the same, using fnmatch. Broken unterminated pattern bracket expressions ought to be rare enough that it is not worth special casing them, fnmatch will do the right thing. */ if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET)) { /* The directory name contains metacharacters, so we have to glob for the directory, and then glob for the pattern in each directory found. */ size_t i; if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\') { /* "foo\\/bar". Remove the final backslash from dirname if it has not been quoted. */ char *p = (char *) &dirname[dirlen - 1]; while (p > dirname && p[-1] == '\\') --p; if ((&dirname[dirlen] - p) & 1) *(char *) &dirname[--dirlen] = '\0'; } if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0)) { /* Use the alternative access functions also in the recursive call. */ dirs.gl_opendir = pglob->gl_opendir; dirs.gl_readdir = pglob->gl_readdir; dirs.gl_closedir = pglob->gl_closedir; dirs.gl_stat = pglob->gl_stat; dirs.gl_lstat = pglob->gl_lstat; } status = glob (dirname, ((flags & (GLOB_ERR | GLOB_NOESCAPE | GLOB_ALTDIRFUNC)) | GLOB_NOSORT | GLOB_ONLYDIR), errfunc, &dirs); if (status != 0) { if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH) { retval = status; goto out; } goto no_matches; } /* We have successfully globbed the preceding directory name. For each name we found, call glob_in_dir on it and FILENAME, appending the results to PGLOB. */ for (i = 0; i < dirs.gl_pathc; ++i) { size_t old_pathc; old_pathc = pglob->gl_pathc; status = glob_in_dir (filename, dirs.gl_pathv[i], ((flags | GLOB_APPEND) & ~(GLOB_NOCHECK | GLOB_NOMAGIC)), errfunc, pglob, alloca_used); if (status == GLOB_NOMATCH) /* No matches in this directory. Try the next. */ continue; if (status != 0) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = status; goto out; } /* Stick the directory on the front of each name. */ if (prefix_array (dirs.gl_pathv[i], &pglob->gl_pathv[old_pathc + pglob->gl_offs], pglob->gl_pathc - old_pathc)) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } } flags |= GLOB_MAGCHAR; /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls. But if we have not found any matching entry and the GLOB_NOCHECK flag was set we must return the input pattern itself. */ if (pglob->gl_pathc + pglob->gl_offs == oldcount) { no_matches: /* No matches. */ if (flags & GLOB_NOCHECK) { size_t newcount = pglob->gl_pathc + pglob->gl_offs; char **new_gl_pathv; if (newcount > SIZE_MAX / sizeof (char *) - 2) { nospace2: globfree (&dirs); retval = GLOB_NOSPACE; goto out; } new_gl_pathv = realloc (pglob->gl_pathv, (newcount + 2) * sizeof (char *)); if (new_gl_pathv == NULL) goto nospace2; pglob->gl_pathv = new_gl_pathv; pglob->gl_pathv[newcount] = strdup (pattern); if (pglob->gl_pathv[newcount] == NULL) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } ++pglob->gl_pathc; ++newcount; pglob->gl_pathv[newcount] = NULL; pglob->gl_flags = flags; } else { globfree (&dirs); retval = GLOB_NOMATCH; goto out; } } globfree (&dirs); } else { size_t old_pathc = pglob->gl_pathc; int orig_flags = flags; if (meta & GLOBPAT_BACKSLASH) { char *p = strchr (dirname, '\\'), *q; /* We need to unescape the dirname string. It is certainly allocated by alloca, as otherwise filename would be NULL or dirname wouldn't contain backslashes. */ q = p; do { if (*p == '\\') { *q = *++p; --dirlen; } else *q = *p; ++q; } while (*p++ != '\0'); dirname_modified = 1; } if (dirname_modified) flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC); status = glob_in_dir (filename, dirname, flags, errfunc, pglob, alloca_used); if (status != 0) { if (status == GLOB_NOMATCH && flags != orig_flags && pglob->gl_pathc + pglob->gl_offs == oldcount) { /* Make sure globfree (&dirs); is a nop. */ dirs.gl_pathv = NULL; flags = orig_flags; goto no_matches; } retval = status; goto out; } if (dirlen > 0) { /* Stick the directory on the front of each name. */ if (prefix_array (dirname, &pglob->gl_pathv[old_pathc + pglob->gl_offs], pglob->gl_pathc - old_pathc)) { globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } } } if (flags & GLOB_MARK) { /* Append slashes to directory names. */ size_t i; for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i) if (is_dir (pglob->gl_pathv[i], flags, pglob)) { size_t len = strlen (pglob->gl_pathv[i]) + 2; char *new = realloc (pglob->gl_pathv[i], len); if (new == NULL) { globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } strcpy (&new[len - 2], "/"); pglob->gl_pathv[i] = new; } } if (!(flags & GLOB_NOSORT)) { /* Sort the vector. */ qsort (&pglob->gl_pathv[oldcount], pglob->gl_pathc + pglob->gl_offs - oldcount, sizeof (char *), collated_compare); } out: if (__glibc_unlikely (malloc_dirname)) free (dirname); return retval; }
298881576183169213772402868020196569538
glob.c
266244104923592097115880749593499653391
CWE-119
CVE-2017-15670
The GNU C Library (aka glibc or libc6) before 2.27 contains an off-by-one error leading to a heap-based buffer overflow in the glob function in glob.c, related to the processing of home directories using the ~ operator followed by a long string.
https://nvd.nist.gov/vuln/detail/CVE-2017-15670
450,812
gnulib
2d1bd71ec70a31b01d01b734faa66bb1ed28961f
https://github.com/coreutils/gnulib
http://git.savannah.gnu.org/cgit/gnulib.git/commit/?id=2d1bd71ec70a31b01d01b734faa66bb1ed28961f
glob: fix heap buffer overflow * lib/glob.c (glob): Fix off-by-one error introduced into glibc in commit dd7d45e838a42b0ed470c44b55901ea98d0c2bab dated 1997-10-29 20:33:40. Problem reported by Tim Rühsen in: https://sourceware.org/bugzilla/show_bug.cgi?id=22320 Fix suggested by Bruno Haible.
0
glob (const char *pattern, int flags, int (*errfunc) (const char *, int), glob_t *pglob) { const char *filename; char *dirname = NULL; size_t dirlen; int status; size_t oldcount; int meta; int dirname_modified; int malloc_dirname = 0; glob_t dirs; int retval = 0; size_t alloca_used = 0; if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0) { __set_errno (EINVAL); return -1; } /* POSIX requires all slashes to be matched. This means that with a trailing slash we must match only directories. */ if (pattern[0] && pattern[strlen (pattern) - 1] == '/') flags |= GLOB_ONLYDIR; if (!(flags & GLOB_DOOFFS)) /* Have to do this so 'globfree' knows where to start freeing. It also makes all the code that uses gl_offs simpler. */ pglob->gl_offs = 0; if (!(flags & GLOB_APPEND)) { pglob->gl_pathc = 0; if (!(flags & GLOB_DOOFFS)) pglob->gl_pathv = NULL; else { size_t i; if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *)) return GLOB_NOSPACE; pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1) * sizeof (char *)); if (pglob->gl_pathv == NULL) return GLOB_NOSPACE; for (i = 0; i <= pglob->gl_offs; ++i) pglob->gl_pathv[i] = NULL; } } if (flags & GLOB_BRACE) { const char *begin; if (flags & GLOB_NOESCAPE) begin = strchr (pattern, '{'); else { begin = pattern; while (1) { if (*begin == '\0') { begin = NULL; break; } if (*begin == '\\' && begin[1] != '\0') ++begin; else if (*begin == '{') break; ++begin; } } if (begin != NULL) { /* Allocate working buffer large enough for our work. Note that we have at least an opening and closing brace. */ size_t firstc; char *alt_start; const char *p; const char *next; const char *rest; size_t rest_len; char *onealt; size_t pattern_len = strlen (pattern) - 1; int alloca_onealt = glob_use_alloca (alloca_used, pattern_len); if (alloca_onealt) onealt = alloca_account (pattern_len, alloca_used); else { onealt = malloc (pattern_len); if (onealt == NULL) return GLOB_NOSPACE; } /* We know the prefix for all sub-patterns. */ alt_start = mempcpy (onealt, pattern, begin - pattern); /* Find the first sub-pattern and at the same time find the rest after the closing brace. */ next = next_brace_sub (begin + 1, flags); if (next == NULL) { /* It is an invalid expression. */ illegal_brace: if (__glibc_unlikely (!alloca_onealt)) free (onealt); flags &= ~GLOB_BRACE; goto no_brace; } /* Now find the end of the whole brace expression. */ rest = next; while (*rest != '}') { rest = next_brace_sub (rest + 1, flags); if (rest == NULL) /* It is an illegal expression. */ goto illegal_brace; } /* Please note that we now can be sure the brace expression is well-formed. */ rest_len = strlen (++rest) + 1; /* We have a brace expression. BEGIN points to the opening {, NEXT points past the terminator of the first element, and END points past the final }. We will accumulate result names from recursive runs for each brace alternative in the buffer using GLOB_APPEND. */ firstc = pglob->gl_pathc; p = begin + 1; while (1) { int result; /* Construct the new glob expression. */ mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len); result = glob (onealt, ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC)) | GLOB_APPEND), errfunc, pglob); /* If we got an error, return it. */ if (result && result != GLOB_NOMATCH) { if (__glibc_unlikely (!alloca_onealt)) free (onealt); if (!(flags & GLOB_APPEND)) { globfree (pglob); pglob->gl_pathc = 0; } return result; } if (*next == '}') /* We saw the last entry. */ break; p = next + 1; next = next_brace_sub (p, flags); assert (next != NULL); } if (__glibc_unlikely (!alloca_onealt)) free (onealt); if (pglob->gl_pathc != firstc) /* We found some entries. */ return 0; else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC))) return GLOB_NOMATCH; } } no_brace: oldcount = pglob->gl_pathc + pglob->gl_offs; /* Find the filename. */ filename = strrchr (pattern, '/'); #if defined __MSDOS__ || defined WINDOWS32 /* The case of "d:pattern". Since ':' is not allowed in file names, we can safely assume that wherever it happens in pattern, it signals the filename part. This is so we could some day support patterns like "[a-z]:foo". */ if (filename == NULL) filename = strchr (pattern, ':'); #endif /* __MSDOS__ || WINDOWS32 */ dirname_modified = 0; if (filename == NULL) { /* This can mean two things: a simple name or "~name". The latter case is nothing but a notation for a directory. */ if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~') { dirname = (char *) pattern; dirlen = strlen (pattern); /* Set FILENAME to NULL as a special flag. This is ugly but other solutions would require much more code. We test for this special case below. */ filename = NULL; } else { if (__glibc_unlikely (pattern[0] == '\0')) { dirs.gl_pathv = NULL; goto no_matches; } filename = pattern; dirname = (char *) "."; dirlen = 0; } } else if (filename == pattern || (filename == pattern + 1 && pattern[0] == '\\' && (flags & GLOB_NOESCAPE) == 0)) { /* "/pattern" or "\\/pattern". */ dirname = (char *) "/"; dirlen = 1; ++filename; } else { char *newp; dirlen = filename - pattern; #if defined __MSDOS__ || defined WINDOWS32 if (*filename == ':' || (filename > pattern + 1 && filename[-1] == ':')) { char *drive_spec; ++dirlen; drive_spec = __alloca (dirlen + 1); *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0'; /* For now, disallow wildcards in the drive spec, to prevent infinite recursion in glob. */ if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE))) return GLOB_NOMATCH; /* If this is "d:pattern", we need to copy ':' to DIRNAME as well. If it's "d:/pattern", don't remove the slash from "d:/", since "d:" and "d:/" are not the same.*/ } #endif if (glob_use_alloca (alloca_used, dirlen + 1)) newp = alloca_account (dirlen + 1, alloca_used); else { newp = malloc (dirlen + 1); if (newp == NULL) return GLOB_NOSPACE; malloc_dirname = 1; } *((char *) mempcpy (newp, pattern, dirlen)) = '\0'; dirname = newp; ++filename; #if defined __MSDOS__ || defined WINDOWS32 bool drive_root = (dirlen > 1 && (dirname[dirlen - 1] == ':' || (dirlen > 2 && dirname[dirlen - 2] == ':' && dirname[dirlen - 1] == '/'))); #else bool drive_root = false; #endif if (filename[0] == '\0' && dirlen > 1 && !drive_root) /* "pattern/". Expand "pattern", appending slashes. */ { int orig_flags = flags; if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\') { /* "pattern\\/". Remove the final backslash if it hasn't been quoted. */ char *p = (char *) &dirname[dirlen - 1]; while (p > dirname && p[-1] == '\\') --p; if ((&dirname[dirlen] - p) & 1) { *(char *) &dirname[--dirlen] = '\0'; flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC); } } int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob); if (val == 0) pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK)); else if (val == GLOB_NOMATCH && flags != orig_flags) { /* Make sure globfree (&dirs); is a nop. */ dirs.gl_pathv = NULL; flags = orig_flags; oldcount = pglob->gl_pathc + pglob->gl_offs; goto no_matches; } retval = val; goto out; } } if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~') { if (dirname[1] == '\0' || dirname[1] == '/' || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\' && (dirname[2] == '\0' || dirname[2] == '/'))) { /* Look up home directory. */ char *home_dir = getenv ("HOME"); int malloc_home_dir = 0; if (home_dir == NULL || home_dir[0] == '\0') { #ifdef WINDOWS32 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference to HOME, because the user can change HOME. */ const char *home_drive = getenv ("HOMEDRIVE"); const char *home_path = getenv ("HOMEPATH"); if (home_drive != NULL && home_path != NULL) { size_t home_drive_len = strlen (home_drive); size_t home_path_len = strlen (home_path); char *mem = alloca (home_drive_len + home_path_len + 1); memcpy (mem, home_drive, home_drive_len); memcpy (mem + home_drive_len, home_path, home_path_len + 1); home_dir = mem; } else home_dir = "c:/users/default"; /* poor default */ #else int err; struct passwd *p; struct passwd pwbuf; struct scratch_buffer s; scratch_buffer_init (&s); while (true) { p = NULL; err = __getlogin_r (s.data, s.length); if (err == 0) { # if defined HAVE_GETPWNAM_R || defined _LIBC size_t ssize = strlen (s.data) + 1; err = getpwnam_r (s.data, &pwbuf, s.data + ssize, s.length - ssize, &p); # else p = getpwnam (s.data); if (p == NULL) err = errno; # endif } if (err != ERANGE) break; if (!scratch_buffer_grow (&s)) { retval = GLOB_NOSPACE; goto out; } } if (err == 0) { home_dir = strdup (p->pw_dir); malloc_home_dir = 1; } scratch_buffer_free (&s); if (err == 0 && home_dir == NULL) { retval = GLOB_NOSPACE; goto out; } #endif /* WINDOWS32 */ } if (home_dir == NULL || home_dir[0] == '\0') { if (__glibc_unlikely (malloc_home_dir)) free (home_dir); if (flags & GLOB_TILDE_CHECK) { retval = GLOB_NOMATCH; goto out; } else { home_dir = (char *) "~"; /* No luck. */ malloc_home_dir = 0; } } /* Now construct the full directory. */ if (dirname[1] == '\0') { if (__glibc_unlikely (malloc_dirname)) free (dirname); dirname = home_dir; dirlen = strlen (dirname); malloc_dirname = malloc_home_dir; } else { char *newp; size_t home_len = strlen (home_dir); int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen); if (use_alloca) newp = alloca_account (home_len + dirlen, alloca_used); else { newp = malloc (home_len + dirlen); if (newp == NULL) { if (__glibc_unlikely (malloc_home_dir)) free (home_dir); retval = GLOB_NOSPACE; goto out; } } mempcpy (mempcpy (newp, home_dir, home_len), &dirname[1], dirlen); if (__glibc_unlikely (malloc_dirname)) free (dirname); dirname = newp; dirlen += home_len - 1; malloc_dirname = !use_alloca; if (__glibc_unlikely (malloc_home_dir)) free (home_dir); } dirname_modified = 1; } else { #ifndef WINDOWS32 char *end_name = strchr (dirname, '/'); char *user_name; int malloc_user_name = 0; char *unescape = NULL; if (!(flags & GLOB_NOESCAPE)) { if (end_name == NULL) { unescape = strchr (dirname, '\\'); if (unescape) end_name = strchr (unescape, '\0'); } else unescape = memchr (dirname, '\\', end_name - dirname); } if (end_name == NULL) user_name = dirname + 1; else { char *newp; if (glob_use_alloca (alloca_used, end_name - dirname)) newp = alloca_account (end_name - dirname, alloca_used); else { newp = malloc (end_name - dirname); if (newp == NULL) { retval = GLOB_NOSPACE; goto out; } malloc_user_name = 1; } if (unescape != NULL) { char *p = mempcpy (newp, dirname + 1, unescape - dirname - 1); char *q = unescape; while (*q != '\0') { if (*q == '\\') { if (q[1] == '\0') { /* "~fo\\o\\" unescape to user_name "foo\\", but "~fo\\o\\/" unescape to user_name "foo". */ if (filename == NULL) *p++ = '\\'; break; } ++q; } *p++ = *q++; } *p = '\0'; } else *((char *) mempcpy (newp, dirname + 1, end_name - dirname - 1)) = '\0'; user_name = newp; } /* Look up specific user's home directory. */ { struct passwd *p; struct scratch_buffer pwtmpbuf; scratch_buffer_init (&pwtmpbuf); # if defined HAVE_GETPWNAM_R || defined _LIBC struct passwd pwbuf; while (getpwnam_r (user_name, &pwbuf, pwtmpbuf.data, pwtmpbuf.length, &p) == ERANGE) { if (!scratch_buffer_grow (&pwtmpbuf)) { retval = GLOB_NOSPACE; goto out; } } # else p = getpwnam (user_name); # endif if (__glibc_unlikely (malloc_user_name)) free (user_name); /* If we found a home directory use this. */ if (p != NULL) { size_t home_len = strlen (p->pw_dir); size_t rest_len = end_name == NULL ? 0 : strlen (end_name); char *d; if (__glibc_unlikely (malloc_dirname)) free (dirname); malloc_dirname = 0; if (glob_use_alloca (alloca_used, home_len + rest_len + 1)) dirname = alloca_account (home_len + rest_len + 1, alloca_used); else { dirname = malloc (home_len + rest_len + 1); if (dirname == NULL) { scratch_buffer_free (&pwtmpbuf); retval = GLOB_NOSPACE; goto out; } malloc_dirname = 1; } d = mempcpy (dirname, p->pw_dir, home_len); if (end_name != NULL) d = mempcpy (d, end_name, rest_len); *d = '\0'; dirlen = home_len + rest_len; dirname_modified = 1; } else { if (flags & GLOB_TILDE_CHECK) { /* We have to regard it as an error if we cannot find the home directory. */ retval = GLOB_NOMATCH; goto out; } } scratch_buffer_free (&pwtmpbuf); } #endif /* !WINDOWS32 */ } } /* Now test whether we looked for "~" or "~NAME". In this case we can give the answer now. */ if (filename == NULL) { size_t newcount = pglob->gl_pathc + pglob->gl_offs; char **new_gl_pathv; if (newcount > SIZE_MAX / sizeof (char *) - 2) { nospace: free (pglob->gl_pathv); pglob->gl_pathv = NULL; pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } new_gl_pathv = realloc (pglob->gl_pathv, (newcount + 2) * sizeof (char *)); if (new_gl_pathv == NULL) goto nospace; pglob->gl_pathv = new_gl_pathv; if (flags & GLOB_MARK && is_dir (dirname, flags, pglob)) { char *p; pglob->gl_pathv[newcount] = malloc (dirlen + 2); if (pglob->gl_pathv[newcount] == NULL) goto nospace; p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen); p[0] = '/'; p[1] = '\0'; if (__glibc_unlikely (malloc_dirname)) free (dirname); } else { if (__glibc_unlikely (malloc_dirname)) pglob->gl_pathv[newcount] = dirname; else { pglob->gl_pathv[newcount] = strdup (dirname); if (pglob->gl_pathv[newcount] == NULL) goto nospace; } } pglob->gl_pathv[++newcount] = NULL; ++pglob->gl_pathc; pglob->gl_flags = flags; return 0; } meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE)); /* meta is 1 if correct glob pattern containing metacharacters. If meta has bit (1 << 2) set, it means there was an unterminated [ which we handle the same, using fnmatch. Broken unterminated pattern bracket expressions ought to be rare enough that it is not worth special casing them, fnmatch will do the right thing. */ if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET)) { /* The directory name contains metacharacters, so we have to glob for the directory, and then glob for the pattern in each directory found. */ size_t i; if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\') { /* "foo\\/bar". Remove the final backslash from dirname if it has not been quoted. */ char *p = (char *) &dirname[dirlen - 1]; while (p > dirname && p[-1] == '\\') --p; if ((&dirname[dirlen] - p) & 1) *(char *) &dirname[--dirlen] = '\0'; } if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0)) { /* Use the alternative access functions also in the recursive call. */ dirs.gl_opendir = pglob->gl_opendir; dirs.gl_readdir = pglob->gl_readdir; dirs.gl_closedir = pglob->gl_closedir; dirs.gl_stat = pglob->gl_stat; dirs.gl_lstat = pglob->gl_lstat; } status = glob (dirname, ((flags & (GLOB_ERR | GLOB_NOESCAPE | GLOB_ALTDIRFUNC)) | GLOB_NOSORT | GLOB_ONLYDIR), errfunc, &dirs); if (status != 0) { if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH) { retval = status; goto out; } goto no_matches; } /* We have successfully globbed the preceding directory name. For each name we found, call glob_in_dir on it and FILENAME, appending the results to PGLOB. */ for (i = 0; i < dirs.gl_pathc; ++i) { size_t old_pathc; old_pathc = pglob->gl_pathc; status = glob_in_dir (filename, dirs.gl_pathv[i], ((flags | GLOB_APPEND) & ~(GLOB_NOCHECK | GLOB_NOMAGIC)), errfunc, pglob, alloca_used); if (status == GLOB_NOMATCH) /* No matches in this directory. Try the next. */ continue; if (status != 0) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = status; goto out; } /* Stick the directory on the front of each name. */ if (prefix_array (dirs.gl_pathv[i], &pglob->gl_pathv[old_pathc + pglob->gl_offs], pglob->gl_pathc - old_pathc)) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } } flags |= GLOB_MAGCHAR; /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls. But if we have not found any matching entry and the GLOB_NOCHECK flag was set we must return the input pattern itself. */ if (pglob->gl_pathc + pglob->gl_offs == oldcount) { no_matches: /* No matches. */ if (flags & GLOB_NOCHECK) { size_t newcount = pglob->gl_pathc + pglob->gl_offs; char **new_gl_pathv; if (newcount > SIZE_MAX / sizeof (char *) - 2) { nospace2: globfree (&dirs); retval = GLOB_NOSPACE; goto out; } new_gl_pathv = realloc (pglob->gl_pathv, (newcount + 2) * sizeof (char *)); if (new_gl_pathv == NULL) goto nospace2; pglob->gl_pathv = new_gl_pathv; pglob->gl_pathv[newcount] = strdup (pattern); if (pglob->gl_pathv[newcount] == NULL) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } ++pglob->gl_pathc; ++newcount; pglob->gl_pathv[newcount] = NULL; pglob->gl_flags = flags; } else { globfree (&dirs); retval = GLOB_NOMATCH; goto out; } } globfree (&dirs); } else { size_t old_pathc = pglob->gl_pathc; int orig_flags = flags; if (meta & GLOBPAT_BACKSLASH) { char *p = strchr (dirname, '\\'), *q; /* We need to unescape the dirname string. It is certainly allocated by alloca, as otherwise filename would be NULL or dirname wouldn't contain backslashes. */ q = p; do { if (*p == '\\') { *q = *++p; --dirlen; } else *q = *p; ++q; } while (*p++ != '\0'); dirname_modified = 1; } if (dirname_modified) flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC); status = glob_in_dir (filename, dirname, flags, errfunc, pglob, alloca_used); if (status != 0) { if (status == GLOB_NOMATCH && flags != orig_flags && pglob->gl_pathc + pglob->gl_offs == oldcount) { /* Make sure globfree (&dirs); is a nop. */ dirs.gl_pathv = NULL; flags = orig_flags; goto no_matches; } retval = status; goto out; } if (dirlen > 0) { /* Stick the directory on the front of each name. */ if (prefix_array (dirname, &pglob->gl_pathv[old_pathc + pglob->gl_offs], pglob->gl_pathc - old_pathc)) { globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } } } if (flags & GLOB_MARK) { /* Append slashes to directory names. */ size_t i; for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i) if (is_dir (pglob->gl_pathv[i], flags, pglob)) { size_t len = strlen (pglob->gl_pathv[i]) + 2; char *new = realloc (pglob->gl_pathv[i], len); if (new == NULL) { globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } strcpy (&new[len - 2], "/"); pglob->gl_pathv[i] = new; } } if (!(flags & GLOB_NOSORT)) { /* Sort the vector. */ qsort (&pglob->gl_pathv[oldcount], pglob->gl_pathc + pglob->gl_offs - oldcount, sizeof (char *), collated_compare); } out: if (__glibc_unlikely (malloc_dirname)) free (dirname); return retval; }
117294583205769293929285722462366033294
glob.c
86657842076081720969928155936908511288
CWE-119
CVE-2017-15670
The GNU C Library (aka glibc or libc6) before 2.27 contains an off-by-one error leading to a heap-based buffer overflow in the glob function in glob.c, related to the processing of home directories using the ~ operator followed by a long string.
https://nvd.nist.gov/vuln/detail/CVE-2017-15670
211,700
linux
4fbcc1a4cb20fe26ad0225679c536c80f1648221
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/4fbcc1a4cb20fe26ad0225679c536c80f1648221
nfc: st21nfca: Fix potential buffer overflows in EVT_TRANSACTION It appears that there are some buffer overflows in EVT_TRANSACTION. This happens because the length parameters that are passed to memcpy come directly from skb->data and are not guarded in any way. Signed-off-by: Jordy Zomer <[email protected]> Reviewed-by: Krzysztof Kozlowski <[email protected]> Signed-off-by: David S. Miller <[email protected]>
1
int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host, u8 event, struct sk_buff *skb) { int r = 0; struct device *dev = &hdev->ndev->dev; struct nfc_evt_transaction *transaction; pr_debug("connectivity gate event: %x\n", event); switch (event) { case ST21NFCA_EVT_CONNECTIVITY: r = nfc_se_connectivity(hdev->ndev, host); break; case ST21NFCA_EVT_TRANSACTION: /* * According to specification etsi 102 622 * 11.2.2.4 EVT_TRANSACTION Table 52 * Description Tag Length * AID 81 5 to 16 * PARAMETERS 82 0 to 255 */ if (skb->len < NFC_MIN_AID_LENGTH + 2 && skb->data[0] != NFC_EVT_TRANSACTION_AID_TAG) return -EPROTO; transaction = devm_kzalloc(dev, skb->len - 2, GFP_KERNEL); if (!transaction) return -ENOMEM; transaction->aid_len = skb->data[1]; memcpy(transaction->aid, &skb->data[2], transaction->aid_len); /* Check next byte is PARAMETERS tag (82) */ if (skb->data[transaction->aid_len + 2] != NFC_EVT_TRANSACTION_PARAMS_TAG) return -EPROTO; transaction->params_len = skb->data[transaction->aid_len + 3]; memcpy(transaction->params, skb->data + transaction->aid_len + 4, transaction->params_len); r = nfc_se_transaction(hdev->ndev, host, transaction); break; default: nfc_err(&hdev->ndev->dev, "Unexpected event on connectivity gate\n"); return 1; } kfree_skb(skb); return r; }
253634808738614127513017365541725702270
se.c
262088554020527485810277505080130104803
CWE-120
CVE-2022-26490
st21nfca_connectivity_event_received in drivers/nfc/st21nfca/se.c in the Linux kernel through 5.16.12 has EVT_TRANSACTION buffer overflows because of untrusted length parameters.
https://nvd.nist.gov/vuln/detail/CVE-2022-26490
450,830
linux
4fbcc1a4cb20fe26ad0225679c536c80f1648221
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/4fbcc1a4cb20fe26ad0225679c536c80f1648221
nfc: st21nfca: Fix potential buffer overflows in EVT_TRANSACTION It appears that there are some buffer overflows in EVT_TRANSACTION. This happens because the length parameters that are passed to memcpy come directly from skb->data and are not guarded in any way. Signed-off-by: Jordy Zomer <[email protected]> Reviewed-by: Krzysztof Kozlowski <[email protected]> Signed-off-by: David S. Miller <[email protected]>
0
int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host, u8 event, struct sk_buff *skb) { int r = 0; struct device *dev = &hdev->ndev->dev; struct nfc_evt_transaction *transaction; pr_debug("connectivity gate event: %x\n", event); switch (event) { case ST21NFCA_EVT_CONNECTIVITY: r = nfc_se_connectivity(hdev->ndev, host); break; case ST21NFCA_EVT_TRANSACTION: /* * According to specification etsi 102 622 * 11.2.2.4 EVT_TRANSACTION Table 52 * Description Tag Length * AID 81 5 to 16 * PARAMETERS 82 0 to 255 */ if (skb->len < NFC_MIN_AID_LENGTH + 2 && skb->data[0] != NFC_EVT_TRANSACTION_AID_TAG) return -EPROTO; transaction = devm_kzalloc(dev, skb->len - 2, GFP_KERNEL); if (!transaction) return -ENOMEM; transaction->aid_len = skb->data[1]; /* Checking if the length of the AID is valid */ if (transaction->aid_len > sizeof(transaction->aid)) return -EINVAL; memcpy(transaction->aid, &skb->data[2], transaction->aid_len); /* Check next byte is PARAMETERS tag (82) */ if (skb->data[transaction->aid_len + 2] != NFC_EVT_TRANSACTION_PARAMS_TAG) return -EPROTO; transaction->params_len = skb->data[transaction->aid_len + 3]; /* Total size is allocated (skb->len - 2) minus fixed array members */ if (transaction->params_len > ((skb->len - 2) - sizeof(struct nfc_evt_transaction))) return -EINVAL; memcpy(transaction->params, skb->data + transaction->aid_len + 4, transaction->params_len); r = nfc_se_transaction(hdev->ndev, host, transaction); break; default: nfc_err(&hdev->ndev->dev, "Unexpected event on connectivity gate\n"); return 1; } kfree_skb(skb); return r; }
192395528803862067074725666985010866676
se.c
50941829261793889476158524684428564511
CWE-120
CVE-2022-26490
st21nfca_connectivity_event_received in drivers/nfc/st21nfca/se.c in the Linux kernel through 5.16.12 has EVT_TRANSACTION buffer overflows because of untrusted length parameters.
https://nvd.nist.gov/vuln/detail/CVE-2022-26490
211,773
ntp
07a5b8141e354a998a52994c3c9cd547927e56ce
https://github.com/ntp-project/ntp
https://github.com/ntp-project/ntp/commit/07a5b8141e354a998a52994c3c9cd547927e56ce
[TALOS-CAN-0063] avoid buffer overrun in ntpq
1
cookedprint( int datatype, int length, const char *data, int status, int quiet, FILE *fp ) { char *name; char *value; char output_raw; int fmt; l_fp lfp; sockaddr_u hval; u_long uval; int narr; size_t len; l_fp lfparr[8]; char b[12]; char bn[2 * MAXVARLEN]; char bv[2 * MAXVALLEN]; UNUSED_ARG(datatype); if (!quiet) fprintf(fp, "status=%04x %s,\n", status, statustoa(datatype, status)); startoutput(); while (nextvar(&length, &data, &name, &value)) { fmt = varfmt(name); output_raw = 0; switch (fmt) { case PADDING: output_raw = '*'; break; case TS: if (!decodets(value, &lfp)) output_raw = '?'; else output(fp, name, prettydate(&lfp)); break; case HA: /* fallthru */ case NA: if (!decodenetnum(value, &hval)) { output_raw = '?'; } else if (fmt == HA){ output(fp, name, nntohost(&hval)); } else { output(fp, name, stoa(&hval)); } break; case RF: if (decodenetnum(value, &hval)) { if (ISREFCLOCKADR(&hval)) output(fp, name, refnumtoa(&hval)); else output(fp, name, stoa(&hval)); } else if (strlen(value) <= 4) { output(fp, name, value); } else { output_raw = '?'; } break; case LP: if (!decodeuint(value, &uval) || uval > 3) { output_raw = '?'; } else { b[0] = (0x2 & uval) ? '1' : '0'; b[1] = (0x1 & uval) ? '1' : '0'; b[2] = '\0'; output(fp, name, b); } break; case OC: if (!decodeuint(value, &uval)) { output_raw = '?'; } else { snprintf(b, sizeof(b), "%03lo", uval); output(fp, name, b); } break; case AR: if (!decodearr(value, &narr, lfparr)) output_raw = '?'; else outputarr(fp, name, narr, lfparr); break; case FX: if (!decodeuint(value, &uval)) output_raw = '?'; else output(fp, name, tstflags(uval)); break; default: fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n", name, value, fmt); output_raw = '?'; break; } if (output_raw != 0) { atoascii(name, MAXVARLEN, bn, sizeof(bn)); atoascii(value, MAXVALLEN, bv, sizeof(bv)); if (output_raw != '*') { len = strlen(bv); bv[len] = output_raw; bv[len+1] = '\0'; } output(fp, bn, bv); } } endoutput(fp); }
117019892599870517074003591750988787973
ntpq.c
263164452008239257044928277190655422420
CWE-20
CVE-2015-7852
ntpq in NTP 4.2.x before 4.2.8p4, and 4.3.x before 4.3.77 allows remote attackers to cause a denial of service (crash) via crafted mode 6 response packets.
https://nvd.nist.gov/vuln/detail/CVE-2015-7852
451,731
ntp
07a5b8141e354a998a52994c3c9cd547927e56ce
https://github.com/ntp-project/ntp
https://github.com/ntp-project/ntp/commit/07a5b8141e354a998a52994c3c9cd547927e56ce
[TALOS-CAN-0063] avoid buffer overrun in ntpq
0
cookedprint( int datatype, int length, const char *data, int status, int quiet, FILE *fp ) { char *name; char *value; char output_raw; int fmt; l_fp lfp; sockaddr_u hval; u_long uval; int narr; size_t len; l_fp lfparr[8]; char b[12]; char bn[2 * MAXVARLEN]; char bv[2 * MAXVALLEN]; UNUSED_ARG(datatype); if (!quiet) fprintf(fp, "status=%04x %s,\n", status, statustoa(datatype, status)); startoutput(); while (nextvar(&length, &data, &name, &value)) { fmt = varfmt(name); output_raw = 0; switch (fmt) { case PADDING: output_raw = '*'; break; case TS: if (!decodets(value, &lfp)) output_raw = '?'; else output(fp, name, prettydate(&lfp)); break; case HA: /* fallthru */ case NA: if (!decodenetnum(value, &hval)) { output_raw = '?'; } else if (fmt == HA){ output(fp, name, nntohost(&hval)); } else { output(fp, name, stoa(&hval)); } break; case RF: if (decodenetnum(value, &hval)) { if (ISREFCLOCKADR(&hval)) output(fp, name, refnumtoa(&hval)); else output(fp, name, stoa(&hval)); } else if (strlen(value) <= 4) { output(fp, name, value); } else { output_raw = '?'; } break; case LP: if (!decodeuint(value, &uval) || uval > 3) { output_raw = '?'; } else { b[0] = (0x2 & uval) ? '1' : '0'; b[1] = (0x1 & uval) ? '1' : '0'; b[2] = '\0'; output(fp, name, b); } break; case OC: if (!decodeuint(value, &uval)) { output_raw = '?'; } else { snprintf(b, sizeof(b), "%03lo", uval); output(fp, name, b); } break; case AR: if (!decodearr(value, &narr, lfparr)) output_raw = '?'; else outputarr(fp, name, narr, lfparr); break; case FX: if (!decodeuint(value, &uval)) output_raw = '?'; else output(fp, name, tstflags(uval)); break; default: fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n", name, value, fmt); output_raw = '?'; break; } if (output_raw != 0) { /* TALOS-CAN-0063: avoid buffer overrun */ atoascii(name, MAXVARLEN, bn, sizeof(bn)); if (output_raw != '*') { atoascii(value, MAXVALLEN, bv, sizeof(bv) - 1); len = strlen(bv); bv[len] = output_raw; bv[len+1] = '\0'; } else { atoascii(value, MAXVALLEN, bv, sizeof(bv)); } output(fp, bn, bv); } } endoutput(fp); }
286888330459003026331284434605345848005
ntpq.c
291788569529258980351890148746025724022
CWE-20
CVE-2015-7852
ntpq in NTP 4.2.x before 4.2.8p4, and 4.3.x before 4.3.77 allows remote attackers to cause a denial of service (crash) via crafted mode 6 response packets.
https://nvd.nist.gov/vuln/detail/CVE-2015-7852
211,785
jasper
4cd52b5daac62b00a0a328451544807ddecf775f
https://github.com/mdadams/jasper
https://github.com/jasper-software/jasper/commit/4cd52b5daac62b00a0a328451544807ddecf775f
Avoid maxrlvls more than upper bound to cause heap-buffer-overflow
1
static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image) { jpc_enc_cp_t *cp; jas_tvparser_t *tvp; int ret; int numilyrrates; double *ilyrrates; int i; int tagid; jpc_enc_tcp_t *tcp; jpc_enc_tccp_t *tccp; jpc_enc_ccp_t *ccp; uint_fast16_t rlvlno; uint_fast16_t prcwidthexpn; uint_fast16_t prcheightexpn; bool enablemct; uint_fast32_t jp2overhead; uint_fast16_t lyrno; uint_fast32_t hsteplcm; uint_fast32_t vsteplcm; bool mctvalid; tvp = 0; cp = 0; ilyrrates = 0; numilyrrates = 0; if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) { goto error; } prcwidthexpn = 15; prcheightexpn = 15; enablemct = true; jp2overhead = 0; cp->ccps = 0; cp->debug = 0; cp->imgareatlx = UINT_FAST32_MAX; cp->imgareatly = UINT_FAST32_MAX; cp->refgrdwidth = 0; cp->refgrdheight = 0; cp->tilegrdoffx = UINT_FAST32_MAX; cp->tilegrdoffy = UINT_FAST32_MAX; cp->tilewidth = 0; cp->tileheight = 0; cp->numcmpts = jas_image_numcmpts(image); hsteplcm = 1; vsteplcm = 1; for (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <= jas_image_brx(image) || jas_image_cmptbry(image, cmptno) + jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) { jas_eprintf("unsupported image type\n"); goto error; } /* Note: We ought to be calculating the LCMs here. Fix some day. */ hsteplcm *= jas_image_cmpthstep(image, cmptno); vsteplcm *= jas_image_cmptvstep(image, cmptno); } if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) { goto error; } unsigned cmptno; for (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno, ++ccp) { ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno); ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno); /* XXX - this isn't quite correct for more general image */ ccp->sampgrdsubstepx = 0; ccp->sampgrdsubstepx = 0; ccp->prec = jas_image_cmptprec(image, cmptno); ccp->sgnd = jas_image_cmptsgnd(image, cmptno); ccp->numstepsizes = 0; memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes)); } cp->rawsize = jas_image_rawsize(image); if (cp->rawsize == 0) { /* prevent division by zero in cp_create() */ goto error; } cp->totalsize = UINT_FAST32_MAX; tcp = &cp->tcp; tcp->csty = 0; tcp->intmode = true; tcp->prg = JPC_COD_LRCPPRG; tcp->numlyrs = 1; tcp->ilyrrates = 0; tccp = &cp->tccp; tccp->csty = 0; tccp->maxrlvls = 6; tccp->cblkwidthexpn = 6; tccp->cblkheightexpn = 6; tccp->cblksty = 0; tccp->numgbits = 2; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { goto error; } while (!(ret = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts, jas_tvparser_gettag(tvp)))->id) { case OPT_DEBUG: cp->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFX: cp->imgareatlx = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFY: cp->imgareatly = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFX: cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFY: cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEWIDTH: cp->tilewidth = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEHEIGHT: cp->tileheight = atoi(jas_tvparser_getval(tvp)); break; case OPT_PRCWIDTH: prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_PRCHEIGHT: prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKWIDTH: tccp->cblkwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKHEIGHT: tccp->cblkheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_MODE: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid mode %s\n", jas_tvparser_getval(tvp)); } else { tcp->intmode = (tagid == MODE_INT); } break; case OPT_PRG: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid progression order %s\n", jas_tvparser_getval(tvp)); } else { tcp->prg = tagid; } break; case OPT_NOMCT: enablemct = false; break; case OPT_MAXRLVLS: tccp->maxrlvls = atoi(jas_tvparser_getval(tvp)); break; case OPT_SOP: cp->tcp.csty |= JPC_COD_SOP; break; case OPT_EPH: cp->tcp.csty |= JPC_COD_EPH; break; case OPT_LAZY: tccp->cblksty |= JPC_COX_LAZY; break; case OPT_TERMALL: tccp->cblksty |= JPC_COX_TERMALL; break; case OPT_SEGSYM: tccp->cblksty |= JPC_COX_SEGSYM; break; case OPT_VCAUSAL: tccp->cblksty |= JPC_COX_VSC; break; case OPT_RESET: tccp->cblksty |= JPC_COX_RESET; break; case OPT_PTERM: tccp->cblksty |= JPC_COX_PTERM; break; case OPT_NUMGBITS: cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp)); break; case OPT_RATE: if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize, &cp->totalsize)) { jas_eprintf("ignoring bad rate specifier %s\n", jas_tvparser_getval(tvp)); } break; case OPT_ILYRRATES: if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates, &ilyrrates)) { jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n", jas_tvparser_getval(tvp)); } break; case OPT_JP2OVERHEAD: jp2overhead = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); tvp = 0; if (cp->totalsize != UINT_FAST32_MAX) { cp->totalsize = (cp->totalsize > jp2overhead) ? (cp->totalsize - jp2overhead) : 0; } if (cp->imgareatlx == UINT_FAST32_MAX) { cp->imgareatlx = 0; } else { if (hsteplcm != 1) { jas_eprintf("warning: overriding imgareatlx value\n"); } cp->imgareatlx *= hsteplcm; } if (cp->imgareatly == UINT_FAST32_MAX) { cp->imgareatly = 0; } else { if (vsteplcm != 1) { jas_eprintf("warning: overriding imgareatly value\n"); } cp->imgareatly *= vsteplcm; } cp->refgrdwidth = cp->imgareatlx + jas_image_width(image); cp->refgrdheight = cp->imgareatly + jas_image_height(image); if (cp->tilegrdoffx == UINT_FAST32_MAX) { cp->tilegrdoffx = cp->imgareatlx; } if (cp->tilegrdoffy == UINT_FAST32_MAX) { cp->tilegrdoffy = cp->imgareatly; } if (!cp->tilewidth) { cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx; } if (!cp->tileheight) { cp->tileheight = cp->refgrdheight - cp->tilegrdoffy; } if (cp->numcmpts == 3) { mctvalid = true; for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) || jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) || jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) || jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) { mctvalid = false; } } } else { mctvalid = false; } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) { jas_eprintf("warning: color space apparently not RGB\n"); } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) { tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT); } else { tcp->mctid = JPC_MCT_NONE; } tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS); for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { tccp->prcwidthexpns[rlvlno] = prcwidthexpn; tccp->prcheightexpns[rlvlno] = prcheightexpn; } if (prcwidthexpn != 15 || prcheightexpn != 15) { tccp->csty |= JPC_COX_PRT; } /* Ensure that the tile width and height is valid. */ if (!cp->tilewidth) { jas_eprintf("invalid tile width %lu\n", (unsigned long) cp->tilewidth); goto error; } if (!cp->tileheight) { jas_eprintf("invalid tile height %lu\n", (unsigned long) cp->tileheight); goto error; } /* Ensure that the tile grid offset is valid. */ if (cp->tilegrdoffx > cp->imgareatlx || cp->tilegrdoffy > cp->imgareatly || cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx || cp->tilegrdoffy + cp->tileheight < cp->imgareatly) { jas_eprintf("invalid tile grid offset (%lu, %lu)\n", (unsigned long) cp->tilegrdoffx, (unsigned long) cp->tilegrdoffy); goto error; } cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx, cp->tilewidth); cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy, cp->tileheight); cp->numtiles = cp->numhtiles * cp->numvtiles; if (ilyrrates && numilyrrates > 0) { tcp->numlyrs = numilyrrates + 1; if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1), sizeof(jpc_fix_t)))) { goto error; } for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) { tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]); } } /* Ensure that the integer mode is used in the case of lossless coding. */ if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) { jas_eprintf("cannot use real mode for lossless coding\n"); goto error; } /* Ensure that the precinct width is valid. */ if (prcwidthexpn > 15) { jas_eprintf("invalid precinct width\n"); goto error; } /* Ensure that the precinct height is valid. */ if (prcheightexpn > 15) { jas_eprintf("invalid precinct height\n"); goto error; } /* Ensure that the code block width is valid. */ if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) { jas_eprintf("invalid code block width %d\n", JPC_POW2(cp->tccp.cblkwidthexpn)); goto error; } /* Ensure that the code block height is valid. */ if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) { jas_eprintf("invalid code block height %d\n", JPC_POW2(cp->tccp.cblkheightexpn)); goto error; } /* Ensure that the code block size is not too large. */ if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) { jas_eprintf("code block size too large\n"); goto error; } /* Ensure that the number of layers is valid. */ if (cp->tcp.numlyrs > 16384) { jas_eprintf("too many layers\n"); goto error; } /* There must be at least one resolution level. */ if (cp->tccp.maxrlvls < 1) { jas_eprintf("must be at least one resolution level\n"); goto error; } /* Ensure that the number of guard bits is valid. */ if (cp->tccp.numgbits > 8) { jas_eprintf("invalid number of guard bits\n"); goto error; } /* Ensure that the rate is within the legal range. */ if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) { jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize); } /* Ensure that the intermediate layer rates are valid. */ if (tcp->numlyrs > 1) { /* The intermediate layers rates must increase monotonically. */ for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) { if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) { jas_eprintf("intermediate layer rates must increase monotonically\n"); goto error; } } /* The intermediate layer rates must be less than the overall rate. */ if (cp->totalsize != UINT_FAST32_MAX) { for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) { if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize) / cp->rawsize) { jas_eprintf("warning: intermediate layer rates must be less than overall rate\n"); goto error; } } } } if (ilyrrates) { jas_free(ilyrrates); } return cp; error: if (ilyrrates) { jas_free(ilyrrates); } if (tvp) { jas_tvparser_destroy(tvp); } if (cp) { jpc_enc_cp_destroy(cp); } return 0; }
179213511260070262932724370978685731129
jpc_enc.c
285191290025689593258555638021323781658
CWE-20
CVE-2020-27828
There's a flaw in jasper's jpc encoder in versions prior to 2.0.23. Crafted input provided to jasper by an attacker could cause an arbitrary out-of-bounds write. This could potentially affect data confidentiality, integrity, or application availability.
https://nvd.nist.gov/vuln/detail/CVE-2020-27828
451,888
jasper
4cd52b5daac62b00a0a328451544807ddecf775f
https://github.com/mdadams/jasper
https://github.com/jasper-software/jasper/commit/4cd52b5daac62b00a0a328451544807ddecf775f
Avoid maxrlvls more than upper bound to cause heap-buffer-overflow
0
static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image) { jpc_enc_cp_t *cp; jas_tvparser_t *tvp; int ret; int numilyrrates; double *ilyrrates; int i; int tagid; jpc_enc_tcp_t *tcp; jpc_enc_tccp_t *tccp; jpc_enc_ccp_t *ccp; uint_fast16_t rlvlno; uint_fast16_t prcwidthexpn; uint_fast16_t prcheightexpn; bool enablemct; uint_fast32_t jp2overhead; uint_fast16_t lyrno; uint_fast32_t hsteplcm; uint_fast32_t vsteplcm; bool mctvalid; tvp = 0; cp = 0; ilyrrates = 0; numilyrrates = 0; if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) { goto error; } prcwidthexpn = 15; prcheightexpn = 15; enablemct = true; jp2overhead = 0; cp->ccps = 0; cp->debug = 0; cp->imgareatlx = UINT_FAST32_MAX; cp->imgareatly = UINT_FAST32_MAX; cp->refgrdwidth = 0; cp->refgrdheight = 0; cp->tilegrdoffx = UINT_FAST32_MAX; cp->tilegrdoffy = UINT_FAST32_MAX; cp->tilewidth = 0; cp->tileheight = 0; cp->numcmpts = jas_image_numcmpts(image); hsteplcm = 1; vsteplcm = 1; for (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <= jas_image_brx(image) || jas_image_cmptbry(image, cmptno) + jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) { jas_eprintf("unsupported image type\n"); goto error; } /* Note: We ought to be calculating the LCMs here. Fix some day. */ hsteplcm *= jas_image_cmpthstep(image, cmptno); vsteplcm *= jas_image_cmptvstep(image, cmptno); } if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) { goto error; } unsigned cmptno; for (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno, ++ccp) { ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno); ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno); /* XXX - this isn't quite correct for more general image */ ccp->sampgrdsubstepx = 0; ccp->sampgrdsubstepx = 0; ccp->prec = jas_image_cmptprec(image, cmptno); ccp->sgnd = jas_image_cmptsgnd(image, cmptno); ccp->numstepsizes = 0; memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes)); } cp->rawsize = jas_image_rawsize(image); if (cp->rawsize == 0) { /* prevent division by zero in cp_create() */ goto error; } cp->totalsize = UINT_FAST32_MAX; tcp = &cp->tcp; tcp->csty = 0; tcp->intmode = true; tcp->prg = JPC_COD_LRCPPRG; tcp->numlyrs = 1; tcp->ilyrrates = 0; tccp = &cp->tccp; tccp->csty = 0; tccp->maxrlvls = 6; tccp->cblkwidthexpn = 6; tccp->cblkheightexpn = 6; tccp->cblksty = 0; tccp->numgbits = 2; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { goto error; } while (!(ret = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts, jas_tvparser_gettag(tvp)))->id) { case OPT_DEBUG: cp->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFX: cp->imgareatlx = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFY: cp->imgareatly = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFX: cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFY: cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEWIDTH: cp->tilewidth = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEHEIGHT: cp->tileheight = atoi(jas_tvparser_getval(tvp)); break; case OPT_PRCWIDTH: prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_PRCHEIGHT: prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKWIDTH: tccp->cblkwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKHEIGHT: tccp->cblkheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_MODE: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid mode %s\n", jas_tvparser_getval(tvp)); } else { tcp->intmode = (tagid == MODE_INT); } break; case OPT_PRG: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid progression order %s\n", jas_tvparser_getval(tvp)); } else { tcp->prg = tagid; } break; case OPT_NOMCT: enablemct = false; break; case OPT_MAXRLVLS: tccp->maxrlvls = atoi(jas_tvparser_getval(tvp)); if(tccp->maxrlvls > JPC_MAXRLVLS) { jas_eprintf("invalid number of resolution levels upper than %d\n",JPC_MAXRLVLS); goto error; } break; case OPT_SOP: cp->tcp.csty |= JPC_COD_SOP; break; case OPT_EPH: cp->tcp.csty |= JPC_COD_EPH; break; case OPT_LAZY: tccp->cblksty |= JPC_COX_LAZY; break; case OPT_TERMALL: tccp->cblksty |= JPC_COX_TERMALL; break; case OPT_SEGSYM: tccp->cblksty |= JPC_COX_SEGSYM; break; case OPT_VCAUSAL: tccp->cblksty |= JPC_COX_VSC; break; case OPT_RESET: tccp->cblksty |= JPC_COX_RESET; break; case OPT_PTERM: tccp->cblksty |= JPC_COX_PTERM; break; case OPT_NUMGBITS: cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp)); break; case OPT_RATE: if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize, &cp->totalsize)) { jas_eprintf("ignoring bad rate specifier %s\n", jas_tvparser_getval(tvp)); } break; case OPT_ILYRRATES: if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates, &ilyrrates)) { jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n", jas_tvparser_getval(tvp)); } break; case OPT_JP2OVERHEAD: jp2overhead = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); tvp = 0; if (cp->totalsize != UINT_FAST32_MAX) { cp->totalsize = (cp->totalsize > jp2overhead) ? (cp->totalsize - jp2overhead) : 0; } if (cp->imgareatlx == UINT_FAST32_MAX) { cp->imgareatlx = 0; } else { if (hsteplcm != 1) { jas_eprintf("warning: overriding imgareatlx value\n"); } cp->imgareatlx *= hsteplcm; } if (cp->imgareatly == UINT_FAST32_MAX) { cp->imgareatly = 0; } else { if (vsteplcm != 1) { jas_eprintf("warning: overriding imgareatly value\n"); } cp->imgareatly *= vsteplcm; } cp->refgrdwidth = cp->imgareatlx + jas_image_width(image); cp->refgrdheight = cp->imgareatly + jas_image_height(image); if (cp->tilegrdoffx == UINT_FAST32_MAX) { cp->tilegrdoffx = cp->imgareatlx; } if (cp->tilegrdoffy == UINT_FAST32_MAX) { cp->tilegrdoffy = cp->imgareatly; } if (!cp->tilewidth) { cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx; } if (!cp->tileheight) { cp->tileheight = cp->refgrdheight - cp->tilegrdoffy; } if (cp->numcmpts == 3) { mctvalid = true; for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) || jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) || jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) || jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) { mctvalid = false; } } } else { mctvalid = false; } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) { jas_eprintf("warning: color space apparently not RGB\n"); } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) { tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT); } else { tcp->mctid = JPC_MCT_NONE; } tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS); for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { tccp->prcwidthexpns[rlvlno] = prcwidthexpn; tccp->prcheightexpns[rlvlno] = prcheightexpn; } if (prcwidthexpn != 15 || prcheightexpn != 15) { tccp->csty |= JPC_COX_PRT; } /* Ensure that the tile width and height is valid. */ if (!cp->tilewidth) { jas_eprintf("invalid tile width %lu\n", (unsigned long) cp->tilewidth); goto error; } if (!cp->tileheight) { jas_eprintf("invalid tile height %lu\n", (unsigned long) cp->tileheight); goto error; } /* Ensure that the tile grid offset is valid. */ if (cp->tilegrdoffx > cp->imgareatlx || cp->tilegrdoffy > cp->imgareatly || cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx || cp->tilegrdoffy + cp->tileheight < cp->imgareatly) { jas_eprintf("invalid tile grid offset (%lu, %lu)\n", (unsigned long) cp->tilegrdoffx, (unsigned long) cp->tilegrdoffy); goto error; } cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx, cp->tilewidth); cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy, cp->tileheight); cp->numtiles = cp->numhtiles * cp->numvtiles; if (ilyrrates && numilyrrates > 0) { tcp->numlyrs = numilyrrates + 1; if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1), sizeof(jpc_fix_t)))) { goto error; } for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) { tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]); } } /* Ensure that the integer mode is used in the case of lossless coding. */ if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) { jas_eprintf("cannot use real mode for lossless coding\n"); goto error; } /* Ensure that the precinct width is valid. */ if (prcwidthexpn > 15) { jas_eprintf("invalid precinct width\n"); goto error; } /* Ensure that the precinct height is valid. */ if (prcheightexpn > 15) { jas_eprintf("invalid precinct height\n"); goto error; } /* Ensure that the code block width is valid. */ if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) { jas_eprintf("invalid code block width %d\n", JPC_POW2(cp->tccp.cblkwidthexpn)); goto error; } /* Ensure that the code block height is valid. */ if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) { jas_eprintf("invalid code block height %d\n", JPC_POW2(cp->tccp.cblkheightexpn)); goto error; } /* Ensure that the code block size is not too large. */ if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) { jas_eprintf("code block size too large\n"); goto error; } /* Ensure that the number of layers is valid. */ if (cp->tcp.numlyrs > 16384) { jas_eprintf("too many layers\n"); goto error; } /* There must be at least one resolution level. */ if (cp->tccp.maxrlvls < 1) { jas_eprintf("must be at least one resolution level\n"); goto error; } /* Ensure that the number of guard bits is valid. */ if (cp->tccp.numgbits > 8) { jas_eprintf("invalid number of guard bits\n"); goto error; } /* Ensure that the rate is within the legal range. */ if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) { jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize); } /* Ensure that the intermediate layer rates are valid. */ if (tcp->numlyrs > 1) { /* The intermediate layers rates must increase monotonically. */ for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) { if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) { jas_eprintf("intermediate layer rates must increase monotonically\n"); goto error; } } /* The intermediate layer rates must be less than the overall rate. */ if (cp->totalsize != UINT_FAST32_MAX) { for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) { if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize) / cp->rawsize) { jas_eprintf("warning: intermediate layer rates must be less than overall rate\n"); goto error; } } } } if (ilyrrates) { jas_free(ilyrrates); } return cp; error: if (ilyrrates) { jas_free(ilyrrates); } if (tvp) { jas_tvparser_destroy(tvp); } if (cp) { jpc_enc_cp_destroy(cp); } return 0; }
258879101783368514234166952366199989021
jpc_enc.c
134316338883827501672124248295180144242
CWE-20
CVE-2020-27828
There's a flaw in jasper's jpc encoder in versions prior to 2.0.23. Crafted input provided to jasper by an attacker could cause an arbitrary out-of-bounds write. This could potentially affect data confidentiality, integrity, or application availability.
https://nvd.nist.gov/vuln/detail/CVE-2020-27828
211,842
vim
4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa
https://github.com/vim/vim
https://github.com/vim/vim/commit/4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa
patch 8.2.4436: crash with weird 'vartabstop' value Problem: Crash with weird 'vartabstop' value. Solution: Check for running into the end of the line.
1
change_indent( int type, int amount, int round, int replaced, // replaced character, put on replace stack int call_changed_bytes) // call changed_bytes() { int vcol; int last_vcol; int insstart_less; // reduction for Insstart.col int new_cursor_col; int i; char_u *ptr; int save_p_list; int start_col; colnr_T vc; colnr_T orig_col = 0; // init for GCC char_u *new_line, *orig_line = NULL; // init for GCC // VREPLACE mode needs to know what the line was like before changing if (State & VREPLACE_FLAG) { orig_line = vim_strsave(ml_get_curline()); // Deal with NULL below orig_col = curwin->w_cursor.col; } // for the following tricks we don't want list mode save_p_list = curwin->w_p_list; curwin->w_p_list = FALSE; vc = getvcol_nolist(&curwin->w_cursor); vcol = vc; // For Replace mode we need to fix the replace stack later, which is only // possible when the cursor is in the indent. Remember the number of // characters before the cursor if it's possible. start_col = curwin->w_cursor.col; // determine offset from first non-blank new_cursor_col = curwin->w_cursor.col; beginline(BL_WHITE); new_cursor_col -= curwin->w_cursor.col; insstart_less = curwin->w_cursor.col; // If the cursor is in the indent, compute how many screen columns the // cursor is to the left of the first non-blank. if (new_cursor_col < 0) vcol = get_indent() - vcol; if (new_cursor_col > 0) // can't fix replace stack start_col = -1; // Set the new indent. The cursor will be put on the first non-blank. if (type == INDENT_SET) (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); else { int save_State = State; // Avoid being called recursively. if (State & VREPLACE_FLAG) State = INSERT; shift_line(type == INDENT_DEC, round, 1, call_changed_bytes); State = save_State; } insstart_less -= curwin->w_cursor.col; // Try to put cursor on same character. // If the cursor is at or after the first non-blank in the line, // compute the cursor column relative to the column of the first // non-blank character. // If we are not in insert mode, leave the cursor on the first non-blank. // If the cursor is before the first non-blank, position it relative // to the first non-blank, counted in screen columns. if (new_cursor_col >= 0) { // When changing the indent while the cursor is touching it, reset // Insstart_col to 0. if (new_cursor_col == 0) insstart_less = MAXCOL; new_cursor_col += curwin->w_cursor.col; } else if (!(State & INSERT)) new_cursor_col = curwin->w_cursor.col; else { // Compute the screen column where the cursor should be. vcol = get_indent() - vcol; curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol); // Advance the cursor until we reach the right screen column. vcol = last_vcol = 0; new_cursor_col = -1; ptr = ml_get_curline(); while (vcol <= (int)curwin->w_virtcol) { last_vcol = vcol; if (has_mbyte && new_cursor_col >= 0) new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col); else ++new_cursor_col; vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol); } vcol = last_vcol; // May need to insert spaces to be able to position the cursor on // the right screen column. if (vcol != (int)curwin->w_virtcol) { curwin->w_cursor.col = (colnr_T)new_cursor_col; i = (int)curwin->w_virtcol - vcol; ptr = alloc(i + 1); if (ptr != NULL) { new_cursor_col += i; ptr[i] = NUL; while (--i >= 0) ptr[i] = ' '; ins_str(ptr); vim_free(ptr); } } // When changing the indent while the cursor is in it, reset // Insstart_col to 0. insstart_less = MAXCOL; } curwin->w_p_list = save_p_list; if (new_cursor_col <= 0) curwin->w_cursor.col = 0; else curwin->w_cursor.col = (colnr_T)new_cursor_col; curwin->w_set_curswant = TRUE; changed_cline_bef_curs(); // May have to adjust the start of the insert. if (State & INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { if ((int)Insstart.col <= insstart_less) Insstart.col = 0; else Insstart.col -= insstart_less; } if ((int)ai_col <= insstart_less) ai_col = 0; else ai_col -= insstart_less; } // For REPLACE mode, may have to fix the replace stack, if it's possible. // If the number of characters before the cursor decreased, need to pop a // few characters from the replace stack. // If the number of characters before the cursor increased, need to push a // few NULs onto the replace stack. if (REPLACE_NORMAL(State) && start_col >= 0) { while (start_col > (int)curwin->w_cursor.col) { replace_join(0); // remove a NUL from the replace stack --start_col; } while (start_col < (int)curwin->w_cursor.col || replaced) { replace_push(NUL); if (replaced) { replace_push(replaced); replaced = NUL; } ++start_col; } } // For VREPLACE mode, we also have to fix the replace stack. In this case // it is always possible because we backspace over the whole line and then // put it back again the way we wanted it. if (State & VREPLACE_FLAG) { // If orig_line didn't allocate, just return. At least we did the job, // even if you can't backspace. if (orig_line == NULL) return; // Save new line new_line = vim_strsave(ml_get_curline()); if (new_line == NULL) return; // We only put back the new line up to the cursor new_line[curwin->w_cursor.col] = NUL; // Put back original line ml_replace(curwin->w_cursor.lnum, orig_line, FALSE); curwin->w_cursor.col = orig_col; // Backspace from cursor to start of line backspace_until_column(0); // Insert new stuff into line again ins_bytes(new_line); vim_free(new_line); } }
104434622616430304167109103842435027722
indent.c
225104819640164774379021828754456921804
CWE-787
CVE-2022-0714
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.4436.
https://nvd.nist.gov/vuln/detail/CVE-2022-0714
452,377
vim
4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa
https://github.com/vim/vim
https://github.com/vim/vim/commit/4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa
patch 8.2.4436: crash with weird 'vartabstop' value Problem: Crash with weird 'vartabstop' value. Solution: Check for running into the end of the line.
0
change_indent( int type, int amount, int round, int replaced, // replaced character, put on replace stack int call_changed_bytes) // call changed_bytes() { int vcol; int last_vcol; int insstart_less; // reduction for Insstart.col int new_cursor_col; int i; char_u *ptr; int save_p_list; int start_col; colnr_T vc; colnr_T orig_col = 0; // init for GCC char_u *new_line, *orig_line = NULL; // init for GCC // VREPLACE mode needs to know what the line was like before changing if (State & VREPLACE_FLAG) { orig_line = vim_strsave(ml_get_curline()); // Deal with NULL below orig_col = curwin->w_cursor.col; } // for the following tricks we don't want list mode save_p_list = curwin->w_p_list; curwin->w_p_list = FALSE; vc = getvcol_nolist(&curwin->w_cursor); vcol = vc; // For Replace mode we need to fix the replace stack later, which is only // possible when the cursor is in the indent. Remember the number of // characters before the cursor if it's possible. start_col = curwin->w_cursor.col; // determine offset from first non-blank new_cursor_col = curwin->w_cursor.col; beginline(BL_WHITE); new_cursor_col -= curwin->w_cursor.col; insstart_less = curwin->w_cursor.col; // If the cursor is in the indent, compute how many screen columns the // cursor is to the left of the first non-blank. if (new_cursor_col < 0) vcol = get_indent() - vcol; if (new_cursor_col > 0) // can't fix replace stack start_col = -1; // Set the new indent. The cursor will be put on the first non-blank. if (type == INDENT_SET) (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); else { int save_State = State; // Avoid being called recursively. if (State & VREPLACE_FLAG) State = INSERT; shift_line(type == INDENT_DEC, round, 1, call_changed_bytes); State = save_State; } insstart_less -= curwin->w_cursor.col; // Try to put cursor on same character. // If the cursor is at or after the first non-blank in the line, // compute the cursor column relative to the column of the first // non-blank character. // If we are not in insert mode, leave the cursor on the first non-blank. // If the cursor is before the first non-blank, position it relative // to the first non-blank, counted in screen columns. if (new_cursor_col >= 0) { // When changing the indent while the cursor is touching it, reset // Insstart_col to 0. if (new_cursor_col == 0) insstart_less = MAXCOL; new_cursor_col += curwin->w_cursor.col; } else if (!(State & INSERT)) new_cursor_col = curwin->w_cursor.col; else { // Compute the screen column where the cursor should be. vcol = get_indent() - vcol; curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol); // Advance the cursor until we reach the right screen column. vcol = last_vcol = 0; new_cursor_col = -1; ptr = ml_get_curline(); while (vcol <= (int)curwin->w_virtcol) { last_vcol = vcol; if (has_mbyte && new_cursor_col >= 0) new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col); else ++new_cursor_col; if (ptr[new_cursor_col] == NUL) break; vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol); } vcol = last_vcol; // May need to insert spaces to be able to position the cursor on // the right screen column. if (vcol != (int)curwin->w_virtcol) { curwin->w_cursor.col = (colnr_T)new_cursor_col; i = (int)curwin->w_virtcol - vcol; ptr = alloc(i + 1); if (ptr != NULL) { new_cursor_col += i; ptr[i] = NUL; while (--i >= 0) ptr[i] = ' '; ins_str(ptr); vim_free(ptr); } } // When changing the indent while the cursor is in it, reset // Insstart_col to 0. insstart_less = MAXCOL; } curwin->w_p_list = save_p_list; if (new_cursor_col <= 0) curwin->w_cursor.col = 0; else curwin->w_cursor.col = (colnr_T)new_cursor_col; curwin->w_set_curswant = TRUE; changed_cline_bef_curs(); // May have to adjust the start of the insert. if (State & INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { if ((int)Insstart.col <= insstart_less) Insstart.col = 0; else Insstart.col -= insstart_less; } if ((int)ai_col <= insstart_less) ai_col = 0; else ai_col -= insstart_less; } // For REPLACE mode, may have to fix the replace stack, if it's possible. // If the number of characters before the cursor decreased, need to pop a // few characters from the replace stack. // If the number of characters before the cursor increased, need to push a // few NULs onto the replace stack. if (REPLACE_NORMAL(State) && start_col >= 0) { while (start_col > (int)curwin->w_cursor.col) { replace_join(0); // remove a NUL from the replace stack --start_col; } while (start_col < (int)curwin->w_cursor.col || replaced) { replace_push(NUL); if (replaced) { replace_push(replaced); replaced = NUL; } ++start_col; } } // For VREPLACE mode, we also have to fix the replace stack. In this case // it is always possible because we backspace over the whole line and then // put it back again the way we wanted it. if (State & VREPLACE_FLAG) { // If orig_line didn't allocate, just return. At least we did the job, // even if you can't backspace. if (orig_line == NULL) return; // Save new line new_line = vim_strsave(ml_get_curline()); if (new_line == NULL) return; // We only put back the new line up to the cursor new_line[curwin->w_cursor.col] = NUL; // Put back original line ml_replace(curwin->w_cursor.lnum, orig_line, FALSE); curwin->w_cursor.col = orig_col; // Backspace from cursor to start of line backspace_until_column(0); // Insert new stuff into line again ins_bytes(new_line); vim_free(new_line); } }
281315459122812097070130024816280546627
indent.c
175343284041603087029849272826009468440
CWE-787
CVE-2022-0714
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.4436.
https://nvd.nist.gov/vuln/detail/CVE-2022-0714
211,845
ImageMagick6
1aea203eb36409ce6903b9e41fe7cb70030e8750
https://github.com/ImageMagick/ImageMagick6
https://github.com/ImageMagick/ImageMagick6/commit/1aea203eb36409ce6903b9e41fe7cb70030e8750
squash heap-buffer-overflow, PoC TIFF from Hardik
1
static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define MaxPixelChannels 32 #define ThrowTIFFException(severity,message) \ { \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity = (float *) NULL, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status = 0; MagickBooleanType more_frames; MagickStatusType status; MemoryInfo *pixel_info = (MemoryInfo *) NULL; QuantumInfo *quantum_info; QuantumType quantum_type; size_t number_pixels; ssize_t i, scanline_size, y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag = 0, bits_per_sample = 0, endian = 0, extra_samples = 0, interlace = 0, max_sample_value = 0, min_sample_value = 0, orientation = 0, pages = 0, photometric = 0, *sample_info = NULL, sample_format = 0, samples_per_pixel = 0, units = 0, value = 0; uint32 height, rows_per_strip, width; unsigned char *pixels; void *sans[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { if (exception->severity == UndefinedException) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); image=DestroyImageList(image); return((Image *) NULL); } if (exception->severity > ErrorException) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */ photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) && ((bits_per_sample <= 0) || (bits_per_sample > 32))) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); } if (samples_per_pixel > MaxPixelChannels) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) image->colorspace=GRAYColorspace; if (photometric == PHOTOMETRIC_SEPARATED) image->colorspace=CMYKColorspace; if (photometric == PHOTOMETRIC_CIELAB) image->colorspace=LabColorspace; if ((photometric == PHOTOMETRIC_YCBCR) && (compress_tag != COMPRESSION_OJPEG) && (compress_tag != COMPRESSION_JPEG)) image->colorspace=YCbCrColorspace; status=TIFFGetProfiles(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=TIFFGetProperties(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetEXIFProperties(tiff,image); option=GetImageOption(image_info,"tiff:gps-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetGPSProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1)) { image->page.x=CastDoubleToLong(ceil(x_position* image->x_resolution-0.5)); image->page.y=CastDoubleToLong(ceil(y_position* image->y_resolution-0.5)); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; #if defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: image->compression=WebPCompression; break; #endif #if defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: image->compression=ZstdCompression; break; #endif default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap = (uint16 *) NULL, *green_colormap = (uint16 *) NULL, *red_colormap = (uint16 *) NULL; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=SetImageColorspace(image,image->colorspace); status&=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } extra_samples=0; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info,sans); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } } if (image->matte != MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); method=ReadStripMethod; if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; } if (TIFFIsTiled(tiff) != MagickFalse) { uint32 columns, rows; if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit"); method=ReadTileMethod; } if ((photometric == PHOTOMETRIC_LOGLUV) || (compress_tag == COMPRESSION_CCITTFAX3)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); quantum_info->endian=LSBEndian; scanline_size=TIFFScanlineSize(tiff); if (scanline_size <= 0) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=MagickMax((MagickSizeType) image->columns*samples_per_pixel* pow(2.0,ceil(log(bits_per_sample)/log(2.0))),image->columns* rows_per_strip); if ((double) scanline_size > 1.5*number_pixels) ThrowTIFFException(CorruptImageError,"CorruptImage"); number_pixels=MagickMax((MagickSizeType) scanline_size,number_pixels); pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,number_pixels*sizeof(uint32)); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; if (interlace != PLANARCONFIG_SEPARATE) { size_t pad; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class == PseudoClass) quantum_type=IndexAlphaQuantum; else quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; } if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE)) { quantum_type=RGBQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-3,0); if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); } if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); } } switch (method) { case ReadYCCKMethod: { /* Convert YCC TIFF image. */ for (y=0; y < (ssize_t) image->rows; y++) { int status; IndexPacket *indexes; PixelPacket *magick_restrict q; ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { unsigned char *p; size_t extent; ssize_t stride, strip_id; tsize_t strip_size; unsigned char *strip_pixels; /* Convert stripped TIFF image. */ extent=4*(samples_per_pixel+1)*TIFFStripSize(tiff); strip_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*strip_pixels)); if (strip_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels)); stride=TIFFVStripSize(tiff,1); strip_id=0; p=strip_pixels; for (i=0; i < (ssize_t) samples_per_pixel; i++) { size_t rows_remaining; switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } rows_remaining=0; for (y=0; y < (ssize_t) image->rows; y++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (rows_remaining == 0) { strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels, TIFFStripSize(tiff)); if (strip_size == -1) break; rows_remaining=rows_per_strip; if ((y+rows_per_strip) > (ssize_t) image->rows) rows_remaining=(rows_per_strip-(y+rows_per_strip- image->rows)); p=strip_pixels; strip_id++; } (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=stride; rows_remaining--; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; } strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels); break; } case ReadTileMethod: { unsigned char *p; size_t extent; uint32 columns, rows; unsigned char *tile_pixels; /* Convert tiled TIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); extent=4*(samples_per_pixel+1)*MagickMax(rows*TIFFTileRowSize(tiff), TIFFTileSize(tiff)); tile_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*tile_pixels)); if (tile_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels)); for (i=0; i < (ssize_t) samples_per_pixel; i++) { switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } for (y=0; y < (ssize_t) image->rows; y+=rows) { ssize_t x; size_t rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t columns_remaining, row; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; tiff_status=TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y, 0,i); if (tiff_status == -1) break; p=tile_pixels; for (row=0; row < rows_remaining; row++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,x,y+row,columns_remaining,1, exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=TIFFTileRowSize(tiff); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i, samples_per_pixel); if (status == MagickFalse) break; } } tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *generic_info = (MemoryInfo *) NULL; uint32 *p; uint32 *pixels; /* Convert generic TIFF image. */ if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; generic_info=AcquireVirtualMemory(number_pixels,sizeof(*pixels)); if (generic_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(uint32 *) GetVirtualMemoryBlob(generic_info); tiff_status=TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); if (tiff_status == -1) { generic_info=RelinquishVirtualMemory(generic_info); break; } p=pixels+(image->columns*image->rows)-1; for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte == MagickFalse) SetPixelOpacity(q,OpaqueOpacity); else SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } generic_info=RelinquishVirtualMemory(generic_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (tiff_status == -1) { status=MagickFalse; break; } if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); TIFFReadPhotoshopLayers(image_info,image,exception); return(GetFirstImageInList(image)); }
282124666378195634578988553119839535376
tiff.c
94999311171482042296542443921541591860
CWE-787
CVE-2022-3213
A heap buffer overflow issue was found in ImageMagick. When an application processes a malformed TIFF file, it could lead to undefined behavior or a crash causing a denial of service.
https://nvd.nist.gov/vuln/detail/CVE-2022-3213
452,391
ImageMagick6
1aea203eb36409ce6903b9e41fe7cb70030e8750
https://github.com/ImageMagick/ImageMagick6
https://github.com/ImageMagick/ImageMagick6/commit/1aea203eb36409ce6903b9e41fe7cb70030e8750
squash heap-buffer-overflow, PoC TIFF from Hardik
0
static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define MaxPixelChannels 32 #define ThrowTIFFException(severity,message) \ { \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity = (float *) NULL, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status = 0; MagickBooleanType more_frames; MagickStatusType status; MemoryInfo *pixel_info = (MemoryInfo *) NULL; QuantumInfo *quantum_info; QuantumType quantum_type; size_t number_pixels; ssize_t i, scanline_size, y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag = 0, bits_per_sample = 0, endian = 0, extra_samples = 0, interlace = 0, max_sample_value = 0, min_sample_value = 0, orientation = 0, pages = 0, photometric = 0, *sample_info = NULL, sample_format = 0, samples_per_pixel = 0, units = 0, value = 0; uint32 height, rows_per_strip, width; unsigned char *pixels; void *sans[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { if (exception->severity == UndefinedException) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); image=DestroyImageList(image); return((Image *) NULL); } if (exception->severity > ErrorException) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */ photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) && ((bits_per_sample <= 0) || (bits_per_sample > 32))) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); } if (samples_per_pixel > MaxPixelChannels) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) image->colorspace=GRAYColorspace; if (photometric == PHOTOMETRIC_SEPARATED) image->colorspace=CMYKColorspace; if (photometric == PHOTOMETRIC_CIELAB) image->colorspace=LabColorspace; if ((photometric == PHOTOMETRIC_YCBCR) && (compress_tag != COMPRESSION_OJPEG) && (compress_tag != COMPRESSION_JPEG)) image->colorspace=YCbCrColorspace; status=TIFFGetProfiles(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=TIFFGetProperties(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetEXIFProperties(tiff,image); option=GetImageOption(image_info,"tiff:gps-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetGPSProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1)) { image->page.x=CastDoubleToLong(ceil(x_position* image->x_resolution-0.5)); image->page.y=CastDoubleToLong(ceil(y_position* image->y_resolution-0.5)); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; #if defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: image->compression=WebPCompression; break; #endif #if defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: image->compression=ZstdCompression; break; #endif default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap = (uint16 *) NULL, *green_colormap = (uint16 *) NULL, *red_colormap = (uint16 *) NULL; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=SetImageColorspace(image,image->colorspace); status&=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } extra_samples=0; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info,sans); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } } if (image->matte != MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); method=ReadStripMethod; if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; } if (TIFFIsTiled(tiff) != MagickFalse) { uint32 columns, rows; if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit"); method=ReadTileMethod; } if ((photometric == PHOTOMETRIC_LOGLUV) || (compress_tag == COMPRESSION_CCITTFAX3)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); quantum_info->endian=LSBEndian; scanline_size=TIFFScanlineSize(tiff); if (scanline_size <= 0) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=MagickMax((MagickSizeType) image->columns*samples_per_pixel* pow(2.0,ceil(log(bits_per_sample)/log(2.0))),image->columns* rows_per_strip); if ((double) scanline_size > 1.5*number_pixels) ThrowTIFFException(CorruptImageError,"CorruptImage"); number_pixels=MagickMax((MagickSizeType) scanline_size,number_pixels); pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,number_pixels*sizeof(uint32)); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; if (interlace != PLANARCONFIG_SEPARATE) { size_t pad; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class == PseudoClass) quantum_type=IndexAlphaQuantum; else quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; } if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE)) { quantum_type=RGBQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-3,0); if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); } if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); } } switch (method) { case ReadYCCKMethod: { /* Convert YCC TIFF image. */ for (y=0; y < (ssize_t) image->rows; y++) { int status; IndexPacket *indexes; PixelPacket *magick_restrict q; ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { unsigned char *p; size_t extent; ssize_t stride, strip_id; tsize_t strip_size; unsigned char *strip_pixels; /* Convert stripped TIFF image. */ extent=4*((image->depth+7)/8)*(samples_per_pixel+1)*TIFFStripSize(tiff); strip_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*strip_pixels)); if (strip_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels)); stride=TIFFVStripSize(tiff,1); strip_id=0; p=strip_pixels; for (i=0; i < (ssize_t) samples_per_pixel; i++) { size_t rows_remaining; switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } rows_remaining=0; for (y=0; y < (ssize_t) image->rows; y++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (rows_remaining == 0) { strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels, TIFFStripSize(tiff)); if (strip_size == -1) break; rows_remaining=rows_per_strip; if ((y+rows_per_strip) > (ssize_t) image->rows) rows_remaining=(rows_per_strip-(y+rows_per_strip- image->rows)); p=strip_pixels; strip_id++; } (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=stride; rows_remaining--; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; } strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels); break; } case ReadTileMethod: { unsigned char *p; size_t extent; uint32 columns, rows; unsigned char *tile_pixels; /* Convert tiled TIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); extent=4*(samples_per_pixel+1)*MagickMax(rows*TIFFTileRowSize(tiff), TIFFTileSize(tiff)); tile_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*tile_pixels)); if (tile_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels)); for (i=0; i < (ssize_t) samples_per_pixel; i++) { switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } for (y=0; y < (ssize_t) image->rows; y+=rows) { ssize_t x; size_t rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t columns_remaining, row; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; tiff_status=TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y, 0,i); if (tiff_status == -1) break; p=tile_pixels; for (row=0; row < rows_remaining; row++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,x,y+row,columns_remaining,1, exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=TIFFTileRowSize(tiff); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i, samples_per_pixel); if (status == MagickFalse) break; } } tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *generic_info = (MemoryInfo *) NULL; uint32 *p; uint32 *pixels; /* Convert generic TIFF image. */ if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; generic_info=AcquireVirtualMemory(number_pixels,sizeof(*pixels)); if (generic_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(uint32 *) GetVirtualMemoryBlob(generic_info); tiff_status=TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); if (tiff_status == -1) { generic_info=RelinquishVirtualMemory(generic_info); break; } p=pixels+(image->columns*image->rows)-1; for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte == MagickFalse) SetPixelOpacity(q,OpaqueOpacity); else SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } generic_info=RelinquishVirtualMemory(generic_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (tiff_status == -1) { status=MagickFalse; break; } if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); TIFFReadPhotoshopLayers(image_info,image,exception); return(GetFirstImageInList(image)); }
299907120858996373991818547886083873911
tiff.c
106627250122948436089504190965714390547
CWE-787
CVE-2022-3213
A heap buffer overflow issue was found in ImageMagick. When an application processes a malformed TIFF file, it could lead to undefined behavior or a crash causing a denial of service.
https://nvd.nist.gov/vuln/detail/CVE-2022-3213
211,868
nf
b1a5983f56e371046dcf164f90bfaf704d2b89f6
http://git.kernel.org/cgit/linux/kernel/git/pablo/nf
https://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git/commit/?id=b1a5983f56e371046dcf164f90bfaf704d2b89f6
netfilter: nf_tables_offload: incorrect flow offload action array size immediate verdict expression needs to allocate one slot in the flow offload action array, however, immediate data expression does not need to do so. fwd and dup expression need to allocate one slot, this is missing. Add a new offload_action interface to report if this expression needs to allocate one slot in the flow offload action array. Fixes: be2861dc36d7 ("netfilter: nft_{fwd,dup}_netdev: add offload support") Reported-and-tested-by: Nick Gregory <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>
1
struct nft_flow_rule *nft_flow_rule_create(struct net *net, const struct nft_rule *rule) { struct nft_offload_ctx *ctx; struct nft_flow_rule *flow; int num_actions = 0, err; struct nft_expr *expr; expr = nft_expr_first(rule); while (nft_expr_more(rule, expr)) { if (expr->ops->offload_flags & NFT_OFFLOAD_F_ACTION) num_actions++; expr = nft_expr_next(expr); } if (num_actions == 0) return ERR_PTR(-EOPNOTSUPP); flow = nft_flow_rule_alloc(num_actions); if (!flow) return ERR_PTR(-ENOMEM); expr = nft_expr_first(rule); ctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL); if (!ctx) { err = -ENOMEM; goto err_out; } ctx->net = net; ctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC; while (nft_expr_more(rule, expr)) { if (!expr->ops->offload) { err = -EOPNOTSUPP; goto err_out; } err = expr->ops->offload(ctx, flow, expr); if (err < 0) goto err_out; expr = nft_expr_next(expr); } nft_flow_rule_transfer_vlan(ctx, flow); flow->proto = ctx->dep.l3num; kfree(ctx); return flow; err_out: kfree(ctx); nft_flow_rule_destroy(flow); return ERR_PTR(err); }
135282973834013788624737629823587242676
nf_tables_offload.c
26603376215652964964004794041493892983
CWE-269
CVE-2022-25636
net/netfilter/nf_dup_netdev.c in the Linux kernel 5.4 through 5.6.10 allows local users to gain privileges because of a heap out-of-bounds write. This is related to nf_tables_offload.
https://nvd.nist.gov/vuln/detail/CVE-2022-25636
452,994
nf
b1a5983f56e371046dcf164f90bfaf704d2b89f6
http://git.kernel.org/cgit/linux/kernel/git/pablo/nf
https://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git/commit/?id=b1a5983f56e371046dcf164f90bfaf704d2b89f6
netfilter: nf_tables_offload: incorrect flow offload action array size immediate verdict expression needs to allocate one slot in the flow offload action array, however, immediate data expression does not need to do so. fwd and dup expression need to allocate one slot, this is missing. Add a new offload_action interface to report if this expression needs to allocate one slot in the flow offload action array. Fixes: be2861dc36d7 ("netfilter: nft_{fwd,dup}_netdev: add offload support") Reported-and-tested-by: Nick Gregory <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>
0
struct nft_flow_rule *nft_flow_rule_create(struct net *net, const struct nft_rule *rule) { struct nft_offload_ctx *ctx; struct nft_flow_rule *flow; int num_actions = 0, err; struct nft_expr *expr; expr = nft_expr_first(rule); while (nft_expr_more(rule, expr)) { if (expr->ops->offload_action && expr->ops->offload_action(expr)) num_actions++; expr = nft_expr_next(expr); } if (num_actions == 0) return ERR_PTR(-EOPNOTSUPP); flow = nft_flow_rule_alloc(num_actions); if (!flow) return ERR_PTR(-ENOMEM); expr = nft_expr_first(rule); ctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL); if (!ctx) { err = -ENOMEM; goto err_out; } ctx->net = net; ctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC; while (nft_expr_more(rule, expr)) { if (!expr->ops->offload) { err = -EOPNOTSUPP; goto err_out; } err = expr->ops->offload(ctx, flow, expr); if (err < 0) goto err_out; expr = nft_expr_next(expr); } nft_flow_rule_transfer_vlan(ctx, flow); flow->proto = ctx->dep.l3num; kfree(ctx); return flow; err_out: kfree(ctx); nft_flow_rule_destroy(flow); return ERR_PTR(err); }
59444629723641299753508256533223671386
nf_tables_offload.c
69217204877048087601961561157864546689
CWE-269
CVE-2022-25636
net/netfilter/nf_dup_netdev.c in the Linux kernel 5.4 through 5.6.10 allows local users to gain privileges because of a heap out-of-bounds write. This is related to nf_tables_offload.
https://nvd.nist.gov/vuln/detail/CVE-2022-25636
211,877
libexpat
a2fe525e660badd64b6c557c2b1ec26ddc07f6e4
https://github.com/libexpat/libexpat
https://github.com/libexpat/libexpat/commit/a2fe525e660badd64b6c557c2b1ec26ddc07f6e4
lib: Protect against malicious namespace declarations (CVE-2022-25236)
1
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr) { static const XML_Char xmlNamespace[] = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0'}; static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1; static const XML_Char xmlnsNamespace[] = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'}; static const int xmlnsLen = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1; XML_Bool mustBeXML = XML_FALSE; XML_Bool isXML = XML_TRUE; XML_Bool isXMLNS = XML_TRUE; BINDING *b; int len; /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */ if (*uri == XML_T('\0') && prefix->name) return XML_ERROR_UNDECLARING_PREFIX; if (prefix->name && prefix->name[0] == XML_T(ASCII_x) && prefix->name[1] == XML_T(ASCII_m) && prefix->name[2] == XML_T(ASCII_l)) { /* Not allowed to bind xmlns */ if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s) && prefix->name[5] == XML_T('\0')) return XML_ERROR_RESERVED_PREFIX_XMLNS; if (prefix->name[3] == XML_T('\0')) mustBeXML = XML_TRUE; } for (len = 0; uri[len]; len++) { if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len])) isXML = XML_FALSE; if (! mustBeXML && isXMLNS && (len > xmlnsLen || uri[len] != xmlnsNamespace[len])) isXMLNS = XML_FALSE; } isXML = isXML && len == xmlLen; isXMLNS = isXMLNS && len == xmlnsLen; if (mustBeXML != isXML) return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML : XML_ERROR_RESERVED_NAMESPACE_URI; if (isXMLNS) return XML_ERROR_RESERVED_NAMESPACE_URI; if (parser->m_namespaceSeparator) len++; if (parser->m_freeBindingList) { b = parser->m_freeBindingList; if (len > b->uriAlloc) { /* Detect and prevent integer overflow */ if (len > INT_MAX - EXPAND_SPARE) { return XML_ERROR_NO_MEMORY; } /* Detect and prevent integer overflow. * The preprocessor guard addresses the "always false" warning * from -Wtype-limits on platforms where * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */ #if UINT_MAX >= SIZE_MAX if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) { return XML_ERROR_NO_MEMORY; } #endif XML_Char *temp = (XML_Char *)REALLOC( parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE)); if (temp == NULL) return XML_ERROR_NO_MEMORY; b->uri = temp; b->uriAlloc = len + EXPAND_SPARE; } parser->m_freeBindingList = b->nextTagBinding; } else { b = (BINDING *)MALLOC(parser, sizeof(BINDING)); if (! b) return XML_ERROR_NO_MEMORY; /* Detect and prevent integer overflow */ if (len > INT_MAX - EXPAND_SPARE) { return XML_ERROR_NO_MEMORY; } /* Detect and prevent integer overflow. * The preprocessor guard addresses the "always false" warning * from -Wtype-limits on platforms where * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */ #if UINT_MAX >= SIZE_MAX if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) { return XML_ERROR_NO_MEMORY; } #endif b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE)); if (! b->uri) { FREE(parser, b); return XML_ERROR_NO_MEMORY; } b->uriAlloc = len + EXPAND_SPARE; } b->uriLen = len; memcpy(b->uri, uri, len * sizeof(XML_Char)); if (parser->m_namespaceSeparator) b->uri[len - 1] = parser->m_namespaceSeparator; b->prefix = prefix; b->attId = attId; b->prevPrefixBinding = prefix->binding; /* NULL binding when default namespace undeclared */ if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix) prefix->binding = NULL; else prefix->binding = b; b->nextTagBinding = *bindingsPtr; *bindingsPtr = b; /* if attId == NULL then we are not starting a namespace scope */ if (attId && parser->m_startNamespaceDeclHandler) parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name, prefix->binding ? uri : 0); return XML_ERROR_NONE; }
22295362737021887331084829836677682659
xmlparse.c
64970761866861782031621044957132437337
CWE-668
CVE-2022-25236
xmlparse.c in Expat (aka libexpat) before 2.4.5 allows attackers to insert namespace-separator characters into namespace URIs.
https://nvd.nist.gov/vuln/detail/CVE-2022-25236
453,109
libexpat
a2fe525e660badd64b6c557c2b1ec26ddc07f6e4
https://github.com/libexpat/libexpat
https://github.com/libexpat/libexpat/commit/a2fe525e660badd64b6c557c2b1ec26ddc07f6e4
lib: Protect against malicious namespace declarations (CVE-2022-25236)
0
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr) { static const XML_Char xmlNamespace[] = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0'}; static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1; static const XML_Char xmlnsNamespace[] = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'}; static const int xmlnsLen = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1; XML_Bool mustBeXML = XML_FALSE; XML_Bool isXML = XML_TRUE; XML_Bool isXMLNS = XML_TRUE; BINDING *b; int len; /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */ if (*uri == XML_T('\0') && prefix->name) return XML_ERROR_UNDECLARING_PREFIX; if (prefix->name && prefix->name[0] == XML_T(ASCII_x) && prefix->name[1] == XML_T(ASCII_m) && prefix->name[2] == XML_T(ASCII_l)) { /* Not allowed to bind xmlns */ if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s) && prefix->name[5] == XML_T('\0')) return XML_ERROR_RESERVED_PREFIX_XMLNS; if (prefix->name[3] == XML_T('\0')) mustBeXML = XML_TRUE; } for (len = 0; uri[len]; len++) { if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len])) isXML = XML_FALSE; if (! mustBeXML && isXMLNS && (len > xmlnsLen || uri[len] != xmlnsNamespace[len])) isXMLNS = XML_FALSE; // NOTE: While Expat does not validate namespace URIs against RFC 3986, // we have to at least make sure that the XML processor on top of // Expat (that is splitting tag names by namespace separator into // 2- or 3-tuples (uri-local or uri-local-prefix)) cannot be confused // by an attacker putting additional namespace separator characters // into namespace declarations. That would be ambiguous and not to // be expected. if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)) { return XML_ERROR_SYNTAX; } } isXML = isXML && len == xmlLen; isXMLNS = isXMLNS && len == xmlnsLen; if (mustBeXML != isXML) return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML : XML_ERROR_RESERVED_NAMESPACE_URI; if (isXMLNS) return XML_ERROR_RESERVED_NAMESPACE_URI; if (parser->m_namespaceSeparator) len++; if (parser->m_freeBindingList) { b = parser->m_freeBindingList; if (len > b->uriAlloc) { /* Detect and prevent integer overflow */ if (len > INT_MAX - EXPAND_SPARE) { return XML_ERROR_NO_MEMORY; } /* Detect and prevent integer overflow. * The preprocessor guard addresses the "always false" warning * from -Wtype-limits on platforms where * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */ #if UINT_MAX >= SIZE_MAX if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) { return XML_ERROR_NO_MEMORY; } #endif XML_Char *temp = (XML_Char *)REALLOC( parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE)); if (temp == NULL) return XML_ERROR_NO_MEMORY; b->uri = temp; b->uriAlloc = len + EXPAND_SPARE; } parser->m_freeBindingList = b->nextTagBinding; } else { b = (BINDING *)MALLOC(parser, sizeof(BINDING)); if (! b) return XML_ERROR_NO_MEMORY; /* Detect and prevent integer overflow */ if (len > INT_MAX - EXPAND_SPARE) { return XML_ERROR_NO_MEMORY; } /* Detect and prevent integer overflow. * The preprocessor guard addresses the "always false" warning * from -Wtype-limits on platforms where * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */ #if UINT_MAX >= SIZE_MAX if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) { return XML_ERROR_NO_MEMORY; } #endif b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE)); if (! b->uri) { FREE(parser, b); return XML_ERROR_NO_MEMORY; } b->uriAlloc = len + EXPAND_SPARE; } b->uriLen = len; memcpy(b->uri, uri, len * sizeof(XML_Char)); if (parser->m_namespaceSeparator) b->uri[len - 1] = parser->m_namespaceSeparator; b->prefix = prefix; b->attId = attId; b->prevPrefixBinding = prefix->binding; /* NULL binding when default namespace undeclared */ if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix) prefix->binding = NULL; else prefix->binding = b; b->nextTagBinding = *bindingsPtr; *bindingsPtr = b; /* if attId == NULL then we are not starting a namespace scope */ if (attId && parser->m_startNamespaceDeclHandler) parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name, prefix->binding ? uri : 0); return XML_ERROR_NONE; }
180909609780994811991308792390157424153
xmlparse.c
39872007825496999526918942248087494728
CWE-668
CVE-2022-25236
xmlparse.c in Expat (aka libexpat) before 2.4.5 allows attackers to insert namespace-separator characters into namespace URIs.
https://nvd.nist.gov/vuln/detail/CVE-2022-25236
211,915
jasper
839b1bcf0450ff036c28e8db40a7abf886e02891
https://github.com/mdadams/jasper
https://github.com/jasper-software/jasper/commit/839b1bcf0450ff036c28e8db40a7abf886e02891
jp2_dec: fix `numchans` mixup When iterating over `dec->cdef->data.cdef.ents`, we need to use its `numchans` variable, not the one in `jp2_dec_t`. Fixes CVE-2018-19543 Fixes CVE-2017-9782 Closes https://github.com/jasper-maint/jasper/issues/13 Closes https://github.com/jasper-maint/jasper/issues/18 Closes https://github.com/mdadams/jasper/issues/140 Closes https://github.com/mdadams/jasper/issues/182
1
jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr) { jp2_box_t *box; int found; jas_image_t *image; jp2_dec_t *dec; bool samedtype; int dtype; unsigned int i; jp2_cmap_t *cmapd; jp2_pclr_t *pclrd; jp2_cdef_t *cdefd; unsigned int channo; int newcmptno; int_fast32_t *lutents; #if 0 jp2_cdefchan_t *cdefent; int cmptno; #endif jp2_cmapent_t *cmapent; jas_icchdr_t icchdr; jas_iccprof_t *iccprof; dec = 0; box = 0; image = 0; JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr)); if (!(dec = jp2_dec_create())) { goto error; } /* Get the first box. This should be a JP box. */ if (!(box = jp2_box_get(in))) { jas_eprintf("error: cannot get box\n"); goto error; } if (box->type != JP2_BOX_JP) { jas_eprintf("error: expecting signature box\n"); goto error; } if (box->data.jp.magic != JP2_JP_MAGIC) { jas_eprintf("incorrect magic number\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get the second box. This should be a FTYP box. */ if (!(box = jp2_box_get(in))) { goto error; } if (box->type != JP2_BOX_FTYP) { jas_eprintf("expecting file type box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get more boxes... */ found = 0; while ((box = jp2_box_get(in))) { if (jas_getdbglevel() >= 1) { jas_eprintf("got box type %s\n", box->info->name); } switch (box->type) { case JP2_BOX_JP2C: found = 1; break; case JP2_BOX_IHDR: if (!dec->ihdr) { dec->ihdr = box; box = 0; } break; case JP2_BOX_BPCC: if (!dec->bpcc) { dec->bpcc = box; box = 0; } break; case JP2_BOX_CDEF: if (!dec->cdef) { dec->cdef = box; box = 0; } break; case JP2_BOX_PCLR: if (!dec->pclr) { dec->pclr = box; box = 0; } break; case JP2_BOX_CMAP: if (!dec->cmap) { dec->cmap = box; box = 0; } break; case JP2_BOX_COLR: if (!dec->colr) { dec->colr = box; box = 0; } break; } if (box) { jp2_box_destroy(box); box = 0; } if (found) { break; } } if (!found) { jas_eprintf("error: no code stream found\n"); goto error; } if (!(dec->image = jpc_decode(in, optstr))) { jas_eprintf("error: cannot decode code stream\n"); goto error; } /* An IHDR box must be present. */ if (!dec->ihdr) { jas_eprintf("error: missing IHDR box\n"); goto error; } /* Does the number of components indicated in the IHDR box match the value specified in the code stream? */ if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* At least one component must be present. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } /* Determine if all components have the same data type. */ samedtype = true; dtype = jas_image_cmptdtype(dec->image, 0); for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != dtype) { samedtype = false; break; } } /* Is the component data type indicated in the IHDR box consistent with the data in the code stream? */ if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { jas_eprintf("warning: component data type mismatch\n"); } /* Is the compression type supported? */ if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { jas_eprintf("error: unsupported compression type\n"); goto error; } if (dec->bpcc) { /* Is the number of components indicated in the BPCC box consistent with the code stream data? */ if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts( dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* Is the component data type information indicated in the BPCC box consistent with the code stream data? */ if (!samedtype) { for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { jas_eprintf("warning: component data type mismatch\n"); } } } else { jas_eprintf("warning: superfluous BPCC box\n"); } } /* A COLR box must be present. */ if (!dec->colr) { jas_eprintf("error: no COLR box\n"); goto error; } switch (dec->colr->data.colr.method) { case JP2_COLR_ENUM: jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); break; case JP2_COLR_ICC: iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, dec->colr->data.colr.iccplen); if (!iccprof) { jas_eprintf("error: failed to parse ICC profile\n"); goto error; } jas_iccprof_gethdr(iccprof, &icchdr); jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc); jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); assert(dec->image->cmprof_); jas_iccprof_destroy(iccprof); break; } /* If a CMAP box is present, a PCLR box must also be present. */ if (dec->cmap && !dec->pclr) { jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n"); jp2_box_destroy(dec->cmap); dec->cmap = 0; } /* If a CMAP box is not present, a PCLR box must not be present. */ if (!dec->cmap && dec->pclr) { jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n"); jp2_box_destroy(dec->pclr); dec->pclr = 0; } /* Determine the number of channels (which is essentially the number of components after any palette mappings have been applied). */ dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); /* Perform a basic sanity check on the CMAP box if present. */ if (dec->cmap) { for (i = 0; i < dec->numchans; ++i) { /* Is the component number reasonable? */ if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("error: invalid component number in CMAP box\n"); goto error; } /* Is the LUT index reasonable? */ if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) { jas_eprintf("error: invalid CMAP LUT index\n"); goto error; } } } /* Allocate space for the channel-number to component-number LUT. */ if (!(dec->chantocmptlut = jas_alloc2(dec->numchans, sizeof(uint_fast16_t)))) { jas_eprintf("error: no memory\n"); goto error; } if (!dec->cmap) { for (i = 0; i < dec->numchans; ++i) { dec->chantocmptlut[i] = i; } } else { cmapd = &dec->cmap->data.cmap; pclrd = &dec->pclr->data.pclr; cdefd = &dec->cdef->data.cdef; for (channo = 0; channo < cmapd->numchans; ++channo) { cmapent = &cmapd->ents[channo]; if (cmapent->map == JP2_CMAP_DIRECT) { dec->chantocmptlut[channo] = channo; } else if (cmapent->map == JP2_CMAP_PALETTE) { lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); for (i = 0; i < pclrd->numlutents; ++i) { lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; } newcmptno = jas_image_numcmpts(dec->image); jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); dec->chantocmptlut[channo] = newcmptno; jas_free(lutents); #if 0 if (dec->cdef) { cdefent = jp2_cdef_lookup(cdefd, channo); if (!cdefent) { abort(); } jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); } else { jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); } #endif } } } /* Mark all components as being of unknown type. */ for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); } /* Determine the type of each component. */ if (dec->cdef) { for (i = 0; i < dec->numchans; ++i) { /* Is the channel number reasonable? */ if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { jas_eprintf("error: invalid channel number in CDEF box\n"); goto error; } jas_image_setcmpttype(dec->image, dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], jp2_getct(jas_image_clrspc(dec->image), dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc)); } } else { for (i = 0; i < dec->numchans; ++i) { jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); } } /* Delete any components that are not of interest. */ for (i = jas_image_numcmpts(dec->image); i > 0; --i) { if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { jas_image_delcmpt(dec->image, i - 1); } } /* Ensure that some components survived. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } #if 0 jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image)); #endif /* Prevent the image from being destroyed later. */ image = dec->image; dec->image = 0; jp2_dec_destroy(dec); return image; error: if (box) { jp2_box_destroy(box); } if (dec) { jp2_dec_destroy(dec); } return 0; }
59868521314205020877993173661951509362
jp2_dec.c
93955147082917127962057718477708272955
CWE-125
CVE-2017-9782
JasPer 2.0.12 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) via a crafted image, related to the jp2_decode function in libjasper/jp2/jp2_dec.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-9782
453,265
jasper
839b1bcf0450ff036c28e8db40a7abf886e02891
https://github.com/mdadams/jasper
https://github.com/jasper-software/jasper/commit/839b1bcf0450ff036c28e8db40a7abf886e02891
jp2_dec: fix `numchans` mixup When iterating over `dec->cdef->data.cdef.ents`, we need to use its `numchans` variable, not the one in `jp2_dec_t`. Fixes CVE-2018-19543 Fixes CVE-2017-9782 Closes https://github.com/jasper-maint/jasper/issues/13 Closes https://github.com/jasper-maint/jasper/issues/18 Closes https://github.com/mdadams/jasper/issues/140 Closes https://github.com/mdadams/jasper/issues/182
0
jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr) { jp2_box_t *box; int found; jas_image_t *image; jp2_dec_t *dec; bool samedtype; int dtype; unsigned int i; jp2_cmap_t *cmapd; jp2_pclr_t *pclrd; jp2_cdef_t *cdefd; unsigned int channo; int newcmptno; int_fast32_t *lutents; #if 0 jp2_cdefchan_t *cdefent; int cmptno; #endif jp2_cmapent_t *cmapent; jas_icchdr_t icchdr; jas_iccprof_t *iccprof; dec = 0; box = 0; image = 0; JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr)); if (!(dec = jp2_dec_create())) { goto error; } /* Get the first box. This should be a JP box. */ if (!(box = jp2_box_get(in))) { jas_eprintf("error: cannot get box\n"); goto error; } if (box->type != JP2_BOX_JP) { jas_eprintf("error: expecting signature box\n"); goto error; } if (box->data.jp.magic != JP2_JP_MAGIC) { jas_eprintf("incorrect magic number\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get the second box. This should be a FTYP box. */ if (!(box = jp2_box_get(in))) { goto error; } if (box->type != JP2_BOX_FTYP) { jas_eprintf("expecting file type box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get more boxes... */ found = 0; while ((box = jp2_box_get(in))) { if (jas_getdbglevel() >= 1) { jas_eprintf("got box type %s\n", box->info->name); } switch (box->type) { case JP2_BOX_JP2C: found = 1; break; case JP2_BOX_IHDR: if (!dec->ihdr) { dec->ihdr = box; box = 0; } break; case JP2_BOX_BPCC: if (!dec->bpcc) { dec->bpcc = box; box = 0; } break; case JP2_BOX_CDEF: if (!dec->cdef) { dec->cdef = box; box = 0; } break; case JP2_BOX_PCLR: if (!dec->pclr) { dec->pclr = box; box = 0; } break; case JP2_BOX_CMAP: if (!dec->cmap) { dec->cmap = box; box = 0; } break; case JP2_BOX_COLR: if (!dec->colr) { dec->colr = box; box = 0; } break; } if (box) { jp2_box_destroy(box); box = 0; } if (found) { break; } } if (!found) { jas_eprintf("error: no code stream found\n"); goto error; } if (!(dec->image = jpc_decode(in, optstr))) { jas_eprintf("error: cannot decode code stream\n"); goto error; } /* An IHDR box must be present. */ if (!dec->ihdr) { jas_eprintf("error: missing IHDR box\n"); goto error; } /* Does the number of components indicated in the IHDR box match the value specified in the code stream? */ if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* At least one component must be present. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } /* Determine if all components have the same data type. */ samedtype = true; dtype = jas_image_cmptdtype(dec->image, 0); for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != dtype) { samedtype = false; break; } } /* Is the component data type indicated in the IHDR box consistent with the data in the code stream? */ if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { jas_eprintf("warning: component data type mismatch\n"); } /* Is the compression type supported? */ if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { jas_eprintf("error: unsupported compression type\n"); goto error; } if (dec->bpcc) { /* Is the number of components indicated in the BPCC box consistent with the code stream data? */ if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts( dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* Is the component data type information indicated in the BPCC box consistent with the code stream data? */ if (!samedtype) { for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { jas_eprintf("warning: component data type mismatch\n"); } } } else { jas_eprintf("warning: superfluous BPCC box\n"); } } /* A COLR box must be present. */ if (!dec->colr) { jas_eprintf("error: no COLR box\n"); goto error; } switch (dec->colr->data.colr.method) { case JP2_COLR_ENUM: jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); break; case JP2_COLR_ICC: iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, dec->colr->data.colr.iccplen); if (!iccprof) { jas_eprintf("error: failed to parse ICC profile\n"); goto error; } jas_iccprof_gethdr(iccprof, &icchdr); jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc); jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); assert(dec->image->cmprof_); jas_iccprof_destroy(iccprof); break; } /* If a CMAP box is present, a PCLR box must also be present. */ if (dec->cmap && !dec->pclr) { jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n"); jp2_box_destroy(dec->cmap); dec->cmap = 0; } /* If a CMAP box is not present, a PCLR box must not be present. */ if (!dec->cmap && dec->pclr) { jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n"); jp2_box_destroy(dec->pclr); dec->pclr = 0; } /* Determine the number of channels (which is essentially the number of components after any palette mappings have been applied). */ dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); /* Perform a basic sanity check on the CMAP box if present. */ if (dec->cmap) { for (i = 0; i < dec->numchans; ++i) { /* Is the component number reasonable? */ if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("error: invalid component number in CMAP box\n"); goto error; } /* Is the LUT index reasonable? */ if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) { jas_eprintf("error: invalid CMAP LUT index\n"); goto error; } } } /* Allocate space for the channel-number to component-number LUT. */ if (!(dec->chantocmptlut = jas_alloc2(dec->numchans, sizeof(uint_fast16_t)))) { jas_eprintf("error: no memory\n"); goto error; } if (!dec->cmap) { for (i = 0; i < dec->numchans; ++i) { dec->chantocmptlut[i] = i; } } else { cmapd = &dec->cmap->data.cmap; pclrd = &dec->pclr->data.pclr; cdefd = &dec->cdef->data.cdef; for (channo = 0; channo < cmapd->numchans; ++channo) { cmapent = &cmapd->ents[channo]; if (cmapent->map == JP2_CMAP_DIRECT) { dec->chantocmptlut[channo] = channo; } else if (cmapent->map == JP2_CMAP_PALETTE) { lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); for (i = 0; i < pclrd->numlutents; ++i) { lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; } newcmptno = jas_image_numcmpts(dec->image); jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); dec->chantocmptlut[channo] = newcmptno; jas_free(lutents); #if 0 if (dec->cdef) { cdefent = jp2_cdef_lookup(cdefd, channo); if (!cdefent) { abort(); } jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); } else { jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); } #endif } } } /* Mark all components as being of unknown type. */ for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); } /* Determine the type of each component. */ if (dec->cdef) { for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) { /* Is the channel number reasonable? */ if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { jas_eprintf("error: invalid channel number in CDEF box\n"); goto error; } jas_image_setcmpttype(dec->image, dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], jp2_getct(jas_image_clrspc(dec->image), dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc)); } } else { for (i = 0; i < dec->numchans; ++i) { jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); } } /* Delete any components that are not of interest. */ for (i = jas_image_numcmpts(dec->image); i > 0; --i) { if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { jas_image_delcmpt(dec->image, i - 1); } } /* Ensure that some components survived. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } #if 0 jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image)); #endif /* Prevent the image from being destroyed later. */ image = dec->image; dec->image = 0; jp2_dec_destroy(dec); return image; error: if (box) { jp2_box_destroy(box); } if (dec) { jp2_dec_destroy(dec); } return 0; }
125813963803436339336182748178269813866
jp2_dec.c
163023647028726236156493371179237582578
CWE-125
CVE-2017-9782
JasPer 2.0.12 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) via a crafted image, related to the jp2_decode function in libjasper/jp2/jp2_dec.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-9782
212,083
linux
690b2549b19563ec5ad53e5c82f6a944d910086e
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/690b2549b19563ec5ad53e5c82f6a944d910086e
i2c: ismt: prevent memory corruption in ismt_access() The "data->block[0]" variable comes from the user and is a number between 0-255. It needs to be capped to prevent writing beyond the end of dma_buffer[]. Fixes: 5e9a97b1f449 ("i2c: ismt: Adding support for I2C_SMBUS_BLOCK_PROC_CALL") Reported-and-tested-by: Zheyu Ma <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Mika Westerberg <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
1
static int ismt_access(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data) { int ret; unsigned long time_left; dma_addr_t dma_addr = 0; /* address of the data buffer */ u8 dma_size = 0; enum dma_data_direction dma_direction = 0; struct ismt_desc *desc; struct ismt_priv *priv = i2c_get_adapdata(adap); struct device *dev = &priv->pci_dev->dev; u8 *dma_buffer = PTR_ALIGN(&priv->buffer[0], 16); desc = &priv->hw[priv->head]; /* Initialize the DMA buffer */ memset(priv->buffer, 0, sizeof(priv->buffer)); /* Initialize the descriptor */ memset(desc, 0, sizeof(struct ismt_desc)); desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, read_write); /* Always clear the log entries */ memset(priv->log, 0, ISMT_LOG_ENTRIES * sizeof(u32)); /* Initialize common control bits */ if (likely(pci_dev_msi_enabled(priv->pci_dev))) desc->control = ISMT_DESC_INT | ISMT_DESC_FAIR; else desc->control = ISMT_DESC_FAIR; if ((flags & I2C_CLIENT_PEC) && (size != I2C_SMBUS_QUICK) && (size != I2C_SMBUS_I2C_BLOCK_DATA)) desc->control |= ISMT_DESC_PEC; switch (size) { case I2C_SMBUS_QUICK: dev_dbg(dev, "I2C_SMBUS_QUICK\n"); break; case I2C_SMBUS_BYTE: if (read_write == I2C_SMBUS_WRITE) { /* * Send Byte * The command field contains the write data */ dev_dbg(dev, "I2C_SMBUS_BYTE: WRITE\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; } else { /* Receive Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE: READ\n"); dma_size = 1; dma_direction = DMA_FROM_DEVICE; desc->rd_len = 1; } break; case I2C_SMBUS_BYTE_DATA: if (read_write == I2C_SMBUS_WRITE) { /* * Write Byte * Command plus 1 data byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: WRITE\n"); desc->wr_len_cmd = 2; dma_size = 2; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->byte; } else { /* Read Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: READ\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; desc->rd_len = 1; dma_size = 1; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_WORD_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Write Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: WRITE\n"); desc->wr_len_cmd = 3; dma_size = 3; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; } else { /* Read Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: READ\n"); desc->wr_len_cmd = command; desc->control |= ISMT_DESC_CWRL; desc->rd_len = 2; dma_size = 2; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_PROC_CALL\n"); desc->wr_len_cmd = 3; desc->rd_len = 2; dma_size = 3; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; break; case I2C_SMBUS_BLOCK_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Block Write */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_BLK; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* Block Read */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: READ\n"); dma_size = I2C_SMBUS_BLOCK_MAX; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_BLK | ISMT_DESC_CWRL); } break; case I2C_SMBUS_BLOCK_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_BLOCK_PROC_CALL\n"); dma_size = I2C_SMBUS_BLOCK_MAX; desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 1); desc->wr_len_cmd = data->block[0] + 1; desc->rd_len = dma_size; desc->control |= ISMT_DESC_BLK; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], data->block[0]); break; case I2C_SMBUS_I2C_BLOCK_DATA: /* Make sure the length is valid */ if (data->block[0] < 1) data->block[0] = 1; if (data->block[0] > I2C_SMBUS_BLOCK_MAX) data->block[0] = I2C_SMBUS_BLOCK_MAX; if (read_write == I2C_SMBUS_WRITE) { /* i2c Block Write */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_I2C; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* i2c Block Read */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: READ\n"); dma_size = data->block[0]; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_I2C | ISMT_DESC_CWRL); /* * Per the "Table 15-15. I2C Commands", * in the External Design Specification (EDS), * (Document Number: 508084, Revision: 2.0), * the _rw bit must be 0 */ desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 0); } break; default: dev_err(dev, "Unsupported transaction %d\n", size); return -EOPNOTSUPP; } /* map the data buffer */ if (dma_size != 0) { dev_dbg(dev, " dev=%p\n", dev); dev_dbg(dev, " data=%p\n", data); dev_dbg(dev, " dma_buffer=%p\n", dma_buffer); dev_dbg(dev, " dma_size=%d\n", dma_size); dev_dbg(dev, " dma_direction=%d\n", dma_direction); dma_addr = dma_map_single(dev, dma_buffer, dma_size, dma_direction); if (dma_mapping_error(dev, dma_addr)) { dev_err(dev, "Error in mapping dma buffer %p\n", dma_buffer); return -EIO; } dev_dbg(dev, " dma_addr = %pad\n", &dma_addr); desc->dptr_low = lower_32_bits(dma_addr); desc->dptr_high = upper_32_bits(dma_addr); } reinit_completion(&priv->cmp); /* Add the descriptor */ ismt_submit_desc(priv); /* Now we wait for interrupt completion, 1s */ time_left = wait_for_completion_timeout(&priv->cmp, HZ*1); /* unmap the data buffer */ if (dma_size != 0) dma_unmap_single(dev, dma_addr, dma_size, dma_direction); if (unlikely(!time_left)) { dev_err(dev, "completion wait timed out\n"); ret = -ETIMEDOUT; goto out; } /* do any post processing of the descriptor here */ ret = ismt_process_desc(desc, data, priv, size, read_write); out: /* Update the ring pointer */ priv->head++; priv->head %= ISMT_DESC_ENTRIES; return ret; }
91513236317351842038056466223233835211
i2c-ismt.c
22364513944485151173045885792643538357
CWE-703
CVE-2022-3077
A buffer overflow vulnerability was found in the Linux kernel Intel’s iSMT SMBus host controller driver in the way it handled the I2C_SMBUS_BLOCK_PROC_CALL case (via the ioctl I2C_SMBUS) with malicious input data. This flaw could allow a local user to crash the system.
https://nvd.nist.gov/vuln/detail/CVE-2022-3077
454,759
linux
690b2549b19563ec5ad53e5c82f6a944d910086e
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/690b2549b19563ec5ad53e5c82f6a944d910086e
i2c: ismt: prevent memory corruption in ismt_access() The "data->block[0]" variable comes from the user and is a number between 0-255. It needs to be capped to prevent writing beyond the end of dma_buffer[]. Fixes: 5e9a97b1f449 ("i2c: ismt: Adding support for I2C_SMBUS_BLOCK_PROC_CALL") Reported-and-tested-by: Zheyu Ma <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Mika Westerberg <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
0
static int ismt_access(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data) { int ret; unsigned long time_left; dma_addr_t dma_addr = 0; /* address of the data buffer */ u8 dma_size = 0; enum dma_data_direction dma_direction = 0; struct ismt_desc *desc; struct ismt_priv *priv = i2c_get_adapdata(adap); struct device *dev = &priv->pci_dev->dev; u8 *dma_buffer = PTR_ALIGN(&priv->buffer[0], 16); desc = &priv->hw[priv->head]; /* Initialize the DMA buffer */ memset(priv->buffer, 0, sizeof(priv->buffer)); /* Initialize the descriptor */ memset(desc, 0, sizeof(struct ismt_desc)); desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, read_write); /* Always clear the log entries */ memset(priv->log, 0, ISMT_LOG_ENTRIES * sizeof(u32)); /* Initialize common control bits */ if (likely(pci_dev_msi_enabled(priv->pci_dev))) desc->control = ISMT_DESC_INT | ISMT_DESC_FAIR; else desc->control = ISMT_DESC_FAIR; if ((flags & I2C_CLIENT_PEC) && (size != I2C_SMBUS_QUICK) && (size != I2C_SMBUS_I2C_BLOCK_DATA)) desc->control |= ISMT_DESC_PEC; switch (size) { case I2C_SMBUS_QUICK: dev_dbg(dev, "I2C_SMBUS_QUICK\n"); break; case I2C_SMBUS_BYTE: if (read_write == I2C_SMBUS_WRITE) { /* * Send Byte * The command field contains the write data */ dev_dbg(dev, "I2C_SMBUS_BYTE: WRITE\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; } else { /* Receive Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE: READ\n"); dma_size = 1; dma_direction = DMA_FROM_DEVICE; desc->rd_len = 1; } break; case I2C_SMBUS_BYTE_DATA: if (read_write == I2C_SMBUS_WRITE) { /* * Write Byte * Command plus 1 data byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: WRITE\n"); desc->wr_len_cmd = 2; dma_size = 2; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->byte; } else { /* Read Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: READ\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; desc->rd_len = 1; dma_size = 1; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_WORD_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Write Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: WRITE\n"); desc->wr_len_cmd = 3; dma_size = 3; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; } else { /* Read Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: READ\n"); desc->wr_len_cmd = command; desc->control |= ISMT_DESC_CWRL; desc->rd_len = 2; dma_size = 2; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_PROC_CALL\n"); desc->wr_len_cmd = 3; desc->rd_len = 2; dma_size = 3; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; break; case I2C_SMBUS_BLOCK_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Block Write */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_BLK; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* Block Read */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: READ\n"); dma_size = I2C_SMBUS_BLOCK_MAX; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_BLK | ISMT_DESC_CWRL); } break; case I2C_SMBUS_BLOCK_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_BLOCK_PROC_CALL\n"); if (data->block[0] > I2C_SMBUS_BLOCK_MAX) return -EINVAL; dma_size = I2C_SMBUS_BLOCK_MAX; desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 1); desc->wr_len_cmd = data->block[0] + 1; desc->rd_len = dma_size; desc->control |= ISMT_DESC_BLK; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], data->block[0]); break; case I2C_SMBUS_I2C_BLOCK_DATA: /* Make sure the length is valid */ if (data->block[0] < 1) data->block[0] = 1; if (data->block[0] > I2C_SMBUS_BLOCK_MAX) data->block[0] = I2C_SMBUS_BLOCK_MAX; if (read_write == I2C_SMBUS_WRITE) { /* i2c Block Write */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_I2C; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* i2c Block Read */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: READ\n"); dma_size = data->block[0]; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_I2C | ISMT_DESC_CWRL); /* * Per the "Table 15-15. I2C Commands", * in the External Design Specification (EDS), * (Document Number: 508084, Revision: 2.0), * the _rw bit must be 0 */ desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 0); } break; default: dev_err(dev, "Unsupported transaction %d\n", size); return -EOPNOTSUPP; } /* map the data buffer */ if (dma_size != 0) { dev_dbg(dev, " dev=%p\n", dev); dev_dbg(dev, " data=%p\n", data); dev_dbg(dev, " dma_buffer=%p\n", dma_buffer); dev_dbg(dev, " dma_size=%d\n", dma_size); dev_dbg(dev, " dma_direction=%d\n", dma_direction); dma_addr = dma_map_single(dev, dma_buffer, dma_size, dma_direction); if (dma_mapping_error(dev, dma_addr)) { dev_err(dev, "Error in mapping dma buffer %p\n", dma_buffer); return -EIO; } dev_dbg(dev, " dma_addr = %pad\n", &dma_addr); desc->dptr_low = lower_32_bits(dma_addr); desc->dptr_high = upper_32_bits(dma_addr); } reinit_completion(&priv->cmp); /* Add the descriptor */ ismt_submit_desc(priv); /* Now we wait for interrupt completion, 1s */ time_left = wait_for_completion_timeout(&priv->cmp, HZ*1); /* unmap the data buffer */ if (dma_size != 0) dma_unmap_single(dev, dma_addr, dma_size, dma_direction); if (unlikely(!time_left)) { dev_err(dev, "completion wait timed out\n"); ret = -ETIMEDOUT; goto out; } /* do any post processing of the descriptor here */ ret = ismt_process_desc(desc, data, priv, size, read_write); out: /* Update the ring pointer */ priv->head++; priv->head %= ISMT_DESC_ENTRIES; return ret; }
337152422880524025166312472003442952073
i2c-ismt.c
51244111268212170404918431081464078764
CWE-703
CVE-2022-3077
A buffer overflow vulnerability was found in the Linux kernel Intel’s iSMT SMBus host controller driver in the way it handled the I2C_SMBUS_BLOCK_PROC_CALL case (via the ioctl I2C_SMBUS) with malicious input data. This flaw could allow a local user to crash the system.
https://nvd.nist.gov/vuln/detail/CVE-2022-3077
212,144
libmobi
c78e186739b50d156cb3da5d08d70294f0490853
https://github.com/bfabiszewski/libmobi
https://github.com/bfabiszewski/libmobi/commit/c78e186739b50d156cb3da5d08d70294f0490853
Fix potential out-of-buffer read while parsing corrupt file, closes #38
1
MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) { MOBI_RET ret; const size_t offset = mobi_get_kf8offset(m); if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) { debug_print("%s", "HUFF/CDIC records metadata not found in MOBI header\n"); return MOBI_DATA_CORRUPT; } const size_t huff_rec_index = *m->mh->huff_rec_index + offset; const size_t huff_rec_count = *m->mh->huff_rec_count; if (huff_rec_count > HUFF_RECORD_MAXCNT) { debug_print("Too many HUFF record (%zu)\n", huff_rec_count); return MOBI_DATA_CORRUPT; } const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index); if (curr == NULL || huff_rec_count < 2) { debug_print("%s", "HUFF/CDIC record not found\n"); return MOBI_DATA_CORRUPT; } if (curr->size < HUFF_RECORD_MINSIZE) { debug_print("HUFF record too short (%zu b)\n", curr->size); return MOBI_DATA_CORRUPT; } ret = mobi_parse_huff(huffcdic, curr); if (ret != MOBI_SUCCESS) { debug_print("%s", "HUFF parsing failed\n"); return ret; } curr = curr->next; /* allocate memory for symbols data in each CDIC record */ huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols)); if (huffcdic->symbols == NULL) { debug_print("%s\n", "Memory allocation failed"); return MOBI_MALLOC_FAILED; } /* get following CDIC records */ size_t i = 0; while (i < huff_rec_count - 1) { if (curr == NULL) { debug_print("%s\n", "CDIC record not found"); return MOBI_DATA_CORRUPT; } ret = mobi_parse_cdic(huffcdic, curr, i++); if (ret != MOBI_SUCCESS) { debug_print("%s", "CDIC parsing failed\n"); return ret; } curr = curr->next; } return MOBI_SUCCESS; }
272789865299199789225315738205107270064
read.c
34500817876088764790813749563983010190
CWE-119
CVE-2021-3888
libmobi is vulnerable to Use of Out-of-range Pointer Offset
https://nvd.nist.gov/vuln/detail/CVE-2021-3888
455,177
libmobi
c78e186739b50d156cb3da5d08d70294f0490853
https://github.com/bfabiszewski/libmobi
https://github.com/bfabiszewski/libmobi/commit/c78e186739b50d156cb3da5d08d70294f0490853
Fix potential out-of-buffer read while parsing corrupt file, closes #38
0
MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) { MOBI_RET ret; const size_t offset = mobi_get_kf8offset(m); if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) { debug_print("%s", "HUFF/CDIC records metadata not found in MOBI header\n"); return MOBI_DATA_CORRUPT; } const size_t huff_rec_index = *m->mh->huff_rec_index + offset; const size_t huff_rec_count = *m->mh->huff_rec_count; if (huff_rec_count > HUFF_RECORD_MAXCNT) { debug_print("Too many HUFF record (%zu)\n", huff_rec_count); return MOBI_DATA_CORRUPT; } const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index); if (curr == NULL || huff_rec_count < 2) { debug_print("%s", "HUFF/CDIC record not found\n"); return MOBI_DATA_CORRUPT; } if (curr->size < HUFF_RECORD_MINSIZE) { debug_print("HUFF record too short (%zu b)\n", curr->size); return MOBI_DATA_CORRUPT; } ret = mobi_parse_huff(huffcdic, curr); if (ret != MOBI_SUCCESS) { debug_print("%s", "HUFF parsing failed\n"); return ret; } curr = curr->next; /* allocate memory for symbols data in each CDIC record */ huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols)); if (huffcdic->symbols == NULL) { debug_print("%s\n", "Memory allocation failed"); return MOBI_MALLOC_FAILED; } /* get following CDIC records */ size_t i = 0; while (i < huff_rec_count - 1) { if (curr == NULL) { debug_print("%s\n", "CDIC record not found"); return MOBI_DATA_CORRUPT; } ret = mobi_parse_cdic(huffcdic, curr, i++); if (ret != MOBI_SUCCESS) { debug_print("%s", "CDIC parsing failed\n"); return ret; } curr = curr->next; } if (huffcdic->index_count != huffcdic->index_read) { debug_print("CDIC: wrong read index count: %zu, total: %zu\n", huffcdic->index_read, huffcdic->index_count); return MOBI_DATA_CORRUPT; } return MOBI_SUCCESS; }
211530049158768490793426546245477731217
read.c
228295168827515416887178420817040616622
CWE-119
CVE-2021-3888
libmobi is vulnerable to Use of Out-of-range Pointer Offset
https://nvd.nist.gov/vuln/detail/CVE-2021-3888
212,152
bash
951bdaad7a18cc0dc1036bba86b18b90874d39ff
https://github.com/bminor/bash
https://github.com/bminor/bash/commit/951bdaad7a18cc0dc1036bba86b18b90874d39ff
commit bash-20190628 snapshot
1
disable_priv_mode () { int e; if (setuid (current_user.uid) < 0) { e = errno; sys_error (_("cannot set uid to %d: effective uid %d"), current_user.uid, current_user.euid); #if defined (EXIT_ON_SETUID_FAILURE) if (e == EAGAIN) exit (e); #endif } if (setgid (current_user.gid) < 0) sys_error (_("cannot set gid to %d: effective gid %d"), current_user.gid, current_user.egid); current_user.euid = current_user.uid; current_user.egid = current_user.gid; }
247622822404411128670815043239926864688
shell.c
63031401309370215256197051387367703039
CWE-787
CVE-2019-18276
An issue was discovered in disable_priv_mode in shell.c in GNU Bash through 5.0 patch 11. By default, if Bash is run with its effective UID not equal to its real UID, it will drop privileges by setting its effective UID to its real UID. However, it does so incorrectly. On Linux and other systems that support "saved UID" functionality, the saved UID is not dropped. An attacker with command execution in the shell can use "enable -f" for runtime loading of a new builtin, which can be a shared object that calls setuid() and therefore regains privileges. However, binaries running with an effective UID of 0 are unaffected.
https://nvd.nist.gov/vuln/detail/CVE-2019-18276
455,356
bash
951bdaad7a18cc0dc1036bba86b18b90874d39ff
https://github.com/bminor/bash
https://github.com/bminor/bash/commit/951bdaad7a18cc0dc1036bba86b18b90874d39ff
commit bash-20190628 snapshot
0
disable_priv_mode () { int e; #if HAVE_DECL_SETRESUID if (setresuid (current_user.uid, current_user.uid, current_user.uid) < 0) #else if (setuid (current_user.uid) < 0) #endif { e = errno; sys_error (_("cannot set uid to %d: effective uid %d"), current_user.uid, current_user.euid); #if defined (EXIT_ON_SETUID_FAILURE) if (e == EAGAIN) exit (e); #endif } #if HAVE_DECL_SETRESGID if (setresgid (current_user.gid, current_user.gid, current_user.gid) < 0) #else if (setgid (current_user.gid) < 0) #endif sys_error (_("cannot set gid to %d: effective gid %d"), current_user.gid, current_user.egid); current_user.euid = current_user.uid; current_user.egid = current_user.gid; }
129442006485124574074853062128903057999
shell.c
275188902865294694619472408620496076656
CWE-787
CVE-2019-18276
An issue was discovered in disable_priv_mode in shell.c in GNU Bash through 5.0 patch 11. By default, if Bash is run with its effective UID not equal to its real UID, it will drop privileges by setting its effective UID to its real UID. However, it does so incorrectly. On Linux and other systems that support "saved UID" functionality, the saved UID is not dropped. An attacker with command execution in the shell can use "enable -f" for runtime loading of a new builtin, which can be a shared object that calls setuid() and therefore regains privileges. However, binaries running with an effective UID of 0 are unaffected.
https://nvd.nist.gov/vuln/detail/CVE-2019-18276
212,339
icecast-server
03ea74c04a5966114c2fe66e4e6892d11a68181e
https://gitlab.xiph.org/xiph/icecast-server
https://gitlab.xiph.org/xiph/icecast-server/commit/03ea74c04a5966114c2fe66e4e6892d11a68181e
Fix: Worked around buffer overflows in URL auth's cURL interface This is only a workaround that keeps compatibility with 2.4.x mainline. A real fix has been implemented in 2.5.x (master).
1
static size_t handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream) { auth_client *auth_user = stream; size_t bytes = size * nmemb; client_t *client = auth_user->client; if (client) { auth_t *auth = client->auth; auth_url *url = auth->state; if (strncasecmp (ptr, url->auth_header, url->auth_header_len) == 0) client->authenticated = 1; if (strncasecmp (ptr, url->timelimit_header, url->timelimit_header_len) == 0) { unsigned int limit = 0; sscanf ((char *)ptr+url->timelimit_header_len, "%u\r\n", &limit); client->con->discon_time = time(NULL) + limit; } if (strncasecmp (ptr, "icecast-auth-message: ", 22) == 0) { char *eol; snprintf (url->errormsg, sizeof (url->errormsg), "%s", (char*)ptr+22); eol = strchr (url->errormsg, '\r'); if (eol == NULL) eol = strchr (url->errormsg, '\n'); if (eol) *eol = '\0'; } } return bytes; }
172813813159602330520810310060333400473
auth_url.c
1122861942142437056113331349516615132
CWE-119
CVE-2018-18820
A buffer overflow was discovered in the URL-authentication backend of the Icecast before 2.4.4. If the backend is enabled, then any malicious HTTP client can send a request for that specific resource including a crafted header, leading to denial of service and potentially remote code execution.
https://nvd.nist.gov/vuln/detail/CVE-2018-18820
457,772
icecast-server
03ea74c04a5966114c2fe66e4e6892d11a68181e
https://gitlab.xiph.org/xiph/icecast-server
https://gitlab.xiph.org/xiph/icecast-server/commit/03ea74c04a5966114c2fe66e4e6892d11a68181e
Fix: Worked around buffer overflows in URL auth's cURL interface This is only a workaround that keeps compatibility with 2.4.x mainline. A real fix has been implemented in 2.5.x (master).
0
static size_t handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream) { auth_client *auth_user = stream; size_t len = size * nmemb; client_t *client = auth_user->client; if (client) { auth_t *auth = client->auth; auth_url *url = auth->state; if (url->auth_header && len >= url->auth_header_len && strncasecmp(ptr, url->auth_header, url->auth_header_len) == 0) client->authenticated = 1; if (url->timelimit_header && len > url->timelimit_header_len && strncasecmp(ptr, url->timelimit_header, url->timelimit_header_len) == 0) { const char *input = ptr; unsigned int limit = 0; if (len >= 2 && input[len - 2] == '\r' && input[len - 1] == '\n') { input += url->timelimit_header_len; if (sscanf(input, "%u\r\n", &limit) == 1) { client->con->discon_time = time(NULL) + limit; } else { ICECAST_LOG_ERROR("Auth backend returned invalid timeline header: Can not parse limit"); } } else { ICECAST_LOG_ERROR("Auth backend returned invalid timelimit header."); } } if (len > 24 && strncasecmp(ptr, "icecast-auth-message: ", 22) == 0) { const char *input = ptr; size_t copy_len = len - 24 + 1; /* length of string plus \0-termination */ if (copy_len > sizeof(url->errormsg)) { copy_len = sizeof(url->errormsg); } if (len >= 2 && input[len - 2] == '\r' && input[len - 1] == '\n') { input += 22; memcpy(url->errormsg, input, copy_len); url->errormsg[copy_len-1] = 0; } else { ICECAST_LOG_ERROR("Auth backend returned invalid message header."); } } } return len; }
325925920263284522777628774415448931953
auth_url.c
331866999271559721275349792045163085611
CWE-119
CVE-2018-18820
A buffer overflow was discovered in the URL-authentication backend of the Icecast before 2.4.4. If the backend is enabled, then any malicious HTTP client can send a request for that specific resource including a crafted header, leading to denial of service and potentially remote code execution.
https://nvd.nist.gov/vuln/detail/CVE-2018-18820
212,407
varnish-cache
c5fd097e5cce8b461c6443af02b3448baef2491d
https://github.com/varnishcache/varnish-cache
https://github.com/varnishcache/varnish-cache/commit/c5fd097e5cce8b461c6443af02b3448baef2491d
Do not call http_hdr_flags() on pseudo-headers In http_EstimateWS(), all headers are passed to the http_isfiltered() function to calculate how many bytes is needed to serialize the entire struct http. http_isfiltered() will check the headers for whether they are going to be filtered out later and if so skip them. However http_isfiltered() would attempt to treat all elements of struct http as regular headers with an implicit structure. That does not hold for the first three pseudo-header entries, which would lead to asserts in later steps. This patch skips the filter step for pseudo-headers. Fixes: #3830
1
http_isfiltered(const struct http *fm, unsigned u, unsigned how) { const char *e; const struct http_hdrflg *f; if (fm->hdf[u] & HDF_FILTER) return (1); e = strchr(fm->hd[u].b, ':'); if (e == NULL) return (0); f = http_hdr_flags(fm->hd[u].b, e); return (f != NULL && f->flag & how); }
811300647438513744666233377828733318
cache_http.c
145239057408586301398711991484884532857
CWE-703
CVE-2022-38150
In Varnish Cache 7.0.0, 7.0.1, 7.0.2, and 7.1.0, it is possible to cause the Varnish Server to assert and automatically restart through forged HTTP/1 backend responses. An attack uses a crafted reason phrase of the backend response status line. This is fixed in 7.0.3 and 7.1.1.
https://nvd.nist.gov/vuln/detail/CVE-2022-38150
459,029
varnish-cache
c5fd097e5cce8b461c6443af02b3448baef2491d
https://github.com/varnishcache/varnish-cache
https://github.com/varnishcache/varnish-cache/commit/c5fd097e5cce8b461c6443af02b3448baef2491d
Do not call http_hdr_flags() on pseudo-headers In http_EstimateWS(), all headers are passed to the http_isfiltered() function to calculate how many bytes is needed to serialize the entire struct http. http_isfiltered() will check the headers for whether they are going to be filtered out later and if so skip them. However http_isfiltered() would attempt to treat all elements of struct http as regular headers with an implicit structure. That does not hold for the first three pseudo-header entries, which would lead to asserts in later steps. This patch skips the filter step for pseudo-headers. Fixes: #3830
0
http_isfiltered(const struct http *fm, unsigned u, unsigned how) { const char *e; const struct http_hdrflg *f; if (fm->hdf[u] & HDF_FILTER) return (1); if (u < HTTP_HDR_FIRST) return (0); e = strchr(fm->hd[u].b, ':'); if (e == NULL) return (0); f = http_hdr_flags(fm->hd[u].b, e); return (f != NULL && f->flag & how); }
214500471714364858208416051205285025611
cache_http.c
148461925742958572930249757440638720534
CWE-703
CVE-2022-38150
In Varnish Cache 7.0.0, 7.0.1, 7.0.2, and 7.1.0, it is possible to cause the Varnish Server to assert and automatically restart through forged HTTP/1 backend responses. An attack uses a crafted reason phrase of the backend response status line. This is fixed in 7.0.3 and 7.1.1.
https://nvd.nist.gov/vuln/detail/CVE-2022-38150
212,414
linux
04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5
net: sched: fix use-after-free in tc_new_tfilter() Whenever tc_new_tfilter() jumps back to replay: label, we need to make sure @q and @chain local variables are cleared again, or risk use-after-free as in [1] For consistency, apply the same fix in tc_ctl_chain() BUG: KASAN: use-after-free in mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581 Write of size 8 at addr ffff8880985c4b08 by task syz-executor.4/1945 CPU: 0 PID: 1945 Comm: syz-executor.4 Not tainted 5.17.0-rc1-syzkaller-00495-gff58831fa02d #0 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: <TASK> __dump_stack lib/dump_stack.c:88 [inline] dump_stack_lvl+0xcd/0x134 lib/dump_stack.c:106 print_address_description.constprop.0.cold+0x8d/0x336 mm/kasan/report.c:255 __kasan_report mm/kasan/report.c:442 [inline] kasan_report.cold+0x83/0xdf mm/kasan/report.c:459 mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581 tcf_chain_head_change_item net/sched/cls_api.c:372 [inline] tcf_chain0_head_change.isra.0+0xb9/0x120 net/sched/cls_api.c:386 tcf_chain_tp_insert net/sched/cls_api.c:1657 [inline] tcf_chain_tp_insert_unique net/sched/cls_api.c:1707 [inline] tc_new_tfilter+0x1e67/0x2350 net/sched/cls_api.c:2086 rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae RIP: 0033:0x7f2647172059 Code: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 b8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f2645aa5168 EFLAGS: 00000246 ORIG_RAX: 0000000000000133 RAX: ffffffffffffffda RBX: 00007f2647285100 RCX: 00007f2647172059 RDX: 040000000000009f RSI: 00000000200002c0 RDI: 0000000000000006 RBP: 00007f26471cc08d R08: 0000000000000000 R09: 0000000000000000 R10: 9e00000000000000 R11: 0000000000000246 R12: 0000000000000000 R13: 00007fffb3f7f02f R14: 00007f2645aa5300 R15: 0000000000022000 </TASK> Allocated by task 1944: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 kasan_set_track mm/kasan/common.c:45 [inline] set_alloc_info mm/kasan/common.c:436 [inline] ____kasan_kmalloc mm/kasan/common.c:515 [inline] ____kasan_kmalloc mm/kasan/common.c:474 [inline] __kasan_kmalloc+0xa9/0xd0 mm/kasan/common.c:524 kmalloc_node include/linux/slab.h:604 [inline] kzalloc_node include/linux/slab.h:726 [inline] qdisc_alloc+0xac/0xa10 net/sched/sch_generic.c:941 qdisc_create.constprop.0+0xce/0x10f0 net/sched/sch_api.c:1211 tc_modify_qdisc+0x4c5/0x1980 net/sched/sch_api.c:1660 rtnetlink_rcv_msg+0x413/0xb80 net/core/rtnetlink.c:5592 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae Freed by task 3609: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 kasan_set_track+0x21/0x30 mm/kasan/common.c:45 kasan_set_free_info+0x20/0x30 mm/kasan/generic.c:370 ____kasan_slab_free mm/kasan/common.c:366 [inline] ____kasan_slab_free+0x130/0x160 mm/kasan/common.c:328 kasan_slab_free include/linux/kasan.h:236 [inline] slab_free_hook mm/slub.c:1728 [inline] slab_free_freelist_hook+0x8b/0x1c0 mm/slub.c:1754 slab_free mm/slub.c:3509 [inline] kfree+0xcb/0x280 mm/slub.c:4562 rcu_do_batch kernel/rcu/tree.c:2527 [inline] rcu_core+0x7b8/0x1540 kernel/rcu/tree.c:2778 __do_softirq+0x29b/0x9c2 kernel/softirq.c:558 Last potentially related work creation: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 __kasan_record_aux_stack+0xbe/0xd0 mm/kasan/generic.c:348 __call_rcu kernel/rcu/tree.c:3026 [inline] call_rcu+0xb1/0x740 kernel/rcu/tree.c:3106 qdisc_put_unlocked+0x6f/0x90 net/sched/sch_generic.c:1109 tcf_block_release+0x86/0x90 net/sched/cls_api.c:1238 tc_new_tfilter+0xc0d/0x2350 net/sched/cls_api.c:2148 rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae The buggy address belongs to the object at ffff8880985c4800 which belongs to the cache kmalloc-1k of size 1024 The buggy address is located 776 bytes inside of 1024-byte region [ffff8880985c4800, ffff8880985c4c00) The buggy address belongs to the page: page:ffffea0002617000 refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x985c0 head:ffffea0002617000 order:3 compound_mapcount:0 compound_pincount:0 flags: 0xfff00000010200(slab|head|node=0|zone=1|lastcpupid=0x7ff) raw: 00fff00000010200 0000000000000000 dead000000000122 ffff888010c41dc0 raw: 0000000000000000 0000000000100010 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected page_owner tracks the page as allocated page last allocated via order 3, migratetype Unmovable, gfp_mask 0x1d20c0(__GFP_IO|__GFP_FS|__GFP_NOWARN|__GFP_NORETRY|__GFP_COMP|__GFP_NOMEMALLOC|__GFP_HARDWALL), pid 1941, ts 1038999441284, free_ts 1033444432829 prep_new_page mm/page_alloc.c:2434 [inline] get_page_from_freelist+0xa72/0x2f50 mm/page_alloc.c:4165 __alloc_pages+0x1b2/0x500 mm/page_alloc.c:5389 alloc_pages+0x1aa/0x310 mm/mempolicy.c:2271 alloc_slab_page mm/slub.c:1799 [inline] allocate_slab mm/slub.c:1944 [inline] new_slab+0x28a/0x3b0 mm/slub.c:2004 ___slab_alloc+0x87c/0xe90 mm/slub.c:3018 __slab_alloc.constprop.0+0x4d/0xa0 mm/slub.c:3105 slab_alloc_node mm/slub.c:3196 [inline] slab_alloc mm/slub.c:3238 [inline] __kmalloc+0x2fb/0x340 mm/slub.c:4420 kmalloc include/linux/slab.h:586 [inline] kzalloc include/linux/slab.h:715 [inline] __register_sysctl_table+0x112/0x1090 fs/proc/proc_sysctl.c:1335 neigh_sysctl_register+0x2c8/0x5e0 net/core/neighbour.c:3787 devinet_sysctl_register+0xb1/0x230 net/ipv4/devinet.c:2618 inetdev_init+0x286/0x580 net/ipv4/devinet.c:278 inetdev_event+0xa8a/0x15d0 net/ipv4/devinet.c:1532 notifier_call_chain+0xb5/0x200 kernel/notifier.c:84 call_netdevice_notifiers_info+0xb5/0x130 net/core/dev.c:1919 call_netdevice_notifiers_extack net/core/dev.c:1931 [inline] call_netdevice_notifiers net/core/dev.c:1945 [inline] register_netdevice+0x1073/0x1500 net/core/dev.c:9698 veth_newlink+0x59c/0xa90 drivers/net/veth.c:1722 page last free stack trace: reset_page_owner include/linux/page_owner.h:24 [inline] free_pages_prepare mm/page_alloc.c:1352 [inline] free_pcp_prepare+0x374/0x870 mm/page_alloc.c:1404 free_unref_page_prepare mm/page_alloc.c:3325 [inline] free_unref_page+0x19/0x690 mm/page_alloc.c:3404 release_pages+0x748/0x1220 mm/swap.c:956 tlb_batch_pages_flush mm/mmu_gather.c:50 [inline] tlb_flush_mmu_free mm/mmu_gather.c:243 [inline] tlb_flush_mmu+0xe9/0x6b0 mm/mmu_gather.c:250 zap_pte_range mm/memory.c:1441 [inline] zap_pmd_range mm/memory.c:1490 [inline] zap_pud_range mm/memory.c:1519 [inline] zap_p4d_range mm/memory.c:1540 [inline] unmap_page_range+0x1d1d/0x2a30 mm/memory.c:1561 unmap_single_vma+0x198/0x310 mm/memory.c:1606 unmap_vmas+0x16b/0x2f0 mm/memory.c:1638 exit_mmap+0x201/0x670 mm/mmap.c:3178 __mmput+0x122/0x4b0 kernel/fork.c:1114 mmput+0x56/0x60 kernel/fork.c:1135 exit_mm kernel/exit.c:507 [inline] do_exit+0xa3c/0x2a30 kernel/exit.c:793 do_group_exit+0xd2/0x2f0 kernel/exit.c:935 __do_sys_exit_group kernel/exit.c:946 [inline] __se_sys_exit_group kernel/exit.c:944 [inline] __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:944 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae Memory state around the buggy address: ffff8880985c4a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8880985c4a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff8880985c4b00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8880985c4b80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8880985c4c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc Fixes: 470502de5bdb ("net: sched: unlock rules update API") Signed-off-by: Eric Dumazet <[email protected]> Cc: Vlad Buslov <[email protected]> Cc: Jiri Pirko <[email protected]> Cc: Cong Wang <[email protected]> Reported-by: syzbot <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Jakub Kicinski <[email protected]>
1
static int tc_new_tfilter(struct sk_buff *skb, struct nlmsghdr *n, struct netlink_ext_ack *extack) { struct net *net = sock_net(skb->sk); struct nlattr *tca[TCA_MAX + 1]; char name[IFNAMSIZ]; struct tcmsg *t; u32 protocol; u32 prio; bool prio_allocate; u32 parent; u32 chain_index; struct Qdisc *q = NULL; struct tcf_chain_info chain_info; struct tcf_chain *chain = NULL; struct tcf_block *block; struct tcf_proto *tp; unsigned long cl; void *fh; int err; int tp_created; bool rtnl_held = false; u32 flags; if (!netlink_ns_capable(skb, net->user_ns, CAP_NET_ADMIN)) return -EPERM; replay: tp_created = 0; err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX, rtm_tca_policy, extack); if (err < 0) return err; t = nlmsg_data(n); protocol = TC_H_MIN(t->tcm_info); prio = TC_H_MAJ(t->tcm_info); prio_allocate = false; parent = t->tcm_parent; tp = NULL; cl = 0; block = NULL; flags = 0; if (prio == 0) { /* If no priority is provided by the user, * we allocate one. */ if (n->nlmsg_flags & NLM_F_CREATE) { prio = TC_H_MAKE(0x80000000U, 0U); prio_allocate = true; } else { NL_SET_ERR_MSG(extack, "Invalid filter command with priority of zero"); return -ENOENT; } } /* Find head of filter chain. */ err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack); if (err) return err; if (tcf_proto_check_kind(tca[TCA_KIND], name)) { NL_SET_ERR_MSG(extack, "Specified TC filter name too long"); err = -EINVAL; goto errout; } /* Take rtnl mutex if rtnl_held was set to true on previous iteration, * block is shared (no qdisc found), qdisc is not unlocked, classifier * type is not specified, classifier is not unlocked. */ if (rtnl_held || (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) || !tcf_proto_is_unlocked(name)) { rtnl_held = true; rtnl_lock(); } err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack); if (err) goto errout; block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index, extack); if (IS_ERR(block)) { err = PTR_ERR(block); goto errout; } block->classid = parent; chain_index = tca[TCA_CHAIN] ? nla_get_u32(tca[TCA_CHAIN]) : 0; if (chain_index > TC_ACT_EXT_VAL_MASK) { NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit"); err = -EINVAL; goto errout; } chain = tcf_chain_get(block, chain_index, true); if (!chain) { NL_SET_ERR_MSG(extack, "Cannot create specified filter chain"); err = -ENOMEM; goto errout; } mutex_lock(&chain->filter_chain_lock); tp = tcf_chain_tp_find(chain, &chain_info, protocol, prio, prio_allocate); if (IS_ERR(tp)) { NL_SET_ERR_MSG(extack, "Filter with specified priority/protocol not found"); err = PTR_ERR(tp); goto errout_locked; } if (tp == NULL) { struct tcf_proto *tp_new = NULL; if (chain->flushing) { err = -EAGAIN; goto errout_locked; } /* Proto-tcf does not exist, create new one */ if (tca[TCA_KIND] == NULL || !protocol) { NL_SET_ERR_MSG(extack, "Filter kind and protocol must be specified"); err = -EINVAL; goto errout_locked; } if (!(n->nlmsg_flags & NLM_F_CREATE)) { NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter"); err = -ENOENT; goto errout_locked; } if (prio_allocate) prio = tcf_auto_prio(tcf_chain_tp_prev(chain, &chain_info)); mutex_unlock(&chain->filter_chain_lock); tp_new = tcf_proto_create(name, protocol, prio, chain, rtnl_held, extack); if (IS_ERR(tp_new)) { err = PTR_ERR(tp_new); goto errout_tp; } tp_created = 1; tp = tcf_chain_tp_insert_unique(chain, tp_new, protocol, prio, rtnl_held); if (IS_ERR(tp)) { err = PTR_ERR(tp); goto errout_tp; } } else { mutex_unlock(&chain->filter_chain_lock); } if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) { NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one"); err = -EINVAL; goto errout; } fh = tp->ops->get(tp, t->tcm_handle); if (!fh) { if (!(n->nlmsg_flags & NLM_F_CREATE)) { NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter"); err = -ENOENT; goto errout; } } else if (n->nlmsg_flags & NLM_F_EXCL) { tfilter_put(tp, fh); NL_SET_ERR_MSG(extack, "Filter already exists"); err = -EEXIST; goto errout; } if (chain->tmplt_ops && chain->tmplt_ops != tp->ops) { NL_SET_ERR_MSG(extack, "Chain template is set to a different filter kind"); err = -EINVAL; goto errout; } if (!(n->nlmsg_flags & NLM_F_CREATE)) flags |= TCA_ACT_FLAGS_REPLACE; if (!rtnl_held) flags |= TCA_ACT_FLAGS_NO_RTNL; err = tp->ops->change(net, skb, tp, cl, t->tcm_handle, tca, &fh, flags, extack); if (err == 0) { tfilter_notify(net, skb, n, tp, block, q, parent, fh, RTM_NEWTFILTER, false, rtnl_held); tfilter_put(tp, fh); /* q pointer is NULL for shared blocks */ if (q) q->flags &= ~TCQ_F_CAN_BYPASS; } errout: if (err && tp_created) tcf_chain_tp_delete_empty(chain, tp, rtnl_held, NULL); errout_tp: if (chain) { if (tp && !IS_ERR(tp)) tcf_proto_put(tp, rtnl_held, NULL); if (!tp_created) tcf_chain_put(chain); } tcf_block_release(q, block, rtnl_held); if (rtnl_held) rtnl_unlock(); if (err == -EAGAIN) { /* Take rtnl lock in case EAGAIN is caused by concurrent flush * of target chain. */ rtnl_held = true; /* Replay the request. */ goto replay; } return err; errout_locked: mutex_unlock(&chain->filter_chain_lock); goto errout; }
18151855959135734228627793679159459802
cls_api.c
251903803472854915466369605008106287178
CWE-416
CVE-2022-1055
A use-after-free exists in the Linux Kernel in tc_new_tfilter that could allow a local attacker to gain privilege escalation. The exploit requires unprivileged user namespaces. We recommend upgrading past commit 04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5
https://nvd.nist.gov/vuln/detail/CVE-2022-1055
459,107
linux
04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5
net: sched: fix use-after-free in tc_new_tfilter() Whenever tc_new_tfilter() jumps back to replay: label, we need to make sure @q and @chain local variables are cleared again, or risk use-after-free as in [1] For consistency, apply the same fix in tc_ctl_chain() BUG: KASAN: use-after-free in mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581 Write of size 8 at addr ffff8880985c4b08 by task syz-executor.4/1945 CPU: 0 PID: 1945 Comm: syz-executor.4 Not tainted 5.17.0-rc1-syzkaller-00495-gff58831fa02d #0 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: <TASK> __dump_stack lib/dump_stack.c:88 [inline] dump_stack_lvl+0xcd/0x134 lib/dump_stack.c:106 print_address_description.constprop.0.cold+0x8d/0x336 mm/kasan/report.c:255 __kasan_report mm/kasan/report.c:442 [inline] kasan_report.cold+0x83/0xdf mm/kasan/report.c:459 mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581 tcf_chain_head_change_item net/sched/cls_api.c:372 [inline] tcf_chain0_head_change.isra.0+0xb9/0x120 net/sched/cls_api.c:386 tcf_chain_tp_insert net/sched/cls_api.c:1657 [inline] tcf_chain_tp_insert_unique net/sched/cls_api.c:1707 [inline] tc_new_tfilter+0x1e67/0x2350 net/sched/cls_api.c:2086 rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae RIP: 0033:0x7f2647172059 Code: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 b8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f2645aa5168 EFLAGS: 00000246 ORIG_RAX: 0000000000000133 RAX: ffffffffffffffda RBX: 00007f2647285100 RCX: 00007f2647172059 RDX: 040000000000009f RSI: 00000000200002c0 RDI: 0000000000000006 RBP: 00007f26471cc08d R08: 0000000000000000 R09: 0000000000000000 R10: 9e00000000000000 R11: 0000000000000246 R12: 0000000000000000 R13: 00007fffb3f7f02f R14: 00007f2645aa5300 R15: 0000000000022000 </TASK> Allocated by task 1944: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 kasan_set_track mm/kasan/common.c:45 [inline] set_alloc_info mm/kasan/common.c:436 [inline] ____kasan_kmalloc mm/kasan/common.c:515 [inline] ____kasan_kmalloc mm/kasan/common.c:474 [inline] __kasan_kmalloc+0xa9/0xd0 mm/kasan/common.c:524 kmalloc_node include/linux/slab.h:604 [inline] kzalloc_node include/linux/slab.h:726 [inline] qdisc_alloc+0xac/0xa10 net/sched/sch_generic.c:941 qdisc_create.constprop.0+0xce/0x10f0 net/sched/sch_api.c:1211 tc_modify_qdisc+0x4c5/0x1980 net/sched/sch_api.c:1660 rtnetlink_rcv_msg+0x413/0xb80 net/core/rtnetlink.c:5592 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae Freed by task 3609: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 kasan_set_track+0x21/0x30 mm/kasan/common.c:45 kasan_set_free_info+0x20/0x30 mm/kasan/generic.c:370 ____kasan_slab_free mm/kasan/common.c:366 [inline] ____kasan_slab_free+0x130/0x160 mm/kasan/common.c:328 kasan_slab_free include/linux/kasan.h:236 [inline] slab_free_hook mm/slub.c:1728 [inline] slab_free_freelist_hook+0x8b/0x1c0 mm/slub.c:1754 slab_free mm/slub.c:3509 [inline] kfree+0xcb/0x280 mm/slub.c:4562 rcu_do_batch kernel/rcu/tree.c:2527 [inline] rcu_core+0x7b8/0x1540 kernel/rcu/tree.c:2778 __do_softirq+0x29b/0x9c2 kernel/softirq.c:558 Last potentially related work creation: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 __kasan_record_aux_stack+0xbe/0xd0 mm/kasan/generic.c:348 __call_rcu kernel/rcu/tree.c:3026 [inline] call_rcu+0xb1/0x740 kernel/rcu/tree.c:3106 qdisc_put_unlocked+0x6f/0x90 net/sched/sch_generic.c:1109 tcf_block_release+0x86/0x90 net/sched/cls_api.c:1238 tc_new_tfilter+0xc0d/0x2350 net/sched/cls_api.c:2148 rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae The buggy address belongs to the object at ffff8880985c4800 which belongs to the cache kmalloc-1k of size 1024 The buggy address is located 776 bytes inside of 1024-byte region [ffff8880985c4800, ffff8880985c4c00) The buggy address belongs to the page: page:ffffea0002617000 refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x985c0 head:ffffea0002617000 order:3 compound_mapcount:0 compound_pincount:0 flags: 0xfff00000010200(slab|head|node=0|zone=1|lastcpupid=0x7ff) raw: 00fff00000010200 0000000000000000 dead000000000122 ffff888010c41dc0 raw: 0000000000000000 0000000000100010 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected page_owner tracks the page as allocated page last allocated via order 3, migratetype Unmovable, gfp_mask 0x1d20c0(__GFP_IO|__GFP_FS|__GFP_NOWARN|__GFP_NORETRY|__GFP_COMP|__GFP_NOMEMALLOC|__GFP_HARDWALL), pid 1941, ts 1038999441284, free_ts 1033444432829 prep_new_page mm/page_alloc.c:2434 [inline] get_page_from_freelist+0xa72/0x2f50 mm/page_alloc.c:4165 __alloc_pages+0x1b2/0x500 mm/page_alloc.c:5389 alloc_pages+0x1aa/0x310 mm/mempolicy.c:2271 alloc_slab_page mm/slub.c:1799 [inline] allocate_slab mm/slub.c:1944 [inline] new_slab+0x28a/0x3b0 mm/slub.c:2004 ___slab_alloc+0x87c/0xe90 mm/slub.c:3018 __slab_alloc.constprop.0+0x4d/0xa0 mm/slub.c:3105 slab_alloc_node mm/slub.c:3196 [inline] slab_alloc mm/slub.c:3238 [inline] __kmalloc+0x2fb/0x340 mm/slub.c:4420 kmalloc include/linux/slab.h:586 [inline] kzalloc include/linux/slab.h:715 [inline] __register_sysctl_table+0x112/0x1090 fs/proc/proc_sysctl.c:1335 neigh_sysctl_register+0x2c8/0x5e0 net/core/neighbour.c:3787 devinet_sysctl_register+0xb1/0x230 net/ipv4/devinet.c:2618 inetdev_init+0x286/0x580 net/ipv4/devinet.c:278 inetdev_event+0xa8a/0x15d0 net/ipv4/devinet.c:1532 notifier_call_chain+0xb5/0x200 kernel/notifier.c:84 call_netdevice_notifiers_info+0xb5/0x130 net/core/dev.c:1919 call_netdevice_notifiers_extack net/core/dev.c:1931 [inline] call_netdevice_notifiers net/core/dev.c:1945 [inline] register_netdevice+0x1073/0x1500 net/core/dev.c:9698 veth_newlink+0x59c/0xa90 drivers/net/veth.c:1722 page last free stack trace: reset_page_owner include/linux/page_owner.h:24 [inline] free_pages_prepare mm/page_alloc.c:1352 [inline] free_pcp_prepare+0x374/0x870 mm/page_alloc.c:1404 free_unref_page_prepare mm/page_alloc.c:3325 [inline] free_unref_page+0x19/0x690 mm/page_alloc.c:3404 release_pages+0x748/0x1220 mm/swap.c:956 tlb_batch_pages_flush mm/mmu_gather.c:50 [inline] tlb_flush_mmu_free mm/mmu_gather.c:243 [inline] tlb_flush_mmu+0xe9/0x6b0 mm/mmu_gather.c:250 zap_pte_range mm/memory.c:1441 [inline] zap_pmd_range mm/memory.c:1490 [inline] zap_pud_range mm/memory.c:1519 [inline] zap_p4d_range mm/memory.c:1540 [inline] unmap_page_range+0x1d1d/0x2a30 mm/memory.c:1561 unmap_single_vma+0x198/0x310 mm/memory.c:1606 unmap_vmas+0x16b/0x2f0 mm/memory.c:1638 exit_mmap+0x201/0x670 mm/mmap.c:3178 __mmput+0x122/0x4b0 kernel/fork.c:1114 mmput+0x56/0x60 kernel/fork.c:1135 exit_mm kernel/exit.c:507 [inline] do_exit+0xa3c/0x2a30 kernel/exit.c:793 do_group_exit+0xd2/0x2f0 kernel/exit.c:935 __do_sys_exit_group kernel/exit.c:946 [inline] __se_sys_exit_group kernel/exit.c:944 [inline] __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:944 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae Memory state around the buggy address: ffff8880985c4a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8880985c4a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff8880985c4b00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8880985c4b80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8880985c4c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc Fixes: 470502de5bdb ("net: sched: unlock rules update API") Signed-off-by: Eric Dumazet <[email protected]> Cc: Vlad Buslov <[email protected]> Cc: Jiri Pirko <[email protected]> Cc: Cong Wang <[email protected]> Reported-by: syzbot <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Jakub Kicinski <[email protected]>
0
static int tc_new_tfilter(struct sk_buff *skb, struct nlmsghdr *n, struct netlink_ext_ack *extack) { struct net *net = sock_net(skb->sk); struct nlattr *tca[TCA_MAX + 1]; char name[IFNAMSIZ]; struct tcmsg *t; u32 protocol; u32 prio; bool prio_allocate; u32 parent; u32 chain_index; struct Qdisc *q; struct tcf_chain_info chain_info; struct tcf_chain *chain; struct tcf_block *block; struct tcf_proto *tp; unsigned long cl; void *fh; int err; int tp_created; bool rtnl_held = false; u32 flags; if (!netlink_ns_capable(skb, net->user_ns, CAP_NET_ADMIN)) return -EPERM; replay: tp_created = 0; err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX, rtm_tca_policy, extack); if (err < 0) return err; t = nlmsg_data(n); protocol = TC_H_MIN(t->tcm_info); prio = TC_H_MAJ(t->tcm_info); prio_allocate = false; parent = t->tcm_parent; tp = NULL; cl = 0; block = NULL; q = NULL; chain = NULL; flags = 0; if (prio == 0) { /* If no priority is provided by the user, * we allocate one. */ if (n->nlmsg_flags & NLM_F_CREATE) { prio = TC_H_MAKE(0x80000000U, 0U); prio_allocate = true; } else { NL_SET_ERR_MSG(extack, "Invalid filter command with priority of zero"); return -ENOENT; } } /* Find head of filter chain. */ err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack); if (err) return err; if (tcf_proto_check_kind(tca[TCA_KIND], name)) { NL_SET_ERR_MSG(extack, "Specified TC filter name too long"); err = -EINVAL; goto errout; } /* Take rtnl mutex if rtnl_held was set to true on previous iteration, * block is shared (no qdisc found), qdisc is not unlocked, classifier * type is not specified, classifier is not unlocked. */ if (rtnl_held || (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) || !tcf_proto_is_unlocked(name)) { rtnl_held = true; rtnl_lock(); } err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack); if (err) goto errout; block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index, extack); if (IS_ERR(block)) { err = PTR_ERR(block); goto errout; } block->classid = parent; chain_index = tca[TCA_CHAIN] ? nla_get_u32(tca[TCA_CHAIN]) : 0; if (chain_index > TC_ACT_EXT_VAL_MASK) { NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit"); err = -EINVAL; goto errout; } chain = tcf_chain_get(block, chain_index, true); if (!chain) { NL_SET_ERR_MSG(extack, "Cannot create specified filter chain"); err = -ENOMEM; goto errout; } mutex_lock(&chain->filter_chain_lock); tp = tcf_chain_tp_find(chain, &chain_info, protocol, prio, prio_allocate); if (IS_ERR(tp)) { NL_SET_ERR_MSG(extack, "Filter with specified priority/protocol not found"); err = PTR_ERR(tp); goto errout_locked; } if (tp == NULL) { struct tcf_proto *tp_new = NULL; if (chain->flushing) { err = -EAGAIN; goto errout_locked; } /* Proto-tcf does not exist, create new one */ if (tca[TCA_KIND] == NULL || !protocol) { NL_SET_ERR_MSG(extack, "Filter kind and protocol must be specified"); err = -EINVAL; goto errout_locked; } if (!(n->nlmsg_flags & NLM_F_CREATE)) { NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter"); err = -ENOENT; goto errout_locked; } if (prio_allocate) prio = tcf_auto_prio(tcf_chain_tp_prev(chain, &chain_info)); mutex_unlock(&chain->filter_chain_lock); tp_new = tcf_proto_create(name, protocol, prio, chain, rtnl_held, extack); if (IS_ERR(tp_new)) { err = PTR_ERR(tp_new); goto errout_tp; } tp_created = 1; tp = tcf_chain_tp_insert_unique(chain, tp_new, protocol, prio, rtnl_held); if (IS_ERR(tp)) { err = PTR_ERR(tp); goto errout_tp; } } else { mutex_unlock(&chain->filter_chain_lock); } if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) { NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one"); err = -EINVAL; goto errout; } fh = tp->ops->get(tp, t->tcm_handle); if (!fh) { if (!(n->nlmsg_flags & NLM_F_CREATE)) { NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter"); err = -ENOENT; goto errout; } } else if (n->nlmsg_flags & NLM_F_EXCL) { tfilter_put(tp, fh); NL_SET_ERR_MSG(extack, "Filter already exists"); err = -EEXIST; goto errout; } if (chain->tmplt_ops && chain->tmplt_ops != tp->ops) { NL_SET_ERR_MSG(extack, "Chain template is set to a different filter kind"); err = -EINVAL; goto errout; } if (!(n->nlmsg_flags & NLM_F_CREATE)) flags |= TCA_ACT_FLAGS_REPLACE; if (!rtnl_held) flags |= TCA_ACT_FLAGS_NO_RTNL; err = tp->ops->change(net, skb, tp, cl, t->tcm_handle, tca, &fh, flags, extack); if (err == 0) { tfilter_notify(net, skb, n, tp, block, q, parent, fh, RTM_NEWTFILTER, false, rtnl_held); tfilter_put(tp, fh); /* q pointer is NULL for shared blocks */ if (q) q->flags &= ~TCQ_F_CAN_BYPASS; } errout: if (err && tp_created) tcf_chain_tp_delete_empty(chain, tp, rtnl_held, NULL); errout_tp: if (chain) { if (tp && !IS_ERR(tp)) tcf_proto_put(tp, rtnl_held, NULL); if (!tp_created) tcf_chain_put(chain); } tcf_block_release(q, block, rtnl_held); if (rtnl_held) rtnl_unlock(); if (err == -EAGAIN) { /* Take rtnl lock in case EAGAIN is caused by concurrent flush * of target chain. */ rtnl_held = true; /* Replay the request. */ goto replay; } return err; errout_locked: mutex_unlock(&chain->filter_chain_lock); goto errout; }
249400845678093962479611801234831545975
cls_api.c
31293344430191637657447401884064089853
CWE-416
CVE-2022-1055
A use-after-free exists in the Linux Kernel in tc_new_tfilter that could allow a local attacker to gain privilege escalation. The exploit requires unprivileged user namespaces. We recommend upgrading past commit 04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5
https://nvd.nist.gov/vuln/detail/CVE-2022-1055
212,433
vim
ccfde4d028e891a41e3548323c3d47b06fb0b83e
https://github.com/vim/vim
https://github.com/vim/vim/commit/ccfde4d028e891a41e3548323c3d47b06fb0b83e
patch 9.0.0389: crash when 'tagfunc' closes the window Problem: Crash when 'tagfunc' closes the window. Solution: Bail out when the window was closed.
1
do_tag( char_u *tag, // tag (pattern) to jump to int type, int count, int forceit, // :ta with ! int verbose) // print "tag not found" message { taggy_T *tagstack = curwin->w_tagstack; int tagstackidx = curwin->w_tagstackidx; int tagstacklen = curwin->w_tagstacklen; int cur_match = 0; int cur_fnum = curbuf->b_fnum; int oldtagstackidx = tagstackidx; int prevtagstackidx = tagstackidx; int prev_num_matches; int new_tag = FALSE; int i; int ic; int no_regexp = FALSE; int error_cur_match = 0; int save_pos = FALSE; fmark_T saved_fmark; #ifdef FEAT_CSCOPE int jumped_to_tag = FALSE; #endif int new_num_matches; char_u **new_matches; int use_tagstack; int skip_msg = FALSE; char_u *buf_ffname = curbuf->b_ffname; // name to use for // priority computation int use_tfu = 1; char_u *tofree = NULL; // remember the matches for the last used tag static int num_matches = 0; static int max_num_matches = 0; // limit used for match search static char_u **matches = NULL; static int flags; #ifdef FEAT_EVAL if (tfu_in_use) { emsg(_(e_cannot_modify_tag_stack_within_tagfunc)); return FALSE; } #endif #ifdef EXITFREE if (type == DT_FREE) { // remove the list of matches FreeWild(num_matches, matches); # ifdef FEAT_CSCOPE cs_free_tags(); # endif num_matches = 0; return FALSE; } #endif if (type == DT_HELP) { type = DT_TAG; no_regexp = TRUE; use_tfu = 0; } prev_num_matches = num_matches; free_string_option(nofile_fname); nofile_fname = NULL; CLEAR_POS(&saved_fmark.mark); // shutup gcc 4.0 saved_fmark.fnum = 0; /* * Don't add a tag to the tagstack if 'tagstack' has been reset. */ if ((!p_tgst && *tag != NUL)) { use_tagstack = FALSE; new_tag = TRUE; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } #endif } else { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) use_tagstack = FALSE; else #endif use_tagstack = TRUE; // new pattern, add to the tag stack if (*tag != NUL && (type == DT_TAG || type == DT_SELECT || type == DT_JUMP #ifdef FEAT_QUICKFIX || type == DT_LTAG #endif #ifdef FEAT_CSCOPE || type == DT_CSCOPE #endif )) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (ptag_entry.tagname != NULL && STRCMP(ptag_entry.tagname, tag) == 0) { // Jumping to same tag: keep the current match, so that // the CursorHold autocommand example works. cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } } else #endif { /* * If the last used entry is not at the top, delete all tag * stack entries above it. */ while (tagstackidx < tagstacklen) tagstack_clear_entry(&tagstack[--tagstacklen]); // if the tagstack is full: remove oldest entry if (++tagstacklen > TAGSTACKSIZE) { tagstacklen = TAGSTACKSIZE; tagstack_clear_entry(&tagstack[0]); for (i = 1; i < tagstacklen; ++i) tagstack[i - 1] = tagstack[i]; --tagstackidx; } /* * put the tag name in the tag stack */ if ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL) { curwin->w_tagstacklen = tagstacklen - 1; goto end_do_tag; } curwin->w_tagstacklen = tagstacklen; save_pos = TRUE; // save the cursor position below } new_tag = TRUE; } else { if ( #if defined(FEAT_QUICKFIX) g_do_tagpreview != 0 ? ptag_entry.tagname == NULL : #endif tagstacklen == 0) { // empty stack emsg(_(e_tag_stack_empty)); goto end_do_tag; } if (type == DT_POP) // go to older position { #ifdef FEAT_FOLDING int old_KeyTyped = KeyTyped; #endif if ((tagstackidx -= count) < 0) { emsg(_(e_at_bottom_of_tag_stack)); if (tagstackidx + count == 0) { // We did [num]^T from the bottom of the stack tagstackidx = 0; goto end_do_tag; } // We weren't at the bottom of the stack, so jump all the // way to the bottom now. tagstackidx = 0; } else if (tagstackidx >= tagstacklen) // count == 0? { emsg(_(e_at_top_of_tag_stack)); goto end_do_tag; } // Make a copy of the fmark, autocommands may invalidate the // tagstack before it's used. saved_fmark = tagstack[tagstackidx].fmark; if (saved_fmark.fnum != curbuf->b_fnum) { /* * Jump to other file. If this fails (e.g. because the * file was changed) keep original position in tag stack. */ if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum, GETF_SETMARK, forceit) == FAIL) { tagstackidx = oldtagstackidx; // back to old posn goto end_do_tag; } // An BufReadPost autocommand may jump to the '" mark, but // we don't what that here. curwin->w_cursor.lnum = saved_fmark.mark.lnum; } else { setpcmark(); curwin->w_cursor.lnum = saved_fmark.mark.lnum; } curwin->w_cursor.col = saved_fmark.mark.col; curwin->w_set_curswant = TRUE; check_cursor(); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_TAG) && old_KeyTyped) foldOpenCursor(); #endif // remove the old list of matches FreeWild(num_matches, matches); #ifdef FEAT_CSCOPE cs_free_tags(); #endif num_matches = 0; tag_freematch(); goto end_do_tag; } if (type == DT_TAG #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { // ":tag" (no argument): go to newer pattern save_pos = TRUE; // save the cursor position below if ((tagstackidx += count - 1) >= tagstacklen) { /* * Beyond the last one, just give an error message and * go to the last one. Don't store the cursor * position. */ tagstackidx = tagstacklen - 1; emsg(_(e_at_top_of_tag_stack)); save_pos = FALSE; } else if (tagstackidx < 0) // must have been count == 0 { emsg(_(e_at_bottom_of_tag_stack)); tagstackidx = 0; goto end_do_tag; } cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } new_tag = TRUE; } else // go to other matching tag { // Save index for when selection is cancelled. prevtagstackidx = tagstackidx; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { if (--tagstackidx < 0) tagstackidx = 0; cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } switch (type) { case DT_FIRST: cur_match = count - 1; break; case DT_SELECT: case DT_JUMP: #ifdef FEAT_CSCOPE case DT_CSCOPE: #endif case DT_LAST: cur_match = MAXCOL - 1; break; case DT_NEXT: cur_match += count; break; case DT_PREV: cur_match -= count; break; } if (cur_match >= MAXCOL) cur_match = MAXCOL - 1; else if (cur_match < 0) { emsg(_(e_cannot_go_before_first_matching_tag)); skip_msg = TRUE; cur_match = 0; cur_fnum = curbuf->b_fnum; } } } #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (type != DT_SELECT && type != DT_JUMP) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } } else #endif { /* * For ":tag [arg]" or ":tselect" remember position before the jump. */ saved_fmark = tagstack[tagstackidx].fmark; if (save_pos) { tagstack[tagstackidx].fmark.mark = curwin->w_cursor; tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum; } // Curwin will change in the call to jumpto_tag() if ":stag" was // used or an autocommand jumps to another window; store value of // tagstackidx now. curwin->w_tagstackidx = tagstackidx; if (type != DT_SELECT && type != DT_JUMP) { curwin->w_tagstack[tagstackidx].cur_match = cur_match; curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum; } } } // When not using the current buffer get the name of buffer "cur_fnum". // Makes sure that the tag order doesn't change when using a remembered // position for "cur_match". if (cur_fnum != curbuf->b_fnum) { buf_T *buf = buflist_findnr(cur_fnum); if (buf != NULL) buf_ffname = buf->b_ffname; } /* * Repeat searching for tags, when a file has not been found. */ for (;;) { int other_name; char_u *name; /* * When desired match not found yet, try to find it (and others). */ if (use_tagstack) { // make a copy, the tagstack may change in 'tagfunc' name = vim_strsave(tagstack[tagstackidx].tagname); vim_free(tofree); tofree = name; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) name = ptag_entry.tagname; #endif else name = tag; other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0); if (new_tag || (cur_match >= num_matches && max_num_matches != MAXCOL) || other_name) { if (other_name) { vim_free(tagmatchname); tagmatchname = vim_strsave(name); } if (type == DT_SELECT || type == DT_JUMP #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) cur_match = MAXCOL - 1; if (type == DT_TAG) max_num_matches = MAXCOL; else max_num_matches = cur_match + 1; // when the argument starts with '/', use it as a regexp if (!no_regexp && *name == '/') { flags = TAG_REGEXP; ++name; } else flags = TAG_NOIC; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE) flags = TAG_CSCOPE; #endif if (verbose) flags |= TAG_VERBOSE; if (!use_tfu) flags |= TAG_NO_TAGFUNC; if (find_tags(name, &new_num_matches, &new_matches, flags, max_num_matches, buf_ffname) == OK && new_num_matches < max_num_matches) max_num_matches = MAXCOL; // If less than max_num_matches // found: all matches found. // If there already were some matches for the same name, move them // to the start. Avoids that the order changes when using // ":tnext" and jumping to another file. if (!new_tag && !other_name) { int j, k; int idx = 0; tagptrs_T tagp, tagp2; // Find the position of each old match in the new list. Need // to use parse_match() to find the tag line. for (j = 0; j < num_matches; ++j) { parse_match(matches[j], &tagp); for (i = idx; i < new_num_matches; ++i) { parse_match(new_matches[i], &tagp2); if (STRCMP(tagp.tagname, tagp2.tagname) == 0) { char_u *p = new_matches[i]; for (k = i; k > idx; --k) new_matches[k] = new_matches[k - 1]; new_matches[idx++] = p; break; } } } } FreeWild(num_matches, matches); num_matches = new_num_matches; matches = new_matches; } if (num_matches <= 0) { if (verbose) semsg(_(e_tag_not_found_str), name); #if defined(FEAT_QUICKFIX) g_do_tagpreview = 0; #endif } else { int ask_for_selection = FALSE; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE && num_matches > 1) { cs_print_tags(); ask_for_selection = TRUE; } else #endif if (type == DT_TAG && *tag != NUL) // If a count is supplied to the ":tag <name>" command, then // jump to count'th matching tag. cur_match = count > 0 ? count - 1 : 0; else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1)) { print_tag_list(new_tag, use_tagstack, num_matches, matches); ask_for_selection = TRUE; } #if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL) else if (type == DT_LTAG) { if (add_llist_tags(tag, num_matches, matches) == FAIL) goto end_do_tag; cur_match = 0; // Jump to the first tag } #endif if (ask_for_selection == TRUE) { /* * Ask to select a tag from the list. */ i = prompt_for_number(NULL); if (i <= 0 || i > num_matches || got_int) { // no valid choice: don't change anything if (use_tagstack) { tagstack[tagstackidx].fmark = saved_fmark; tagstackidx = prevtagstackidx; } #ifdef FEAT_CSCOPE cs_free_tags(); jumped_to_tag = TRUE; #endif break; } cur_match = i - 1; } if (cur_match >= num_matches) { // Avoid giving this error when a file wasn't found and we're // looking for a match in another file, which wasn't found. // There will be an emsg("file doesn't exist") below then. if ((type == DT_NEXT || type == DT_FIRST) && nofile_fname == NULL) { if (num_matches == 1) emsg(_(e_there_is_only_one_matching_tag)); else emsg(_(e_cannot_go_beyond_last_matching_tag)); skip_msg = TRUE; } cur_match = num_matches - 1; } if (use_tagstack) { tagptrs_T tagp; tagstack[tagstackidx].cur_match = cur_match; tagstack[tagstackidx].cur_fnum = cur_fnum; // store user-provided data originating from tagfunc if (use_tfu && parse_match(matches[cur_match], &tagp) == OK && tagp.user_data) { VIM_CLEAR(tagstack[tagstackidx].user_data); tagstack[tagstackidx].user_data = vim_strnsave( tagp.user_data, tagp.user_data_end - tagp.user_data); } ++tagstackidx; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } #endif /* * Only when going to try the next match, report that the previous * file didn't exist. Otherwise an emsg() is given below. */ if (nofile_fname != NULL && error_cur_match != cur_match) smsg(_("File \"%s\" does not exist"), nofile_fname); ic = (matches[cur_match][0] & MT_IC_OFF); if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP #ifdef FEAT_CSCOPE && type != DT_CSCOPE #endif && (num_matches > 1 || ic) && !skip_msg) { // Give an indication of the number of matching tags sprintf((char *)IObuff, _("tag %d of %d%s"), cur_match + 1, num_matches, max_num_matches != MAXCOL ? _(" or more") : ""); if (ic) STRCAT(IObuff, _(" Using tag with different case!")); if ((num_matches > prev_num_matches || new_tag) && num_matches > 1) { if (ic) msg_attr((char *)IObuff, HL_ATTR(HLF_W)); else msg((char *)IObuff); msg_scroll = TRUE; // don't overwrite this message } else give_warning(IObuff, ic); if (ic && !msg_scrolled && msg_silent == 0) { out_flush(); ui_delay(1007L, TRUE); } } #if defined(FEAT_EVAL) // Let the SwapExists event know what tag we are jumping to. vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name); set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1); #endif /* * Jump to the desired match. */ i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE); #if defined(FEAT_EVAL) set_vim_var_string(VV_SWAPCOMMAND, NULL, -1); #endif if (i == NOTAGFILE) { // File not found: try again with another matching tag if ((type == DT_PREV && cur_match > 0) || ((type == DT_TAG || type == DT_NEXT || type == DT_FIRST) && (max_num_matches != MAXCOL || cur_match < num_matches - 1))) { error_cur_match = cur_match; if (use_tagstack) --tagstackidx; if (type == DT_PREV) --cur_match; else { type = DT_NEXT; ++cur_match; } continue; } semsg(_(e_file_str_does_not_exist), nofile_fname); } else { // We may have jumped to another window, check that // tagstackidx is still valid. if (use_tagstack && tagstackidx > curwin->w_tagstacklen) tagstackidx = curwin->w_tagstackidx; #ifdef FEAT_CSCOPE jumped_to_tag = TRUE; #endif } } break; } end_do_tag: // Only store the new index when using the tagstack and it's valid. if (use_tagstack && tagstackidx <= curwin->w_tagstacklen) curwin->w_tagstackidx = tagstackidx; postponed_split = 0; // don't split next time # ifdef FEAT_QUICKFIX g_do_tagpreview = 0; // don't do tag preview next time # endif vim_free(tofree); #ifdef FEAT_CSCOPE return jumped_to_tag; #else return FALSE; #endif }
163270354086098606424218695920397836600
tag.c
256312624888395967188545141531528405807
CWE-416
CVE-2022-3134
Use After Free in GitHub repository vim/vim prior to 9.0.0389.
https://nvd.nist.gov/vuln/detail/CVE-2022-3134
459,400
vim
ccfde4d028e891a41e3548323c3d47b06fb0b83e
https://github.com/vim/vim
https://github.com/vim/vim/commit/ccfde4d028e891a41e3548323c3d47b06fb0b83e
patch 9.0.0389: crash when 'tagfunc' closes the window Problem: Crash when 'tagfunc' closes the window. Solution: Bail out when the window was closed.
0
do_tag( char_u *tag, // tag (pattern) to jump to int type, int count, int forceit, // :ta with ! int verbose) // print "tag not found" message { taggy_T *tagstack = curwin->w_tagstack; int tagstackidx = curwin->w_tagstackidx; int tagstacklen = curwin->w_tagstacklen; int cur_match = 0; int cur_fnum = curbuf->b_fnum; int oldtagstackidx = tagstackidx; int prevtagstackidx = tagstackidx; int prev_num_matches; int new_tag = FALSE; int i; int ic; int no_regexp = FALSE; int error_cur_match = 0; int save_pos = FALSE; fmark_T saved_fmark; #ifdef FEAT_CSCOPE int jumped_to_tag = FALSE; #endif int new_num_matches; char_u **new_matches; int use_tagstack; int skip_msg = FALSE; char_u *buf_ffname = curbuf->b_ffname; // name to use for // priority computation int use_tfu = 1; char_u *tofree = NULL; // remember the matches for the last used tag static int num_matches = 0; static int max_num_matches = 0; // limit used for match search static char_u **matches = NULL; static int flags; #ifdef FEAT_EVAL if (tfu_in_use) { emsg(_(e_cannot_modify_tag_stack_within_tagfunc)); return FALSE; } #endif #ifdef EXITFREE if (type == DT_FREE) { // remove the list of matches FreeWild(num_matches, matches); # ifdef FEAT_CSCOPE cs_free_tags(); # endif num_matches = 0; return FALSE; } #endif if (type == DT_HELP) { type = DT_TAG; no_regexp = TRUE; use_tfu = 0; } prev_num_matches = num_matches; free_string_option(nofile_fname); nofile_fname = NULL; CLEAR_POS(&saved_fmark.mark); // shutup gcc 4.0 saved_fmark.fnum = 0; /* * Don't add a tag to the tagstack if 'tagstack' has been reset. */ if ((!p_tgst && *tag != NUL)) { use_tagstack = FALSE; new_tag = TRUE; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } #endif } else { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) use_tagstack = FALSE; else #endif use_tagstack = TRUE; // new pattern, add to the tag stack if (*tag != NUL && (type == DT_TAG || type == DT_SELECT || type == DT_JUMP #ifdef FEAT_QUICKFIX || type == DT_LTAG #endif #ifdef FEAT_CSCOPE || type == DT_CSCOPE #endif )) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (ptag_entry.tagname != NULL && STRCMP(ptag_entry.tagname, tag) == 0) { // Jumping to same tag: keep the current match, so that // the CursorHold autocommand example works. cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } } else #endif { /* * If the last used entry is not at the top, delete all tag * stack entries above it. */ while (tagstackidx < tagstacklen) tagstack_clear_entry(&tagstack[--tagstacklen]); // if the tagstack is full: remove oldest entry if (++tagstacklen > TAGSTACKSIZE) { tagstacklen = TAGSTACKSIZE; tagstack_clear_entry(&tagstack[0]); for (i = 1; i < tagstacklen; ++i) tagstack[i - 1] = tagstack[i]; --tagstackidx; } /* * put the tag name in the tag stack */ if ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL) { curwin->w_tagstacklen = tagstacklen - 1; goto end_do_tag; } curwin->w_tagstacklen = tagstacklen; save_pos = TRUE; // save the cursor position below } new_tag = TRUE; } else { if ( #if defined(FEAT_QUICKFIX) g_do_tagpreview != 0 ? ptag_entry.tagname == NULL : #endif tagstacklen == 0) { // empty stack emsg(_(e_tag_stack_empty)); goto end_do_tag; } if (type == DT_POP) // go to older position { #ifdef FEAT_FOLDING int old_KeyTyped = KeyTyped; #endif if ((tagstackidx -= count) < 0) { emsg(_(e_at_bottom_of_tag_stack)); if (tagstackidx + count == 0) { // We did [num]^T from the bottom of the stack tagstackidx = 0; goto end_do_tag; } // We weren't at the bottom of the stack, so jump all the // way to the bottom now. tagstackidx = 0; } else if (tagstackidx >= tagstacklen) // count == 0? { emsg(_(e_at_top_of_tag_stack)); goto end_do_tag; } // Make a copy of the fmark, autocommands may invalidate the // tagstack before it's used. saved_fmark = tagstack[tagstackidx].fmark; if (saved_fmark.fnum != curbuf->b_fnum) { /* * Jump to other file. If this fails (e.g. because the * file was changed) keep original position in tag stack. */ if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum, GETF_SETMARK, forceit) == FAIL) { tagstackidx = oldtagstackidx; // back to old posn goto end_do_tag; } // An BufReadPost autocommand may jump to the '" mark, but // we don't what that here. curwin->w_cursor.lnum = saved_fmark.mark.lnum; } else { setpcmark(); curwin->w_cursor.lnum = saved_fmark.mark.lnum; } curwin->w_cursor.col = saved_fmark.mark.col; curwin->w_set_curswant = TRUE; check_cursor(); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_TAG) && old_KeyTyped) foldOpenCursor(); #endif // remove the old list of matches FreeWild(num_matches, matches); #ifdef FEAT_CSCOPE cs_free_tags(); #endif num_matches = 0; tag_freematch(); goto end_do_tag; } if (type == DT_TAG #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { // ":tag" (no argument): go to newer pattern save_pos = TRUE; // save the cursor position below if ((tagstackidx += count - 1) >= tagstacklen) { /* * Beyond the last one, just give an error message and * go to the last one. Don't store the cursor * position. */ tagstackidx = tagstacklen - 1; emsg(_(e_at_top_of_tag_stack)); save_pos = FALSE; } else if (tagstackidx < 0) // must have been count == 0 { emsg(_(e_at_bottom_of_tag_stack)); tagstackidx = 0; goto end_do_tag; } cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } new_tag = TRUE; } else // go to other matching tag { // Save index for when selection is cancelled. prevtagstackidx = tagstackidx; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { if (--tagstackidx < 0) tagstackidx = 0; cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } switch (type) { case DT_FIRST: cur_match = count - 1; break; case DT_SELECT: case DT_JUMP: #ifdef FEAT_CSCOPE case DT_CSCOPE: #endif case DT_LAST: cur_match = MAXCOL - 1; break; case DT_NEXT: cur_match += count; break; case DT_PREV: cur_match -= count; break; } if (cur_match >= MAXCOL) cur_match = MAXCOL - 1; else if (cur_match < 0) { emsg(_(e_cannot_go_before_first_matching_tag)); skip_msg = TRUE; cur_match = 0; cur_fnum = curbuf->b_fnum; } } } #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (type != DT_SELECT && type != DT_JUMP) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } } else #endif { /* * For ":tag [arg]" or ":tselect" remember position before the jump. */ saved_fmark = tagstack[tagstackidx].fmark; if (save_pos) { tagstack[tagstackidx].fmark.mark = curwin->w_cursor; tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum; } // Curwin will change in the call to jumpto_tag() if ":stag" was // used or an autocommand jumps to another window; store value of // tagstackidx now. curwin->w_tagstackidx = tagstackidx; if (type != DT_SELECT && type != DT_JUMP) { curwin->w_tagstack[tagstackidx].cur_match = cur_match; curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum; } } } // When not using the current buffer get the name of buffer "cur_fnum". // Makes sure that the tag order doesn't change when using a remembered // position for "cur_match". if (cur_fnum != curbuf->b_fnum) { buf_T *buf = buflist_findnr(cur_fnum); if (buf != NULL) buf_ffname = buf->b_ffname; } /* * Repeat searching for tags, when a file has not been found. */ for (;;) { int other_name; char_u *name; /* * When desired match not found yet, try to find it (and others). */ if (use_tagstack) { // make a copy, the tagstack may change in 'tagfunc' name = vim_strsave(tagstack[tagstackidx].tagname); vim_free(tofree); tofree = name; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) name = ptag_entry.tagname; #endif else name = tag; other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0); if (new_tag || (cur_match >= num_matches && max_num_matches != MAXCOL) || other_name) { if (other_name) { vim_free(tagmatchname); tagmatchname = vim_strsave(name); } if (type == DT_SELECT || type == DT_JUMP #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) cur_match = MAXCOL - 1; if (type == DT_TAG) max_num_matches = MAXCOL; else max_num_matches = cur_match + 1; // when the argument starts with '/', use it as a regexp if (!no_regexp && *name == '/') { flags = TAG_REGEXP; ++name; } else flags = TAG_NOIC; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE) flags = TAG_CSCOPE; #endif if (verbose) flags |= TAG_VERBOSE; if (!use_tfu) flags |= TAG_NO_TAGFUNC; if (find_tags(name, &new_num_matches, &new_matches, flags, max_num_matches, buf_ffname) == OK && new_num_matches < max_num_matches) max_num_matches = MAXCOL; // If less than max_num_matches // found: all matches found. // A tag function may do anything, which may cause various // information to become invalid. At least check for the tagstack // to still be the same. if (tagstack != curwin->w_tagstack) { emsg(_(e_window_unexpectedly_close_while_searching_for_tags)); FreeWild(new_num_matches, new_matches); break; } // If there already were some matches for the same name, move them // to the start. Avoids that the order changes when using // ":tnext" and jumping to another file. if (!new_tag && !other_name) { int j, k; int idx = 0; tagptrs_T tagp, tagp2; // Find the position of each old match in the new list. Need // to use parse_match() to find the tag line. for (j = 0; j < num_matches; ++j) { parse_match(matches[j], &tagp); for (i = idx; i < new_num_matches; ++i) { parse_match(new_matches[i], &tagp2); if (STRCMP(tagp.tagname, tagp2.tagname) == 0) { char_u *p = new_matches[i]; for (k = i; k > idx; --k) new_matches[k] = new_matches[k - 1]; new_matches[idx++] = p; break; } } } } FreeWild(num_matches, matches); num_matches = new_num_matches; matches = new_matches; } if (num_matches <= 0) { if (verbose) semsg(_(e_tag_not_found_str), name); #if defined(FEAT_QUICKFIX) g_do_tagpreview = 0; #endif } else { int ask_for_selection = FALSE; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE && num_matches > 1) { cs_print_tags(); ask_for_selection = TRUE; } else #endif if (type == DT_TAG && *tag != NUL) // If a count is supplied to the ":tag <name>" command, then // jump to count'th matching tag. cur_match = count > 0 ? count - 1 : 0; else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1)) { print_tag_list(new_tag, use_tagstack, num_matches, matches); ask_for_selection = TRUE; } #if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL) else if (type == DT_LTAG) { if (add_llist_tags(tag, num_matches, matches) == FAIL) goto end_do_tag; cur_match = 0; // Jump to the first tag } #endif if (ask_for_selection == TRUE) { /* * Ask to select a tag from the list. */ i = prompt_for_number(NULL); if (i <= 0 || i > num_matches || got_int) { // no valid choice: don't change anything if (use_tagstack) { tagstack[tagstackidx].fmark = saved_fmark; tagstackidx = prevtagstackidx; } #ifdef FEAT_CSCOPE cs_free_tags(); jumped_to_tag = TRUE; #endif break; } cur_match = i - 1; } if (cur_match >= num_matches) { // Avoid giving this error when a file wasn't found and we're // looking for a match in another file, which wasn't found. // There will be an emsg("file doesn't exist") below then. if ((type == DT_NEXT || type == DT_FIRST) && nofile_fname == NULL) { if (num_matches == 1) emsg(_(e_there_is_only_one_matching_tag)); else emsg(_(e_cannot_go_beyond_last_matching_tag)); skip_msg = TRUE; } cur_match = num_matches - 1; } if (use_tagstack) { tagptrs_T tagp; tagstack[tagstackidx].cur_match = cur_match; tagstack[tagstackidx].cur_fnum = cur_fnum; // store user-provided data originating from tagfunc if (use_tfu && parse_match(matches[cur_match], &tagp) == OK && tagp.user_data) { VIM_CLEAR(tagstack[tagstackidx].user_data); tagstack[tagstackidx].user_data = vim_strnsave( tagp.user_data, tagp.user_data_end - tagp.user_data); } ++tagstackidx; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } #endif /* * Only when going to try the next match, report that the previous * file didn't exist. Otherwise an emsg() is given below. */ if (nofile_fname != NULL && error_cur_match != cur_match) smsg(_("File \"%s\" does not exist"), nofile_fname); ic = (matches[cur_match][0] & MT_IC_OFF); if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP #ifdef FEAT_CSCOPE && type != DT_CSCOPE #endif && (num_matches > 1 || ic) && !skip_msg) { // Give an indication of the number of matching tags sprintf((char *)IObuff, _("tag %d of %d%s"), cur_match + 1, num_matches, max_num_matches != MAXCOL ? _(" or more") : ""); if (ic) STRCAT(IObuff, _(" Using tag with different case!")); if ((num_matches > prev_num_matches || new_tag) && num_matches > 1) { if (ic) msg_attr((char *)IObuff, HL_ATTR(HLF_W)); else msg((char *)IObuff); msg_scroll = TRUE; // don't overwrite this message } else give_warning(IObuff, ic); if (ic && !msg_scrolled && msg_silent == 0) { out_flush(); ui_delay(1007L, TRUE); } } #if defined(FEAT_EVAL) // Let the SwapExists event know what tag we are jumping to. vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name); set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1); #endif /* * Jump to the desired match. */ i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE); #if defined(FEAT_EVAL) set_vim_var_string(VV_SWAPCOMMAND, NULL, -1); #endif if (i == NOTAGFILE) { // File not found: try again with another matching tag if ((type == DT_PREV && cur_match > 0) || ((type == DT_TAG || type == DT_NEXT || type == DT_FIRST) && (max_num_matches != MAXCOL || cur_match < num_matches - 1))) { error_cur_match = cur_match; if (use_tagstack) --tagstackidx; if (type == DT_PREV) --cur_match; else { type = DT_NEXT; ++cur_match; } continue; } semsg(_(e_file_str_does_not_exist), nofile_fname); } else { // We may have jumped to another window, check that // tagstackidx is still valid. if (use_tagstack && tagstackidx > curwin->w_tagstacklen) tagstackidx = curwin->w_tagstackidx; #ifdef FEAT_CSCOPE jumped_to_tag = TRUE; #endif } } break; } end_do_tag: // Only store the new index when using the tagstack and it's valid. if (use_tagstack && tagstackidx <= curwin->w_tagstacklen) curwin->w_tagstackidx = tagstackidx; postponed_split = 0; // don't split next time # ifdef FEAT_QUICKFIX g_do_tagpreview = 0; // don't do tag preview next time # endif vim_free(tofree); #ifdef FEAT_CSCOPE return jumped_to_tag; #else return FALSE; #endif }
294928399408778524511468577192657953231
None
CWE-416
CVE-2022-3134
Use After Free in GitHub repository vim/vim prior to 9.0.0389.
https://nvd.nist.gov/vuln/detail/CVE-2022-3134
212,436
linux
30e29a9a2bc6a4888335a6ede968b75cd329657a
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/30e29a9a2bc6a4888335a6ede968b75cd329657a
bpf: Fix integer overflow in prealloc_elems_and_freelist() In prealloc_elems_and_freelist(), the multiplication to calculate the size passed to bpf_map_area_alloc() could lead to an integer overflow. As a result, out-of-bounds write could occur in pcpu_freelist_populate() as reported by KASAN: [...] [ 16.968613] BUG: KASAN: slab-out-of-bounds in pcpu_freelist_populate+0xd9/0x100 [ 16.969408] Write of size 8 at addr ffff888104fc6ea0 by task crash/78 [ 16.970038] [ 16.970195] CPU: 0 PID: 78 Comm: crash Not tainted 5.15.0-rc2+ #1 [ 16.970878] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014 [ 16.972026] Call Trace: [ 16.972306] dump_stack_lvl+0x34/0x44 [ 16.972687] print_address_description.constprop.0+0x21/0x140 [ 16.973297] ? pcpu_freelist_populate+0xd9/0x100 [ 16.973777] ? pcpu_freelist_populate+0xd9/0x100 [ 16.974257] kasan_report.cold+0x7f/0x11b [ 16.974681] ? pcpu_freelist_populate+0xd9/0x100 [ 16.975190] pcpu_freelist_populate+0xd9/0x100 [ 16.975669] stack_map_alloc+0x209/0x2a0 [ 16.976106] __sys_bpf+0xd83/0x2ce0 [...] The possibility of this overflow was originally discussed in [0], but was overlooked. Fix the integer overflow by changing elem_size to u64 from u32. [0] https://lore.kernel.org/bpf/[email protected]/ Fixes: 557c0c6e7df8 ("bpf: convert stackmap to pre-allocation") Signed-off-by: Tatsuhiko Yasumatsu <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
1
static int prealloc_elems_and_freelist(struct bpf_stack_map *smap) { u32 elem_size = sizeof(struct stack_map_bucket) + smap->map.value_size; int err; smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries, smap->map.numa_node); if (!smap->elems) return -ENOMEM; err = pcpu_freelist_init(&smap->freelist); if (err) goto free_elems; pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size, smap->map.max_entries); return 0; free_elems: bpf_map_area_free(smap->elems); return err; }
178134261771669129761013963339102987528
stackmap.c
212947868785159241816012605096544782433
CWE-787
CVE-2021-41864
prealloc_elems_and_freelist in kernel/bpf/stackmap.c in the Linux kernel before 5.14.12 allows unprivileged users to trigger an eBPF multiplication integer overflow with a resultant out-of-bounds write.
https://nvd.nist.gov/vuln/detail/CVE-2021-41864
459,524
linux
30e29a9a2bc6a4888335a6ede968b75cd329657a
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/30e29a9a2bc6a4888335a6ede968b75cd329657a
bpf: Fix integer overflow in prealloc_elems_and_freelist() In prealloc_elems_and_freelist(), the multiplication to calculate the size passed to bpf_map_area_alloc() could lead to an integer overflow. As a result, out-of-bounds write could occur in pcpu_freelist_populate() as reported by KASAN: [...] [ 16.968613] BUG: KASAN: slab-out-of-bounds in pcpu_freelist_populate+0xd9/0x100 [ 16.969408] Write of size 8 at addr ffff888104fc6ea0 by task crash/78 [ 16.970038] [ 16.970195] CPU: 0 PID: 78 Comm: crash Not tainted 5.15.0-rc2+ #1 [ 16.970878] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014 [ 16.972026] Call Trace: [ 16.972306] dump_stack_lvl+0x34/0x44 [ 16.972687] print_address_description.constprop.0+0x21/0x140 [ 16.973297] ? pcpu_freelist_populate+0xd9/0x100 [ 16.973777] ? pcpu_freelist_populate+0xd9/0x100 [ 16.974257] kasan_report.cold+0x7f/0x11b [ 16.974681] ? pcpu_freelist_populate+0xd9/0x100 [ 16.975190] pcpu_freelist_populate+0xd9/0x100 [ 16.975669] stack_map_alloc+0x209/0x2a0 [ 16.976106] __sys_bpf+0xd83/0x2ce0 [...] The possibility of this overflow was originally discussed in [0], but was overlooked. Fix the integer overflow by changing elem_size to u64 from u32. [0] https://lore.kernel.org/bpf/[email protected]/ Fixes: 557c0c6e7df8 ("bpf: convert stackmap to pre-allocation") Signed-off-by: Tatsuhiko Yasumatsu <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
0
static int prealloc_elems_and_freelist(struct bpf_stack_map *smap) { u64 elem_size = sizeof(struct stack_map_bucket) + (u64)smap->map.value_size; int err; smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries, smap->map.numa_node); if (!smap->elems) return -ENOMEM; err = pcpu_freelist_init(&smap->freelist); if (err) goto free_elems; pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size, smap->map.max_entries); return 0; free_elems: bpf_map_area_free(smap->elems); return err; }
247842121005492107026661682297731302199
stackmap.c
198452357082465344097055898312719400384
CWE-787
CVE-2021-41864
prealloc_elems_and_freelist in kernel/bpf/stackmap.c in the Linux kernel before 5.14.12 allows unprivileged users to trigger an eBPF multiplication integer overflow with a resultant out-of-bounds write.
https://nvd.nist.gov/vuln/detail/CVE-2021-41864
212,818
pjproject
15663e3f37091069b8c98a7fce680dc04bc8e865
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/15663e3f37091069b8c98a7fce680dc04bc8e865
Merge pull request from GHSA-2qpg-f6wf-w984
1
static pj_status_t decode_errcode_attr(pj_pool_t *pool, const pj_uint8_t *buf, const pj_stun_msg_hdr *msghdr, void **p_attr) { pj_stun_errcode_attr *attr; pj_str_t value; PJ_UNUSED_ARG(msghdr); /* Create the attribute */ attr = PJ_POOL_ZALLOC_T(pool, pj_stun_errcode_attr); GETATTRHDR(buf, &attr->hdr); attr->err_code = buf[6] * 100 + buf[7]; /* Get pointer to the string in the message */ value.ptr = ((char*)buf + ATTR_HDR_LEN + 4); value.slen = attr->hdr.length - 4; /* Copy the string to the attribute */ pj_strdup(pool, &attr->reason, &value); /* Done */ *p_attr = attr; return PJ_SUCCESS; }
82181264062889236862873379634797479013
None
CWE-191
CVE-2021-37706
PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In affected versions if the incoming STUN message contains an ERROR-CODE attribute, the header length is not checked before performing a subtraction operation, potentially resulting in an integer underflow scenario. This issue affects all users that use STUN. A malicious actor located within the victim’s network may forge and send a specially crafted UDP (STUN) message that could remotely execute arbitrary code on the victim’s machine. Users are advised to upgrade as soon as possible. There are no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2021-37706
462,278
pjproject
15663e3f37091069b8c98a7fce680dc04bc8e865
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/15663e3f37091069b8c98a7fce680dc04bc8e865
Merge pull request from GHSA-2qpg-f6wf-w984
0
static pj_status_t decode_errcode_attr(pj_pool_t *pool, const pj_uint8_t *buf, const pj_stun_msg_hdr *msghdr, void **p_attr) { pj_stun_errcode_attr *attr; pj_str_t value; PJ_UNUSED_ARG(msghdr); /* Create the attribute */ attr = PJ_POOL_ZALLOC_T(pool, pj_stun_errcode_attr); GETATTRHDR(buf, &attr->hdr); attr->err_code = buf[6] * 100 + buf[7]; /* Get pointer to the string in the message */ value.ptr = ((char*)buf + ATTR_HDR_LEN + 4); value.slen = attr->hdr.length - 4; /* Make sure the length is never negative */ if (value.slen < 0) value.slen = 0; /* Copy the string to the attribute */ pj_strdup(pool, &attr->reason, &value); /* Done */ *p_attr = attr; return PJ_SUCCESS; }
288158129212060678092169077807436012711
None
CWE-191
CVE-2021-37706
PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In affected versions if the incoming STUN message contains an ERROR-CODE attribute, the header length is not checked before performing a subtraction operation, potentially resulting in an integer underflow scenario. This issue affects all users that use STUN. A malicious actor located within the victim’s network may forge and send a specially crafted UDP (STUN) message that could remotely execute arbitrary code on the victim’s machine. Users are advised to upgrade as soon as possible. There are no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2021-37706
212,822
ghostpdl
e1134d375e2ca176068e19a2aa9b040baffe1c22
https://github.com/ArtifexSoftware/ghostpdl
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=e1134d375e2ca176068e19a2aa9b040baffe1c22
Bug 705156(1): Avoid double free of PCL error buffer
1
pcl_status_read(byte * data, uint max_data, pcl_state_t * pcs) { uint count = min(max_data, pcs->status.write_pos - pcs->status.read_pos); if (count) memcpy(data, pcs->status.buffer + pcs->status.read_pos, count); pcs->status.read_pos += count; if (pcs->status.read_pos == pcs->status.write_pos) { gs_free_object(pcs->memory, pcs->status.buffer, "status buffer"); pcs->status.write_pos = pcs->status.read_pos = 0; } return count; }
16750323744555373538118400797572057026
None
CWE-787
CVE-2022-1350
A vulnerability classified as problematic was found in GhostPCL 9.55.0. This vulnerability affects the function chunk_free_object of the file gsmchunk.c. The manipulation with a malicious file leads to a memory corruption. The attack can be initiated remotely but requires user interaction. The exploit has been disclosed to the public as a POC and may be used. It is recommended to apply the patches to fix this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-1350
462,316
ghostpdl
e1134d375e2ca176068e19a2aa9b040baffe1c22
https://github.com/ArtifexSoftware/ghostpdl
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=e1134d375e2ca176068e19a2aa9b040baffe1c22
Bug 705156(1): Avoid double free of PCL error buffer
0
pcl_status_read(byte * data, uint max_data, pcl_state_t * pcs) { uint count = min(max_data, pcs->status.write_pos - pcs->status.read_pos); if (count) memcpy(data, pcs->status.buffer + pcs->status.read_pos, count); pcs->status.read_pos += count; if (pcs->status.read_pos == pcs->status.write_pos) { gs_free_object(pcs->memory, pcs->status.buffer, "status buffer"); pcs->status.buffer = NULL; pcs->status.write_pos = pcs->status.read_pos = 0; } return count; }
64666065290032911431051417469693013930
None
CWE-787
CVE-2022-1350
A vulnerability classified as problematic was found in GhostPCL 9.55.0. This vulnerability affects the function chunk_free_object of the file gsmchunk.c. The manipulation with a malicious file leads to a memory corruption. The attack can be initiated remotely but requires user interaction. The exploit has been disclosed to the public as a POC and may be used. It is recommended to apply the patches to fix this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-1350
212,829
php-src
698a691724c0a949295991e5df091ce16f899e02
https://github.com/php/php-src
https://github.com/php/php-src/commit/698a691724c0a949295991e5df091ce16f899e02?w=1
Fix bug #72750: wddx_deserialize null dereference
1
*/ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; }
256847714577175382991355330020307438516
wddx.c
145600633466725124063532436200225083004
CWE-476
CVE-2016-7130
The php_wddx_pop_element function in ext/wddx/wddx.c in PHP before 5.6.25 and 7.x before 7.0.10 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) or possibly have unspecified other impact via an invalid base64 binary value, as demonstrated by a wddx_deserialize call that mishandles a binary element in a wddxPacket XML document.
https://nvd.nist.gov/vuln/detail/CVE-2016-7130
462,395
php-src
698a691724c0a949295991e5df091ce16f899e02
https://github.com/php/php-src
https://github.com/php/php-src/commit/698a691724c0a949295991e5df091ce16f899e02?w=1
Fix bug #72750: wddx_deserialize null dereference
0
*/ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; }
281846366232469448026733489364664016551
wddx.c
180653157857930473406661829830823818897
CWE-476
CVE-2016-7130
The php_wddx_pop_element function in ext/wddx/wddx.c in PHP before 5.6.25 and 7.x before 7.0.10 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) or possibly have unspecified other impact via an invalid base64 binary value, as demonstrated by a wddx_deserialize call that mishandles a binary element in a wddxPacket XML document.
https://nvd.nist.gov/vuln/detail/CVE-2016-7130
212,834
rsyslog
0381a0de64a5a048c3d48b79055bd9848d0c7fc2
https://github.com/rsyslog/rsyslog
https://github.com/rsyslog/rsyslog/commit/0381a0de64a5a048c3d48b79055bd9848d0c7fc2
imptcp: fix Segmentation Fault when octet count is to high
1
processDataRcvd(ptcpsess_t *const __restrict__ pThis, char **buff, const int buffLen, struct syslogTime *stTime, const time_t ttGenTime, multi_submit_t *pMultiSub, unsigned *const __restrict__ pnMsgs) { DEFiRet; char c = **buff; int octatesToCopy, octatesToDiscard; if(pThis->inputState == eAtStrtFram) { if(pThis->bSuppOctetFram && isdigit((int) c)) { pThis->inputState = eInOctetCnt; pThis->iOctetsRemain = 0; pThis->eFraming = TCP_FRAMING_OCTET_COUNTING; } else if(pThis->bSPFramingFix && c == ' ') { /* Cisco very occasionally sends a SP after a LF, which * thrashes framing if not taken special care of. Here, * we permit space *in front of the next frame* and * ignore it. */ FINALIZE; } else { pThis->inputState = eInMsg; pThis->eFraming = TCP_FRAMING_OCTET_STUFFING; } } if(pThis->inputState == eInOctetCnt) { if(isdigit(c)) { pThis->iOctetsRemain = pThis->iOctetsRemain * 10 + c - '0'; } else { /* done with the octet count, so this must be the SP terminator */ DBGPRINTF("TCP Message with octet-counter, size %d.\n", pThis->iOctetsRemain); if(c != ' ') { errmsg.LogError(0, NO_ERRCODE, "Framing Error in received TCP message: " "delimiter is not SP but has ASCII value %d.", c); } if(pThis->iOctetsRemain < 1) { /* TODO: handle the case where the octet count is 0! */ DBGPRINTF("Framing Error: invalid octet count\n"); errmsg.LogError(0, NO_ERRCODE, "Framing Error in received TCP message: " "invalid octet count %d.", pThis->iOctetsRemain); } else if(pThis->iOctetsRemain > iMaxLine) { /* while we can not do anything against it, we can at least log an indication * that something went wrong) -- rgerhards, 2008-03-14 */ DBGPRINTF("truncating message with %d octets - max msg size is %d\n", pThis->iOctetsRemain, iMaxLine); errmsg.LogError(0, NO_ERRCODE, "received oversize message: size is %d bytes, " "max msg size is %d, truncating...", pThis->iOctetsRemain, iMaxLine); } pThis->inputState = eInMsg; } } else { assert(pThis->inputState == eInMsg); if (pThis->eFraming == TCP_FRAMING_OCTET_STUFFING) { if(pThis->iMsg >= iMaxLine) { /* emergency, we now need to flush, no matter if we are at end of message or not... */ int i = 1; char currBuffChar; while(i < buffLen && ((currBuffChar = (*buff)[i]) != '\n' && (pThis->pLstn->pSrv->iAddtlFrameDelim == TCPSRV_NO_ADDTL_DELIMITER || currBuffChar != pThis->pLstn->pSrv->iAddtlFrameDelim))) { i++; } LogError(0, NO_ERRCODE, "error: message received is at least %d byte larger than max msg" " size; message will be split starting at: \"%.*s\"\n", i, (i < 32) ? i : 32, *buff); doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); /* we might think if it is better to ignore the rest of the * message than to treat it as a new one. Maybe this is a good * candidate for a configuration parameter... * rgerhards, 2006-12-04 */ } if ((c == '\n') || ((pThis->pLstn->pSrv->iAddtlFrameDelim != TCPSRV_NO_ADDTL_DELIMITER) && (c == pThis->pLstn->pSrv->iAddtlFrameDelim)) ) { /* record delimiter? */ doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); pThis->inputState = eAtStrtFram; } else { /* IMPORTANT: here we copy the actual frame content to the message - for BOTH framing modes! * If we have a message that is larger than the max msg size, we truncate it. This is the best * we can do in light of what the engine supports. -- rgerhards, 2008-03-14 */ if(pThis->iMsg < iMaxLine) { *(pThis->pMsg + pThis->iMsg++) = c; } } } else { assert(pThis->eFraming == TCP_FRAMING_OCTET_COUNTING); octatesToCopy = pThis->iOctetsRemain; octatesToDiscard = 0; if (buffLen < octatesToCopy) { octatesToCopy = buffLen; } if (octatesToCopy + pThis->iMsg > iMaxLine) { octatesToDiscard = octatesToCopy - (iMaxLine - pThis->iMsg); octatesToCopy = iMaxLine - pThis->iMsg; } memcpy(pThis->pMsg + pThis->iMsg, *buff, octatesToCopy); pThis->iMsg += octatesToCopy; pThis->iOctetsRemain -= (octatesToCopy + octatesToDiscard); *buff += (octatesToCopy + octatesToDiscard - 1); if (pThis->iOctetsRemain == 0) { /* we have end of frame! */ doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); pThis->inputState = eAtStrtFram; } } } finalize_it: RETiRet; }
175845780697344678841951403700990960175
imptcp.c
66608949268386945207139768258979939814
CWE-190
CVE-2018-16881
A denial of service vulnerability was found in rsyslog in the imptcp module. An attacker could send a specially crafted message to the imptcp socket, which would cause rsyslog to crash. Versions before 8.27.0 are vulnerable.
https://nvd.nist.gov/vuln/detail/CVE-2018-16881
462,409
rsyslog
0381a0de64a5a048c3d48b79055bd9848d0c7fc2
https://github.com/rsyslog/rsyslog
https://github.com/rsyslog/rsyslog/commit/0381a0de64a5a048c3d48b79055bd9848d0c7fc2
imptcp: fix Segmentation Fault when octet count is to high
0
processDataRcvd(ptcpsess_t *const __restrict__ pThis, char **buff, const int buffLen, struct syslogTime *stTime, const time_t ttGenTime, multi_submit_t *pMultiSub, unsigned *const __restrict__ pnMsgs) { DEFiRet; char c = **buff; int octatesToCopy, octatesToDiscard; if(pThis->inputState == eAtStrtFram) { if(pThis->bSuppOctetFram && isdigit((int) c)) { pThis->inputState = eInOctetCnt; pThis->iOctetsRemain = 0; pThis->eFraming = TCP_FRAMING_OCTET_COUNTING; } else if(pThis->bSPFramingFix && c == ' ') { /* Cisco very occasionally sends a SP after a LF, which * thrashes framing if not taken special care of. Here, * we permit space *in front of the next frame* and * ignore it. */ FINALIZE; } else { pThis->inputState = eInMsg; pThis->eFraming = TCP_FRAMING_OCTET_STUFFING; } } if(pThis->inputState == eInOctetCnt) { if(isdigit(c)) { if(pThis->iOctetsRemain <= 200000000) { pThis->iOctetsRemain = pThis->iOctetsRemain * 10 + c - '0'; } else { errmsg.LogError(0, NO_ERRCODE, "Framing Error in received TCP message: " "frame too large (at least %d%c), change to octet stuffing", pThis->iOctetsRemain, c); pThis->eFraming = TCP_FRAMING_OCTET_STUFFING; pThis->inputState = eInMsg; } *(pThis->pMsg + pThis->iMsg++) = c; } else { /* done with the octet count, so this must be the SP terminator */ DBGPRINTF("TCP Message with octet-counter, size %d.\n", pThis->iOctetsRemain); if(c != ' ') { errmsg.LogError(0, NO_ERRCODE, "Framing Error in received TCP message: " "delimiter is not SP but has ASCII value %d.", c); } if(pThis->iOctetsRemain < 1) { /* TODO: handle the case where the octet count is 0! */ errmsg.LogError(0, NO_ERRCODE, "Framing Error in received TCP message: " "invalid octet count %d.", pThis->iOctetsRemain); pThis->eFraming = TCP_FRAMING_OCTET_STUFFING; } else if(pThis->iOctetsRemain > iMaxLine) { /* while we can not do anything against it, we can at least log an indication * that something went wrong) -- rgerhards, 2008-03-14 */ DBGPRINTF("truncating message with %d octets - max msg size is %d\n", pThis->iOctetsRemain, iMaxLine); errmsg.LogError(0, NO_ERRCODE, "received oversize message: size is %d bytes, " "max msg size is %d, truncating...", pThis->iOctetsRemain, iMaxLine); } pThis->inputState = eInMsg; pThis->iMsg = 0; } } else { assert(pThis->inputState == eInMsg); if (pThis->eFraming == TCP_FRAMING_OCTET_STUFFING) { if(pThis->iMsg >= iMaxLine) { /* emergency, we now need to flush, no matter if we are at end of message or not... */ int i = 1; char currBuffChar; while(i < buffLen && ((currBuffChar = (*buff)[i]) != '\n' && (pThis->pLstn->pSrv->iAddtlFrameDelim == TCPSRV_NO_ADDTL_DELIMITER || currBuffChar != pThis->pLstn->pSrv->iAddtlFrameDelim))) { i++; } LogError(0, NO_ERRCODE, "error: message received is at least %d byte larger than max msg" " size; message will be split starting at: \"%.*s\"\n", i, (i < 32) ? i : 32, *buff); doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); /* we might think if it is better to ignore the rest of the * message than to treat it as a new one. Maybe this is a good * candidate for a configuration parameter... * rgerhards, 2006-12-04 */ } if ((c == '\n') || ((pThis->pLstn->pSrv->iAddtlFrameDelim != TCPSRV_NO_ADDTL_DELIMITER) && (c == pThis->pLstn->pSrv->iAddtlFrameDelim)) ) { /* record delimiter? */ doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); pThis->inputState = eAtStrtFram; } else { /* IMPORTANT: here we copy the actual frame content to the message - for BOTH framing modes! * If we have a message that is larger than the max msg size, we truncate it. This is the best * we can do in light of what the engine supports. -- rgerhards, 2008-03-14 */ if(pThis->iMsg < iMaxLine) { *(pThis->pMsg + pThis->iMsg++) = c; } } } else { assert(pThis->eFraming == TCP_FRAMING_OCTET_COUNTING); octatesToCopy = pThis->iOctetsRemain; octatesToDiscard = 0; if (buffLen < octatesToCopy) { octatesToCopy = buffLen; } if (octatesToCopy + pThis->iMsg > iMaxLine) { octatesToDiscard = octatesToCopy - (iMaxLine - pThis->iMsg); octatesToCopy = iMaxLine - pThis->iMsg; } memcpy(pThis->pMsg + pThis->iMsg, *buff, octatesToCopy); pThis->iMsg += octatesToCopy; pThis->iOctetsRemain -= (octatesToCopy + octatesToDiscard); *buff += (octatesToCopy + octatesToDiscard - 1); if (pThis->iOctetsRemain == 0) { /* we have end of frame! */ doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); pThis->inputState = eAtStrtFram; } } } finalize_it: RETiRet; }
319180109338452321529530788318348241217
imptcp.c
222511081390723120608536252618686301143
CWE-190
CVE-2018-16881
A denial of service vulnerability was found in rsyslog in the imptcp module. An attacker could send a specially crafted message to the imptcp socket, which would cause rsyslog to crash. Versions before 8.27.0 are vulnerable.
https://nvd.nist.gov/vuln/detail/CVE-2018-16881
212,857
vim
4f1b083be43f351bc107541e7b0c9655a5d2c0bb
https://github.com/vim/vim
https://github.com/vim/vim/commit/4f1b083be43f351bc107541e7b0c9655a5d2c0bb
patch 9.0.0322: crash when no errors and 'quickfixtextfunc' is set Problem: Crash when no errors and 'quickfixtextfunc' is set. Solution: Do not handle errors if there aren't any.
1
qf_fill_buffer(qf_list_T *qfl, buf_T *buf, qfline_T *old_last, int qf_winid) { linenr_T lnum; qfline_T *qfp; int old_KeyTyped = KeyTyped; list_T *qftf_list = NULL; listitem_T *qftf_li = NULL; if (old_last == NULL) { if (buf != curbuf) { internal_error("qf_fill_buffer()"); return; } // delete all existing lines while ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0) (void)ml_delete((linenr_T)1); } // Check if there is anything to display if (qfl != NULL) { char_u dirname[MAXPATHL]; int invalid_val = FALSE; int prev_bufnr = -1; *dirname = NUL; // Add one line for each error if (old_last == NULL) { qfp = qfl->qf_start; lnum = 0; } else { if (old_last->qf_next != NULL) qfp = old_last->qf_next; else qfp = old_last; lnum = buf->b_ml.ml_line_count; } qftf_list = call_qftf_func(qfl, qf_winid, (long)(lnum + 1), (long)qfl->qf_count); if (qftf_list != NULL) qftf_li = qftf_list->lv_first; while (lnum < qfl->qf_count) { char_u *qftf_str = NULL; // Use the text supplied by the user defined function (if any). // If the returned value is not string, then ignore the rest // of the returned values and use the default. if (qftf_li != NULL && !invalid_val) { qftf_str = tv_get_string_chk(&qftf_li->li_tv); if (qftf_str == NULL) invalid_val = TRUE; } if (qf_buf_add_line(buf, lnum, qfp, dirname, prev_bufnr != qfp->qf_fnum, qftf_str) == FAIL) break; prev_bufnr = qfp->qf_fnum; ++lnum; qfp = qfp->qf_next; if (qfp == NULL) break; if (qftf_li != NULL) qftf_li = qftf_li->li_next; } if (old_last == NULL) // Delete the empty line which is now at the end (void)ml_delete(lnum + 1); } // correct cursor position check_lnums(TRUE); if (old_last == NULL) { // Set the 'filetype' to "qf" each time after filling the buffer. // This resembles reading a file into a buffer, it's more logical when // using autocommands. ++curbuf_lock; set_option_value_give_err((char_u *)"ft", 0L, (char_u *)"qf", OPT_LOCAL); curbuf->b_p_ma = FALSE; keep_filetype = TRUE; // don't detect 'filetype' apply_autocmds(EVENT_BUFREADPOST, (char_u *)"quickfix", NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFWINENTER, (char_u *)"quickfix", NULL, FALSE, curbuf); keep_filetype = FALSE; --curbuf_lock; // make sure it will be redrawn redraw_curbuf_later(UPD_NOT_VALID); } // Restore KeyTyped, setting 'filetype' may reset it. KeyTyped = old_KeyTyped; }
19896236176049682773029755500370526703
quickfix.c
67097038911895244025002740290880368768
CWE-416
CVE-2022-3037
Use After Free in GitHub repository vim/vim prior to 9.0.0322.
https://nvd.nist.gov/vuln/detail/CVE-2022-3037
462,511
vim
4f1b083be43f351bc107541e7b0c9655a5d2c0bb
https://github.com/vim/vim
https://github.com/vim/vim/commit/4f1b083be43f351bc107541e7b0c9655a5d2c0bb
patch 9.0.0322: crash when no errors and 'quickfixtextfunc' is set Problem: Crash when no errors and 'quickfixtextfunc' is set. Solution: Do not handle errors if there aren't any.
0
qf_fill_buffer(qf_list_T *qfl, buf_T *buf, qfline_T *old_last, int qf_winid) { linenr_T lnum; qfline_T *qfp; int old_KeyTyped = KeyTyped; list_T *qftf_list = NULL; listitem_T *qftf_li = NULL; if (old_last == NULL) { if (buf != curbuf) { internal_error("qf_fill_buffer()"); return; } // delete all existing lines while ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0) (void)ml_delete((linenr_T)1); } // Check if there is anything to display if (qfl != NULL && qfl->qf_start != NULL) { char_u dirname[MAXPATHL]; int invalid_val = FALSE; int prev_bufnr = -1; *dirname = NUL; // Add one line for each error if (old_last == NULL) { qfp = qfl->qf_start; lnum = 0; } else { if (old_last->qf_next != NULL) qfp = old_last->qf_next; else qfp = old_last; lnum = buf->b_ml.ml_line_count; } qftf_list = call_qftf_func(qfl, qf_winid, (long)(lnum + 1), (long)qfl->qf_count); if (qftf_list != NULL) qftf_li = qftf_list->lv_first; while (lnum < qfl->qf_count) { char_u *qftf_str = NULL; // Use the text supplied by the user defined function (if any). // If the returned value is not string, then ignore the rest // of the returned values and use the default. if (qftf_li != NULL && !invalid_val) { qftf_str = tv_get_string_chk(&qftf_li->li_tv); if (qftf_str == NULL) invalid_val = TRUE; } if (qf_buf_add_line(buf, lnum, qfp, dirname, prev_bufnr != qfp->qf_fnum, qftf_str) == FAIL) break; prev_bufnr = qfp->qf_fnum; ++lnum; qfp = qfp->qf_next; if (qfp == NULL) break; if (qftf_li != NULL) qftf_li = qftf_li->li_next; } if (old_last == NULL) // Delete the empty line which is now at the end (void)ml_delete(lnum + 1); } // correct cursor position check_lnums(TRUE); if (old_last == NULL) { // Set the 'filetype' to "qf" each time after filling the buffer. // This resembles reading a file into a buffer, it's more logical when // using autocommands. ++curbuf_lock; set_option_value_give_err((char_u *)"ft", 0L, (char_u *)"qf", OPT_LOCAL); curbuf->b_p_ma = FALSE; keep_filetype = TRUE; // don't detect 'filetype' apply_autocmds(EVENT_BUFREADPOST, (char_u *)"quickfix", NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFWINENTER, (char_u *)"quickfix", NULL, FALSE, curbuf); keep_filetype = FALSE; --curbuf_lock; // make sure it will be redrawn redraw_curbuf_later(UPD_NOT_VALID); } // Restore KeyTyped, setting 'filetype' may reset it. KeyTyped = old_KeyTyped; }
333242954823260199301291407740047378845
quickfix.c
221790887990910120742119728344121157301
CWE-416
CVE-2022-3037
Use After Free in GitHub repository vim/vim prior to 9.0.0322.
https://nvd.nist.gov/vuln/detail/CVE-2022-3037
212,871
newsbeuter
96e9506ae9e252c548665152d1b8968297128307
https://github.com/akrennmair/newsbeuter
https://github.com/akrennmair/newsbeuter/commit/96e9506ae9e252c548665152d1b8968297128307
Sanitize inputs to bookmark-cmd (#591) Newsbeuter didn't properly shell-escape the arguments passed to bookmarking command, which allows a remote attacker to perform remote code execution by crafting an RSS item whose title and/or URL contain something interpretable by the shell (most notably subshell invocations.) This has been reported by Jeriko One <[email protected]>, complete with PoC and a patch. This vulnerability was assigned CVE-2017-12904.
1
std::string controller::bookmark( const std::string& url, const std::string& title, const std::string& description, const std::string& feed_title) { std::string bookmark_cmd = cfg.get_configvalue("bookmark-cmd"); bool is_interactive = cfg.get_configvalue_as_bool("bookmark-interactive"); if (bookmark_cmd.length() > 0) { std::string cmdline = strprintf::fmt("%s '%s' %s %s %s", bookmark_cmd, utils::replace_all(url,"'", "%27"), quote_empty(stfl::quote(title)), quote_empty(stfl::quote(description)), quote_empty(stfl::quote(feed_title))); LOG(level::DEBUG, "controller::bookmark: cmd = %s", cmdline); if (is_interactive) { v->push_empty_formaction(); stfl::reset(); utils::run_interactively(cmdline, "controller::bookmark"); v->pop_current_formaction(); return ""; } else { char * my_argv[4]; my_argv[0] = const_cast<char *>("/bin/sh"); my_argv[1] = const_cast<char *>("-c"); my_argv[2] = const_cast<char *>(cmdline.c_str()); my_argv[3] = nullptr; return utils::run_program(my_argv, ""); } } else { return _("bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly."); } }
264539000779301749255245601679907359223
controller.cpp
304698252897756630266738619508328009845
CWE-787
CVE-2017-12904
Improper Neutralization of Special Elements used in an OS Command in bookmarking function of Newsbeuter versions 0.7 through 2.9 allows remote attackers to perform user-assisted code execution by crafting an RSS item that includes shell code in its title and/or URL.
https://nvd.nist.gov/vuln/detail/CVE-2017-12904
462,566
newsbeuter
96e9506ae9e252c548665152d1b8968297128307
https://github.com/akrennmair/newsbeuter
https://github.com/akrennmair/newsbeuter/commit/96e9506ae9e252c548665152d1b8968297128307
Sanitize inputs to bookmark-cmd (#591) Newsbeuter didn't properly shell-escape the arguments passed to bookmarking command, which allows a remote attacker to perform remote code execution by crafting an RSS item whose title and/or URL contain something interpretable by the shell (most notably subshell invocations.) This has been reported by Jeriko One <[email protected]>, complete with PoC and a patch. This vulnerability was assigned CVE-2017-12904.
0
std::string controller::bookmark( const std::string& url, const std::string& title, const std::string& description, const std::string& feed_title) { std::string bookmark_cmd = cfg.get_configvalue("bookmark-cmd"); bool is_interactive = cfg.get_configvalue_as_bool("bookmark-interactive"); if (bookmark_cmd.length() > 0) { std::string cmdline = strprintf::fmt("%s '%s' '%s' '%s' '%s'", bookmark_cmd, utils::replace_all(url,"'", "%27"), utils::replace_all(title,"'", "%27"), utils::replace_all(description,"'", "%27"), utils::replace_all(feed_title,"'", "%27")); LOG(level::DEBUG, "controller::bookmark: cmd = %s", cmdline); if (is_interactive) { v->push_empty_formaction(); stfl::reset(); utils::run_interactively(cmdline, "controller::bookmark"); v->pop_current_formaction(); return ""; } else { char * my_argv[4]; my_argv[0] = const_cast<char *>("/bin/sh"); my_argv[1] = const_cast<char *>("-c"); my_argv[2] = const_cast<char *>(cmdline.c_str()); my_argv[3] = nullptr; return utils::run_program(my_argv, ""); } } else { return _("bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly."); } }
79271714330892808671163251460832419876
controller.cpp
323926139485782731853395949715316223577
CWE-787
CVE-2017-12904
Improper Neutralization of Special Elements used in an OS Command in bookmarking function of Newsbeuter versions 0.7 through 2.9 allows remote attackers to perform user-assisted code execution by crafting an RSS item that includes shell code in its title and/or URL.
https://nvd.nist.gov/vuln/detail/CVE-2017-12904
212,927
qemu
8c92060d3c0248bd4d515719a35922cd2391b9b4
https://github.com/bonzini/qemu
https://git.qemu.org/?p=qemu.git;a=commit;h=8c92060d3c0248bd4d515719a35922cd2391b9b4
sungem: switch to use qemu_receive_packet() for loopback This patch switches to use qemu_receive_packet() which can detect reentrancy and return early. This is intended to address CVE-2021-3416. Cc: Prasad J Pandit <[email protected]> Cc: [email protected] Reviewed-by: Mark Cave-Ayland <[email protected]> Reviewed-by: Philippe Mathieu-Daudé <[email protected]> Reviewed-by: Alistair Francis <[email protected]> Signed-off-by: Jason Wang <[email protected]>
1
static void sungem_send_packet(SunGEMState *s, const uint8_t *buf, int size) { NetClientState *nc = qemu_get_queue(s->nic); if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) { nc->info->receive(nc, buf, size); } else { qemu_send_packet(nc, buf, size); } }
112948077964204681005351426202657971698
sungem.c
256783431250079747313896805247705613463
CWE-835
CVE-2021-3416
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.
https://nvd.nist.gov/vuln/detail/CVE-2021-3416
463,051
qemu
8c92060d3c0248bd4d515719a35922cd2391b9b4
https://github.com/bonzini/qemu
https://git.qemu.org/?p=qemu.git;a=commit;h=8c92060d3c0248bd4d515719a35922cd2391b9b4
sungem: switch to use qemu_receive_packet() for loopback This patch switches to use qemu_receive_packet() which can detect reentrancy and return early. This is intended to address CVE-2021-3416. Cc: Prasad J Pandit <[email protected]> Cc: [email protected] Reviewed-by: Mark Cave-Ayland <[email protected]> Reviewed-by: Philippe Mathieu-Daudé <[email protected]> Reviewed-by: Alistair Francis <[email protected]> Signed-off-by: Jason Wang <[email protected]>
0
static void sungem_send_packet(SunGEMState *s, const uint8_t *buf, int size) { NetClientState *nc = qemu_get_queue(s->nic); if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) { qemu_receive_packet(nc, buf, size); } else { qemu_send_packet(nc, buf, size); } }
84544313584680412999632571366119869555
sungem.c
289260737548619033998236290754655826819
CWE-835
CVE-2021-3416
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.
https://nvd.nist.gov/vuln/detail/CVE-2021-3416
212,934
cyrus-imapd
621f9e41465b521399f691c241181300fab55995
https://github.com/cyrusimap/cyrus-imapd
https://github.com/cyrusimap/cyrus-imapd/commit/621f9e41465b521399f691c241181300fab55995
annotate: don't allow everyone to write shared server entries
1
static int write_entry(struct mailbox *mailbox, unsigned int uid, const char *entry, const char *userid, const struct buf *value, int ignorequota, int silent, const struct annotate_metadata *mdata, int maywrite) { char key[MAX_MAILBOX_PATH+1]; int keylen, r; annotate_db_t *d = NULL; struct buf oldval = BUF_INITIALIZER; const char *mboxname = mailbox ? mailbox->name : ""; modseq_t modseq = mdata ? mdata->modseq : 0; r = _annotate_getdb(mboxname, uid, CYRUSDB_CREATE, &d); if (r) return r; /* must be in a transaction to modify the db */ annotate_begin(d); keylen = make_key(mboxname, uid, entry, userid, key, sizeof(key)); if (mailbox) { struct annotate_metadata oldmdata; r = read_old_value(d, key, keylen, &oldval, &oldmdata); if (r) goto out; /* if the value is identical, don't touch the mailbox */ if (oldval.len == value->len && (!value->len || !memcmp(oldval.s, value->s, value->len))) goto out; if (!ignorequota) { quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_DONTCARE_INITIALIZER; qdiffs[QUOTA_ANNOTSTORAGE] = value->len - (quota_t)oldval.len; r = mailbox_quota_check(mailbox, qdiffs); if (r) goto out; } if (!maywrite) { r = IMAP_PERMISSION_DENIED; if (r) goto out; } /* do the annot-changed here before altering the DB */ mailbox_annot_changed(mailbox, uid, entry, userid, &oldval, value, silent); /* grab the message annotation modseq, if not overridden */ if (uid && !mdata) { modseq = mailbox->i.highestmodseq; } } /* zero length annotation is deletion. * keep tombstones for message annotations */ if (!value->len && !uid) { #if DEBUG syslog(LOG_ERR, "write_entry: deleting key %s from %s", key_as_string(d, key, keylen), d->filename); #endif do { r = cyrusdb_delete(d->db, key, keylen, tid(d), /*force*/1); } while (r == CYRUSDB_AGAIN); } else { struct buf data = BUF_INITIALIZER; unsigned char flags = 0; if (!value->len || value->s == NULL) { flags |= ANNOTATE_FLAG_DELETED; } else { // this is only here to allow cleanup of invalid values in the past... // the calling of this API with a NULL "userid" is bogus, because that's // supposed to be reserved for the make_key of prefixes - but there has // been API abuse in the past, so some of these are in the wild. *sigh*. // Don't allow new ones to be written if (!userid) goto out; } make_entry(&data, value, modseq, flags); #if DEBUG syslog(LOG_ERR, "write_entry: storing key %s (value: %s) to %s (modseq=" MODSEQ_FMT ")", key_as_string(d, key, keylen), value->s, d->filename, modseq); #endif do { r = cyrusdb_store(d->db, key, keylen, data.s, data.len, tid(d)); } while (r == CYRUSDB_AGAIN); buf_free(&data); } if (!mailbox) sync_log_annotation(""); out: annotate_putdb(&d); buf_free(&oldval); return r; }
63211042070136121773849314849857565491
annotate.c
152032054661376167383830098805318046193
CWE-732
CVE-2021-32056
Cyrus IMAP before 3.2.7, and 3.3.x and 3.4.x before 3.4.1, allows remote authenticated users to bypass intended access restrictions on server annotations and consequently cause replication to stall.
https://nvd.nist.gov/vuln/detail/CVE-2021-32056
463,134
cyrus-imapd
621f9e41465b521399f691c241181300fab55995
https://github.com/cyrusimap/cyrus-imapd
https://github.com/cyrusimap/cyrus-imapd/commit/621f9e41465b521399f691c241181300fab55995
annotate: don't allow everyone to write shared server entries
0
static int write_entry(struct mailbox *mailbox, unsigned int uid, const char *entry, const char *userid, const struct buf *value, int ignorequota, int silent, const struct annotate_metadata *mdata, int maywrite) { char key[MAX_MAILBOX_PATH+1]; int keylen, r; annotate_db_t *d = NULL; struct buf oldval = BUF_INITIALIZER; const char *mboxname = mailbox ? mailbox->name : ""; modseq_t modseq = mdata ? mdata->modseq : 0; r = _annotate_getdb(mboxname, uid, CYRUSDB_CREATE, &d); if (r) return r; /* must be in a transaction to modify the db */ annotate_begin(d); keylen = make_key(mboxname, uid, entry, userid, key, sizeof(key)); struct annotate_metadata oldmdata; r = read_old_value(d, key, keylen, &oldval, &oldmdata); if (r) goto out; /* if the value is identical, don't touch the mailbox */ if (oldval.len == value->len && (!value->len || !memcmp(oldval.s, value->s, value->len))) goto out; if (!maywrite) { r = IMAP_PERMISSION_DENIED; if (r) goto out; } if (mailbox) { if (!ignorequota) { quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_DONTCARE_INITIALIZER; qdiffs[QUOTA_ANNOTSTORAGE] = value->len - (quota_t)oldval.len; r = mailbox_quota_check(mailbox, qdiffs); if (r) goto out; } /* do the annot-changed here before altering the DB */ mailbox_annot_changed(mailbox, uid, entry, userid, &oldval, value, silent); /* grab the message annotation modseq, if not overridden */ if (uid && !mdata) { modseq = mailbox->i.highestmodseq; } } /* zero length annotation is deletion. * keep tombstones for message annotations */ if (!value->len && !uid) { #if DEBUG syslog(LOG_ERR, "write_entry: deleting key %s from %s", key_as_string(d, key, keylen), d->filename); #endif do { r = cyrusdb_delete(d->db, key, keylen, tid(d), /*force*/1); } while (r == CYRUSDB_AGAIN); } else { struct buf data = BUF_INITIALIZER; unsigned char flags = 0; if (!value->len || value->s == NULL) { flags |= ANNOTATE_FLAG_DELETED; } else { // this is only here to allow cleanup of invalid values in the past... // the calling of this API with a NULL "userid" is bogus, because that's // supposed to be reserved for the make_key of prefixes - but there has // been API abuse in the past, so some of these are in the wild. *sigh*. // Don't allow new ones to be written if (!userid) goto out; } make_entry(&data, value, modseq, flags); #if DEBUG syslog(LOG_ERR, "write_entry: storing key %s (value: %s) to %s (modseq=" MODSEQ_FMT ")", key_as_string(d, key, keylen), value->s, d->filename, modseq); #endif do { r = cyrusdb_store(d->db, key, keylen, data.s, data.len, tid(d)); } while (r == CYRUSDB_AGAIN); buf_free(&data); } if (!mailbox) sync_log_annotation(""); out: annotate_putdb(&d); buf_free(&oldval); return r; }
337608514204534148463343228875212022606
annotate.c
55084981439029014796527313329432397099
CWE-732
CVE-2021-32056
Cyrus IMAP before 3.2.7, and 3.3.x and 3.4.x before 3.4.1, allows remote authenticated users to bypass intended access restrictions on server annotations and consequently cause replication to stall.
https://nvd.nist.gov/vuln/detail/CVE-2021-32056
212,955
linux
82e31755e55fbcea6a9dfaae5fe4860ade17cbc0
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/82e31755e55fbcea6a9dfaae5fe4860ade17cbc0
ax25: Fix UAF bugs in ax25 timers There are race conditions that may lead to UAF bugs in ax25_heartbeat_expiry(), ax25_t1timer_expiry(), ax25_t2timer_expiry(), ax25_t3timer_expiry() and ax25_idletimer_expiry(), when we call ax25_release() to deallocate ax25_dev. One of the UAF bugs caused by ax25_release() is shown below: (Thread 1) | (Thread 2) ax25_dev_device_up() //(1) | ... | ax25_kill_by_device() ax25_bind() //(2) | ax25_connect() | ... ax25_std_establish_data_link() | ax25_start_t1timer() | ax25_dev_device_down() //(3) mod_timer(&ax25->t1timer,..) | | ax25_release() (wait a time) | ... | ax25_dev_put(ax25_dev) //(4)FREE ax25_t1timer_expiry() | ax25->ax25_dev->values[..] //USE| ... ... | We increase the refcount of ax25_dev in position (1) and (2), and decrease the refcount of ax25_dev in position (3) and (4). The ax25_dev will be freed in position (4) and be used in ax25_t1timer_expiry(). The fail log is shown below: ============================================================== [ 106.116942] BUG: KASAN: use-after-free in ax25_t1timer_expiry+0x1c/0x60 [ 106.116942] Read of size 8 at addr ffff88800bda9028 by task swapper/0/0 [ 106.116942] CPU: 0 PID: 0 Comm: swapper/0 Not tainted 5.17.0-06123-g0905eec574 [ 106.116942] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-14 [ 106.116942] Call Trace: ... [ 106.116942] ax25_t1timer_expiry+0x1c/0x60 [ 106.116942] call_timer_fn+0x122/0x3d0 [ 106.116942] __run_timers.part.0+0x3f6/0x520 [ 106.116942] run_timer_softirq+0x4f/0xb0 [ 106.116942] __do_softirq+0x1c2/0x651 ... This patch adds del_timer_sync() in ax25_release(), which could ensure that all timers stop before we deallocate ax25_dev. Signed-off-by: Duoming Zhou <[email protected]> Signed-off-by: Paolo Abeni <[email protected]>
1
static int ax25_release(struct socket *sock) { struct sock *sk = sock->sk; ax25_cb *ax25; ax25_dev *ax25_dev; if (sk == NULL) return 0; sock_hold(sk); lock_sock(sk); sock_orphan(sk); ax25 = sk_to_ax25(sk); ax25_dev = ax25->ax25_dev; if (sk->sk_type == SOCK_SEQPACKET) { switch (ax25->state) { case AX25_STATE_0: release_sock(sk); ax25_disconnect(ax25, 0); lock_sock(sk); ax25_destroy_socket(ax25); break; case AX25_STATE_1: case AX25_STATE_2: ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND); release_sock(sk); ax25_disconnect(ax25, 0); lock_sock(sk); if (!sock_flag(ax25->sk, SOCK_DESTROY)) ax25_destroy_socket(ax25); break; case AX25_STATE_3: case AX25_STATE_4: ax25_clear_queues(ax25); ax25->n2count = 0; switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) { case AX25_PROTO_STD_SIMPLEX: case AX25_PROTO_STD_DUPLEX: ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND); ax25_stop_t2timer(ax25); ax25_stop_t3timer(ax25); ax25_stop_idletimer(ax25); break; #ifdef CONFIG_AX25_DAMA_SLAVE case AX25_PROTO_DAMA_SLAVE: ax25_stop_t3timer(ax25); ax25_stop_idletimer(ax25); break; #endif } ax25_calculate_t1(ax25); ax25_start_t1timer(ax25); ax25->state = AX25_STATE_2; sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DESTROY); break; default: break; } } else { sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); ax25_destroy_socket(ax25); } if (ax25_dev) { dev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker); ax25_dev_put(ax25_dev); } sock->sk = NULL; release_sock(sk); sock_put(sk); return 0; }
322863638930156349228190868934879958122
af_ax25.c
161595370162210735322175103800372569534
CWE-476
CVE-2022-1205
A NULL pointer dereference flaw was found in the Linux kernel’s Amateur Radio AX.25 protocol functionality in the way a user connects with the protocol. This flaw allows a local user to crash the system.
https://nvd.nist.gov/vuln/detail/CVE-2022-1205
463,476
linux
82e31755e55fbcea6a9dfaae5fe4860ade17cbc0
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/82e31755e55fbcea6a9dfaae5fe4860ade17cbc0
ax25: Fix UAF bugs in ax25 timers There are race conditions that may lead to UAF bugs in ax25_heartbeat_expiry(), ax25_t1timer_expiry(), ax25_t2timer_expiry(), ax25_t3timer_expiry() and ax25_idletimer_expiry(), when we call ax25_release() to deallocate ax25_dev. One of the UAF bugs caused by ax25_release() is shown below: (Thread 1) | (Thread 2) ax25_dev_device_up() //(1) | ... | ax25_kill_by_device() ax25_bind() //(2) | ax25_connect() | ... ax25_std_establish_data_link() | ax25_start_t1timer() | ax25_dev_device_down() //(3) mod_timer(&ax25->t1timer,..) | | ax25_release() (wait a time) | ... | ax25_dev_put(ax25_dev) //(4)FREE ax25_t1timer_expiry() | ax25->ax25_dev->values[..] //USE| ... ... | We increase the refcount of ax25_dev in position (1) and (2), and decrease the refcount of ax25_dev in position (3) and (4). The ax25_dev will be freed in position (4) and be used in ax25_t1timer_expiry(). The fail log is shown below: ============================================================== [ 106.116942] BUG: KASAN: use-after-free in ax25_t1timer_expiry+0x1c/0x60 [ 106.116942] Read of size 8 at addr ffff88800bda9028 by task swapper/0/0 [ 106.116942] CPU: 0 PID: 0 Comm: swapper/0 Not tainted 5.17.0-06123-g0905eec574 [ 106.116942] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-14 [ 106.116942] Call Trace: ... [ 106.116942] ax25_t1timer_expiry+0x1c/0x60 [ 106.116942] call_timer_fn+0x122/0x3d0 [ 106.116942] __run_timers.part.0+0x3f6/0x520 [ 106.116942] run_timer_softirq+0x4f/0xb0 [ 106.116942] __do_softirq+0x1c2/0x651 ... This patch adds del_timer_sync() in ax25_release(), which could ensure that all timers stop before we deallocate ax25_dev. Signed-off-by: Duoming Zhou <[email protected]> Signed-off-by: Paolo Abeni <[email protected]>
0
static int ax25_release(struct socket *sock) { struct sock *sk = sock->sk; ax25_cb *ax25; ax25_dev *ax25_dev; if (sk == NULL) return 0; sock_hold(sk); lock_sock(sk); sock_orphan(sk); ax25 = sk_to_ax25(sk); ax25_dev = ax25->ax25_dev; if (sk->sk_type == SOCK_SEQPACKET) { switch (ax25->state) { case AX25_STATE_0: release_sock(sk); ax25_disconnect(ax25, 0); lock_sock(sk); ax25_destroy_socket(ax25); break; case AX25_STATE_1: case AX25_STATE_2: ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND); release_sock(sk); ax25_disconnect(ax25, 0); lock_sock(sk); if (!sock_flag(ax25->sk, SOCK_DESTROY)) ax25_destroy_socket(ax25); break; case AX25_STATE_3: case AX25_STATE_4: ax25_clear_queues(ax25); ax25->n2count = 0; switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) { case AX25_PROTO_STD_SIMPLEX: case AX25_PROTO_STD_DUPLEX: ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND); ax25_stop_t2timer(ax25); ax25_stop_t3timer(ax25); ax25_stop_idletimer(ax25); break; #ifdef CONFIG_AX25_DAMA_SLAVE case AX25_PROTO_DAMA_SLAVE: ax25_stop_t3timer(ax25); ax25_stop_idletimer(ax25); break; #endif } ax25_calculate_t1(ax25); ax25_start_t1timer(ax25); ax25->state = AX25_STATE_2; sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DESTROY); break; default: break; } } else { sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); ax25_destroy_socket(ax25); } if (ax25_dev) { del_timer_sync(&ax25->timer); del_timer_sync(&ax25->t1timer); del_timer_sync(&ax25->t2timer); del_timer_sync(&ax25->t3timer); del_timer_sync(&ax25->idletimer); dev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker); ax25_dev_put(ax25_dev); } sock->sk = NULL; release_sock(sk); sock_put(sk); return 0; }
148812270576683691154381215671514833423
af_ax25.c
305687071181329049431144170214324654974
CWE-476
CVE-2022-1205
A NULL pointer dereference flaw was found in the Linux kernel’s Amateur Radio AX.25 protocol functionality in the way a user connects with the protocol. This flaw allows a local user to crash the system.
https://nvd.nist.gov/vuln/detail/CVE-2022-1205
213,037
php-src
2bcbc95f033c31b00595ed39f79c3a99b4ed0501
https://github.com/php/php-src
http://git.php.net/?p=php-src.git;a=commit;h=2bcbc95f033c31b00595ed39f79c3a99b4ed0501
Fix bug #79037 (global buffer-overflow in `mbfl_filt_conv_big5_wchar`)
1
mbfl_filt_conv_big5_wchar(int c, mbfl_convert_filter *filter) { int k; int c1, w, c2; switch (filter->status) { case 0: if (filter->from->no_encoding == mbfl_no_encoding_cp950) { c1 = 0x80; } else { c1 = 0xa0; } if (c >= 0 && c <= 0x80) { /* latin */ CK((*filter->output_function)(c, filter->data)); } else if (c == 0xff) { CK((*filter->output_function)(0xf8f8, filter->data)); } else if (c > c1 && c < 0xff) { /* dbcs lead byte */ filter->status = 1; filter->cache = c; } else { w = c & MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; case 1: /* dbcs second byte */ filter->status = 0; c1 = filter->cache; if ((c > 0x39 && c < 0x7f) | (c > 0xa0 && c < 0xff)) { if (c < 0x7f){ w = (c1 - 0xa1)*157 + (c - 0x40); } else { w = (c1 - 0xa1)*157 + (c - 0xa1) + 0x3f; } if (w >= 0 && w < big5_ucs_table_size) { w = big5_ucs_table[w]; } else { w = 0; } if (filter->from->no_encoding == mbfl_no_encoding_cp950) { /* PUA for CP950 */ if (w <= 0 && (((c1 >= 0xfa && c1 <= 0xfe) || (c1 >= 0x8e && c1 <= 0xa0) || (c1 >= 0x81 && c1 <= 0x8d) ||(c1 >= 0xc7 && c1 <= 0xc8)) && ((c > 0x39 && c < 0x7f) || (c > 0xa0 && c < 0xff))) || ((c1 == 0xc6) && (c > 0xa0 && c < 0xff))) { c2 = c1 << 8 | c; for (k = 0; k < sizeof(cp950_pua_tbl)/(sizeof(unsigned short)*4); k++) { if (c2 >= cp950_pua_tbl[k][2] && c2 <= cp950_pua_tbl[k][3]) { break; } } if ((cp950_pua_tbl[k][2] & 0xff) == 0x40) { w = 157*(c1 - (cp950_pua_tbl[k][2]>>8)) + c - (c >= 0xa1 ? 0x62 : 0x40) + cp950_pua_tbl[k][0]; } else { w = c2 - cp950_pua_tbl[k][2] + cp950_pua_tbl[k][0]; } } } if (w <= 0) { w = (c1 << 8) | c; w &= MBFL_WCSPLANE_MASK; w |= MBFL_WCSPLANE_BIG5; } CK((*filter->output_function)(w, filter->data)); } else if ((c >= 0 && c < 0x21) || c == 0x7f) { /* CTLs */ CK((*filter->output_function)(c, filter->data)); } else { w = (c1 << 8) | c; w &= MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; default: filter->status = 0; break; } return c; }
8283586201644887300915898295948875795
mbfilter_big5.c
67113767760618335945735132719612525083
CWE-125
CVE-2020-7060
When using certain mbstring functions to convert multibyte encodings, in PHP versions 7.2.x below 7.2.27, 7.3.x below 7.3.14 and 7.4.x below 7.4.2 it is possible to supply data that will cause function mbfl_filt_conv_big5_wchar to read past the allocated buffer. This may lead to information disclosure or crash.
https://nvd.nist.gov/vuln/detail/CVE-2020-7060
464,942
php-src
2bcbc95f033c31b00595ed39f79c3a99b4ed0501
https://github.com/php/php-src
http://git.php.net/?p=php-src.git;a=commit;h=2bcbc95f033c31b00595ed39f79c3a99b4ed0501
Fix bug #79037 (global buffer-overflow in `mbfl_filt_conv_big5_wchar`)
0
mbfl_filt_conv_big5_wchar(int c, mbfl_convert_filter *filter) { int k; int c1, w, c2; switch (filter->status) { case 0: if (filter->from->no_encoding == mbfl_no_encoding_cp950) { c1 = 0x80; } else { c1 = 0xa0; } if (c >= 0 && c <= 0x80) { /* latin */ CK((*filter->output_function)(c, filter->data)); } else if (c == 0xff) { CK((*filter->output_function)(0xf8f8, filter->data)); } else if (c > c1 && c < 0xff) { /* dbcs lead byte */ filter->status = 1; filter->cache = c; } else { w = c & MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; case 1: /* dbcs second byte */ filter->status = 0; c1 = filter->cache; if ((c > 0x39 && c < 0x7f) | (c > 0xa0 && c < 0xff)) { if (c < 0x7f){ w = (c1 - 0xa1)*157 + (c - 0x40); } else { w = (c1 - 0xa1)*157 + (c - 0xa1) + 0x3f; } if (w >= 0 && w < big5_ucs_table_size) { w = big5_ucs_table[w]; } else { w = 0; } if (filter->from->no_encoding == mbfl_no_encoding_cp950) { /* PUA for CP950 */ if (w <= 0 && is_in_cp950_pua(c1, c)) { c2 = c1 << 8 | c; for (k = 0; k < sizeof(cp950_pua_tbl)/(sizeof(unsigned short)*4); k++) { if (c2 >= cp950_pua_tbl[k][2] && c2 <= cp950_pua_tbl[k][3]) { break; } } if ((cp950_pua_tbl[k][2] & 0xff) == 0x40) { w = 157*(c1 - (cp950_pua_tbl[k][2]>>8)) + c - (c >= 0xa1 ? 0x62 : 0x40) + cp950_pua_tbl[k][0]; } else { w = c2 - cp950_pua_tbl[k][2] + cp950_pua_tbl[k][0]; } } } if (w <= 0) { w = (c1 << 8) | c; w &= MBFL_WCSPLANE_MASK; w |= MBFL_WCSPLANE_BIG5; } CK((*filter->output_function)(w, filter->data)); } else if ((c >= 0 && c < 0x21) || c == 0x7f) { /* CTLs */ CK((*filter->output_function)(c, filter->data)); } else { w = (c1 << 8) | c; w &= MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; default: filter->status = 0; break; } return c; }
324298547167958214830404594575086371894
mbfilter_big5.c
135358838595920427772392870415942108469
CWE-125
CVE-2020-7060
When using certain mbstring functions to convert multibyte encodings, in PHP versions 7.2.x below 7.2.27, 7.3.x below 7.3.14 and 7.4.x below 7.4.2 it is possible to supply data that will cause function mbfl_filt_conv_big5_wchar to read past the allocated buffer. This may lead to information disclosure or crash.
https://nvd.nist.gov/vuln/detail/CVE-2020-7060
213,075
linux
d270453a0d9ec10bb8a802a142fb1b3601a83098
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/d270453a0d9ec10bb8a802a142fb1b3601a83098
nfc: nfcmrvl: main: reorder destructive operations in nfcmrvl_nci_unregister_dev to avoid bugs There are destructive operations such as nfcmrvl_fw_dnld_abort and gpio_free in nfcmrvl_nci_unregister_dev. The resources such as firmware, gpio and so on could be destructed while the upper layer functions such as nfcmrvl_fw_dnld_start and nfcmrvl_nci_recv_frame is executing, which leads to double-free, use-after-free and null-ptr-deref bugs. There are three situations that could lead to double-free bugs. The first situation is shown below: (Thread 1) | (Thread 2) nfcmrvl_fw_dnld_start | ... | nfcmrvl_nci_unregister_dev release_firmware() | nfcmrvl_fw_dnld_abort kfree(fw) //(1) | fw_dnld_over | release_firmware ... | kfree(fw) //(2) | ... The second situation is shown below: (Thread 1) | (Thread 2) nfcmrvl_fw_dnld_start | ... | mod_timer | (wait a time) | fw_dnld_timeout | nfcmrvl_nci_unregister_dev fw_dnld_over | nfcmrvl_fw_dnld_abort release_firmware | fw_dnld_over kfree(fw) //(1) | release_firmware ... | kfree(fw) //(2) The third situation is shown below: (Thread 1) | (Thread 2) nfcmrvl_nci_recv_frame | if(..->fw_download_in_progress)| nfcmrvl_fw_dnld_recv_frame | queue_work | | fw_dnld_rx_work | nfcmrvl_nci_unregister_dev fw_dnld_over | nfcmrvl_fw_dnld_abort release_firmware | fw_dnld_over kfree(fw) //(1) | release_firmware | kfree(fw) //(2) The firmware struct is deallocated in position (1) and deallocated in position (2) again. The crash trace triggered by POC is like below: BUG: KASAN: double-free or invalid-free in fw_dnld_over Call Trace: kfree fw_dnld_over nfcmrvl_nci_unregister_dev nci_uart_tty_close tty_ldisc_kill tty_ldisc_hangup __tty_hangup.part.0 tty_release ... What's more, there are also use-after-free and null-ptr-deref bugs in nfcmrvl_fw_dnld_start. If we deallocate firmware struct, gpio or set null to the members of priv->fw_dnld in nfcmrvl_nci_unregister_dev, then, we dereference firmware, gpio or the members of priv->fw_dnld in nfcmrvl_fw_dnld_start, the UAF or NPD bugs will happen. This patch reorders destructive operations after nci_unregister_device in order to synchronize between cleanup routine and firmware download routine. The nci_unregister_device is well synchronized. If the device is detaching, the firmware download routine will goto error. If firmware download routine is executing, nci_unregister_device will wait until firmware download routine is finished. Fixes: 3194c6870158 ("NFC: nfcmrvl: add firmware download support") Signed-off-by: Duoming Zhou <[email protected]> Signed-off-by: David S. Miller <[email protected]>
1
void nfcmrvl_nci_unregister_dev(struct nfcmrvl_private *priv) { struct nci_dev *ndev = priv->ndev; if (priv->ndev->nfc_dev->fw_download_in_progress) nfcmrvl_fw_dnld_abort(priv); nfcmrvl_fw_dnld_deinit(priv); if (gpio_is_valid(priv->config.reset_n_io)) gpio_free(priv->config.reset_n_io); nci_unregister_device(ndev); nci_free_device(ndev); kfree(priv); }
80022393435189393698798858771068403226
main.c
269589724165464795755961413543377431257
CWE-416
CVE-2022-1734
A flaw in Linux Kernel found in nfcmrvl_nci_unregister_dev() in drivers/nfc/nfcmrvl/main.c can lead to use after free both read or write when non synchronized between cleanup routine and firmware download routine.
https://nvd.nist.gov/vuln/detail/CVE-2022-1734
465,854
linux
d270453a0d9ec10bb8a802a142fb1b3601a83098
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/d270453a0d9ec10bb8a802a142fb1b3601a83098
nfc: nfcmrvl: main: reorder destructive operations in nfcmrvl_nci_unregister_dev to avoid bugs There are destructive operations such as nfcmrvl_fw_dnld_abort and gpio_free in nfcmrvl_nci_unregister_dev. The resources such as firmware, gpio and so on could be destructed while the upper layer functions such as nfcmrvl_fw_dnld_start and nfcmrvl_nci_recv_frame is executing, which leads to double-free, use-after-free and null-ptr-deref bugs. There are three situations that could lead to double-free bugs. The first situation is shown below: (Thread 1) | (Thread 2) nfcmrvl_fw_dnld_start | ... | nfcmrvl_nci_unregister_dev release_firmware() | nfcmrvl_fw_dnld_abort kfree(fw) //(1) | fw_dnld_over | release_firmware ... | kfree(fw) //(2) | ... The second situation is shown below: (Thread 1) | (Thread 2) nfcmrvl_fw_dnld_start | ... | mod_timer | (wait a time) | fw_dnld_timeout | nfcmrvl_nci_unregister_dev fw_dnld_over | nfcmrvl_fw_dnld_abort release_firmware | fw_dnld_over kfree(fw) //(1) | release_firmware ... | kfree(fw) //(2) The third situation is shown below: (Thread 1) | (Thread 2) nfcmrvl_nci_recv_frame | if(..->fw_download_in_progress)| nfcmrvl_fw_dnld_recv_frame | queue_work | | fw_dnld_rx_work | nfcmrvl_nci_unregister_dev fw_dnld_over | nfcmrvl_fw_dnld_abort release_firmware | fw_dnld_over kfree(fw) //(1) | release_firmware | kfree(fw) //(2) The firmware struct is deallocated in position (1) and deallocated in position (2) again. The crash trace triggered by POC is like below: BUG: KASAN: double-free or invalid-free in fw_dnld_over Call Trace: kfree fw_dnld_over nfcmrvl_nci_unregister_dev nci_uart_tty_close tty_ldisc_kill tty_ldisc_hangup __tty_hangup.part.0 tty_release ... What's more, there are also use-after-free and null-ptr-deref bugs in nfcmrvl_fw_dnld_start. If we deallocate firmware struct, gpio or set null to the members of priv->fw_dnld in nfcmrvl_nci_unregister_dev, then, we dereference firmware, gpio or the members of priv->fw_dnld in nfcmrvl_fw_dnld_start, the UAF or NPD bugs will happen. This patch reorders destructive operations after nci_unregister_device in order to synchronize between cleanup routine and firmware download routine. The nci_unregister_device is well synchronized. If the device is detaching, the firmware download routine will goto error. If firmware download routine is executing, nci_unregister_device will wait until firmware download routine is finished. Fixes: 3194c6870158 ("NFC: nfcmrvl: add firmware download support") Signed-off-by: Duoming Zhou <[email protected]> Signed-off-by: David S. Miller <[email protected]>
0
void nfcmrvl_nci_unregister_dev(struct nfcmrvl_private *priv) { struct nci_dev *ndev = priv->ndev; nci_unregister_device(ndev); if (priv->ndev->nfc_dev->fw_download_in_progress) nfcmrvl_fw_dnld_abort(priv); nfcmrvl_fw_dnld_deinit(priv); if (gpio_is_valid(priv->config.reset_n_io)) gpio_free(priv->config.reset_n_io); nci_free_device(ndev); kfree(priv); }
316889922482617255369760811895973398042
main.c
72783035661229533043408251312926412443
CWE-416
CVE-2022-1734
A flaw in Linux Kernel found in nfcmrvl_nci_unregister_dev() in drivers/nfc/nfcmrvl/main.c can lead to use after free both read or write when non synchronized between cleanup routine and firmware download routine.
https://nvd.nist.gov/vuln/detail/CVE-2022-1734
213,370
glib
d553d92d6e9f53cbe5a34166fcb919ba652c6a8e
https://gitlab.gnome.org/GNOME/glib
https://gitlab.gnome.org/GNOME/glib/commit/d553d92d6e9f53cbe5a34166fcb919ba652c6a8e
gsocketclient: Fix criticals This ensures the parent GTask is kept alive as long as an enumeration is running and trying to connect. Closes #1646 Closes #1649
1
g_socket_client_connected_callback (GObject *source, GAsyncResult *result, gpointer user_data) { ConnectionAttempt *attempt = user_data; GSocketClientAsyncConnectData *data = attempt->data; GSList *l; GError *error = NULL; GProxy *proxy; const gchar *protocol; /* data is NULL once the task is completed */ if (data && g_task_return_error_if_cancelled (data->task)) { g_object_unref (data->task); connection_attempt_unref (attempt); return; } if (attempt->timeout_source) { g_source_destroy (attempt->timeout_source); g_clear_pointer (&attempt->timeout_source, g_source_unref); } if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source), result, &error)) { if (!g_cancellable_is_cancelled (attempt->cancellable)) { clarify_connect_error (error, data->connectable, attempt->address); set_last_error (data, error); } else g_clear_error (&error); if (data) { connection_attempt_remove (attempt); enumerator_next_async (data); } else connection_attempt_unref (attempt); return; } data->socket = g_steal_pointer (&attempt->socket); data->connection = g_steal_pointer (&attempt->connection); for (l = data->connection_attempts; l; l = g_slist_next (l)) { ConnectionAttempt *attempt_entry = l->data; g_cancellable_cancel (attempt_entry->cancellable); attempt_entry->data = NULL; connection_attempt_unref (attempt_entry); } g_slist_free (data->connection_attempts); data->connection_attempts = NULL; connection_attempt_unref (attempt); g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, NULL); g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection); /* wrong, but backward compatible */ g_socket_set_blocking (data->socket, TRUE); if (!data->proxy_addr) { g_socket_client_tls_handshake (data); return; } protocol = g_proxy_address_get_protocol (data->proxy_addr); /* The connection should not be anything other than TCP, * but let's put a safety guard in case */ if (!G_IS_TCP_CONNECTION (data->connection)) { g_critical ("Trying to proxy over non-TCP connection, this is " "most likely a bug in GLib IO library."); g_set_error_literal (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Proxying over a non-TCP connection is not supported.")); enumerator_next_async (data); } else if (g_hash_table_contains (data->client->priv->app_proxies, protocol)) { /* Simply complete the connection, we don't want to do TLS handshake * as the application proxy handling may need proxy handshake first */ g_socket_client_async_connect_complete (data); } else if ((proxy = g_proxy_get_default_for_protocol (protocol))) { g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection); g_proxy_connect_async (proxy, data->connection, data->proxy_addr, g_task_get_cancellable (data->task), g_socket_client_proxy_connect_callback, data); g_object_unref (proxy); } else { g_clear_error (&data->last_error); g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Proxy protocol “%s” is not supported."), protocol); enumerator_next_async (data); } }
303931634452049999477477859565079753152
gsocketclient.c
112189477762116433441013263383719019263
CWE-754
CVE-2019-9633
gio/gsocketclient.c in GNOME GLib 2.59.2 does not ensure that a parent GTask remains alive during the execution of a connection-attempting enumeration, which allows remote attackers to cause a denial of service (g_socket_client_connected_callback mishandling and application crash) via a crafted web site, as demonstrated by GNOME Web (aka Epiphany).
https://nvd.nist.gov/vuln/detail/CVE-2019-9633
468,349
glib
d553d92d6e9f53cbe5a34166fcb919ba652c6a8e
https://gitlab.gnome.org/GNOME/glib
https://gitlab.gnome.org/GNOME/glib/commit/d553d92d6e9f53cbe5a34166fcb919ba652c6a8e
gsocketclient: Fix criticals This ensures the parent GTask is kept alive as long as an enumeration is running and trying to connect. Closes #1646 Closes #1649
0
g_socket_client_connected_callback (GObject *source, GAsyncResult *result, gpointer user_data) { ConnectionAttempt *attempt = user_data; GSocketClientAsyncConnectData *data = attempt->data; GSList *l; GError *error = NULL; GProxy *proxy; const gchar *protocol; if (g_cancellable_is_cancelled (attempt->cancellable) || task_completed_or_cancelled (data->task)) { g_object_unref (data->task); connection_attempt_unref (attempt); return; } if (attempt->timeout_source) { g_source_destroy (attempt->timeout_source); g_clear_pointer (&attempt->timeout_source, g_source_unref); } if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source), result, &error)) { if (!g_cancellable_is_cancelled (attempt->cancellable)) { clarify_connect_error (error, data->connectable, attempt->address); set_last_error (data, error); connection_attempt_remove (attempt); enumerator_next_async (data, FALSE); } else { g_clear_error (&error); g_object_unref (data->task); connection_attempt_unref (attempt); } return; } data->socket = g_steal_pointer (&attempt->socket); data->connection = g_steal_pointer (&attempt->connection); for (l = data->connection_attempts; l; l = g_slist_next (l)) { ConnectionAttempt *attempt_entry = l->data; g_cancellable_cancel (attempt_entry->cancellable); connection_attempt_unref (attempt_entry); } g_slist_free (data->connection_attempts); data->connection_attempts = NULL; connection_attempt_unref (attempt); g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, NULL); g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection); /* wrong, but backward compatible */ g_socket_set_blocking (data->socket, TRUE); if (!data->proxy_addr) { g_socket_client_tls_handshake (data); return; } protocol = g_proxy_address_get_protocol (data->proxy_addr); /* The connection should not be anything other than TCP, * but let's put a safety guard in case */ if (!G_IS_TCP_CONNECTION (data->connection)) { g_critical ("Trying to proxy over non-TCP connection, this is " "most likely a bug in GLib IO library."); g_set_error_literal (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Proxying over a non-TCP connection is not supported.")); enumerator_next_async (data, FALSE); } else if (g_hash_table_contains (data->client->priv->app_proxies, protocol)) { /* Simply complete the connection, we don't want to do TLS handshake * as the application proxy handling may need proxy handshake first */ g_socket_client_async_connect_complete (data); } else if ((proxy = g_proxy_get_default_for_protocol (protocol))) { g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection); g_proxy_connect_async (proxy, data->connection, data->proxy_addr, g_task_get_cancellable (data->task), g_socket_client_proxy_connect_callback, data); g_object_unref (proxy); } else { g_clear_error (&data->last_error); g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Proxy protocol “%s” is not supported."), protocol); enumerator_next_async (data, FALSE); } }
284257451684326472377624066772232784907
gsocketclient.c
157905572963596557383512485968044873989
CWE-754
CVE-2019-9633
gio/gsocketclient.c in GNOME GLib 2.59.2 does not ensure that a parent GTask remains alive during the execution of a connection-attempting enumeration, which allows remote attackers to cause a denial of service (g_socket_client_connected_callback mishandling and application crash) via a crafted web site, as demonstrated by GNOME Web (aka Epiphany).
https://nvd.nist.gov/vuln/detail/CVE-2019-9633
213,515
vim
5c68617d395f9d7b824f68475b24ce3e38d653a3
https://github.com/vim/vim
https://github.com/vim/vim/commit/5c68617d395f9d7b824f68475b24ce3e38d653a3
patch 8.2.4563: "z=" in Visual mode may go beyond the end of the line Problem: "z=" in Visual mode may go beyond the end of the line. Solution: Adjust "badlen".
1
spell_suggest(int count) { char_u *line; pos_T prev_cursor = curwin->w_cursor; char_u wcopy[MAXWLEN + 2]; char_u *p; int i; int c; suginfo_T sug; suggest_T *stp; int mouse_used; int need_cap; int limit; int selected = count; int badlen = 0; int msg_scroll_save = msg_scroll; int wo_spell_save = curwin->w_p_spell; if (!curwin->w_p_spell) { did_set_spelllang(curwin); curwin->w_p_spell = TRUE; } if (*curwin->w_s->b_p_spl == NUL) { emsg(_(e_spell_checking_is_not_possible)); return; } if (VIsual_active) { // Use the Visually selected text as the bad word. But reject // a multi-line selection. if (curwin->w_cursor.lnum != VIsual.lnum) { vim_beep(BO_SPELL); return; } badlen = (int)curwin->w_cursor.col - (int)VIsual.col; if (badlen < 0) badlen = -badlen; else curwin->w_cursor.col = VIsual.col; ++badlen; end_visual_mode(); } // Find the start of the badly spelled word. else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0 || curwin->w_cursor.col > prev_cursor.col) { // No bad word or it starts after the cursor: use the word under the // cursor. curwin->w_cursor = prev_cursor; line = ml_get_curline(); p = line + curwin->w_cursor.col; // Backup to before start of word. while (p > line && spell_iswordp_nmw(p, curwin)) MB_PTR_BACK(line, p); // Forward to start of word. while (*p != NUL && !spell_iswordp_nmw(p, curwin)) MB_PTR_ADV(p); if (!spell_iswordp_nmw(p, curwin)) // No word found. { beep_flush(); return; } curwin->w_cursor.col = (colnr_T)(p - line); } // Get the word and its length. // Figure out if the word should be capitalised. need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col); // Make a copy of current line since autocommands may free the line. line = vim_strsave(ml_get_curline()); if (line == NULL) goto skip; // Get the list of suggestions. Limit to 'lines' - 2 or the number in // 'spellsuggest', whatever is smaller. if (sps_limit > (int)Rows - 2) limit = (int)Rows - 2; else limit = sps_limit; spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit, TRUE, need_cap, TRUE); if (sug.su_ga.ga_len == 0) msg(_("Sorry, no suggestions")); else if (count > 0) { if (count > sug.su_ga.ga_len) smsg(_("Sorry, only %ld suggestions"), (long)sug.su_ga.ga_len); } else { #ifdef FEAT_RIGHTLEFT // When 'rightleft' is set the list is drawn right-left. cmdmsg_rl = curwin->w_p_rl; if (cmdmsg_rl) msg_col = Columns - 1; #endif // List the suggestions. msg_start(); msg_row = Rows - 1; // for when 'cmdheight' > 1 lines_left = Rows; // avoid more prompt vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"), sug.su_badlen, sug.su_badptr); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0) { // And now the rabbit from the high hat: Avoid showing the // untranslated message rightleft. vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC", sug.su_badlen, sug.su_badptr); } #endif msg_puts((char *)IObuff); msg_clr_eos(); msg_putchar('\n'); msg_scroll = TRUE; for (i = 0; i < sug.su_ga.ga_len; ++i) { stp = &SUG(sug.su_ga, i); // The suggested word may replace only part of the bad word, add // the not replaced part. vim_strncpy(wcopy, stp->st_word, MAXWLEN); if (sug.su_badlen > stp->st_orglen) vim_strncpy(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen, sug.su_badlen - stp->st_orglen); vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) rl_mirror(IObuff); #endif msg_puts((char *)IObuff); vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy); msg_puts((char *)IObuff); // The word may replace more than "su_badlen". if (sug.su_badlen < stp->st_orglen) { vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""), stp->st_orglen, sug.su_badptr); msg_puts((char *)IObuff); } if (p_verbose > 0) { // Add the score. if (sps_flags & (SPS_DOUBLE | SPS_BEST)) vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)", stp->st_salscore ? "s " : "", stp->st_score, stp->st_altscore); else vim_snprintf((char *)IObuff, IOSIZE, " (%d)", stp->st_score); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) // Mirror the numbers, but keep the leading space. rl_mirror(IObuff + 1); #endif msg_advance(30); msg_puts((char *)IObuff); } msg_putchar('\n'); } #ifdef FEAT_RIGHTLEFT cmdmsg_rl = FALSE; msg_col = 0; #endif // Ask for choice. selected = prompt_for_number(&mouse_used); if (mouse_used) selected -= lines_left; lines_left = Rows; // avoid more prompt // don't delay for 'smd' in normal_cmd() msg_scroll = msg_scroll_save; } if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK) { // Save the from and to text for :spellrepall. VIM_CLEAR(repl_from); VIM_CLEAR(repl_to); stp = &SUG(sug.su_ga, selected - 1); if (sug.su_badlen > stp->st_orglen) { // Replacing less than "su_badlen", append the remainder to // repl_to. repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen); vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word, sug.su_badlen - stp->st_orglen, sug.su_badptr + stp->st_orglen); repl_to = vim_strsave(IObuff); } else { // Replacing su_badlen or more, use the whole word. repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen); repl_to = vim_strsave(stp->st_word); } // Replace the word. p = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1); if (p != NULL) { c = (int)(sug.su_badptr - line); mch_memmove(p, line, c); STRCPY(p + c, stp->st_word); STRCAT(p, sug.su_badptr + stp->st_orglen); // For redo we use a change-word command. ResetRedobuff(); AppendToRedobuff((char_u *)"ciw"); AppendToRedobuffLit(p + c, stp->st_wordlen + sug.su_badlen - stp->st_orglen); AppendCharToRedobuff(ESC); // "p" may be freed here ml_replace(curwin->w_cursor.lnum, p, FALSE); curwin->w_cursor.col = c; changed_bytes(curwin->w_cursor.lnum, c); } } else curwin->w_cursor = prev_cursor; spell_find_cleanup(&sug); skip: vim_free(line); curwin->w_p_spell = wo_spell_save; }
283321822802394416488141327214287342104
spellsuggest.c
284064000006918275605147443263550733278
CWE-787
CVE-2022-0943
Heap-based Buffer Overflow occurs in vim in GitHub repository vim/vim prior to 8.2.4563.
https://nvd.nist.gov/vuln/detail/CVE-2022-0943
471,902
vim
5c68617d395f9d7b824f68475b24ce3e38d653a3
https://github.com/vim/vim
https://github.com/vim/vim/commit/5c68617d395f9d7b824f68475b24ce3e38d653a3
patch 8.2.4563: "z=" in Visual mode may go beyond the end of the line Problem: "z=" in Visual mode may go beyond the end of the line. Solution: Adjust "badlen".
0
spell_suggest(int count) { char_u *line; pos_T prev_cursor = curwin->w_cursor; char_u wcopy[MAXWLEN + 2]; char_u *p; int i; int c; suginfo_T sug; suggest_T *stp; int mouse_used; int need_cap; int limit; int selected = count; int badlen = 0; int msg_scroll_save = msg_scroll; int wo_spell_save = curwin->w_p_spell; if (!curwin->w_p_spell) { did_set_spelllang(curwin); curwin->w_p_spell = TRUE; } if (*curwin->w_s->b_p_spl == NUL) { emsg(_(e_spell_checking_is_not_possible)); return; } if (VIsual_active) { // Use the Visually selected text as the bad word. But reject // a multi-line selection. if (curwin->w_cursor.lnum != VIsual.lnum) { vim_beep(BO_SPELL); return; } badlen = (int)curwin->w_cursor.col - (int)VIsual.col; if (badlen < 0) badlen = -badlen; else curwin->w_cursor.col = VIsual.col; ++badlen; end_visual_mode(); // make sure we don't include the NUL at the end of the line line = ml_get_curline(); if (badlen > STRLEN(line) - curwin->w_cursor.col) badlen = STRLEN(line) - curwin->w_cursor.col; } // Find the start of the badly spelled word. else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0 || curwin->w_cursor.col > prev_cursor.col) { // No bad word or it starts after the cursor: use the word under the // cursor. curwin->w_cursor = prev_cursor; line = ml_get_curline(); p = line + curwin->w_cursor.col; // Backup to before start of word. while (p > line && spell_iswordp_nmw(p, curwin)) MB_PTR_BACK(line, p); // Forward to start of word. while (*p != NUL && !spell_iswordp_nmw(p, curwin)) MB_PTR_ADV(p); if (!spell_iswordp_nmw(p, curwin)) // No word found. { beep_flush(); return; } curwin->w_cursor.col = (colnr_T)(p - line); } // Get the word and its length. // Figure out if the word should be capitalised. need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col); // Make a copy of current line since autocommands may free the line. line = vim_strsave(ml_get_curline()); if (line == NULL) goto skip; // Get the list of suggestions. Limit to 'lines' - 2 or the number in // 'spellsuggest', whatever is smaller. if (sps_limit > (int)Rows - 2) limit = (int)Rows - 2; else limit = sps_limit; spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit, TRUE, need_cap, TRUE); if (sug.su_ga.ga_len == 0) msg(_("Sorry, no suggestions")); else if (count > 0) { if (count > sug.su_ga.ga_len) smsg(_("Sorry, only %ld suggestions"), (long)sug.su_ga.ga_len); } else { #ifdef FEAT_RIGHTLEFT // When 'rightleft' is set the list is drawn right-left. cmdmsg_rl = curwin->w_p_rl; if (cmdmsg_rl) msg_col = Columns - 1; #endif // List the suggestions. msg_start(); msg_row = Rows - 1; // for when 'cmdheight' > 1 lines_left = Rows; // avoid more prompt vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"), sug.su_badlen, sug.su_badptr); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0) { // And now the rabbit from the high hat: Avoid showing the // untranslated message rightleft. vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC", sug.su_badlen, sug.su_badptr); } #endif msg_puts((char *)IObuff); msg_clr_eos(); msg_putchar('\n'); msg_scroll = TRUE; for (i = 0; i < sug.su_ga.ga_len; ++i) { stp = &SUG(sug.su_ga, i); // The suggested word may replace only part of the bad word, add // the not replaced part. vim_strncpy(wcopy, stp->st_word, MAXWLEN); if (sug.su_badlen > stp->st_orglen) vim_strncpy(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen, sug.su_badlen - stp->st_orglen); vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) rl_mirror(IObuff); #endif msg_puts((char *)IObuff); vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy); msg_puts((char *)IObuff); // The word may replace more than "su_badlen". if (sug.su_badlen < stp->st_orglen) { vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""), stp->st_orglen, sug.su_badptr); msg_puts((char *)IObuff); } if (p_verbose > 0) { // Add the score. if (sps_flags & (SPS_DOUBLE | SPS_BEST)) vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)", stp->st_salscore ? "s " : "", stp->st_score, stp->st_altscore); else vim_snprintf((char *)IObuff, IOSIZE, " (%d)", stp->st_score); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) // Mirror the numbers, but keep the leading space. rl_mirror(IObuff + 1); #endif msg_advance(30); msg_puts((char *)IObuff); } msg_putchar('\n'); } #ifdef FEAT_RIGHTLEFT cmdmsg_rl = FALSE; msg_col = 0; #endif // Ask for choice. selected = prompt_for_number(&mouse_used); if (mouse_used) selected -= lines_left; lines_left = Rows; // avoid more prompt // don't delay for 'smd' in normal_cmd() msg_scroll = msg_scroll_save; } if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK) { // Save the from and to text for :spellrepall. VIM_CLEAR(repl_from); VIM_CLEAR(repl_to); stp = &SUG(sug.su_ga, selected - 1); if (sug.su_badlen > stp->st_orglen) { // Replacing less than "su_badlen", append the remainder to // repl_to. repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen); vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word, sug.su_badlen - stp->st_orglen, sug.su_badptr + stp->st_orglen); repl_to = vim_strsave(IObuff); } else { // Replacing su_badlen or more, use the whole word. repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen); repl_to = vim_strsave(stp->st_word); } // Replace the word. p = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1); if (p != NULL) { c = (int)(sug.su_badptr - line); mch_memmove(p, line, c); STRCPY(p + c, stp->st_word); STRCAT(p, sug.su_badptr + stp->st_orglen); // For redo we use a change-word command. ResetRedobuff(); AppendToRedobuff((char_u *)"ciw"); AppendToRedobuffLit(p + c, stp->st_wordlen + sug.su_badlen - stp->st_orglen); AppendCharToRedobuff(ESC); // "p" may be freed here ml_replace(curwin->w_cursor.lnum, p, FALSE); curwin->w_cursor.col = c; changed_bytes(curwin->w_cursor.lnum, c); } } else curwin->w_cursor = prev_cursor; spell_find_cleanup(&sug); skip: vim_free(line); curwin->w_p_spell = wo_spell_save; }
210769611717793726730537343470434116318
spellsuggest.c
285304759407649884654167568930599876914
CWE-787
CVE-2022-0943
Heap-based Buffer Overflow occurs in vim in GitHub repository vim/vim prior to 8.2.4563.
https://nvd.nist.gov/vuln/detail/CVE-2022-0943
213,528
linux
3b0462726e7ef281c35a7a4ae33e93ee2bc9975b
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/3b0462726e7ef281c35a7a4ae33e93ee2bc9975b
cgroup: verify that source is a string The following sequence can be used to trigger a UAF: int fscontext_fd = fsopen("cgroup"); int fd_null = open("/dev/null, O_RDONLY); int fsconfig(fscontext_fd, FSCONFIG_SET_FD, "source", fd_null); close_range(3, ~0U, 0); The cgroup v1 specific fs parser expects a string for the "source" parameter. However, it is perfectly legitimate to e.g. specify a file descriptor for the "source" parameter. The fs parser doesn't know what a filesystem allows there. So it's a bug to assume that "source" is always of type fs_value_is_string when it can reasonably also be fs_value_is_file. This assumption in the cgroup code causes a UAF because struct fs_parameter uses a union for the actual value. Access to that union is guarded by the param->type member. Since the cgroup paramter parser didn't check param->type but unconditionally moved param->string into fc->source a close on the fscontext_fd would trigger a UAF during put_fs_context() which frees fc->source thereby freeing the file stashed in param->file causing a UAF during a close of the fd_null. Fix this by verifying that param->type is actually a string and report an error if not. In follow up patches I'll add a new generic helper that can be used here and by other filesystems instead of this error-prone copy-pasta fix. But fixing it in here first makes backporting a it to stable a lot easier. Fixes: 8d2451f4994f ("cgroup1: switch to option-by-option parsing") Reported-by: [email protected] Cc: Christoph Hellwig <[email protected]> Cc: Alexander Viro <[email protected]> Cc: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Cc: syzkaller-bugs <[email protected]> Signed-off-by: Christian Brauner <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
1
int cgroup1_parse_param(struct fs_context *fc, struct fs_parameter *param) { struct cgroup_fs_context *ctx = cgroup_fc2context(fc); struct cgroup_subsys *ss; struct fs_parse_result result; int opt, i; opt = fs_parse(fc, cgroup1_fs_parameters, param, &result); if (opt == -ENOPARAM) { if (strcmp(param->key, "source") == 0) { if (fc->source) return invalf(fc, "Multiple sources not supported"); fc->source = param->string; param->string = NULL; return 0; } for_each_subsys(ss, i) { if (strcmp(param->key, ss->legacy_name)) continue; if (!cgroup_ssid_enabled(i) || cgroup1_ssid_disabled(i)) return invalfc(fc, "Disabled controller '%s'", param->key); ctx->subsys_mask |= (1 << i); return 0; } return invalfc(fc, "Unknown subsys name '%s'", param->key); } if (opt < 0) return opt; switch (opt) { case Opt_none: /* Explicitly have no subsystems */ ctx->none = true; break; case Opt_all: ctx->all_ss = true; break; case Opt_noprefix: ctx->flags |= CGRP_ROOT_NOPREFIX; break; case Opt_clone_children: ctx->cpuset_clone_children = true; break; case Opt_cpuset_v2_mode: ctx->flags |= CGRP_ROOT_CPUSET_V2_MODE; break; case Opt_xattr: ctx->flags |= CGRP_ROOT_XATTR; break; case Opt_release_agent: /* Specifying two release agents is forbidden */ if (ctx->release_agent) return invalfc(fc, "release_agent respecified"); ctx->release_agent = param->string; param->string = NULL; break; case Opt_name: /* blocked by boot param? */ if (cgroup_no_v1_named) return -ENOENT; /* Can't specify an empty name */ if (!param->size) return invalfc(fc, "Empty name"); if (param->size > MAX_CGROUP_ROOT_NAMELEN - 1) return invalfc(fc, "Name too long"); /* Must match [\w.-]+ */ for (i = 0; i < param->size; i++) { char c = param->string[i]; if (isalnum(c)) continue; if ((c == '.') || (c == '-') || (c == '_')) continue; return invalfc(fc, "Invalid name"); } /* Specifying two names is forbidden */ if (ctx->name) return invalfc(fc, "name respecified"); ctx->name = param->string; param->string = NULL; break; } return 0; }
2447930720327269598694221319559062155
cgroup-v1.c
304027161926251240992448703175506915313
CWE-416
CVE-2021-4154
A use-after-free flaw was found in cgroup1_parse_param in kernel/cgroup/cgroup-v1.c in the Linux kernel's cgroup v1 parser. A local attacker with a user privilege could cause a privilege escalation by exploiting the fsconfig syscall parameter leading to a container breakout and a denial of service on the system.
https://nvd.nist.gov/vuln/detail/CVE-2021-4154
472,123
linux
3b0462726e7ef281c35a7a4ae33e93ee2bc9975b
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/3b0462726e7ef281c35a7a4ae33e93ee2bc9975b
cgroup: verify that source is a string The following sequence can be used to trigger a UAF: int fscontext_fd = fsopen("cgroup"); int fd_null = open("/dev/null, O_RDONLY); int fsconfig(fscontext_fd, FSCONFIG_SET_FD, "source", fd_null); close_range(3, ~0U, 0); The cgroup v1 specific fs parser expects a string for the "source" parameter. However, it is perfectly legitimate to e.g. specify a file descriptor for the "source" parameter. The fs parser doesn't know what a filesystem allows there. So it's a bug to assume that "source" is always of type fs_value_is_string when it can reasonably also be fs_value_is_file. This assumption in the cgroup code causes a UAF because struct fs_parameter uses a union for the actual value. Access to that union is guarded by the param->type member. Since the cgroup paramter parser didn't check param->type but unconditionally moved param->string into fc->source a close on the fscontext_fd would trigger a UAF during put_fs_context() which frees fc->source thereby freeing the file stashed in param->file causing a UAF during a close of the fd_null. Fix this by verifying that param->type is actually a string and report an error if not. In follow up patches I'll add a new generic helper that can be used here and by other filesystems instead of this error-prone copy-pasta fix. But fixing it in here first makes backporting a it to stable a lot easier. Fixes: 8d2451f4994f ("cgroup1: switch to option-by-option parsing") Reported-by: [email protected] Cc: Christoph Hellwig <[email protected]> Cc: Alexander Viro <[email protected]> Cc: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Cc: syzkaller-bugs <[email protected]> Signed-off-by: Christian Brauner <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
0
int cgroup1_parse_param(struct fs_context *fc, struct fs_parameter *param) { struct cgroup_fs_context *ctx = cgroup_fc2context(fc); struct cgroup_subsys *ss; struct fs_parse_result result; int opt, i; opt = fs_parse(fc, cgroup1_fs_parameters, param, &result); if (opt == -ENOPARAM) { if (strcmp(param->key, "source") == 0) { if (param->type != fs_value_is_string) return invalf(fc, "Non-string source"); if (fc->source) return invalf(fc, "Multiple sources not supported"); fc->source = param->string; param->string = NULL; return 0; } for_each_subsys(ss, i) { if (strcmp(param->key, ss->legacy_name)) continue; if (!cgroup_ssid_enabled(i) || cgroup1_ssid_disabled(i)) return invalfc(fc, "Disabled controller '%s'", param->key); ctx->subsys_mask |= (1 << i); return 0; } return invalfc(fc, "Unknown subsys name '%s'", param->key); } if (opt < 0) return opt; switch (opt) { case Opt_none: /* Explicitly have no subsystems */ ctx->none = true; break; case Opt_all: ctx->all_ss = true; break; case Opt_noprefix: ctx->flags |= CGRP_ROOT_NOPREFIX; break; case Opt_clone_children: ctx->cpuset_clone_children = true; break; case Opt_cpuset_v2_mode: ctx->flags |= CGRP_ROOT_CPUSET_V2_MODE; break; case Opt_xattr: ctx->flags |= CGRP_ROOT_XATTR; break; case Opt_release_agent: /* Specifying two release agents is forbidden */ if (ctx->release_agent) return invalfc(fc, "release_agent respecified"); ctx->release_agent = param->string; param->string = NULL; break; case Opt_name: /* blocked by boot param? */ if (cgroup_no_v1_named) return -ENOENT; /* Can't specify an empty name */ if (!param->size) return invalfc(fc, "Empty name"); if (param->size > MAX_CGROUP_ROOT_NAMELEN - 1) return invalfc(fc, "Name too long"); /* Must match [\w.-]+ */ for (i = 0; i < param->size; i++) { char c = param->string[i]; if (isalnum(c)) continue; if ((c == '.') || (c == '-') || (c == '_')) continue; return invalfc(fc, "Invalid name"); } /* Specifying two names is forbidden */ if (ctx->name) return invalfc(fc, "name respecified"); ctx->name = param->string; param->string = NULL; break; } return 0; }
334870785845210346899642963550735857549
cgroup-v1.c
43168048456517404384153301721017353964
CWE-416
CVE-2021-4154
A use-after-free flaw was found in cgroup1_parse_param in kernel/cgroup/cgroup-v1.c in the Linux kernel's cgroup v1 parser. A local attacker with a user privilege could cause a privilege escalation by exploiting the fsconfig syscall parameter leading to a container breakout and a denial of service on the system.
https://nvd.nist.gov/vuln/detail/CVE-2021-4154
213,998
libtpms
ea62fd9679f8c6fc5e79471b33cfbd8227bfed72
https://github.com/stefanberger/libtpms
https://github.com/stefanberger/libtpms/commit/ea62fd9679f8c6fc5e79471b33cfbd8227bfed72
tpm2: Initialize a whole OBJECT before using it Initialize a whole OBJECT before using it. This is necessary since an OBJECT may also be used as a HASH_OBJECT via the ANY_OBJECT union and that HASH_OBJECT can leave bad size inidicators in TPM2B buffer in the OBJECT. To get rid of this problem we reset the whole OBJECT to 0 before using it. This is as if the memory for the OBJECT was just initialized. Signed-off-by: Stefan Berger <[email protected]>
1
FindEmptyObjectSlot( TPMI_DH_OBJECT *handle // OUT: (optional) ) { UINT32 i; OBJECT *object; for(i = 0; i < MAX_LOADED_OBJECTS; i++) { object = &s_objects[i]; if(object->attributes.occupied == CLEAR) { if(handle) *handle = i + TRANSIENT_FIRST; // Initialize the object attributes MemorySet(&object->attributes, 0, sizeof(OBJECT_ATTRIBUTES)); return object; } } return NULL; }
267307307566893737550652048570735094605
Object.c
21721239087984404174741324804041111077
CWE-119
CVE-2021-3746
A flaw was found in the libtpms code that may cause access beyond the boundary of internal buffers. The vulnerability is triggered by specially-crafted TPM2 command packets that then trigger the issue when the state of the TPM2's volatile state is written. The highest threat from this vulnerability is to system availability. This issue affects libtpms versions before 0.8.5, before 0.7.9 and before 0.6.6.
https://nvd.nist.gov/vuln/detail/CVE-2021-3746
474,434
libtpms
ea62fd9679f8c6fc5e79471b33cfbd8227bfed72
https://github.com/stefanberger/libtpms
https://github.com/stefanberger/libtpms/commit/ea62fd9679f8c6fc5e79471b33cfbd8227bfed72
tpm2: Initialize a whole OBJECT before using it Initialize a whole OBJECT before using it. This is necessary since an OBJECT may also be used as a HASH_OBJECT via the ANY_OBJECT union and that HASH_OBJECT can leave bad size inidicators in TPM2B buffer in the OBJECT. To get rid of this problem we reset the whole OBJECT to 0 before using it. This is as if the memory for the OBJECT was just initialized. Signed-off-by: Stefan Berger <[email protected]>
0
FindEmptyObjectSlot( TPMI_DH_OBJECT *handle // OUT: (optional) ) { UINT32 i; OBJECT *object; for(i = 0; i < MAX_LOADED_OBJECTS; i++) { object = &s_objects[i]; if(object->attributes.occupied == CLEAR) { if(handle) *handle = i + TRANSIENT_FIRST; // Initialize the object attributes // MemorySet(&object->attributes, 0, sizeof(OBJECT_ATTRIBUTES)); MemorySet(object, 0, sizeof(*object)); // libtpms added: Initialize the whole object return object; } } return NULL; }
327698206124968939324347029407328822774
Object.c
122617348389867631937316179213551374827
CWE-119
CVE-2021-3746
A flaw was found in the libtpms code that may cause access beyond the boundary of internal buffers. The vulnerability is triggered by specially-crafted TPM2 command packets that then trigger the issue when the state of the TPM2's volatile state is written. The highest threat from this vulnerability is to system availability. This issue affects libtpms versions before 0.8.5, before 0.7.9 and before 0.6.6.
https://nvd.nist.gov/vuln/detail/CVE-2021-3746
214,003
libvncserver
7b1ef0ffc4815cab9a96c7278394152bdc89dc4d
https://github.com/LibVNC/libvncserver
https://github.com/LibVNC/libvncserver/commit/7b1ef0ffc4815cab9a96c7278394152bdc89dc4d
LibVNCClient: really fix #250
1
HandleCoRREBPP (rfbClient* client, int rx, int ry, int rw, int rh) { rfbRREHeader hdr; int i; CARDBPP pix; uint8_t *ptr; int x, y, w, h; if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbRREHeader)) return FALSE; hdr.nSubrects = rfbClientSwap32IfLE(hdr.nSubrects); if (!ReadFromRFBServer(client, (char *)&pix, sizeof(pix))) return FALSE; client->GotFillRect(client, rx, ry, rw, rh, pix); if (hdr.nSubrects * (4 + (BPP / 8)) > RFB_BUFFER_SIZE || !ReadFromRFBServer(client, client->buffer, hdr.nSubrects * (4 + (BPP / 8)))) return FALSE; ptr = (uint8_t *)client->buffer; for (i = 0; i < hdr.nSubrects; i++) { pix = *(CARDBPP *)ptr; ptr += BPP/8; x = *ptr++; y = *ptr++; w = *ptr++; h = *ptr++; client->GotFillRect(client, rx+x, ry+y, w, h, pix); } return TRUE; }
237803274447948071871623859823888407579
corre.c
261775603875912977761086457849276889433
CWE-787
CVE-2018-20020
LibVNC before commit 7b1ef0ffc4815cab9a96c7278394152bdc89dc4d contains heap out-of-bound write vulnerability inside structure in VNC client code that can result remote code execution
https://nvd.nist.gov/vuln/detail/CVE-2018-20020
474,462
libvncserver
7b1ef0ffc4815cab9a96c7278394152bdc89dc4d
https://github.com/LibVNC/libvncserver
https://github.com/LibVNC/libvncserver/commit/7b1ef0ffc4815cab9a96c7278394152bdc89dc4d
LibVNCClient: really fix #250
0
HandleCoRREBPP (rfbClient* client, int rx, int ry, int rw, int rh) { rfbRREHeader hdr; int i; CARDBPP pix; uint8_t *ptr; int x, y, w, h; if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbRREHeader)) return FALSE; hdr.nSubrects = rfbClientSwap32IfLE(hdr.nSubrects); if (!ReadFromRFBServer(client, (char *)&pix, sizeof(pix))) return FALSE; client->GotFillRect(client, rx, ry, rw, rh, pix); if (hdr.nSubrects > RFB_BUFFER_SIZE / (4 + (BPP / 8)) || !ReadFromRFBServer(client, client->buffer, hdr.nSubrects * (4 + (BPP / 8)))) return FALSE; ptr = (uint8_t *)client->buffer; for (i = 0; i < hdr.nSubrects; i++) { pix = *(CARDBPP *)ptr; ptr += BPP/8; x = *ptr++; y = *ptr++; w = *ptr++; h = *ptr++; client->GotFillRect(client, rx+x, ry+y, w, h, pix); } return TRUE; }
270120955611228778905999334086826608945
corre.c
95538594092483864981062945399271614171
CWE-787
CVE-2018-20020
LibVNC before commit 7b1ef0ffc4815cab9a96c7278394152bdc89dc4d contains heap out-of-bound write vulnerability inside structure in VNC client code that can result remote code execution
https://nvd.nist.gov/vuln/detail/CVE-2018-20020
214,124
chafa
e6ce3746cdcf0836b9dae659a5aed15d73a080d8
https://github.com/hpjansson/chafa
https://github.com/hpjansson/chafa/commit/e6ce3746cdcf0836b9dae659a5aed15d73a080d8
libnsgif: fix oob in lzw_decode
1
lzw_result lzw_decode(struct lzw_ctx *ctx, const uint8_t ** const stack_pos_out) { lzw_result res; uint32_t code_new; uint32_t code_out; uint8_t last_value; uint8_t *stack_pos = ctx->stack_base; uint32_t clear_code = ctx->clear_code; uint32_t current_entry = ctx->current_entry; struct lzw_dictionary_entry * const table = ctx->table; /* Get a new code from the input */ res = lzw__next_code(&ctx->input, ctx->current_code_size, &code_new); if (res != LZW_OK) { return res; } /* Handle the new code */ if (code_new == clear_code) { /* Got Clear code */ return lzw__clear_codes(ctx, stack_pos_out); } else if (code_new == ctx->eoi_code) { /* Got End of Information code */ return LZW_EOI_CODE; } else if (code_new > current_entry) { /* Code is invalid */ return LZW_BAD_CODE; } else if (code_new < current_entry) { /* Code is in table */ code_out = code_new; last_value = table[code_new].first_value; } else { /* Code not in table */ *stack_pos++ = ctx->previous_code_first; code_out = ctx->previous_code; last_value = ctx->previous_code_first; } /* Add to the dictionary, only if there's space */ if (current_entry < (1 << LZW_CODE_MAX)) { struct lzw_dictionary_entry *entry = table + current_entry; entry->last_value = last_value; entry->first_value = ctx->previous_code_first; entry->previous_entry = ctx->previous_code; ctx->current_entry++; } /* Ensure code size is increased, if needed. */ if (current_entry == ctx->current_code_size_max) { if (ctx->current_code_size < LZW_CODE_MAX) { ctx->current_code_size++; ctx->current_code_size_max = (1 << ctx->current_code_size) - 1; } } /* Store details of this code as "previous code" to the context. */ ctx->previous_code_first = table[code_new].first_value; ctx->previous_code = code_new; /* Put rest of data for this code on output stack. * Note, in the case of "code not in table", the last entry of the * current code has already been placed on the stack above. */ while (code_out > clear_code) { struct lzw_dictionary_entry *entry = table + code_out; *stack_pos++ = entry->last_value; code_out = entry->previous_entry; } *stack_pos++ = table[code_out].last_value; *stack_pos_out = stack_pos; return LZW_OK; }
197312030105469318680562726195282198881
lzw.c
206609516216923718063023254663769273017
CWE-125
CVE-2022-2061
Heap-based Buffer Overflow in GitHub repository hpjansson/chafa prior to 1.12.0.
https://nvd.nist.gov/vuln/detail/CVE-2022-2061
475,987
chafa
e6ce3746cdcf0836b9dae659a5aed15d73a080d8
https://github.com/hpjansson/chafa
https://github.com/hpjansson/chafa/commit/e6ce3746cdcf0836b9dae659a5aed15d73a080d8
libnsgif: fix oob in lzw_decode
0
lzw_result lzw_decode(struct lzw_ctx *ctx, const uint8_t ** const stack_pos_out) { lzw_result res; uint32_t code_new; uint32_t code_out; uint8_t last_value; uint8_t *stack_pos = ctx->stack_base; uint32_t clear_code = ctx->clear_code; uint32_t current_entry = ctx->current_entry; struct lzw_dictionary_entry * const table = ctx->table; /* Get a new code from the input */ res = lzw__next_code(&ctx->input, ctx->current_code_size, &code_new); if (res != LZW_OK) { return res; } /* Handle the new code */ if (code_new == clear_code) { /* Got Clear code */ return lzw__clear_codes(ctx, stack_pos_out); } else if (code_new == ctx->eoi_code) { /* Got End of Information code */ return LZW_EOI_CODE; } else if (code_new > current_entry) { /* Code is invalid */ return LZW_BAD_CODE; } else if (code_new >= 1 << LZW_CODE_MAX) { /* Don't access out of bound */ return LZW_BAD_CODE; } else if (code_new < current_entry) { /* Code is in table */ code_out = code_new; last_value = table[code_new].first_value; } else { /* Code not in table */ *stack_pos++ = ctx->previous_code_first; code_out = ctx->previous_code; last_value = ctx->previous_code_first; } /* Add to the dictionary, only if there's space */ if (current_entry < (1 << LZW_CODE_MAX)) { struct lzw_dictionary_entry *entry = table + current_entry; entry->last_value = last_value; entry->first_value = ctx->previous_code_first; entry->previous_entry = ctx->previous_code; ctx->current_entry++; } /* Ensure code size is increased, if needed. */ if (current_entry == ctx->current_code_size_max) { if (ctx->current_code_size < LZW_CODE_MAX) { ctx->current_code_size++; ctx->current_code_size_max = (1 << ctx->current_code_size) - 1; } } /* Store details of this code as "previous code" to the context. */ ctx->previous_code_first = table[code_new].first_value; ctx->previous_code = code_new; /* Put rest of data for this code on output stack. * Note, in the case of "code not in table", the last entry of the * current code has already been placed on the stack above. */ while (code_out > clear_code) { struct lzw_dictionary_entry *entry = table + code_out; *stack_pos++ = entry->last_value; code_out = entry->previous_entry; } *stack_pos++ = table[code_out].last_value; *stack_pos_out = stack_pos; return LZW_OK; }
232258018845507324994493987384082077230
lzw.c
168965779407481929590316655829608211083
CWE-125
CVE-2022-2061
Heap-based Buffer Overflow in GitHub repository hpjansson/chafa prior to 1.12.0.
https://nvd.nist.gov/vuln/detail/CVE-2022-2061
214,160
linux
75e5b4849b81e19e9efe1654b30d7f3151c33c2c
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/75e5b4849b81e19e9efe1654b30d7f3151c33c2c
USB: gadget: validate interface OS descriptor requests Stall the control endpoint in case provided index exceeds array size of MAX_CONFIG_INTERFACES or when the retrieved function pointer is null. Signed-off-by: Szymon Heidrich <[email protected]> Cc: [email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
1
composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) { struct usb_composite_dev *cdev = get_gadget_data(gadget); struct usb_request *req = cdev->req; int value = -EOPNOTSUPP; int status = 0; u16 w_index = le16_to_cpu(ctrl->wIndex); u8 intf = w_index & 0xFF; u16 w_value = le16_to_cpu(ctrl->wValue); u16 w_length = le16_to_cpu(ctrl->wLength); struct usb_function *f = NULL; u8 endp; if (w_length > USB_COMP_EP0_BUFSIZ) { if (ctrl->bRequestType & USB_DIR_IN) { /* Cast away the const, we are going to overwrite on purpose. */ __le16 *temp = (__le16 *)&ctrl->wLength; *temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ); w_length = USB_COMP_EP0_BUFSIZ; } else { goto done; } } /* partial re-init of the response message; the function or the * gadget might need to intercept e.g. a control-OUT completion * when we delegate to it. */ req->zero = 0; req->context = cdev; req->complete = composite_setup_complete; req->length = 0; gadget->ep0->driver_data = cdev; /* * Don't let non-standard requests match any of the cases below * by accident. */ if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD) goto unknown; switch (ctrl->bRequest) { /* we handle all standard USB descriptors */ case USB_REQ_GET_DESCRIPTOR: if (ctrl->bRequestType != USB_DIR_IN) goto unknown; switch (w_value >> 8) { case USB_DT_DEVICE: cdev->desc.bNumConfigurations = count_configs(cdev, USB_DT_DEVICE); cdev->desc.bMaxPacketSize0 = cdev->gadget->ep0->maxpacket; if (gadget_is_superspeed(gadget)) { if (gadget->speed >= USB_SPEED_SUPER) { cdev->desc.bcdUSB = cpu_to_le16(0x0320); cdev->desc.bMaxPacketSize0 = 9; } else { cdev->desc.bcdUSB = cpu_to_le16(0x0210); } } else { if (gadget->lpm_capable) cdev->desc.bcdUSB = cpu_to_le16(0x0201); else cdev->desc.bcdUSB = cpu_to_le16(0x0200); } value = min(w_length, (u16) sizeof cdev->desc); memcpy(req->buf, &cdev->desc, value); break; case USB_DT_DEVICE_QUALIFIER: if (!gadget_is_dualspeed(gadget) || gadget->speed >= USB_SPEED_SUPER) break; device_qual(cdev); value = min_t(int, w_length, sizeof(struct usb_qualifier_descriptor)); break; case USB_DT_OTHER_SPEED_CONFIG: if (!gadget_is_dualspeed(gadget) || gadget->speed >= USB_SPEED_SUPER) break; fallthrough; case USB_DT_CONFIG: value = config_desc(cdev, w_value); if (value >= 0) value = min(w_length, (u16) value); break; case USB_DT_STRING: value = get_string(cdev, req->buf, w_index, w_value & 0xff); if (value >= 0) value = min(w_length, (u16) value); break; case USB_DT_BOS: if (gadget_is_superspeed(gadget) || gadget->lpm_capable) { value = bos_desc(cdev); value = min(w_length, (u16) value); } break; case USB_DT_OTG: if (gadget_is_otg(gadget)) { struct usb_configuration *config; int otg_desc_len = 0; if (cdev->config) config = cdev->config; else config = list_first_entry( &cdev->configs, struct usb_configuration, list); if (!config) goto done; if (gadget->otg_caps && (gadget->otg_caps->otg_rev >= 0x0200)) otg_desc_len += sizeof( struct usb_otg20_descriptor); else otg_desc_len += sizeof( struct usb_otg_descriptor); value = min_t(int, w_length, otg_desc_len); memcpy(req->buf, config->descriptors[0], value); } break; } break; /* any number of configs can work */ case USB_REQ_SET_CONFIGURATION: if (ctrl->bRequestType != 0) goto unknown; if (gadget_is_otg(gadget)) { if (gadget->a_hnp_support) DBG(cdev, "HNP available\n"); else if (gadget->a_alt_hnp_support) DBG(cdev, "HNP on another port\n"); else VDBG(cdev, "HNP inactive\n"); } spin_lock(&cdev->lock); value = set_config(cdev, ctrl, w_value); spin_unlock(&cdev->lock); break; case USB_REQ_GET_CONFIGURATION: if (ctrl->bRequestType != USB_DIR_IN) goto unknown; if (cdev->config) *(u8 *)req->buf = cdev->config->bConfigurationValue; else *(u8 *)req->buf = 0; value = min(w_length, (u16) 1); break; /* function drivers must handle get/set altsetting */ case USB_REQ_SET_INTERFACE: if (ctrl->bRequestType != USB_RECIP_INTERFACE) goto unknown; if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; /* * If there's no get_alt() method, we know only altsetting zero * works. There is no need to check if set_alt() is not NULL * as we check this in usb_add_function(). */ if (w_value && !f->get_alt) break; spin_lock(&cdev->lock); value = f->set_alt(f, w_index, w_value); if (value == USB_GADGET_DELAYED_STATUS) { DBG(cdev, "%s: interface %d (%s) requested delayed status\n", __func__, intf, f->name); cdev->delayed_status++; DBG(cdev, "delayed_status count %d\n", cdev->delayed_status); } spin_unlock(&cdev->lock); break; case USB_REQ_GET_INTERFACE: if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)) goto unknown; if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; /* lots of interfaces only need altsetting zero... */ value = f->get_alt ? f->get_alt(f, w_index) : 0; if (value < 0) break; *((u8 *)req->buf) = value; value = min(w_length, (u16) 1); break; case USB_REQ_GET_STATUS: if (gadget_is_otg(gadget) && gadget->hnp_polling_support && (w_index == OTG_STS_SELECTOR)) { if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_DEVICE)) goto unknown; *((u8 *)req->buf) = gadget->host_request_flag; value = 1; break; } /* * USB 3.0 additions: * Function driver should handle get_status request. If such cb * wasn't supplied we respond with default value = 0 * Note: function driver should supply such cb only for the * first interface of the function */ if (!gadget_is_superspeed(gadget)) goto unknown; if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE)) goto unknown; value = 2; /* This is the length of the get_status reply */ put_unaligned_le16(0, req->buf); if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; status = f->get_status ? f->get_status(f) : 0; if (status < 0) break; put_unaligned_le16(status & 0x0000ffff, req->buf); break; /* * Function drivers should handle SetFeature/ClearFeature * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied * only for the first interface of the function */ case USB_REQ_CLEAR_FEATURE: case USB_REQ_SET_FEATURE: if (!gadget_is_superspeed(gadget)) goto unknown; if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE)) goto unknown; switch (w_value) { case USB_INTRF_FUNC_SUSPEND: if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; value = 0; if (f->func_suspend) value = f->func_suspend(f, w_index >> 8); if (value < 0) { ERROR(cdev, "func_suspend() returned error %d\n", value); value = 0; } break; } break; default: unknown: /* * OS descriptors handling */ if (cdev->use_os_string && cdev->os_desc_config && (ctrl->bRequestType & USB_TYPE_VENDOR) && ctrl->bRequest == cdev->b_vendor_code) { struct usb_configuration *os_desc_cfg; u8 *buf; int interface; int count = 0; req = cdev->os_desc_req; req->context = cdev; req->complete = composite_setup_complete; buf = req->buf; os_desc_cfg = cdev->os_desc_config; w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ); memset(buf, 0, w_length); buf[5] = 0x01; switch (ctrl->bRequestType & USB_RECIP_MASK) { case USB_RECIP_DEVICE: if (w_index != 0x4 || (w_value >> 8)) break; buf[6] = w_index; /* Number of ext compat interfaces */ count = count_ext_compat(os_desc_cfg); buf[8] = count; count *= 24; /* 24 B/ext compat desc */ count += 16; /* header */ put_unaligned_le32(count, buf); value = w_length; if (w_length > 0x10) { value = fill_ext_compat(os_desc_cfg, buf); value = min_t(u16, w_length, value); } break; case USB_RECIP_INTERFACE: if (w_index != 0x5 || (w_value >> 8)) break; interface = w_value & 0xFF; buf[6] = w_index; count = count_ext_prop(os_desc_cfg, interface); put_unaligned_le16(count, buf + 8); count = len_ext_prop(os_desc_cfg, interface); put_unaligned_le32(count, buf); value = w_length; if (w_length > 0x0A) { value = fill_ext_prop(os_desc_cfg, interface, buf); if (value >= 0) value = min_t(u16, w_length, value); } break; } goto check_value; } VDBG(cdev, "non-core control req%02x.%02x v%04x i%04x l%d\n", ctrl->bRequestType, ctrl->bRequest, w_value, w_index, w_length); /* functions always handle their interfaces and endpoints... * punt other recipients (other, WUSB, ...) to the current * configuration code. */ if (cdev->config) { list_for_each_entry(f, &cdev->config->functions, list) if (f->req_match && f->req_match(f, ctrl, false)) goto try_fun_setup; } else { struct usb_configuration *c; list_for_each_entry(c, &cdev->configs, list) list_for_each_entry(f, &c->functions, list) if (f->req_match && f->req_match(f, ctrl, true)) goto try_fun_setup; } f = NULL; switch (ctrl->bRequestType & USB_RECIP_MASK) { case USB_RECIP_INTERFACE: if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; break; case USB_RECIP_ENDPOINT: if (!cdev->config) break; endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f); list_for_each_entry(f, &cdev->config->functions, list) { if (test_bit(endp, f->endpoints)) break; } if (&f->list == &cdev->config->functions) f = NULL; break; } try_fun_setup: if (f && f->setup) value = f->setup(f, ctrl); else { struct usb_configuration *c; c = cdev->config; if (!c) goto done; /* try current config's setup */ if (c->setup) { value = c->setup(c, ctrl); goto done; } /* try the only function in the current config */ if (!list_is_singular(&c->functions)) goto done; f = list_first_entry(&c->functions, struct usb_function, list); if (f->setup) value = f->setup(f, ctrl); } goto done; } check_value: /* respond with data transfer before status phase? */ if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) { req->length = value; req->context = cdev; req->zero = value < w_length; value = composite_ep0_queue(cdev, req, GFP_ATOMIC); if (value < 0) { DBG(cdev, "ep_queue --> %d\n", value); req->status = 0; composite_setup_complete(gadget->ep0, req); } } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) { WARN(cdev, "%s: Delayed status not supported for w_length != 0", __func__); } done: /* device either stalls (value < 0) or reports success */ return value; }
303126640832251617876878392273862526744
composite.c
18887355761308803276229129312051135602
CWE-476
CVE-2022-25258
An issue was discovered in drivers/usb/gadget/composite.c in the Linux kernel before 5.16.10. The USB Gadget subsystem lacks certain validation of interface OS descriptor requests (ones with a large array index and ones associated with NULL function pointer retrieval). Memory corruption might occur.
https://nvd.nist.gov/vuln/detail/CVE-2022-25258
476,103
linux
75e5b4849b81e19e9efe1654b30d7f3151c33c2c
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/75e5b4849b81e19e9efe1654b30d7f3151c33c2c
USB: gadget: validate interface OS descriptor requests Stall the control endpoint in case provided index exceeds array size of MAX_CONFIG_INTERFACES or when the retrieved function pointer is null. Signed-off-by: Szymon Heidrich <[email protected]> Cc: [email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
0
composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) { struct usb_composite_dev *cdev = get_gadget_data(gadget); struct usb_request *req = cdev->req; int value = -EOPNOTSUPP; int status = 0; u16 w_index = le16_to_cpu(ctrl->wIndex); u8 intf = w_index & 0xFF; u16 w_value = le16_to_cpu(ctrl->wValue); u16 w_length = le16_to_cpu(ctrl->wLength); struct usb_function *f = NULL; u8 endp; if (w_length > USB_COMP_EP0_BUFSIZ) { if (ctrl->bRequestType & USB_DIR_IN) { /* Cast away the const, we are going to overwrite on purpose. */ __le16 *temp = (__le16 *)&ctrl->wLength; *temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ); w_length = USB_COMP_EP0_BUFSIZ; } else { goto done; } } /* partial re-init of the response message; the function or the * gadget might need to intercept e.g. a control-OUT completion * when we delegate to it. */ req->zero = 0; req->context = cdev; req->complete = composite_setup_complete; req->length = 0; gadget->ep0->driver_data = cdev; /* * Don't let non-standard requests match any of the cases below * by accident. */ if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD) goto unknown; switch (ctrl->bRequest) { /* we handle all standard USB descriptors */ case USB_REQ_GET_DESCRIPTOR: if (ctrl->bRequestType != USB_DIR_IN) goto unknown; switch (w_value >> 8) { case USB_DT_DEVICE: cdev->desc.bNumConfigurations = count_configs(cdev, USB_DT_DEVICE); cdev->desc.bMaxPacketSize0 = cdev->gadget->ep0->maxpacket; if (gadget_is_superspeed(gadget)) { if (gadget->speed >= USB_SPEED_SUPER) { cdev->desc.bcdUSB = cpu_to_le16(0x0320); cdev->desc.bMaxPacketSize0 = 9; } else { cdev->desc.bcdUSB = cpu_to_le16(0x0210); } } else { if (gadget->lpm_capable) cdev->desc.bcdUSB = cpu_to_le16(0x0201); else cdev->desc.bcdUSB = cpu_to_le16(0x0200); } value = min(w_length, (u16) sizeof cdev->desc); memcpy(req->buf, &cdev->desc, value); break; case USB_DT_DEVICE_QUALIFIER: if (!gadget_is_dualspeed(gadget) || gadget->speed >= USB_SPEED_SUPER) break; device_qual(cdev); value = min_t(int, w_length, sizeof(struct usb_qualifier_descriptor)); break; case USB_DT_OTHER_SPEED_CONFIG: if (!gadget_is_dualspeed(gadget) || gadget->speed >= USB_SPEED_SUPER) break; fallthrough; case USB_DT_CONFIG: value = config_desc(cdev, w_value); if (value >= 0) value = min(w_length, (u16) value); break; case USB_DT_STRING: value = get_string(cdev, req->buf, w_index, w_value & 0xff); if (value >= 0) value = min(w_length, (u16) value); break; case USB_DT_BOS: if (gadget_is_superspeed(gadget) || gadget->lpm_capable) { value = bos_desc(cdev); value = min(w_length, (u16) value); } break; case USB_DT_OTG: if (gadget_is_otg(gadget)) { struct usb_configuration *config; int otg_desc_len = 0; if (cdev->config) config = cdev->config; else config = list_first_entry( &cdev->configs, struct usb_configuration, list); if (!config) goto done; if (gadget->otg_caps && (gadget->otg_caps->otg_rev >= 0x0200)) otg_desc_len += sizeof( struct usb_otg20_descriptor); else otg_desc_len += sizeof( struct usb_otg_descriptor); value = min_t(int, w_length, otg_desc_len); memcpy(req->buf, config->descriptors[0], value); } break; } break; /* any number of configs can work */ case USB_REQ_SET_CONFIGURATION: if (ctrl->bRequestType != 0) goto unknown; if (gadget_is_otg(gadget)) { if (gadget->a_hnp_support) DBG(cdev, "HNP available\n"); else if (gadget->a_alt_hnp_support) DBG(cdev, "HNP on another port\n"); else VDBG(cdev, "HNP inactive\n"); } spin_lock(&cdev->lock); value = set_config(cdev, ctrl, w_value); spin_unlock(&cdev->lock); break; case USB_REQ_GET_CONFIGURATION: if (ctrl->bRequestType != USB_DIR_IN) goto unknown; if (cdev->config) *(u8 *)req->buf = cdev->config->bConfigurationValue; else *(u8 *)req->buf = 0; value = min(w_length, (u16) 1); break; /* function drivers must handle get/set altsetting */ case USB_REQ_SET_INTERFACE: if (ctrl->bRequestType != USB_RECIP_INTERFACE) goto unknown; if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; /* * If there's no get_alt() method, we know only altsetting zero * works. There is no need to check if set_alt() is not NULL * as we check this in usb_add_function(). */ if (w_value && !f->get_alt) break; spin_lock(&cdev->lock); value = f->set_alt(f, w_index, w_value); if (value == USB_GADGET_DELAYED_STATUS) { DBG(cdev, "%s: interface %d (%s) requested delayed status\n", __func__, intf, f->name); cdev->delayed_status++; DBG(cdev, "delayed_status count %d\n", cdev->delayed_status); } spin_unlock(&cdev->lock); break; case USB_REQ_GET_INTERFACE: if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)) goto unknown; if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; /* lots of interfaces only need altsetting zero... */ value = f->get_alt ? f->get_alt(f, w_index) : 0; if (value < 0) break; *((u8 *)req->buf) = value; value = min(w_length, (u16) 1); break; case USB_REQ_GET_STATUS: if (gadget_is_otg(gadget) && gadget->hnp_polling_support && (w_index == OTG_STS_SELECTOR)) { if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_DEVICE)) goto unknown; *((u8 *)req->buf) = gadget->host_request_flag; value = 1; break; } /* * USB 3.0 additions: * Function driver should handle get_status request. If such cb * wasn't supplied we respond with default value = 0 * Note: function driver should supply such cb only for the * first interface of the function */ if (!gadget_is_superspeed(gadget)) goto unknown; if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE)) goto unknown; value = 2; /* This is the length of the get_status reply */ put_unaligned_le16(0, req->buf); if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; status = f->get_status ? f->get_status(f) : 0; if (status < 0) break; put_unaligned_le16(status & 0x0000ffff, req->buf); break; /* * Function drivers should handle SetFeature/ClearFeature * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied * only for the first interface of the function */ case USB_REQ_CLEAR_FEATURE: case USB_REQ_SET_FEATURE: if (!gadget_is_superspeed(gadget)) goto unknown; if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE)) goto unknown; switch (w_value) { case USB_INTRF_FUNC_SUSPEND: if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; value = 0; if (f->func_suspend) value = f->func_suspend(f, w_index >> 8); if (value < 0) { ERROR(cdev, "func_suspend() returned error %d\n", value); value = 0; } break; } break; default: unknown: /* * OS descriptors handling */ if (cdev->use_os_string && cdev->os_desc_config && (ctrl->bRequestType & USB_TYPE_VENDOR) && ctrl->bRequest == cdev->b_vendor_code) { struct usb_configuration *os_desc_cfg; u8 *buf; int interface; int count = 0; req = cdev->os_desc_req; req->context = cdev; req->complete = composite_setup_complete; buf = req->buf; os_desc_cfg = cdev->os_desc_config; w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ); memset(buf, 0, w_length); buf[5] = 0x01; switch (ctrl->bRequestType & USB_RECIP_MASK) { case USB_RECIP_DEVICE: if (w_index != 0x4 || (w_value >> 8)) break; buf[6] = w_index; /* Number of ext compat interfaces */ count = count_ext_compat(os_desc_cfg); buf[8] = count; count *= 24; /* 24 B/ext compat desc */ count += 16; /* header */ put_unaligned_le32(count, buf); value = w_length; if (w_length > 0x10) { value = fill_ext_compat(os_desc_cfg, buf); value = min_t(u16, w_length, value); } break; case USB_RECIP_INTERFACE: if (w_index != 0x5 || (w_value >> 8)) break; interface = w_value & 0xFF; if (interface >= MAX_CONFIG_INTERFACES || !os_desc_cfg->interface[interface]) break; buf[6] = w_index; count = count_ext_prop(os_desc_cfg, interface); put_unaligned_le16(count, buf + 8); count = len_ext_prop(os_desc_cfg, interface); put_unaligned_le32(count, buf); value = w_length; if (w_length > 0x0A) { value = fill_ext_prop(os_desc_cfg, interface, buf); if (value >= 0) value = min_t(u16, w_length, value); } break; } goto check_value; } VDBG(cdev, "non-core control req%02x.%02x v%04x i%04x l%d\n", ctrl->bRequestType, ctrl->bRequest, w_value, w_index, w_length); /* functions always handle their interfaces and endpoints... * punt other recipients (other, WUSB, ...) to the current * configuration code. */ if (cdev->config) { list_for_each_entry(f, &cdev->config->functions, list) if (f->req_match && f->req_match(f, ctrl, false)) goto try_fun_setup; } else { struct usb_configuration *c; list_for_each_entry(c, &cdev->configs, list) list_for_each_entry(f, &c->functions, list) if (f->req_match && f->req_match(f, ctrl, true)) goto try_fun_setup; } f = NULL; switch (ctrl->bRequestType & USB_RECIP_MASK) { case USB_RECIP_INTERFACE: if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; break; case USB_RECIP_ENDPOINT: if (!cdev->config) break; endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f); list_for_each_entry(f, &cdev->config->functions, list) { if (test_bit(endp, f->endpoints)) break; } if (&f->list == &cdev->config->functions) f = NULL; break; } try_fun_setup: if (f && f->setup) value = f->setup(f, ctrl); else { struct usb_configuration *c; c = cdev->config; if (!c) goto done; /* try current config's setup */ if (c->setup) { value = c->setup(c, ctrl); goto done; } /* try the only function in the current config */ if (!list_is_singular(&c->functions)) goto done; f = list_first_entry(&c->functions, struct usb_function, list); if (f->setup) value = f->setup(f, ctrl); } goto done; } check_value: /* respond with data transfer before status phase? */ if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) { req->length = value; req->context = cdev; req->zero = value < w_length; value = composite_ep0_queue(cdev, req, GFP_ATOMIC); if (value < 0) { DBG(cdev, "ep_queue --> %d\n", value); req->status = 0; composite_setup_complete(gadget->ep0, req); } } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) { WARN(cdev, "%s: Delayed status not supported for w_length != 0", __func__); } done: /* device either stalls (value < 0) or reports success */ return value; }
150169819708721543824384188358095206836
composite.c
106311505474453071070186160185104780414
CWE-476
CVE-2022-25258
An issue was discovered in drivers/usb/gadget/composite.c in the Linux kernel before 5.16.10. The USB Gadget subsystem lacks certain validation of interface OS descriptor requests (ones with a large array index and ones associated with NULL function pointer retrieval). Memory corruption might occur.
https://nvd.nist.gov/vuln/detail/CVE-2022-25258
214,276
linux
fa40d9734a57bcbfa79a280189799f76c88f7bb0
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/fa40d9734a57bcbfa79a280189799f76c88f7bb0
tipc: fix size validations for the MSG_CRYPTO type The function tipc_crypto_key_rcv is used to parse MSG_CRYPTO messages to receive keys from other nodes in the cluster in order to decrypt any further messages from them. This patch verifies that any supplied sizes in the message body are valid for the received message. Fixes: 1ef6f7c9390f ("tipc: add automatic session key exchange") Signed-off-by: Max VA <[email protected]> Acked-by: Ying Xue <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> Acked-by: Jon Maloy <[email protected]> Signed-off-by: David S. Miller <[email protected]>
1
static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr) { struct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx; struct tipc_aead_key *skey = NULL; u16 key_gen = msg_key_gen(hdr); u16 size = msg_data_sz(hdr); u8 *data = msg_data(hdr); spin_lock(&rx->lock); if (unlikely(rx->skey || (key_gen == rx->key_gen && rx->key.keys))) { pr_err("%s: key existed <%p>, gen %d vs %d\n", rx->name, rx->skey, key_gen, rx->key_gen); goto exit; } /* Allocate memory for the key */ skey = kmalloc(size, GFP_ATOMIC); if (unlikely(!skey)) { pr_err("%s: unable to allocate memory for skey\n", rx->name); goto exit; } /* Copy key from msg data */ skey->keylen = ntohl(*((__be32 *)(data + TIPC_AEAD_ALG_NAME))); memcpy(skey->alg_name, data, TIPC_AEAD_ALG_NAME); memcpy(skey->key, data + TIPC_AEAD_ALG_NAME + sizeof(__be32), skey->keylen); /* Sanity check */ if (unlikely(size != tipc_aead_key_size(skey))) { kfree(skey); skey = NULL; goto exit; } rx->key_gen = key_gen; rx->skey_mode = msg_key_mode(hdr); rx->skey = skey; rx->nokey = 0; mb(); /* for nokey flag */ exit: spin_unlock(&rx->lock); /* Schedule the key attaching on this crypto */ if (likely(skey && queue_delayed_work(tx->wq, &rx->work, 0))) return true; return false; }
150450145750082729683403565650901445106
crypto.c
58733917967082493268842355411939930161
CWE-20
CVE-2021-43267
An issue was discovered in net/tipc/crypto.c in the Linux kernel before 5.14.16. The Transparent Inter-Process Communication (TIPC) functionality allows remote attackers to exploit insufficient validation of user-supplied sizes for the MSG_CRYPTO message type.
https://nvd.nist.gov/vuln/detail/CVE-2021-43267
477,273
linux
fa40d9734a57bcbfa79a280189799f76c88f7bb0
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/fa40d9734a57bcbfa79a280189799f76c88f7bb0
tipc: fix size validations for the MSG_CRYPTO type The function tipc_crypto_key_rcv is used to parse MSG_CRYPTO messages to receive keys from other nodes in the cluster in order to decrypt any further messages from them. This patch verifies that any supplied sizes in the message body are valid for the received message. Fixes: 1ef6f7c9390f ("tipc: add automatic session key exchange") Signed-off-by: Max VA <[email protected]> Acked-by: Ying Xue <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> Acked-by: Jon Maloy <[email protected]> Signed-off-by: David S. Miller <[email protected]>
0
static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr) { struct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx; struct tipc_aead_key *skey = NULL; u16 key_gen = msg_key_gen(hdr); u16 size = msg_data_sz(hdr); u8 *data = msg_data(hdr); unsigned int keylen; /* Verify whether the size can exist in the packet */ if (unlikely(size < sizeof(struct tipc_aead_key) + TIPC_AEAD_KEYLEN_MIN)) { pr_debug("%s: message data size is too small\n", rx->name); goto exit; } keylen = ntohl(*((__be32 *)(data + TIPC_AEAD_ALG_NAME))); /* Verify the supplied size values */ if (unlikely(size != keylen + sizeof(struct tipc_aead_key) || keylen > TIPC_AEAD_KEY_SIZE_MAX)) { pr_debug("%s: invalid MSG_CRYPTO key size\n", rx->name); goto exit; } spin_lock(&rx->lock); if (unlikely(rx->skey || (key_gen == rx->key_gen && rx->key.keys))) { pr_err("%s: key existed <%p>, gen %d vs %d\n", rx->name, rx->skey, key_gen, rx->key_gen); goto exit_unlock; } /* Allocate memory for the key */ skey = kmalloc(size, GFP_ATOMIC); if (unlikely(!skey)) { pr_err("%s: unable to allocate memory for skey\n", rx->name); goto exit_unlock; } /* Copy key from msg data */ skey->keylen = keylen; memcpy(skey->alg_name, data, TIPC_AEAD_ALG_NAME); memcpy(skey->key, data + TIPC_AEAD_ALG_NAME + sizeof(__be32), skey->keylen); rx->key_gen = key_gen; rx->skey_mode = msg_key_mode(hdr); rx->skey = skey; rx->nokey = 0; mb(); /* for nokey flag */ exit_unlock: spin_unlock(&rx->lock); exit: /* Schedule the key attaching on this crypto */ if (likely(skey && queue_delayed_work(tx->wq, &rx->work, 0))) return true; return false; }
21444025468428283247999063273803236471
crypto.c
97644738698722030133364122587095840919
CWE-20
CVE-2021-43267
An issue was discovered in net/tipc/crypto.c in the Linux kernel before 5.14.16. The Transparent Inter-Process Communication (TIPC) functionality allows remote attackers to exploit insufficient validation of user-supplied sizes for the MSG_CRYPTO message type.
https://nvd.nist.gov/vuln/detail/CVE-2021-43267
214,282
radare2
9650e3c352f675687bf6c6f65ff2c4a3d0e288fa
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/9650e3c352f675687bf6c6f65ff2c4a3d0e288fa
Fix oobread segfault in java arith8.class ##crash * Reported by Cen Zhang via huntr.dev
1
R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { RBinJavaClassesAttribute *icattr; RBinJavaAttrInfo *attr = NULL; RBinJavaCPTypeObj *obj; ut32 i = 0; ut64 offset = 0, curpos; attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (attr == NULL) { // TODO eprintf return attr; } attr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR; attr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free); for (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) { curpos = buf_offset + offset; if (offset + 8 > sz) { eprintf ("Invalid amount of inner classes\n"); break; } icattr = R_NEW0 (RBinJavaClassesAttribute); if (!icattr) { break; } icattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags); icattr->file_offset = curpos; icattr->size = 8; obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx); if (obj == NULL) { eprintf ("BINCPLIS IS HULL %d\n", icattr->inner_name_idx); } icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj); if (!icattr->name) { obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx); if (!obj) { eprintf ("BINCPLIST IS NULL %d\n", icattr->inner_class_info_idx); } icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj); if (!icattr->name) { icattr->name = r_str_dup (NULL, "NULL"); eprintf ("r_bin_java_inner_classes_attr: Unable to find the name for %d index.\n", icattr->inner_name_idx); free (icattr); break; } } IFDBG eprintf("r_bin_java_inner_classes_attr: Inner class name %d is %s.\n", icattr->inner_name_idx, icattr->name); r_list_append (attr->info.inner_classes_attr.classes, (void *) icattr); } attr->size = offset; // IFDBG r_bin_java_print_inner_classes_attr_summary(attr); return attr; }
64487889579921550880626488390413278294
None
CWE-787
CVE-2022-0518
Heap-based Buffer Overflow in GitHub repository radareorg/radare2 prior to 5.6.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0518
477,380
radare2
9650e3c352f675687bf6c6f65ff2c4a3d0e288fa
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/9650e3c352f675687bf6c6f65ff2c4a3d0e288fa
Fix oobread segfault in java arith8.class ##crash * Reported by Cen Zhang via huntr.dev
0
R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { RBinJavaClassesAttribute *icattr; RBinJavaAttrInfo *attr = NULL; RBinJavaCPTypeObj *obj; ut32 i = 0; ut64 offset = 0, curpos; attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (buf_offset + offset + 8 > sz) { eprintf ("Invalid amount of inner classes\n"); return NULL; } if (attr == NULL) { // TODO eprintf return attr; } attr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR; attr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free); for (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) { curpos = buf_offset + offset; if (buf_offset + offset + 8 > sz) { eprintf ("Invalid amount of inner classes\n"); break; } icattr = R_NEW0 (RBinJavaClassesAttribute); if (!icattr) { break; } icattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; icattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags); icattr->file_offset = curpos; icattr->size = 8; obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx); if (obj == NULL) { eprintf ("BINCPLIS IS HULL %d\n", icattr->inner_name_idx); } icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj); if (!icattr->name) { obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx); if (!obj) { eprintf ("BINCPLIST IS NULL %d\n", icattr->inner_class_info_idx); } icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj); if (!icattr->name) { icattr->name = r_str_dup (NULL, "NULL"); eprintf ("r_bin_java_inner_classes_attr: Unable to find the name for %d index.\n", icattr->inner_name_idx); free (icattr); break; } } IFDBG eprintf("r_bin_java_inner_classes_attr: Inner class name %d is %s.\n", icattr->inner_name_idx, icattr->name); r_list_append (attr->info.inner_classes_attr.classes, (void *) icattr); } attr->size = offset; // IFDBG r_bin_java_print_inner_classes_attr_summary(attr); return attr; }
64877756474443733674480622739162380352
None
CWE-787
CVE-2022-0518
Heap-based Buffer Overflow in GitHub repository radareorg/radare2 prior to 5.6.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0518
214,335
ceph
be7679007c3dfab3e19c22c38c36ccac91828e3b
https://github.com/ceph/ceph
https://github.com/ceph/ceph/commit/be7679007c3dfab3e19c22c38c36ccac91828e3b
rgw: reject control characters in response-header actions S3 GetObject permits overriding response header values, but those inputs need to be validated to insure only characters that are valid in an HTTP header value are present. Credit: Initial vulnerability discovery by William Bowling (@wcbowling) Credit: Further vulnerability discovery by Robin H. Johnson <[email protected]> Signed-off-by: Robin H. Johnson <[email protected]>
1
int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; string expires = get_s3_expiration_header(s, lastmod); if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); dump_header_if_nonempty(s, "x-amz-expiration", expires); if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) { dump_header(s, "x-rgw-object-type", "Appendable"); dump_header(s, "x-rgw-next-append-position", s->obj_size); } else { dump_header(s, "x-rgw-object-type", "Normal"); } if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { /* reject unauthenticated response header manipulation, see * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */ if (s->auth.identity->is_anonymous()) { return -ERR_INVALID_REQUEST; } if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ size_t len = iter->second.length(); string s(iter->second.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } response_attrs[aiter->second] = s; } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type_str = rgw_bl_str(iter->second); content_type = content_type_str.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ auto it = iter->second.cbegin(); obj_tags.decode(it); } catch (buffer::error &err) { ldpp_dout(this,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){ RGWObjectRetention retention; try { decode(retention, iter->second); dump_header(s, "x-amz-object-lock-mode", retention.get_mode()); dump_time_header(s, "x-amz-object-lock-retain-until-date", retention.get_retain_until_date()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl; } } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) { RGWObjectLegalHold legal_hold; try { decode(legal_hold, iter->second); dump_header(s, "x-amz-object-lock-legal-hold",legal_hold.get_status()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl; } } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; }
252320959275346519647300715417843120718
rgw_rest_s3.cc
121704064633287557349192949015382644860
CWE-79
CVE-2020-1760
A flaw was found in the Ceph Object Gateway, where it supports request sent by an anonymous user in Amazon S3. This flaw could lead to potential XSS attacks due to the lack of proper neutralization of untrusted input.
https://nvd.nist.gov/vuln/detail/CVE-2020-1760
477,800
ceph
be7679007c3dfab3e19c22c38c36ccac91828e3b
https://github.com/ceph/ceph
https://github.com/ceph/ceph/commit/be7679007c3dfab3e19c22c38c36ccac91828e3b
rgw: reject control characters in response-header actions S3 GetObject permits overriding response header values, but those inputs need to be validated to insure only characters that are valid in an HTTP header value are present. Credit: Initial vulnerability discovery by William Bowling (@wcbowling) Credit: Further vulnerability discovery by Robin H. Johnson <[email protected]> Signed-off-by: Robin H. Johnson <[email protected]>
0
int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; string expires = get_s3_expiration_header(s, lastmod); if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); dump_header_if_nonempty(s, "x-amz-expiration", expires); if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) { dump_header(s, "x-rgw-object-type", "Appendable"); dump_header(s, "x-rgw-next-append-position", s->obj_size); } else { dump_header(s, "x-rgw-object-type", "Normal"); } if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { /* reject unauthenticated response header manipulation, see * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */ if (s->auth.identity->is_anonymous()) { return -ERR_INVALID_REQUEST; } /* HTTP specification says no control characters should be present in * header values: https://tools.ietf.org/html/rfc7230#section-3.2 * field-vchar = VCHAR / obs-text * * Failure to validate this permits a CRLF injection in HTTP headers, * whereas S3 GetObject only permits specific headers. */ if(str_has_cntrl(val)) { /* TODO: return a more distinct error in future; * stating what the problem is */ return -ERR_INVALID_REQUEST; } if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ size_t len = iter->second.length(); string s(iter->second.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } response_attrs[aiter->second] = s; } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type_str = rgw_bl_str(iter->second); content_type = content_type_str.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ auto it = iter->second.cbegin(); obj_tags.decode(it); } catch (buffer::error &err) { ldpp_dout(this,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){ RGWObjectRetention retention; try { decode(retention, iter->second); dump_header(s, "x-amz-object-lock-mode", retention.get_mode()); dump_time_header(s, "x-amz-object-lock-retain-until-date", retention.get_retain_until_date()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl; } } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) { RGWObjectLegalHold legal_hold; try { decode(legal_hold, iter->second); dump_header(s, "x-amz-object-lock-legal-hold",legal_hold.get_status()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl; } } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; }
262581748288231212684344001949485433363
rgw_rest_s3.cc
18601801279536370570230302891439737230
CWE-79
CVE-2020-1760
A flaw was found in the Ceph Object Gateway, where it supports request sent by an anonymous user in Amazon S3. This flaw could lead to potential XSS attacks due to the lack of proper neutralization of untrusted input.
https://nvd.nist.gov/vuln/detail/CVE-2020-1760
214,336
linux
ba953a9d89a00c078b85f4b190bc1dde66fe16b5
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/ba953a9d89a00c078b85f4b190bc1dde66fe16b5
af_key: Do not call xfrm_probe_algs in parallel When namespace support was added to xfrm/afkey, it caused the previously single-threaded call to xfrm_probe_algs to become multi-threaded. This is buggy and needs to be fixed with a mutex. Reported-by: Abhishek Shah <[email protected]> Fixes: 283bc9f35bbb ("xfrm: Namespacify xfrm state/policy locks") Signed-off-by: Herbert Xu <[email protected]> Signed-off-by: Steffen Klassert <[email protected]>
1
static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *supp_skb; if (hdr->sadb_msg_satype > SADB_SATYPE_MAX) return -EINVAL; if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) { if (pfk->registered&(1<<hdr->sadb_msg_satype)) return -EEXIST; pfk->registered |= (1<<hdr->sadb_msg_satype); } xfrm_probe_algs(); supp_skb = compose_sadb_supported(hdr, GFP_KERNEL | __GFP_ZERO); if (!supp_skb) { if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) pfk->registered &= ~(1<<hdr->sadb_msg_satype); return -ENOBUFS; } pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk)); return 0; }
31330987608984194197058225349266288841
af_key.c
41141499114881598479952301810943667867
CWE-362
CVE-2022-3028
A race condition was found in the Linux kernel's IP framework for transforming packets (XFRM subsystem) when multiple calls to xfrm_probe_algs occurred simultaneously. This flaw could allow a local attacker to potentially trigger an out-of-bounds write or leak kernel heap memory by performing an out-of-bounds read and copying it into a socket.
https://nvd.nist.gov/vuln/detail/CVE-2022-3028
477,803
linux
ba953a9d89a00c078b85f4b190bc1dde66fe16b5
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/ba953a9d89a00c078b85f4b190bc1dde66fe16b5
af_key: Do not call xfrm_probe_algs in parallel When namespace support was added to xfrm/afkey, it caused the previously single-threaded call to xfrm_probe_algs to become multi-threaded. This is buggy and needs to be fixed with a mutex. Reported-by: Abhishek Shah <[email protected]> Fixes: 283bc9f35bbb ("xfrm: Namespacify xfrm state/policy locks") Signed-off-by: Herbert Xu <[email protected]> Signed-off-by: Steffen Klassert <[email protected]>
0
static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *supp_skb; if (hdr->sadb_msg_satype > SADB_SATYPE_MAX) return -EINVAL; if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) { if (pfk->registered&(1<<hdr->sadb_msg_satype)) return -EEXIST; pfk->registered |= (1<<hdr->sadb_msg_satype); } mutex_lock(&pfkey_mutex); xfrm_probe_algs(); supp_skb = compose_sadb_supported(hdr, GFP_KERNEL | __GFP_ZERO); mutex_unlock(&pfkey_mutex); if (!supp_skb) { if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) pfk->registered &= ~(1<<hdr->sadb_msg_satype); return -ENOBUFS; } pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk)); return 0; }
267484480773860224509939208990668486476
af_key.c
320308785060277331715018929148947306218
CWE-362
CVE-2022-3028
A race condition was found in the Linux kernel's IP framework for transforming packets (XFRM subsystem) when multiple calls to xfrm_probe_algs occurred simultaneously. This flaw could allow a local attacker to potentially trigger an out-of-bounds write or leak kernel heap memory by performing an out-of-bounds read and copying it into a socket.
https://nvd.nist.gov/vuln/detail/CVE-2022-3028
214,339
linux
f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a
https://github.com/torvalds/linux
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a
KVM: PPC: Book3S: Fix H_RTAS rets buffer overflow The kvmppc_rtas_hcall() sets the host rtas_args.rets pointer based on the rtas_args.nargs that was provided by the guest. That guest nargs value is not range checked, so the guest can cause the host rets pointer to be pointed outside the args array. The individual rtas function handlers check the nargs and nrets values to ensure they are correct, but if they are not, the handlers store a -3 (0xfffffffd) failure indication in rets[0] which corrupts host memory. Fix this by testing up front whether the guest supplied nargs and nret would exceed the array size, and fail the hcall directly without storing a failure indication to rets[0]. Also expand on a comment about why we kill the guest and try not to return errors directly if we have a valid rets[0] pointer. Fixes: 8e591cb72047 ("KVM: PPC: Book3S: Add infrastructure to implement kernel-side RTAS calls") Cc: [email protected] # v3.10+ Reported-by: Alexey Kardashevskiy <[email protected]> Signed-off-by: Nicholas Piggin <[email protected]> Signed-off-by: Michael Ellerman <[email protected]>
1
int kvmppc_rtas_hcall(struct kvm_vcpu *vcpu) { struct rtas_token_definition *d; struct rtas_args args; rtas_arg_t *orig_rets; gpa_t args_phys; int rc; /* * r4 contains the guest physical address of the RTAS args * Mask off the top 4 bits since this is a guest real address */ args_phys = kvmppc_get_gpr(vcpu, 4) & KVM_PAM; vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu); rc = kvm_read_guest(vcpu->kvm, args_phys, &args, sizeof(args)); srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx); if (rc) goto fail; /* * args->rets is a pointer into args->args. Now that we've * copied args we need to fix it up to point into our copy, * not the guest args. We also need to save the original * value so we can restore it on the way out. */ orig_rets = args.rets; args.rets = &args.args[be32_to_cpu(args.nargs)]; mutex_lock(&vcpu->kvm->arch.rtas_token_lock); rc = -ENOENT; list_for_each_entry(d, &vcpu->kvm->arch.rtas_tokens, list) { if (d->token == be32_to_cpu(args.token)) { d->handler->handler(vcpu, &args); rc = 0; break; } } mutex_unlock(&vcpu->kvm->arch.rtas_token_lock); if (rc == 0) { args.rets = orig_rets; rc = kvm_write_guest(vcpu->kvm, args_phys, &args, sizeof(args)); if (rc) goto fail; } return rc; fail: /* * We only get here if the guest has called RTAS with a bogus * args pointer. That means we can't get to the args, and so we * can't fail the RTAS call. So fail right out to userspace, * which should kill the guest. */ return rc; }
66579788869283176691450230454774242085
book3s_rtas.c
244969410022637408362665450874858593503
CWE-787
CVE-2021-37576
arch/powerpc/kvm/book3s_rtas.c in the Linux kernel through 5.13.5 on the powerpc platform allows KVM guest OS users to cause host OS memory corruption via rtas_args.nargs, aka CID-f62f3c20647e.
https://nvd.nist.gov/vuln/detail/CVE-2021-37576
477,811
linux
f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a
https://github.com/torvalds/linux
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a
KVM: PPC: Book3S: Fix H_RTAS rets buffer overflow The kvmppc_rtas_hcall() sets the host rtas_args.rets pointer based on the rtas_args.nargs that was provided by the guest. That guest nargs value is not range checked, so the guest can cause the host rets pointer to be pointed outside the args array. The individual rtas function handlers check the nargs and nrets values to ensure they are correct, but if they are not, the handlers store a -3 (0xfffffffd) failure indication in rets[0] which corrupts host memory. Fix this by testing up front whether the guest supplied nargs and nret would exceed the array size, and fail the hcall directly without storing a failure indication to rets[0]. Also expand on a comment about why we kill the guest and try not to return errors directly if we have a valid rets[0] pointer. Fixes: 8e591cb72047 ("KVM: PPC: Book3S: Add infrastructure to implement kernel-side RTAS calls") Cc: [email protected] # v3.10+ Reported-by: Alexey Kardashevskiy <[email protected]> Signed-off-by: Nicholas Piggin <[email protected]> Signed-off-by: Michael Ellerman <[email protected]>
0
int kvmppc_rtas_hcall(struct kvm_vcpu *vcpu) { struct rtas_token_definition *d; struct rtas_args args; rtas_arg_t *orig_rets; gpa_t args_phys; int rc; /* * r4 contains the guest physical address of the RTAS args * Mask off the top 4 bits since this is a guest real address */ args_phys = kvmppc_get_gpr(vcpu, 4) & KVM_PAM; vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu); rc = kvm_read_guest(vcpu->kvm, args_phys, &args, sizeof(args)); srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx); if (rc) goto fail; /* * args->rets is a pointer into args->args. Now that we've * copied args we need to fix it up to point into our copy, * not the guest args. We also need to save the original * value so we can restore it on the way out. */ orig_rets = args.rets; if (be32_to_cpu(args.nargs) >= ARRAY_SIZE(args.args)) { /* * Don't overflow our args array: ensure there is room for * at least rets[0] (even if the call specifies 0 nret). * * Each handler must then check for the correct nargs and nret * values, but they may always return failure in rets[0]. */ rc = -EINVAL; goto fail; } args.rets = &args.args[be32_to_cpu(args.nargs)]; mutex_lock(&vcpu->kvm->arch.rtas_token_lock); rc = -ENOENT; list_for_each_entry(d, &vcpu->kvm->arch.rtas_tokens, list) { if (d->token == be32_to_cpu(args.token)) { d->handler->handler(vcpu, &args); rc = 0; break; } } mutex_unlock(&vcpu->kvm->arch.rtas_token_lock); if (rc == 0) { args.rets = orig_rets; rc = kvm_write_guest(vcpu->kvm, args_phys, &args, sizeof(args)); if (rc) goto fail; } return rc; fail: /* * We only get here if the guest has called RTAS with a bogus * args pointer or nargs/nret values that would overflow the * array. That means we can't get to the args, and so we can't * fail the RTAS call. So fail right out to userspace, which * should kill the guest. * * SLOF should actually pass the hcall return value from the * rtas handler call in r3, so enter_rtas could be modified to * return a failure indication in r3 and we could return such * errors to the guest rather than failing to host userspace. * However old guests that don't test for failure could then * continue silently after errors, so for now we won't do this. */ return rc; }
270253933279643819807414798855847113264
book3s_rtas.c
244634684304024017969354424959522055540
CWE-787
CVE-2021-37576
arch/powerpc/kvm/book3s_rtas.c in the Linux kernel through 5.13.5 on the powerpc platform allows KVM guest OS users to cause host OS memory corruption via rtas_args.nargs, aka CID-f62f3c20647e.
https://nvd.nist.gov/vuln/detail/CVE-2021-37576
214,358
clamav-devel
224fee54dd6cd8933d7007331ec2bfca0398d4b4
https://github.com/vrtadmin/clamav-devel
http://git.clamav.net/gitweb?p=clamav-devel.git;a=commit;h=224fee54dd6cd8933d7007331ec2bfca0398d4b4
libclamav/mspack.c: fix Quantum decompressor (bb#1771)
1
int qtm_decompress(struct qtm_stream *qtm, off_t out_bytes) { unsigned int frame_start, frame_end, window_posn, match_offset, range; unsigned char *window, *i_ptr, *i_end, *runsrc, *rundest; int i, j, selector, extra, sym, match_length, ret; unsigned short H, L, C, symf; register unsigned int bit_buffer; register unsigned char bits_left; unsigned char bits_needed, bit_run; /* easy answers */ if (!qtm || (out_bytes < 0)) return CL_ENULLARG; if (qtm->error) return qtm->error; /* flush out any stored-up bytes before we begin */ i = qtm->o_end - qtm->o_ptr; if ((off_t) i > out_bytes) i = (int) out_bytes; if (i) { if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } qtm->o_ptr += i; out_bytes -= i; } if (out_bytes == 0) return CL_SUCCESS; /* restore local state */ QTM_RESTORE_BITS; window = qtm->window; window_posn = qtm->window_posn; frame_start = qtm->frame_start; H = qtm->H; L = qtm->L; C = qtm->C; /* while we do not have enough decoded bytes in reserve: */ while ((qtm->o_end - qtm->o_ptr) < out_bytes) { /* read header if necessary. Initialises H, L and C */ if (!qtm->header_read) { H = 0xFFFF; L = 0; QTM_READ_BITS(C, 16); qtm->header_read = 1; } /* decode more, at most up to to frame boundary */ frame_end = window_posn + (out_bytes - (qtm->o_end - qtm->o_ptr)); if ((frame_start + QTM_FRAME_SIZE) < frame_end) { frame_end = frame_start + QTM_FRAME_SIZE; } while (window_posn < frame_end) { QTM_GET_SYMBOL(qtm->model7, selector); if (selector < 4) { struct qtm_model *mdl = (selector == 0) ? &qtm->model0 : ((selector == 1) ? &qtm->model1 : ((selector == 2) ? &qtm->model2 : &qtm->model3)); QTM_GET_SYMBOL((*mdl), sym); window[window_posn++] = sym; } else { switch (selector) { case 4: /* selector 4 = fixed length match (3 bytes) */ QTM_GET_SYMBOL(qtm->model4, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; match_length = 3; break; case 5: /* selector 5 = fixed length match (4 bytes) */ QTM_GET_SYMBOL(qtm->model5, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; match_length = 4; break; case 6: /* selector 6 = variable length match */ QTM_GET_SYMBOL(qtm->model6len, sym); QTM_READ_BITS(extra, qtm->length_extra[sym]); match_length = qtm->length_base[sym] + extra + 5; QTM_GET_SYMBOL(qtm->model6, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; break; default: /* should be impossible, model7 can only return 0-6 */ return qtm->error = CL_EFORMAT; } rundest = &window[window_posn]; i = match_length; /* does match offset wrap the window? */ if (match_offset > window_posn) { /* j = length from match offset to end of window */ j = match_offset - window_posn; if (j > (int) qtm->window_size) { cli_dbgmsg("qtm_decompress: match offset beyond window boundaries\n"); return qtm->error = CL_EFORMAT; } runsrc = &window[qtm->window_size - j]; if (j < i) { /* if match goes over the window edge, do two copy runs */ i -= j; while (j-- > 0) *rundest++ = *runsrc++; runsrc = window; } while (i-- > 0) *rundest++ = *runsrc++; } else { runsrc = rundest - match_offset; if(i > (int) (qtm->window_size - window_posn)) i = qtm->window_size - window_posn; while (i-- > 0) *rundest++ = *runsrc++; } window_posn += match_length; } } /* while (window_posn < frame_end) */ qtm->o_end = &window[window_posn]; /* another frame completed? */ if ((window_posn - frame_start) >= QTM_FRAME_SIZE) { if ((window_posn - frame_start) != QTM_FRAME_SIZE) { cli_dbgmsg("qtm_decompress: overshot frame alignment\n"); return qtm->error = CL_EFORMAT; } /* re-align input */ if (bits_left & 7) QTM_REMOVE_BITS(bits_left & 7); do { QTM_READ_BITS(i, 8); } while (i != 0xFF); qtm->header_read = 0; /* window wrap? */ if (window_posn == qtm->window_size) { /* flush all currently stored data */ i = (qtm->o_end - qtm->o_ptr); if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } out_bytes -= i; qtm->o_ptr = &window[0]; qtm->o_end = &window[0]; window_posn = 0; } frame_start = window_posn; } } /* while (more bytes needed) */ if (out_bytes) { i = (int) out_bytes; if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } qtm->o_ptr += i; } /* store local state */ QTM_STORE_BITS; qtm->window_posn = window_posn; qtm->frame_start = frame_start; qtm->H = H; qtm->L = L; qtm->C = C; return CL_SUCCESS; }
291050376752284006088755347145639053650
mspack.c
137114659534783781079186144852150621076
CWE-20
CVE-2010-1311
The qtm_decompress function in libclamav/mspack.c in ClamAV before 0.96 allows remote attackers to cause a denial of service (memory corruption and application crash) via a crafted CAB archive that uses the Quantum (aka .Q) compression format. NOTE: some of these details are obtained from third party information.
https://nvd.nist.gov/vuln/detail/CVE-2010-1311
477,946
clamav-devel
224fee54dd6cd8933d7007331ec2bfca0398d4b4
https://github.com/vrtadmin/clamav-devel
http://git.clamav.net/gitweb?p=clamav-devel.git;a=commit;h=224fee54dd6cd8933d7007331ec2bfca0398d4b4
libclamav/mspack.c: fix Quantum decompressor (bb#1771)
0
int qtm_decompress(struct qtm_stream *qtm, off_t out_bytes) { unsigned int frame_start, frame_end, window_posn, match_offset, range; unsigned char *window, *i_ptr, *i_end, *runsrc, *rundest; int i, j, selector, extra, sym, match_length, ret; unsigned short H, L, C, symf; register unsigned int bit_buffer; register unsigned char bits_left; unsigned char bits_needed, bit_run; /* easy answers */ if (!qtm || (out_bytes < 0)) return CL_ENULLARG; if (qtm->error) return qtm->error; /* flush out any stored-up bytes before we begin */ i = qtm->o_end - qtm->o_ptr; if ((off_t) i > out_bytes) i = (int) out_bytes; if (i) { if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } qtm->o_ptr += i; out_bytes -= i; } if (out_bytes == 0) return CL_SUCCESS; /* restore local state */ QTM_RESTORE_BITS; window = qtm->window; window_posn = qtm->window_posn; frame_start = qtm->frame_start; H = qtm->H; L = qtm->L; C = qtm->C; /* while we do not have enough decoded bytes in reserve: */ while ((qtm->o_end - qtm->o_ptr) < out_bytes) { /* read header if necessary. Initialises H, L and C */ if (!qtm->header_read) { H = 0xFFFF; L = 0; QTM_READ_BITS(C, 16); qtm->header_read = 1; } /* decode more, at most up to to frame boundary */ frame_end = window_posn + (out_bytes - (qtm->o_end - qtm->o_ptr)); if ((frame_start + QTM_FRAME_SIZE) < frame_end) { frame_end = frame_start + QTM_FRAME_SIZE; } while (window_posn < frame_end) { QTM_GET_SYMBOL(qtm->model7, selector); if (selector < 4) { struct qtm_model *mdl = (selector == 0) ? &qtm->model0 : ((selector == 1) ? &qtm->model1 : ((selector == 2) ? &qtm->model2 : &qtm->model3)); QTM_GET_SYMBOL((*mdl), sym); window[window_posn++] = sym; } else { switch (selector) { case 4: /* selector 4 = fixed length match (3 bytes) */ QTM_GET_SYMBOL(qtm->model4, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; match_length = 3; break; case 5: /* selector 5 = fixed length match (4 bytes) */ QTM_GET_SYMBOL(qtm->model5, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; match_length = 4; break; case 6: /* selector 6 = variable length match */ QTM_GET_SYMBOL(qtm->model6len, sym); QTM_READ_BITS(extra, qtm->length_extra[sym]); match_length = qtm->length_base[sym] + extra + 5; QTM_GET_SYMBOL(qtm->model6, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; break; default: /* should be impossible, model7 can only return 0-6 */ return qtm->error = CL_EFORMAT; } if (window_posn + match_length > qtm->window_size) { cli_dbgmsg("qtm_decompress: match ran over window wrap\n"); return qtm->error = CL_EFORMAT; } rundest = &window[window_posn]; i = match_length; /* does match offset wrap the window? */ if (match_offset > window_posn) { /* j = length from match offset to end of window */ j = match_offset - window_posn; if (j > (int) qtm->window_size) { cli_dbgmsg("qtm_decompress: match offset beyond window boundaries\n"); return qtm->error = CL_EFORMAT; } runsrc = &window[qtm->window_size - j]; if (j < i) { /* if match goes over the window edge, do two copy runs */ i -= j; while (j-- > 0) *rundest++ = *runsrc++; runsrc = window; } while (i-- > 0) *rundest++ = *runsrc++; } else { runsrc = rundest - match_offset; if(i > (int) (qtm->window_size - window_posn)) i = qtm->window_size - window_posn; while (i-- > 0) *rundest++ = *runsrc++; } window_posn += match_length; } } /* while (window_posn < frame_end) */ qtm->o_end = &window[window_posn]; /* another frame completed? */ if ((window_posn - frame_start) >= QTM_FRAME_SIZE) { if ((window_posn - frame_start) != QTM_FRAME_SIZE) { cli_dbgmsg("qtm_decompress: overshot frame alignment\n"); return qtm->error = CL_EFORMAT; } /* re-align input */ if (bits_left & 7) QTM_REMOVE_BITS(bits_left & 7); do { QTM_READ_BITS(i, 8); } while (i != 0xFF); qtm->header_read = 0; /* window wrap? */ if (window_posn == qtm->window_size) { /* flush all currently stored data */ i = (qtm->o_end - qtm->o_ptr); if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } out_bytes -= i; qtm->o_ptr = &window[0]; qtm->o_end = &window[0]; window_posn = 0; } frame_start = window_posn; } } /* while (more bytes needed) */ if (out_bytes) { i = (int) out_bytes; if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } qtm->o_ptr += i; } /* store local state */ QTM_STORE_BITS; qtm->window_posn = window_posn; qtm->frame_start = frame_start; qtm->H = H; qtm->L = L; qtm->C = C; return CL_SUCCESS; }
309561544522405112370599990059884786931
mspack.c
294647704290965311324683497678599566631
CWE-20
CVE-2010-1311
The qtm_decompress function in libclamav/mspack.c in ClamAV before 0.96 allows remote attackers to cause a denial of service (memory corruption and application crash) via a crafted CAB archive that uses the Quantum (aka .Q) compression format. NOTE: some of these details are obtained from third party information.
https://nvd.nist.gov/vuln/detail/CVE-2010-1311
214,364
php-src
e6c48213c22ed50b2b987b479fcc1ac709394caa
https://github.com/php/php-src
http://git.php.net/?p=php-src.git;a=commit;h=e6c48213c22ed50b2b987b479fcc1ac709394caa
Fix bug #72606: heap-buffer-overflow (write) simplestring_addn simplestring.c
1
void simplestring_addn(simplestring* target, const char* source, int add_len) { if(target && source) { if(!target->str) { simplestring_init_str(target); } if(target->len + add_len + 1 > target->size) { /* newsize is current length + new length */ int newsize = target->len + add_len + 1; int incr = target->size * 2; /* align to SIMPLESTRING_INCR increments */ newsize = newsize - (newsize % incr) + incr; target->str = (char*)realloc(target->str, newsize); target->size = target->str ? newsize : 0; } if(target->str) { if(add_len) { memcpy(target->str + target->len, source, add_len); } target->len += add_len; target->str[target->len] = 0; /* null terminate */ } } }
48339101902926135808878707654868204878
simplestring.c
338610095237188637437183530843859723766
CWE-119
CVE-2016-6296
Integer signedness error in the simplestring_addn function in simplestring.c in xmlrpc-epi through 0.54.2, as used in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9, allows remote attackers to cause a denial of service (heap-based buffer overflow) or possibly have unspecified other impact via a long first argument to the PHP xmlrpc_encode_request function.
https://nvd.nist.gov/vuln/detail/CVE-2016-6296
477,975
php-src
e6c48213c22ed50b2b987b479fcc1ac709394caa
https://github.com/php/php-src
http://git.php.net/?p=php-src.git;a=commit;h=e6c48213c22ed50b2b987b479fcc1ac709394caa
Fix bug #72606: heap-buffer-overflow (write) simplestring_addn simplestring.c
0
void simplestring_addn(simplestring* target, const char* source, size_t add_len) { size_t newsize = target->size, incr = 0; if(target && source) { if(!target->str) { simplestring_init_str(target); } if((SIZE_MAX - add_len) < target->len || (SIZE_MAX - add_len - 1) < target->len) { /* check for overflows, if there's a potential overflow do nothing */ return; } if(target->len + add_len + 1 > target->size) { /* newsize is current length + new length */ newsize = target->len + add_len + 1; incr = target->size * 2; /* align to SIMPLESTRING_INCR increments */ if (incr) { newsize = newsize - (newsize % incr) + incr; } if(newsize < (target->len + add_len + 1)) { /* some kind of overflow happened */ return; } target->str = (char*)realloc(target->str, newsize); target->size = target->str ? newsize : 0; } if(target->str) { if(add_len) { memcpy(target->str + target->len, source, add_len); } target->len += add_len; target->str[target->len] = 0; /* null terminate */ } } }
17303339734462956863208308798642286429
simplestring.c
335043387623274482983135088926291395510
CWE-119
CVE-2016-6296
Integer signedness error in the simplestring_addn function in simplestring.c in xmlrpc-epi through 0.54.2, as used in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9, allows remote attackers to cause a denial of service (heap-based buffer overflow) or possibly have unspecified other impact via a long first argument to the PHP xmlrpc_encode_request function.
https://nvd.nist.gov/vuln/detail/CVE-2016-6296
214,909
linux
c8c2a057fdc7de1cd16f4baa51425b932a42eb39
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/c8c2a057fdc7de1cd16f4baa51425b932a42eb39
net/mlx5: prevent memory leak in mlx5_fpga_conn_create_cq In mlx5_fpga_conn_create_cq if mlx5_vector2eqn fails the allocated memory should be released. Fixes: 537a50574175 ("net/mlx5: FPGA, Add high-speed connection routines") Signed-off-by: Navid Emamdoost <[email protected]> Signed-off-by: Saeed Mahameed <[email protected]>
1
static int mlx5_fpga_conn_create_cq(struct mlx5_fpga_conn *conn, int cq_size) { struct mlx5_fpga_device *fdev = conn->fdev; struct mlx5_core_dev *mdev = fdev->mdev; u32 temp_cqc[MLX5_ST_SZ_DW(cqc)] = {0}; u32 out[MLX5_ST_SZ_DW(create_cq_out)]; struct mlx5_wq_param wqp; struct mlx5_cqe64 *cqe; int inlen, err, eqn; unsigned int irqn; void *cqc, *in; __be64 *pas; u32 i; cq_size = roundup_pow_of_two(cq_size); MLX5_SET(cqc, temp_cqc, log_cq_size, ilog2(cq_size)); wqp.buf_numa_node = mdev->priv.numa_node; wqp.db_numa_node = mdev->priv.numa_node; err = mlx5_cqwq_create(mdev, &wqp, temp_cqc, &conn->cq.wq, &conn->cq.wq_ctrl); if (err) return err; for (i = 0; i < mlx5_cqwq_get_size(&conn->cq.wq); i++) { cqe = mlx5_cqwq_get_wqe(&conn->cq.wq, i); cqe->op_own = MLX5_CQE_INVALID << 4 | MLX5_CQE_OWNER_MASK; } inlen = MLX5_ST_SZ_BYTES(create_cq_in) + sizeof(u64) * conn->cq.wq_ctrl.buf.npages; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err_cqwq; } err = mlx5_vector2eqn(mdev, smp_processor_id(), &eqn, &irqn); if (err) goto err_cqwq; cqc = MLX5_ADDR_OF(create_cq_in, in, cq_context); MLX5_SET(cqc, cqc, log_cq_size, ilog2(cq_size)); MLX5_SET(cqc, cqc, c_eqn, eqn); MLX5_SET(cqc, cqc, uar_page, fdev->conn_res.uar->index); MLX5_SET(cqc, cqc, log_page_size, conn->cq.wq_ctrl.buf.page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET64(cqc, cqc, dbr_addr, conn->cq.wq_ctrl.db.dma); pas = (__be64 *)MLX5_ADDR_OF(create_cq_in, in, pas); mlx5_fill_page_frag_array(&conn->cq.wq_ctrl.buf, pas); err = mlx5_core_create_cq(mdev, &conn->cq.mcq, in, inlen, out, sizeof(out)); kvfree(in); if (err) goto err_cqwq; conn->cq.mcq.cqe_sz = 64; conn->cq.mcq.set_ci_db = conn->cq.wq_ctrl.db.db; conn->cq.mcq.arm_db = conn->cq.wq_ctrl.db.db + 1; *conn->cq.mcq.set_ci_db = 0; *conn->cq.mcq.arm_db = 0; conn->cq.mcq.vector = 0; conn->cq.mcq.comp = mlx5_fpga_conn_cq_complete; conn->cq.mcq.event = mlx5_fpga_conn_cq_event; conn->cq.mcq.irqn = irqn; conn->cq.mcq.uar = fdev->conn_res.uar; tasklet_init(&conn->cq.tasklet, mlx5_fpga_conn_cq_tasklet, (unsigned long)conn); mlx5_fpga_dbg(fdev, "Created CQ #0x%x\n", conn->cq.mcq.cqn); goto out; err_cqwq: mlx5_wq_destroy(&conn->cq.wq_ctrl); out: return err; }
49458891717982371333799410023640328338
conn.c
180696471421094307893886411619232621599
CWE-401
CVE-2019-19045
A memory leak in the mlx5_fpga_conn_create_cq() function in drivers/net/ethernet/mellanox/mlx5/core/fpga/conn.c in the Linux kernel before 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering mlx5_vector2eqn() failures, aka CID-c8c2a057fdc7.
https://nvd.nist.gov/vuln/detail/CVE-2019-19045
481,267
linux
c8c2a057fdc7de1cd16f4baa51425b932a42eb39
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/c8c2a057fdc7de1cd16f4baa51425b932a42eb39
net/mlx5: prevent memory leak in mlx5_fpga_conn_create_cq In mlx5_fpga_conn_create_cq if mlx5_vector2eqn fails the allocated memory should be released. Fixes: 537a50574175 ("net/mlx5: FPGA, Add high-speed connection routines") Signed-off-by: Navid Emamdoost <[email protected]> Signed-off-by: Saeed Mahameed <[email protected]>
0
static int mlx5_fpga_conn_create_cq(struct mlx5_fpga_conn *conn, int cq_size) { struct mlx5_fpga_device *fdev = conn->fdev; struct mlx5_core_dev *mdev = fdev->mdev; u32 temp_cqc[MLX5_ST_SZ_DW(cqc)] = {0}; u32 out[MLX5_ST_SZ_DW(create_cq_out)]; struct mlx5_wq_param wqp; struct mlx5_cqe64 *cqe; int inlen, err, eqn; unsigned int irqn; void *cqc, *in; __be64 *pas; u32 i; cq_size = roundup_pow_of_two(cq_size); MLX5_SET(cqc, temp_cqc, log_cq_size, ilog2(cq_size)); wqp.buf_numa_node = mdev->priv.numa_node; wqp.db_numa_node = mdev->priv.numa_node; err = mlx5_cqwq_create(mdev, &wqp, temp_cqc, &conn->cq.wq, &conn->cq.wq_ctrl); if (err) return err; for (i = 0; i < mlx5_cqwq_get_size(&conn->cq.wq); i++) { cqe = mlx5_cqwq_get_wqe(&conn->cq.wq, i); cqe->op_own = MLX5_CQE_INVALID << 4 | MLX5_CQE_OWNER_MASK; } inlen = MLX5_ST_SZ_BYTES(create_cq_in) + sizeof(u64) * conn->cq.wq_ctrl.buf.npages; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err_cqwq; } err = mlx5_vector2eqn(mdev, smp_processor_id(), &eqn, &irqn); if (err) { kvfree(in); goto err_cqwq; } cqc = MLX5_ADDR_OF(create_cq_in, in, cq_context); MLX5_SET(cqc, cqc, log_cq_size, ilog2(cq_size)); MLX5_SET(cqc, cqc, c_eqn, eqn); MLX5_SET(cqc, cqc, uar_page, fdev->conn_res.uar->index); MLX5_SET(cqc, cqc, log_page_size, conn->cq.wq_ctrl.buf.page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET64(cqc, cqc, dbr_addr, conn->cq.wq_ctrl.db.dma); pas = (__be64 *)MLX5_ADDR_OF(create_cq_in, in, pas); mlx5_fill_page_frag_array(&conn->cq.wq_ctrl.buf, pas); err = mlx5_core_create_cq(mdev, &conn->cq.mcq, in, inlen, out, sizeof(out)); kvfree(in); if (err) goto err_cqwq; conn->cq.mcq.cqe_sz = 64; conn->cq.mcq.set_ci_db = conn->cq.wq_ctrl.db.db; conn->cq.mcq.arm_db = conn->cq.wq_ctrl.db.db + 1; *conn->cq.mcq.set_ci_db = 0; *conn->cq.mcq.arm_db = 0; conn->cq.mcq.vector = 0; conn->cq.mcq.comp = mlx5_fpga_conn_cq_complete; conn->cq.mcq.event = mlx5_fpga_conn_cq_event; conn->cq.mcq.irqn = irqn; conn->cq.mcq.uar = fdev->conn_res.uar; tasklet_init(&conn->cq.tasklet, mlx5_fpga_conn_cq_tasklet, (unsigned long)conn); mlx5_fpga_dbg(fdev, "Created CQ #0x%x\n", conn->cq.mcq.cqn); goto out; err_cqwq: mlx5_wq_destroy(&conn->cq.wq_ctrl); out: return err; }
166786309951983227645990078525765970677
conn.c
179201474190149214779616550859114985162
CWE-401
CVE-2019-19045
A memory leak in the mlx5_fpga_conn_create_cq() function in drivers/net/ethernet/mellanox/mlx5/core/fpga/conn.c in the Linux kernel before 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering mlx5_vector2eqn() failures, aka CID-c8c2a057fdc7.
https://nvd.nist.gov/vuln/detail/CVE-2019-19045
214,948
nagioscore
b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76
https://github.com/NagiosEnterprises/nagioscore
https://github.com/NagiosEnterprises/nagioscore/commit/b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76
merge accidental master PR (#553) into maint and fix changelog merge conflict
1
static int qh_help(int sd, char *buf, unsigned int len) { struct query_handler *qh = NULL; if (!*buf || !strcmp(buf, "help")) { nsock_printf_nul(sd, " help <name> show help for handler <name>\n" " help list list registered handlers\n"); return 0; } if (!strcmp(buf, "list")) { for (qh = qhandlers; qh != NULL; qh = qh->next_qh) { nsock_printf(sd, "%-10s %s\n", qh->name, qh->description ? qh->description : "(No description available)"); } nsock_printf(sd, "%c", 0); return 0; } qh = qh_find_handler(buf); if (qh == NULL) { nsock_printf_nul(sd, "No handler named '%s' is registered\n", buf); } else if (qh->handler(sd, "help", 4) > 200) { nsock_printf_nul(sd, "The handler %s doesn't have any help yet.", buf); } return 0; }
94205848469413247134990431510795041073
query-handler.c
69411467652185615530893490033539842403
CWE-476
CVE-2018-13441
qh_help in Nagios Core version 4.4.1 and earlier is prone to a NULL pointer dereference vulnerability, which allows attacker to cause a local denial-of-service condition by sending a crafted payload to the listening UNIX socket.
https://nvd.nist.gov/vuln/detail/CVE-2018-13441
481,787
nagioscore
b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76
https://github.com/NagiosEnterprises/nagioscore
https://github.com/NagiosEnterprises/nagioscore/commit/b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76
merge accidental master PR (#553) into maint and fix changelog merge conflict
0
static int qh_help(int sd, char *buf, unsigned int len) { struct query_handler *qh = NULL; if (buf == NULL || !strcmp(buf, "help")) { nsock_printf_nul(sd, " help <name> show help for handler <name>\n" " help list list registered handlers\n"); return 0; } if (!strcmp(buf, "list")) { for (qh = qhandlers; qh != NULL; qh = qh->next_qh) { nsock_printf(sd, "%-10s %s\n", qh->name, qh->description ? qh->description : "(No description available)"); } nsock_printf(sd, "%c", 0); return 0; } qh = qh_find_handler(buf); if (qh == NULL) { nsock_printf_nul(sd, "No handler named '%s' is registered\n", buf); } else if (qh->handler(sd, "help", 4) > 200) { nsock_printf_nul(sd, "The handler %s doesn't have any help yet.", buf); } return 0; }
205155132129673453942496407625358391443
query-handler.c
275184931270866221094094086326042798019
CWE-476
CVE-2018-13441
qh_help in Nagios Core version 4.4.1 and earlier is prone to a NULL pointer dereference vulnerability, which allows attacker to cause a local denial-of-service condition by sending a crafted payload to the listening UNIX socket.
https://nvd.nist.gov/vuln/detail/CVE-2018-13441
214,997
liblouis
2e4772befb2b1c37cb4b9d6572945115ee28630a
https://github.com/liblouis/liblouis
https://github.com/liblouis/liblouis/commit/2e4772befb2b1c37cb4b9d6572945115ee28630a
Prevent an invalid memory writes in compileRule Thanks to Han Zheng for reporting it Fixes #1214
1
compileRule(FileInfo *file, TranslationTableHeader **table, DisplayTableHeader **displayTable, const MacroList **inScopeMacros) { CharsString token; TranslationTableOpcode opcode; CharsString ruleChars; CharsString ruleDots; CharsString cells; CharsString scratchPad; CharsString emphClass; TranslationTableCharacterAttributes after = 0; TranslationTableCharacterAttributes before = 0; int noback, nofor, nocross; noback = nofor = nocross = 0; doOpcode: if (!getToken(file, &token, NULL)) return 1; /* blank line */ if (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */ if (file->lineNumber == 1 && (eqasc2uni((unsigned char *)"ISO", token.chars, 3) || eqasc2uni((unsigned char *)"UTF-8", token.chars, 5))) { if (table) compileHyphenation(file, &token, table); else /* ignore the whole file */ while (_lou_getALine(file)) ; return 1; } opcode = getOpcode(file, &token); switch (opcode) { case CTO_Macro: { const Macro *macro; #ifdef ENABLE_MACROS if (!inScopeMacros) { compileError(file, "Defining macros only allowed in table files."); return 0; } if (compileMacro(file, &macro)) { *inScopeMacros = cons_macro(macro, *inScopeMacros); return 1; } return 0; #else compileError(file, "Macro feature is disabled."); return 0; #endif } case CTO_IncludeFile: { CharsString includedFile; if (!getToken(file, &token, "include file name")) return 0; if (!parseChars(file, &includedFile, &token)) return 0; return includeFile(file, &includedFile, table, displayTable); } case CTO_NoBack: if (nofor) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoFor)); return 0; } noback = 1; goto doOpcode; case CTO_NoFor: if (noback) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoBack)); return 0; } nofor = 1; goto doOpcode; case CTO_Space: return compileCharDef( file, opcode, CTC_Space, noback, nofor, table, displayTable); case CTO_Digit: return compileCharDef( file, opcode, CTC_Digit, noback, nofor, table, displayTable); case CTO_LitDigit: return compileCharDef( file, opcode, CTC_LitDigit, noback, nofor, table, displayTable); case CTO_Punctuation: return compileCharDef( file, opcode, CTC_Punctuation, noback, nofor, table, displayTable); case CTO_Math: return compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable); case CTO_Sign: return compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable); case CTO_Letter: return compileCharDef( file, opcode, CTC_Letter, noback, nofor, table, displayTable); case CTO_UpperCase: return compileCharDef( file, opcode, CTC_UpperCase, noback, nofor, table, displayTable); case CTO_LowerCase: return compileCharDef( file, opcode, CTC_LowerCase, noback, nofor, table, displayTable); case CTO_Grouping: return compileGrouping(file, noback, nofor, table, displayTable); case CTO_Display: if (!displayTable) return 1; // ignore if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length != 1) { compileError(file, "Exactly one character and one cell are required."); return 0; } return putCharDotsMapping( file, ruleChars.chars[0], ruleDots.chars[0], displayTable); case CTO_UpLow: case CTO_None: { // check if token is a macro name if (inScopeMacros) { const MacroList *macros = *inScopeMacros; while (macros) { const Macro *m = macros->head; if (token.length == strlen(m->name) && eqasc2uni((unsigned char *)m->name, token.chars, token.length)) { if (!inScopeMacros) { compileError(file, "Calling macros only allowed in table files."); return 0; } FileInfo tmpFile; memset(&tmpFile, 0, sizeof(tmpFile)); tmpFile.fileName = file->fileName; tmpFile.sourceFile = file->sourceFile; tmpFile.lineNumber = file->lineNumber; tmpFile.encoding = noEncoding; tmpFile.status = 0; tmpFile.linepos = 0; tmpFile.linelen = 0; int argument_count = 0; CharsString *arguments = malloc(m->argument_count * sizeof(CharsString)); while (argument_count < m->argument_count) { if (getToken(file, &token, "macro argument")) arguments[argument_count++] = token; else break; } if (argument_count < m->argument_count) { compileError(file, "Expected %d arguments", m->argument_count); return 0; } int i = 0; int subst = 0; int next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; for (;;) { while (i < next) { widechar c = m->definition[i++]; if (c == '\n') { if (!compileRule(&tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } tmpFile.linepos = 0; tmpFile.linelen = 0; } else if (tmpFile.linelen >= MAXSTRING) { compileError(file, "Line exceeds %d characters (post macro " "expansion)", MAXSTRING); return 0; } else tmpFile.line[tmpFile.linelen++] = c; } if (subst < m->substitution_count) { CharsString arg = arguments[m->substitutions[2 * subst + 1] - 1]; for (int j = 0; j < arg.length; j++) tmpFile.line[tmpFile.linelen++] = arg.chars[j]; subst++; next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; } else { if (!compileRule( &tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } break; } } return 1; } macros = macros->tail; } } if (opcode == CTO_UpLow) { compileError(file, "The uplow opcode is deprecated."); return 0; } compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } /* now only opcodes follow that don't modify the display table */ default: if (!table) return 1; switch (opcode) { case CTO_Locale: compileWarning(file, "The locale opcode is not implemented. Use the locale meta data " "instead."); return 1; case CTO_Undefined: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->undefined; if (!compileBrailleIndicator(file, "undefined character opcode", CTO_Undefined, &ruleOffset, noback, nofor, table)) return 0; (*table)->undefined = ruleOffset; return 1; } case CTO_Match: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternsOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); noback = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, &rule, noback, nofor, table)) goto CTO_Match_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_Match_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_Match_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternsOffset, len * sizeof(widechar), table)) goto CTO_Match_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar)); rule->patterns = patternsOffset; ok = 1; CTO_Match_cleanup: free(patterns); return ok; } case CTO_BackMatch: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); nofor = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule, noback, nofor, table)) goto CTO_BackMatch_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternOffset, len * sizeof(widechar), table)) goto CTO_BackMatch_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar)); rule->patterns = patternOffset; ok = 1; CTO_BackMatch_cleanup: free(patterns); return ok; } case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: /* these 8 general purpose opcodes are compiled further down to more specific * internal opcodes: * - modeletter * - begmodeword * - endmodeword * - begmode * - endmode * - begmodephrase * - endmodephrase * - lenmodephrase */ case CTO_ModeLetter: case CTO_BegModeWord: case CTO_EndModeWord: case CTO_BegMode: case CTO_EndMode: case CTO_BegModePhrase: case CTO_EndModePhrase: case CTO_LenModePhrase: { TranslationTableCharacterAttributes mode; int i; switch (opcode) { case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: mode = CTC_UpperCase; i = 0; opcode += (CTO_ModeLetter - CTO_CapsLetter); break; default: if (!getToken(file, &token, "attribute name")) return 0; if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *characterClass = findCharacterClass(&token, *table); if (!characterClass) { characterClass = addCharacterClass(file, token.chars, token.length, *table, 1); if (!characterClass) return 0; } mode = characterClass->attribute; if (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space && mode <= CTC_LitDigit) { compileError(file, "mode must be \"uppercase\", \"digit\", or a custom " "attribute name."); return 0; } /* check if this mode is already defined and if the number of modes does * not exceed the maximal number */ if (mode == CTC_UpperCase) i = 0; else { for (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) { if ((*table)->modes[i].mode == mode) { break; } } if (i == MAX_MODES) { compileError(file, "Max number of modes (%i) reached", MAX_MODES); return 0; } } } if (!(*table)->modes[i].value) (*table)->modes[i] = (EmphasisClass){ plain_text, mode, 0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i }; switch (opcode) { case CTO_BegModePhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word capital sign", CTO_BegCapsPhraseRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset; return 1; } case CTO_EndModePhrase: { TranslationTableOffset ruleOffset; switch (compileBeforeAfter(file)) { case 1: // before if ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) { compileError( file, "Capital sign after last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "capital sign before last word", CTO_EndCapsPhraseBeforeRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] = ruleOffset; return 1; case 2: // after if ((*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]) { compileError( file, "Capital sign before last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "capital sign after last word", CTO_EndCapsPhraseAfterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] = ruleOffset; return 1; default: // error compileError(file, "Invalid lastword indicator location."); return 0; } return 0; } case CTO_BegMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset]; if (!compileBrailleIndicator(file, "first letter capital sign", CTO_BegCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset; return 1; } case CTO_EndMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset]; if (!compileBrailleIndicator(file, "last letter capital sign", CTO_EndCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset; return 1; } case CTO_ModeLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset]; if (!compileBrailleIndicator(file, "single letter capital sign", CTO_CapsLetterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset; return 1; } case CTO_BegModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset]; if (!compileBrailleIndicator(file, "capital word", CTO_BegCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset; return 1; } case CTO_EndModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset]; if (!compileBrailleIndicator(file, "capital word stop", CTO_EndCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset; return 1; } case CTO_LenModePhrase: return (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] = compileNumber(file); default: break; } break; } /* these 8 general purpose emphasis opcodes are compiled further down to more * specific internal opcodes: * - emphletter * - begemphword * - endemphword * - begemph * - endemph * - begemphphrase * - endemphphrase * - lenemphphrase */ case CTO_EmphClass: if (!getToken(file, &emphClass, "emphasis class")) { compileError(file, "emphclass must be followed by a valid class name."); return 0; } int k, i; char *s = malloc(sizeof(char) * (emphClass.length + 1)); for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) { _lou_logMessage(LOU_LOG_WARN, "Duplicate emphasis class: %s", s); warningCount++; free(s); return 1; } if (i == MAX_EMPH_CLASSES) { _lou_logMessage(LOU_LOG_ERROR, "Max number of emphasis classes (%i) reached", MAX_EMPH_CLASSES); errorCount++; free(s); return 0; } switch (i) { /* For backwards compatibility (i.e. because programs will assume * the first 3 typeform bits are `italic', `underline' and `bold') * we require that the first 3 emphclass definitions are (in that * order): * * emphclass italic * emphclass underline * emphclass bold * * While it would be possible to use the emphclass opcode only for * defining _additional_ classes (not allowing for them to be called * italic, underline or bold), thereby reducing the amount of * boilerplate, we deliberately choose not to do that in order to * not give italic, underline and bold any special status. The * hope is that eventually all programs will use liblouis for * emphasis the recommended way (i.e. by looking up the supported * typeforms in the documentation or API) so that we can drop this * restriction. */ case 0: if (strcmp(s, "italic") != 0) { _lou_logMessage(LOU_LOG_ERROR, "First emphasis class must be \"italic\" but got " "%s", s); errorCount++; free(s); return 0; } break; case 1: if (strcmp(s, "underline") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Second emphasis class must be \"underline\" but " "got " "%s", s); errorCount++; free(s); return 0; } break; case 2: if (strcmp(s, "bold") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Third emphasis class must be \"bold\" but got " "%s", s); errorCount++; free(s); return 0; } break; } (*table)->emphClassNames[i] = s; (*table)->emphClasses[i] = (EmphasisClass){ emph_1 << i, /* relies on the order of typeforms emph_1..emph_10 */ 0, 0x1 << i, i }; return 1; case CTO_EmphLetter: case CTO_BegEmphWord: case CTO_EndEmphWord: case CTO_BegEmph: case CTO_EndEmph: case CTO_BegEmphPhrase: case CTO_EndEmphPhrase: case CTO_LenEmphPhrase: case CTO_EmphModeChars: case CTO_NoEmphChars: { if (!getToken(file, &token, "emphasis class")) return 0; if (!parseChars(file, &emphClass, &token)) return 0; char *s = malloc(sizeof(char) * (emphClass.length + 1)); int k, i; for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) break; if (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) { _lou_logMessage(LOU_LOG_ERROR, "Emphasis class %s not declared", s); errorCount++; free(s); return 0; } int ok = 0; switch (opcode) { case CTO_EmphLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][letterOffset]; if (!compileBrailleIndicator(file, "single letter", CTO_Emph1LetterRule + letterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][letterOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begWordOffset]; if (!compileBrailleIndicator(file, "word", CTO_Emph1LetterRule + begWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begWordOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endWordOffset]; if (!compileBrailleIndicator(file, "word stop", CTO_Emph1LetterRule + endWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endWordOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmph: { /* fail if both begemph and any of begemphphrase or begemphword are * defined */ if ((*table)->emphRules[i][begWordOffset] || (*table)->emphRules[i][begPhraseOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both begemph and " "begemphword or begemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begOffset]; if (!compileBrailleIndicator(file, "first letter", CTO_Emph1LetterRule + begOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmph: { if ((*table)->emphRules[i][endWordOffset] || (*table)->emphRules[i][endPhraseBeforeOffset] || (*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both endemph and " "endemphword or endemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endOffset]; if (!compileBrailleIndicator(file, "last letter", CTO_Emph1LetterRule + endOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphPhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word", CTO_Emph1LetterRule + begPhraseOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begPhraseOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphPhrase: switch (compileBeforeAfter(file)) { case 1: { // before if ((*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "last word after already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "last word before", CTO_Emph1LetterRule + endPhraseBeforeOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset; ok = 1; break; } case 2: { // after if ((*table)->emphRules[i][endPhraseBeforeOffset]) { compileError(file, "last word before already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "last word after", CTO_Emph1LetterRule + endPhraseAfterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset; ok = 1; break; } default: // error compileError(file, "Invalid lastword indicator location."); break; } break; case CTO_LenEmphPhrase: if (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file))) ok = 1; break; case CTO_EmphModeChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *emphmodechars = (*table)->emphModeChars[i]; int len; for (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++) ; if (len + ruleChars.length > EMPHMODECHARSSIZE) { compileError(file, "More than %d characters", EMPHMODECHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Emphasis mode character undefined"); ok = 0; break; } emphmodechars[len++] = ruleChars.chars[k]; } break; } case CTO_NoEmphChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *noemphchars = (*table)->noEmphChars[i]; int len; for (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++) ; if (len + ruleChars.length > NOEMPHCHARSSIZE) { compileError(file, "More than %d characters", NOEMPHCHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Character undefined"); ok = 0; break; } noemphchars[len++] = ruleChars.chars[k]; } break; } default: break; } free(s); return ok; } case CTO_LetterSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->letterSign; if (!compileBrailleIndicator(file, "letter sign", CTO_LetterRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->letterSign = ruleOffset; return 1; } case CTO_NoLetsignBefore: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) { compileError(file, "More than %d characters", LETSIGNBEFORESIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsign: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) { compileError(file, "More than %d characters", LETSIGNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsignAfter: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) { compileError(file, "More than %d characters", LETSIGNAFTERSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] = ruleChars.chars[k]; return 1; case CTO_NumberSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->numberSign; if (!compileBrailleIndicator(file, "number sign", CTO_NumberRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->numberSign = ruleOffset; return 1; } case CTO_NumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric mode character undefined: %s", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } c->attributes |= CTC_NumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_MidEndNumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Midendnumeric mode character undefined"); return 0; } c->attributes |= CTC_MidEndNumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_NumericNoContractChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric no contraction character undefined"); return 0; } c->attributes |= CTC_NumericNoContract; (*table)->usesNumericMode = 1; } return 1; case CTO_NoContractSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->noContractSign; if (!compileBrailleIndicator(file, "no contractions sign", CTO_NoContractRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->noContractSign = ruleOffset; return 1; } case CTO_SeqDelimiter: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence delimiter character undefined"); return 0; } c->attributes |= CTC_SeqDelimiter; (*table)->usesSequences = 1; } return 1; case CTO_SeqBeforeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence before character undefined"); return 0; } c->attributes |= CTC_SeqBefore; } return 1; case CTO_SeqAfterChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence after character undefined"); return 0; } c->attributes |= CTC_SeqAfter; } return 1; case CTO_SeqAfterPattern: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) { compileError(file, "More than %d characters", SEQPATTERNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k]; (*table)->seqPatterns[(*table)->seqPatternsCount++] = 0; return 1; case CTO_SeqAfterExpression: if (!getRuleCharsText(file, &ruleChars)) return 0; for ((*table)->seqAfterExpressionLength = 0; (*table)->seqAfterExpressionLength < ruleChars.length; (*table)->seqAfterExpressionLength++) (*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = ruleChars.chars[(*table)->seqAfterExpressionLength]; (*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = 0; return 1; case CTO_CapsModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Capital mode character undefined"); return 0; } c->attributes |= CTC_CapsMode; (*table)->hasCapsModeChars = 1; } return 1; case CTO_BegComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->begComp; if (!compileBrailleIndicator(file, "begin computer braille", CTO_BegCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->begComp = ruleOffset; return 1; } case CTO_EndComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->endComp; if (!compileBrailleIndicator(file, "end computer braslle", CTO_EndCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->endComp = ruleOffset; return 1; } case CTO_NoCross: if (nocross) { compileError( file, "%s already specified.", _lou_findOpcodeName(CTO_NoCross)); return 0; } nocross = 1; goto doOpcode; case CTO_Syllable: (*table)->syllables = 1; case CTO_Always: case CTO_LargeSign: case CTO_WholeWord: case CTO_PartWord: case CTO_JoinNum: case CTO_JoinableWord: case CTO_LowWord: case CTO_SuffixableWord: case CTO_PrefixableWord: case CTO_BegWord: case CTO_BegMidWord: case CTO_MidWord: case CTO_MidEndWord: case CTO_EndWord: case CTO_PrePunc: case CTO_PostPunc: case CTO_BegNum: case CTO_MidNum: case CTO_EndNum: case CTO_Repeated: case CTO_RepWord: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleDots.length == 0) // check that all characters in a rule with `=` as second operand are // defined (or based on another character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } TranslationTableRule *r; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r, noback, nofor, table)) return 0; if (nocross) r->nocross = 1; return 1; // if (opcode == CTO_MidNum) // { // TranslationTableCharacter *c = getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } case CTO_RepEndWord: if (!getRuleCharsText(file, &ruleChars)) return 0; CharsString dots; if (!getToken(file, &dots, "dots,dots operand")) return 0; int len = dots.length; for (int k = 0; k < len - 1; k++) { if (dots.chars[k] == ',') { dots.length = k; if (!parseDots(file, &ruleDots, &dots)) return 0; ruleDots.chars[ruleDots.length++] = ','; k++; if (k == len - 1 && dots.chars[k] == '=') { // check that all characters are defined (or based on another // character) for (int l = 0; l < ruleChars.length; l++) { TranslationTableCharacter *c = getChar(ruleChars.chars[l], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[l], 1, 0)); return 0; } } } else { CharsString x, y; x.length = 0; while (k < len) x.chars[x.length++] = dots.chars[k++]; if (parseDots(file, &y, &x)) for (int l = 0; l < y.length; l++) ruleDots.chars[ruleDots.length++] = y.chars[l]; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); } } return 0; case CTO_CompDots: case CTO_Comp6: { TranslationTableOffset ruleOffset; if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.length != 1) { compileError(file, "first operand must be 1 character"); return 0; } if (nofor || noback) { compileWarning(file, "nofor and noback not allowed on comp6 rules"); } if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; return 1; } case CTO_ExactDots: if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.chars[0] != '@') { compileError(file, "The operand must begin with an at sign (@)"); return 0; } for (int k = 1; k < ruleChars.length; k++) scratchPad.chars[k - 1] = ruleChars.chars[k]; scratchPad.length = ruleChars.length - 1; if (!parseDots(file, &ruleDots, &scratchPad)) return 0; return addRule(file, opcode, &ruleChars, &ruleDots, before, after, NULL, NULL, noback, nofor, table); case CTO_CapsNoCont: { TranslationTableOffset ruleOffset; ruleChars.length = 1; ruleChars.chars[0] = 'a'; if (!addRule(file, CTO_CapsNoContRule, &ruleChars, NULL, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; (*table)->capsNoCont = ruleOffset; return 1; } case CTO_Replace: if (getRuleCharsText(file, &ruleChars)) { if (atEndOfLine(file)) ruleDots.length = ruleDots.chars[0] = 0; else { getRuleDotsText(file, &ruleDots); if (ruleDots.chars[0] == '#') ruleDots.length = ruleDots.chars[0] = 0; else if (ruleDots.chars[0] == '\\' && ruleDots.chars[1] == '#') memmove(&ruleDots.chars[0], &ruleDots.chars[1], ruleDots.length-- * CHARSIZE); } } for (int k = 0; k < ruleChars.length; k++) putChar(file, ruleChars.chars[k], table, NULL); for (int k = 0; k < ruleDots.length; k++) putChar(file, ruleDots.chars[k], table, NULL); return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); case CTO_Correct: (*table)->corrections = 1; goto doPass; case CTO_Pass2: if ((*table)->numPasses < 2) (*table)->numPasses = 2; goto doPass; case CTO_Pass3: if ((*table)->numPasses < 3) (*table)->numPasses = 3; goto doPass; case CTO_Pass4: if ((*table)->numPasses < 4) (*table)->numPasses = 4; doPass: case CTO_Context: if (!(nofor || noback)) { compileError(file, "%s or %s must be specified.", _lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack)); return 0; } return compilePassOpcode(file, opcode, noback, nofor, table); case CTO_Contraction: case CTO_NoCont: case CTO_CompBrl: case CTO_Literal: if (!getRuleCharsText(file, &ruleChars)) return 0; // check that all characters in a compbrl, contraction, // nocont or literal rule are defined (or based on another // character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } return addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL, noback, nofor, table); case CTO_MultInd: { ruleChars.length = 0; if (!getToken(file, &token, "multiple braille indicators") || !parseDots(file, &cells, &token)) return 0; while (getToken(file, &token, "multind opcodes")) { opcode = getOpcode(file, &token); if (opcode == CTO_None) { compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } if (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) { compileError(file, "Not a braille indicator opcode."); return 0; } ruleChars.chars[ruleChars.length++] = (widechar)opcode; if (atEndOfLine(file)) break; } return addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL, NULL, noback, nofor, table); } case CTO_Class: compileWarning(file, "class is deprecated, use attribute instead"); case CTO_Attribute: { if (nofor || noback) { compileWarning( file, "nofor and noback not allowed before class/attribute"); } if ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) || (opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) { compileError(file, "attribute and class rules must not be both present in a table"); return 0; } if (opcode == CTO_Class) (*table)->usesAttributeOrClass = 2; else (*table)->usesAttributeOrClass = 1; if (!getToken(file, &token, "attribute name")) { compileError(file, "Expected %s", "attribute name"); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } TranslationTableCharacterAttributes attribute = 0; { int attrNumber = -1; switch (token.chars[0]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': attrNumber = token.chars[0] - '0'; break; } if (attrNumber >= 0) { if (opcode == CTO_Class) { compileError(file, "Invalid class name: may not contain digits, use " "attribute instead of class"); return 0; } if (token.length > 1 || attrNumber > 7) { compileError(file, "Invalid attribute name: must be a digit between 0 and 7 " "or a word containing only letters"); return 0; } if (!(*table)->numberedAttributes[attrNumber]) // attribute not used before yet: assign it a value (*table)->numberedAttributes[attrNumber] = getNextNumberedAttribute(*table); attribute = (*table)->numberedAttributes[attrNumber]; } else { const CharacterClass *namedAttr = findCharacterClass(&token, *table); if (!namedAttr) { // no class with that name: create one namedAttr = addCharacterClass( file, &token.chars[0], token.length, *table, 1); if (!namedAttr) return 0; } // there is a class with that name or a new class was successfully // created attribute = namedAttr->attribute; if (attribute == CTC_UpperCase || attribute == CTC_LowerCase) attribute |= CTC_Letter; } } CharsString characters; if (!getCharacters(file, &characters)) return 0; for (int i = 0; i < characters.length; i++) { // get the character from the table, or if it is not defined yet, // define it TranslationTableCharacter *character = putChar(file, characters.chars[i], table, NULL); // set the attribute character->attributes |= attribute; // also set the attribute on the associated dots (if any) if (character->basechar) character = (TranslationTableCharacter *)&(*table) ->ruleArea[character->basechar]; if (character->definitionRule) { TranslationTableRule *defRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; if (defRule->dotslen == 1) { TranslationTableCharacter *dots = getDots(defRule->charsdots[defRule->charslen], *table); if (dots) dots->attributes |= attribute; } } } return 1; } { TranslationTableCharacterAttributes *attributes; const CharacterClass *class; case CTO_After: attributes = &after; goto doBeforeAfter; case CTO_Before: attributes = &before; doBeforeAfter: if (!(*table)->characterClasses) { if (!allocateCharacterClasses(*table)) return 0; } if (!getToken(file, &token, "attribute name")) return 0; if (!(class = findCharacterClass(&token, *table))) { compileError(file, "attribute not defined"); return 0; } *attributes |= class->attribute; goto doOpcode; } case CTO_Base: if (nofor || noback) { compileWarning(file, "nofor and noback not allowed before base"); } if (!getToken(file, &token, "attribute name")) { compileError( file, "base opcode must be followed by a valid attribute name."); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *mode = findCharacterClass(&token, *table); if (!mode) { mode = addCharacterClass(file, token.chars, token.length, *table, 1); if (!mode) return 0; } if (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) && mode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) { compileError(file, "base opcode must be followed by \"uppercase\", \"digit\", or a " "custom attribute name."); return 0; } if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one character followed by one base character is " "required."); return 0; } TranslationTableOffset characterOffset; TranslationTableCharacter *character = putChar(file, token.chars[0], table, &characterOffset); if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one base character is required."); return 0; } if (character->definitionRule) { TranslationTableRule *prevRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Character already defined (%s). The base rule will take " "precedence.", file->fileName, file->lineNumber, printSource(file, prevRule->sourceFile, prevRule->sourceLine)); character->definitionRule = 0; } TranslationTableOffset basechar; putChar(file, token.chars[0], table, &basechar); // putChar may have moved table, so make sure character is still valid character = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset]; if (character->basechar) { if (character->basechar == basechar && character->mode == mode->attribute) { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Duplicate base rule.", file->fileName, file->lineNumber); } else { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: A different base rule already exists for this " "character (%s). The new rule will take precedence.", file->fileName, file->lineNumber, printSource( file, character->sourceFile, character->sourceLine)); } } character->basechar = basechar; character->mode = mode->attribute; character->sourceFile = file->sourceFile; character->sourceLine = file->lineNumber; /* some other processing is done at the end of the compilation, in * finalizeTable() */ return 1; case CTO_EmpMatchBefore: before |= CTC_EmpMatch; goto doOpcode; case CTO_EmpMatchAfter: after |= CTC_EmpMatch; goto doOpcode; case CTO_SwapCc: case CTO_SwapCd: case CTO_SwapDd: return compileSwap(file, opcode, noback, nofor, table); case CTO_Hyphen: case CTO_DecPoint: // case CTO_Apostrophe: // case CTO_Initial: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length < 1) { compileError(file, "One Unicode character and at least one cell are " "required."); return 0; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); // if (opcode == CTO_DecPoint) // { // TranslationTableCharacter *c = // getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } default: compileError(file, "unimplemented opcode."); return 0; } } return 0; }
114188111189139492438388270487144198902
compileTranslationTable.c
130160890521779483138755278607355501086
CWE-787
CVE-2022-31783
Liblouis 3.21.0 has an out-of-bounds write in compileRule in compileTranslationTable.c, as demonstrated by lou_trace.
https://nvd.nist.gov/vuln/detail/CVE-2022-31783
482,533
liblouis
2e4772befb2b1c37cb4b9d6572945115ee28630a
https://github.com/liblouis/liblouis
https://github.com/liblouis/liblouis/commit/2e4772befb2b1c37cb4b9d6572945115ee28630a
Prevent an invalid memory writes in compileRule Thanks to Han Zheng for reporting it Fixes #1214
0
compileRule(FileInfo *file, TranslationTableHeader **table, DisplayTableHeader **displayTable, const MacroList **inScopeMacros) { CharsString token; TranslationTableOpcode opcode; CharsString ruleChars; CharsString ruleDots; CharsString cells; CharsString scratchPad; CharsString emphClass; TranslationTableCharacterAttributes after = 0; TranslationTableCharacterAttributes before = 0; int noback, nofor, nocross; noback = nofor = nocross = 0; doOpcode: if (!getToken(file, &token, NULL)) return 1; /* blank line */ if (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */ if (file->lineNumber == 1 && (eqasc2uni((unsigned char *)"ISO", token.chars, 3) || eqasc2uni((unsigned char *)"UTF-8", token.chars, 5))) { if (table) compileHyphenation(file, &token, table); else /* ignore the whole file */ while (_lou_getALine(file)) ; return 1; } opcode = getOpcode(file, &token); switch (opcode) { case CTO_Macro: { const Macro *macro; #ifdef ENABLE_MACROS if (!inScopeMacros) { compileError(file, "Defining macros only allowed in table files."); return 0; } if (compileMacro(file, &macro)) { *inScopeMacros = cons_macro(macro, *inScopeMacros); return 1; } return 0; #else compileError(file, "Macro feature is disabled."); return 0; #endif } case CTO_IncludeFile: { CharsString includedFile; if (!getToken(file, &token, "include file name")) return 0; if (!parseChars(file, &includedFile, &token)) return 0; return includeFile(file, &includedFile, table, displayTable); } case CTO_NoBack: if (nofor) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoFor)); return 0; } noback = 1; goto doOpcode; case CTO_NoFor: if (noback) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoBack)); return 0; } nofor = 1; goto doOpcode; case CTO_Space: return compileCharDef( file, opcode, CTC_Space, noback, nofor, table, displayTable); case CTO_Digit: return compileCharDef( file, opcode, CTC_Digit, noback, nofor, table, displayTable); case CTO_LitDigit: return compileCharDef( file, opcode, CTC_LitDigit, noback, nofor, table, displayTable); case CTO_Punctuation: return compileCharDef( file, opcode, CTC_Punctuation, noback, nofor, table, displayTable); case CTO_Math: return compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable); case CTO_Sign: return compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable); case CTO_Letter: return compileCharDef( file, opcode, CTC_Letter, noback, nofor, table, displayTable); case CTO_UpperCase: return compileCharDef( file, opcode, CTC_UpperCase, noback, nofor, table, displayTable); case CTO_LowerCase: return compileCharDef( file, opcode, CTC_LowerCase, noback, nofor, table, displayTable); case CTO_Grouping: return compileGrouping(file, noback, nofor, table, displayTable); case CTO_Display: if (!displayTable) return 1; // ignore if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length != 1) { compileError(file, "Exactly one character and one cell are required."); return 0; } return putCharDotsMapping( file, ruleChars.chars[0], ruleDots.chars[0], displayTable); case CTO_UpLow: case CTO_None: { // check if token is a macro name if (inScopeMacros) { const MacroList *macros = *inScopeMacros; while (macros) { const Macro *m = macros->head; if (token.length == strlen(m->name) && eqasc2uni((unsigned char *)m->name, token.chars, token.length)) { if (!inScopeMacros) { compileError(file, "Calling macros only allowed in table files."); return 0; } FileInfo tmpFile; memset(&tmpFile, 0, sizeof(tmpFile)); tmpFile.fileName = file->fileName; tmpFile.sourceFile = file->sourceFile; tmpFile.lineNumber = file->lineNumber; tmpFile.encoding = noEncoding; tmpFile.status = 0; tmpFile.linepos = 0; tmpFile.linelen = 0; int argument_count = 0; CharsString *arguments = malloc(m->argument_count * sizeof(CharsString)); while (argument_count < m->argument_count) { if (getToken(file, &token, "macro argument")) arguments[argument_count++] = token; else break; } if (argument_count < m->argument_count) { compileError(file, "Expected %d arguments", m->argument_count); return 0; } int i = 0; int subst = 0; int next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; for (;;) { while (i < next) { widechar c = m->definition[i++]; if (c == '\n') { if (!compileRule(&tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } tmpFile.linepos = 0; tmpFile.linelen = 0; } else if (tmpFile.linelen >= MAXSTRING) { compileError(file, "Line exceeds %d characters (post macro " "expansion)", MAXSTRING); return 0; } else tmpFile.line[tmpFile.linelen++] = c; } if (subst < m->substitution_count) { CharsString arg = arguments[m->substitutions[2 * subst + 1] - 1]; for (int j = 0; j < arg.length; j++) tmpFile.line[tmpFile.linelen++] = arg.chars[j]; subst++; next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; } else { if (!compileRule( &tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } break; } } return 1; } macros = macros->tail; } } if (opcode == CTO_UpLow) { compileError(file, "The uplow opcode is deprecated."); return 0; } compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } /* now only opcodes follow that don't modify the display table */ default: if (!table) return 1; switch (opcode) { case CTO_Locale: compileWarning(file, "The locale opcode is not implemented. Use the locale meta data " "instead."); return 1; case CTO_Undefined: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->undefined; if (!compileBrailleIndicator(file, "undefined character opcode", CTO_Undefined, &ruleOffset, noback, nofor, table)) return 0; (*table)->undefined = ruleOffset; return 1; } case CTO_Match: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternsOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); noback = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, &rule, noback, nofor, table)) goto CTO_Match_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_Match_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_Match_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternsOffset, len * sizeof(widechar), table)) goto CTO_Match_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar)); rule->patterns = patternsOffset; ok = 1; CTO_Match_cleanup: free(patterns); return ok; } case CTO_BackMatch: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); nofor = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule, noback, nofor, table)) goto CTO_BackMatch_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternOffset, len * sizeof(widechar), table)) goto CTO_BackMatch_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar)); rule->patterns = patternOffset; ok = 1; CTO_BackMatch_cleanup: free(patterns); return ok; } case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: /* these 8 general purpose opcodes are compiled further down to more specific * internal opcodes: * - modeletter * - begmodeword * - endmodeword * - begmode * - endmode * - begmodephrase * - endmodephrase * - lenmodephrase */ case CTO_ModeLetter: case CTO_BegModeWord: case CTO_EndModeWord: case CTO_BegMode: case CTO_EndMode: case CTO_BegModePhrase: case CTO_EndModePhrase: case CTO_LenModePhrase: { TranslationTableCharacterAttributes mode; int i; switch (opcode) { case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: mode = CTC_UpperCase; i = 0; opcode += (CTO_ModeLetter - CTO_CapsLetter); break; default: if (!getToken(file, &token, "attribute name")) return 0; if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *characterClass = findCharacterClass(&token, *table); if (!characterClass) { characterClass = addCharacterClass(file, token.chars, token.length, *table, 1); if (!characterClass) return 0; } mode = characterClass->attribute; if (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space && mode <= CTC_LitDigit) { compileError(file, "mode must be \"uppercase\", \"digit\", or a custom " "attribute name."); return 0; } /* check if this mode is already defined and if the number of modes does * not exceed the maximal number */ if (mode == CTC_UpperCase) i = 0; else { for (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) { if ((*table)->modes[i].mode == mode) { break; } } if (i == MAX_MODES) { compileError(file, "Max number of modes (%i) reached", MAX_MODES); return 0; } } } if (!(*table)->modes[i].value) (*table)->modes[i] = (EmphasisClass){ plain_text, mode, 0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i }; switch (opcode) { case CTO_BegModePhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word capital sign", CTO_BegCapsPhraseRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset; return 1; } case CTO_EndModePhrase: { TranslationTableOffset ruleOffset; switch (compileBeforeAfter(file)) { case 1: // before if ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) { compileError( file, "Capital sign after last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "capital sign before last word", CTO_EndCapsPhraseBeforeRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] = ruleOffset; return 1; case 2: // after if ((*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]) { compileError( file, "Capital sign before last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "capital sign after last word", CTO_EndCapsPhraseAfterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] = ruleOffset; return 1; default: // error compileError(file, "Invalid lastword indicator location."); return 0; } return 0; } case CTO_BegMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset]; if (!compileBrailleIndicator(file, "first letter capital sign", CTO_BegCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset; return 1; } case CTO_EndMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset]; if (!compileBrailleIndicator(file, "last letter capital sign", CTO_EndCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset; return 1; } case CTO_ModeLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset]; if (!compileBrailleIndicator(file, "single letter capital sign", CTO_CapsLetterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset; return 1; } case CTO_BegModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset]; if (!compileBrailleIndicator(file, "capital word", CTO_BegCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset; return 1; } case CTO_EndModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset]; if (!compileBrailleIndicator(file, "capital word stop", CTO_EndCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset; return 1; } case CTO_LenModePhrase: return (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] = compileNumber(file); default: break; } break; } /* these 8 general purpose emphasis opcodes are compiled further down to more * specific internal opcodes: * - emphletter * - begemphword * - endemphword * - begemph * - endemph * - begemphphrase * - endemphphrase * - lenemphphrase */ case CTO_EmphClass: if (!getToken(file, &emphClass, "emphasis class")) { compileError(file, "emphclass must be followed by a valid class name."); return 0; } int k, i; char *s = malloc(sizeof(char) * (emphClass.length + 1)); for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) { _lou_logMessage(LOU_LOG_WARN, "Duplicate emphasis class: %s", s); warningCount++; free(s); return 1; } if (i == MAX_EMPH_CLASSES) { _lou_logMessage(LOU_LOG_ERROR, "Max number of emphasis classes (%i) reached", MAX_EMPH_CLASSES); errorCount++; free(s); return 0; } switch (i) { /* For backwards compatibility (i.e. because programs will assume * the first 3 typeform bits are `italic', `underline' and `bold') * we require that the first 3 emphclass definitions are (in that * order): * * emphclass italic * emphclass underline * emphclass bold * * While it would be possible to use the emphclass opcode only for * defining _additional_ classes (not allowing for them to be called * italic, underline or bold), thereby reducing the amount of * boilerplate, we deliberately choose not to do that in order to * not give italic, underline and bold any special status. The * hope is that eventually all programs will use liblouis for * emphasis the recommended way (i.e. by looking up the supported * typeforms in the documentation or API) so that we can drop this * restriction. */ case 0: if (strcmp(s, "italic") != 0) { _lou_logMessage(LOU_LOG_ERROR, "First emphasis class must be \"italic\" but got " "%s", s); errorCount++; free(s); return 0; } break; case 1: if (strcmp(s, "underline") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Second emphasis class must be \"underline\" but " "got " "%s", s); errorCount++; free(s); return 0; } break; case 2: if (strcmp(s, "bold") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Third emphasis class must be \"bold\" but got " "%s", s); errorCount++; free(s); return 0; } break; } (*table)->emphClassNames[i] = s; (*table)->emphClasses[i] = (EmphasisClass){ emph_1 << i, /* relies on the order of typeforms emph_1..emph_10 */ 0, 0x1 << i, i }; return 1; case CTO_EmphLetter: case CTO_BegEmphWord: case CTO_EndEmphWord: case CTO_BegEmph: case CTO_EndEmph: case CTO_BegEmphPhrase: case CTO_EndEmphPhrase: case CTO_LenEmphPhrase: case CTO_EmphModeChars: case CTO_NoEmphChars: { if (!getToken(file, &token, "emphasis class")) return 0; if (!parseChars(file, &emphClass, &token)) return 0; char *s = malloc(sizeof(char) * (emphClass.length + 1)); int k, i; for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) break; if (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) { _lou_logMessage(LOU_LOG_ERROR, "Emphasis class %s not declared", s); errorCount++; free(s); return 0; } int ok = 0; switch (opcode) { case CTO_EmphLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][letterOffset]; if (!compileBrailleIndicator(file, "single letter", CTO_Emph1LetterRule + letterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][letterOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begWordOffset]; if (!compileBrailleIndicator(file, "word", CTO_Emph1LetterRule + begWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begWordOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endWordOffset]; if (!compileBrailleIndicator(file, "word stop", CTO_Emph1LetterRule + endWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endWordOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmph: { /* fail if both begemph and any of begemphphrase or begemphword are * defined */ if ((*table)->emphRules[i][begWordOffset] || (*table)->emphRules[i][begPhraseOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both begemph and " "begemphword or begemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begOffset]; if (!compileBrailleIndicator(file, "first letter", CTO_Emph1LetterRule + begOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmph: { if ((*table)->emphRules[i][endWordOffset] || (*table)->emphRules[i][endPhraseBeforeOffset] || (*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both endemph and " "endemphword or endemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endOffset]; if (!compileBrailleIndicator(file, "last letter", CTO_Emph1LetterRule + endOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphPhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word", CTO_Emph1LetterRule + begPhraseOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begPhraseOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphPhrase: switch (compileBeforeAfter(file)) { case 1: { // before if ((*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "last word after already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "last word before", CTO_Emph1LetterRule + endPhraseBeforeOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset; ok = 1; break; } case 2: { // after if ((*table)->emphRules[i][endPhraseBeforeOffset]) { compileError(file, "last word before already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "last word after", CTO_Emph1LetterRule + endPhraseAfterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset; ok = 1; break; } default: // error compileError(file, "Invalid lastword indicator location."); break; } break; case CTO_LenEmphPhrase: if (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file))) ok = 1; break; case CTO_EmphModeChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *emphmodechars = (*table)->emphModeChars[i]; int len; for (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++) ; if (len + ruleChars.length > EMPHMODECHARSSIZE) { compileError(file, "More than %d characters", EMPHMODECHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Emphasis mode character undefined"); ok = 0; break; } emphmodechars[len++] = ruleChars.chars[k]; } break; } case CTO_NoEmphChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *noemphchars = (*table)->noEmphChars[i]; int len; for (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++) ; if (len + ruleChars.length > NOEMPHCHARSSIZE) { compileError(file, "More than %d characters", NOEMPHCHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Character undefined"); ok = 0; break; } noemphchars[len++] = ruleChars.chars[k]; } break; } default: break; } free(s); return ok; } case CTO_LetterSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->letterSign; if (!compileBrailleIndicator(file, "letter sign", CTO_LetterRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->letterSign = ruleOffset; return 1; } case CTO_NoLetsignBefore: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) { compileError(file, "More than %d characters", LETSIGNBEFORESIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsign: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) { compileError(file, "More than %d characters", LETSIGNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsignAfter: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) { compileError(file, "More than %d characters", LETSIGNAFTERSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] = ruleChars.chars[k]; return 1; case CTO_NumberSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->numberSign; if (!compileBrailleIndicator(file, "number sign", CTO_NumberRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->numberSign = ruleOffset; return 1; } case CTO_NumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric mode character undefined: %s", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } c->attributes |= CTC_NumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_MidEndNumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Midendnumeric mode character undefined"); return 0; } c->attributes |= CTC_MidEndNumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_NumericNoContractChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric no contraction character undefined"); return 0; } c->attributes |= CTC_NumericNoContract; (*table)->usesNumericMode = 1; } return 1; case CTO_NoContractSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->noContractSign; if (!compileBrailleIndicator(file, "no contractions sign", CTO_NoContractRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->noContractSign = ruleOffset; return 1; } case CTO_SeqDelimiter: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence delimiter character undefined"); return 0; } c->attributes |= CTC_SeqDelimiter; (*table)->usesSequences = 1; } return 1; case CTO_SeqBeforeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence before character undefined"); return 0; } c->attributes |= CTC_SeqBefore; } return 1; case CTO_SeqAfterChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence after character undefined"); return 0; } c->attributes |= CTC_SeqAfter; } return 1; case CTO_SeqAfterPattern: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) { compileError(file, "More than %d characters", SEQPATTERNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k]; (*table)->seqPatterns[(*table)->seqPatternsCount++] = 0; return 1; case CTO_SeqAfterExpression: if (!getRuleCharsText(file, &ruleChars)) return 0; if ((ruleChars.length + 1) > SEQPATTERNSIZE) { compileError(file, "More than %d characters", SEQPATTERNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->seqAfterExpression[k] = ruleChars.chars[k]; (*table)->seqAfterExpression[ruleChars.length] = 0; (*table)->seqAfterExpressionLength = ruleChars.length; return 1; case CTO_CapsModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Capital mode character undefined"); return 0; } c->attributes |= CTC_CapsMode; (*table)->hasCapsModeChars = 1; } return 1; case CTO_BegComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->begComp; if (!compileBrailleIndicator(file, "begin computer braille", CTO_BegCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->begComp = ruleOffset; return 1; } case CTO_EndComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->endComp; if (!compileBrailleIndicator(file, "end computer braslle", CTO_EndCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->endComp = ruleOffset; return 1; } case CTO_NoCross: if (nocross) { compileError( file, "%s already specified.", _lou_findOpcodeName(CTO_NoCross)); return 0; } nocross = 1; goto doOpcode; case CTO_Syllable: (*table)->syllables = 1; case CTO_Always: case CTO_LargeSign: case CTO_WholeWord: case CTO_PartWord: case CTO_JoinNum: case CTO_JoinableWord: case CTO_LowWord: case CTO_SuffixableWord: case CTO_PrefixableWord: case CTO_BegWord: case CTO_BegMidWord: case CTO_MidWord: case CTO_MidEndWord: case CTO_EndWord: case CTO_PrePunc: case CTO_PostPunc: case CTO_BegNum: case CTO_MidNum: case CTO_EndNum: case CTO_Repeated: case CTO_RepWord: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleDots.length == 0) // check that all characters in a rule with `=` as second operand are // defined (or based on another character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } TranslationTableRule *r; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r, noback, nofor, table)) return 0; if (nocross) r->nocross = 1; return 1; // if (opcode == CTO_MidNum) // { // TranslationTableCharacter *c = getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } case CTO_RepEndWord: if (!getRuleCharsText(file, &ruleChars)) return 0; CharsString dots; if (!getToken(file, &dots, "dots,dots operand")) return 0; int len = dots.length; for (int k = 0; k < len - 1; k++) { if (dots.chars[k] == ',') { dots.length = k; if (!parseDots(file, &ruleDots, &dots)) return 0; ruleDots.chars[ruleDots.length++] = ','; k++; if (k == len - 1 && dots.chars[k] == '=') { // check that all characters are defined (or based on another // character) for (int l = 0; l < ruleChars.length; l++) { TranslationTableCharacter *c = getChar(ruleChars.chars[l], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[l], 1, 0)); return 0; } } } else { CharsString x, y; x.length = 0; while (k < len) x.chars[x.length++] = dots.chars[k++]; if (parseDots(file, &y, &x)) for (int l = 0; l < y.length; l++) ruleDots.chars[ruleDots.length++] = y.chars[l]; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); } } return 0; case CTO_CompDots: case CTO_Comp6: { TranslationTableOffset ruleOffset; if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.length != 1) { compileError(file, "first operand must be 1 character"); return 0; } if (nofor || noback) { compileWarning(file, "nofor and noback not allowed on comp6 rules"); } if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; return 1; } case CTO_ExactDots: if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.chars[0] != '@') { compileError(file, "The operand must begin with an at sign (@)"); return 0; } for (int k = 1; k < ruleChars.length; k++) scratchPad.chars[k - 1] = ruleChars.chars[k]; scratchPad.length = ruleChars.length - 1; if (!parseDots(file, &ruleDots, &scratchPad)) return 0; return addRule(file, opcode, &ruleChars, &ruleDots, before, after, NULL, NULL, noback, nofor, table); case CTO_CapsNoCont: { TranslationTableOffset ruleOffset; ruleChars.length = 1; ruleChars.chars[0] = 'a'; if (!addRule(file, CTO_CapsNoContRule, &ruleChars, NULL, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; (*table)->capsNoCont = ruleOffset; return 1; } case CTO_Replace: if (getRuleCharsText(file, &ruleChars)) { if (atEndOfLine(file)) ruleDots.length = ruleDots.chars[0] = 0; else { getRuleDotsText(file, &ruleDots); if (ruleDots.chars[0] == '#') ruleDots.length = ruleDots.chars[0] = 0; else if (ruleDots.chars[0] == '\\' && ruleDots.chars[1] == '#') memmove(&ruleDots.chars[0], &ruleDots.chars[1], ruleDots.length-- * CHARSIZE); } } for (int k = 0; k < ruleChars.length; k++) putChar(file, ruleChars.chars[k], table, NULL); for (int k = 0; k < ruleDots.length; k++) putChar(file, ruleDots.chars[k], table, NULL); return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); case CTO_Correct: (*table)->corrections = 1; goto doPass; case CTO_Pass2: if ((*table)->numPasses < 2) (*table)->numPasses = 2; goto doPass; case CTO_Pass3: if ((*table)->numPasses < 3) (*table)->numPasses = 3; goto doPass; case CTO_Pass4: if ((*table)->numPasses < 4) (*table)->numPasses = 4; doPass: case CTO_Context: if (!(nofor || noback)) { compileError(file, "%s or %s must be specified.", _lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack)); return 0; } return compilePassOpcode(file, opcode, noback, nofor, table); case CTO_Contraction: case CTO_NoCont: case CTO_CompBrl: case CTO_Literal: if (!getRuleCharsText(file, &ruleChars)) return 0; // check that all characters in a compbrl, contraction, // nocont or literal rule are defined (or based on another // character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } return addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL, noback, nofor, table); case CTO_MultInd: { ruleChars.length = 0; if (!getToken(file, &token, "multiple braille indicators") || !parseDots(file, &cells, &token)) return 0; while (getToken(file, &token, "multind opcodes")) { opcode = getOpcode(file, &token); if (opcode == CTO_None) { compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } if (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) { compileError(file, "Not a braille indicator opcode."); return 0; } ruleChars.chars[ruleChars.length++] = (widechar)opcode; if (atEndOfLine(file)) break; } return addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL, NULL, noback, nofor, table); } case CTO_Class: compileWarning(file, "class is deprecated, use attribute instead"); case CTO_Attribute: { if (nofor || noback) { compileWarning( file, "nofor and noback not allowed before class/attribute"); } if ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) || (opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) { compileError(file, "attribute and class rules must not be both present in a table"); return 0; } if (opcode == CTO_Class) (*table)->usesAttributeOrClass = 2; else (*table)->usesAttributeOrClass = 1; if (!getToken(file, &token, "attribute name")) { compileError(file, "Expected %s", "attribute name"); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } TranslationTableCharacterAttributes attribute = 0; { int attrNumber = -1; switch (token.chars[0]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': attrNumber = token.chars[0] - '0'; break; } if (attrNumber >= 0) { if (opcode == CTO_Class) { compileError(file, "Invalid class name: may not contain digits, use " "attribute instead of class"); return 0; } if (token.length > 1 || attrNumber > 7) { compileError(file, "Invalid attribute name: must be a digit between 0 and 7 " "or a word containing only letters"); return 0; } if (!(*table)->numberedAttributes[attrNumber]) // attribute not used before yet: assign it a value (*table)->numberedAttributes[attrNumber] = getNextNumberedAttribute(*table); attribute = (*table)->numberedAttributes[attrNumber]; } else { const CharacterClass *namedAttr = findCharacterClass(&token, *table); if (!namedAttr) { // no class with that name: create one namedAttr = addCharacterClass( file, &token.chars[0], token.length, *table, 1); if (!namedAttr) return 0; } // there is a class with that name or a new class was successfully // created attribute = namedAttr->attribute; if (attribute == CTC_UpperCase || attribute == CTC_LowerCase) attribute |= CTC_Letter; } } CharsString characters; if (!getCharacters(file, &characters)) return 0; for (int i = 0; i < characters.length; i++) { // get the character from the table, or if it is not defined yet, // define it TranslationTableCharacter *character = putChar(file, characters.chars[i], table, NULL); // set the attribute character->attributes |= attribute; // also set the attribute on the associated dots (if any) if (character->basechar) character = (TranslationTableCharacter *)&(*table) ->ruleArea[character->basechar]; if (character->definitionRule) { TranslationTableRule *defRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; if (defRule->dotslen == 1) { TranslationTableCharacter *dots = getDots(defRule->charsdots[defRule->charslen], *table); if (dots) dots->attributes |= attribute; } } } return 1; } { TranslationTableCharacterAttributes *attributes; const CharacterClass *class; case CTO_After: attributes = &after; goto doBeforeAfter; case CTO_Before: attributes = &before; doBeforeAfter: if (!(*table)->characterClasses) { if (!allocateCharacterClasses(*table)) return 0; } if (!getToken(file, &token, "attribute name")) return 0; if (!(class = findCharacterClass(&token, *table))) { compileError(file, "attribute not defined"); return 0; } *attributes |= class->attribute; goto doOpcode; } case CTO_Base: if (nofor || noback) { compileWarning(file, "nofor and noback not allowed before base"); } if (!getToken(file, &token, "attribute name")) { compileError( file, "base opcode must be followed by a valid attribute name."); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *mode = findCharacterClass(&token, *table); if (!mode) { mode = addCharacterClass(file, token.chars, token.length, *table, 1); if (!mode) return 0; } if (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) && mode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) { compileError(file, "base opcode must be followed by \"uppercase\", \"digit\", or a " "custom attribute name."); return 0; } if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one character followed by one base character is " "required."); return 0; } TranslationTableOffset characterOffset; TranslationTableCharacter *character = putChar(file, token.chars[0], table, &characterOffset); if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one base character is required."); return 0; } if (character->definitionRule) { TranslationTableRule *prevRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Character already defined (%s). The base rule will take " "precedence.", file->fileName, file->lineNumber, printSource(file, prevRule->sourceFile, prevRule->sourceLine)); character->definitionRule = 0; } TranslationTableOffset basechar; putChar(file, token.chars[0], table, &basechar); // putChar may have moved table, so make sure character is still valid character = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset]; if (character->basechar) { if (character->basechar == basechar && character->mode == mode->attribute) { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Duplicate base rule.", file->fileName, file->lineNumber); } else { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: A different base rule already exists for this " "character (%s). The new rule will take precedence.", file->fileName, file->lineNumber, printSource( file, character->sourceFile, character->sourceLine)); } } character->basechar = basechar; character->mode = mode->attribute; character->sourceFile = file->sourceFile; character->sourceLine = file->lineNumber; /* some other processing is done at the end of the compilation, in * finalizeTable() */ return 1; case CTO_EmpMatchBefore: before |= CTC_EmpMatch; goto doOpcode; case CTO_EmpMatchAfter: after |= CTC_EmpMatch; goto doOpcode; case CTO_SwapCc: case CTO_SwapCd: case CTO_SwapDd: return compileSwap(file, opcode, noback, nofor, table); case CTO_Hyphen: case CTO_DecPoint: // case CTO_Apostrophe: // case CTO_Initial: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length < 1) { compileError(file, "One Unicode character and at least one cell are " "required."); return 0; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); // if (opcode == CTO_DecPoint) // { // TranslationTableCharacter *c = // getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } default: compileError(file, "unimplemented opcode."); return 0; } } return 0; }
188995041946566375099409962387038802381
compileTranslationTable.c
129515444966510079462991982245291196170
CWE-787
CVE-2022-31783
Liblouis 3.21.0 has an out-of-bounds write in compileRule in compileTranslationTable.c, as demonstrated by lou_trace.
https://nvd.nist.gov/vuln/detail/CVE-2022-31783
215,038
gst-plugins-good
b31c504645a814c59d91d49e4fe218acaf93f4ca
https://github.com/GStreamer/gst-plugins-good
https://github.com/GStreamer/gst-plugins-good/commit/b31c504645a814c59d91d49e4fe218acaf93f4ca
flxdec: Don't unref() parent in the chain function We don't own the reference here, it is owned by the caller and given to us for the scope of this function. Leftover mistake from 0.10 porting. https://bugzilla.gnome.org/show_bug.cgi?id=774897
1
gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf) { GstCaps *caps; guint avail; GstFlowReturn res = GST_FLOW_OK; GstFlxDec *flxdec; FlxHeader *flxh; g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR); flxdec = (GstFlxDec *) parent; g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR); gst_adapter_push (flxdec->adapter, buf); avail = gst_adapter_available (flxdec->adapter); if (flxdec->state == GST_FLXDEC_READ_HEADER) { if (avail >= FlxHeaderSize) { const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize); GstCaps *templ; memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize); FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr)); gst_adapter_unmap (flxdec->adapter); gst_adapter_flush (flxdec->adapter, FlxHeaderSize); flxh = &flxdec->hdr; /* check header */ if (flxh->type != FLX_MAGICHDR_FLI && flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX) goto wrong_type; GST_LOG ("size : %d", flxh->size); GST_LOG ("frames : %d", flxh->frames); GST_LOG ("width : %d", flxh->width); GST_LOG ("height : %d", flxh->height); GST_LOG ("depth : %d", flxh->depth); GST_LOG ("speed : %d", flxh->speed); flxdec->next_time = 0; if (flxh->type == FLX_MAGICHDR_FLI) { flxdec->frame_time = JIFFIE * flxh->speed; } else if (flxh->speed == 0) { flxdec->frame_time = GST_SECOND / 70; } else { flxdec->frame_time = flxh->speed * GST_MSECOND; } flxdec->duration = flxh->frames * flxdec->frame_time; GST_LOG ("duration : %" GST_TIME_FORMAT, GST_TIME_ARGS (flxdec->duration)); templ = gst_pad_get_pad_template_caps (flxdec->srcpad); caps = gst_caps_copy (templ); gst_caps_unref (templ); gst_caps_set_simple (caps, "width", G_TYPE_INT, flxh->width, "height", G_TYPE_INT, flxh->height, "framerate", GST_TYPE_FRACTION, (gint) GST_MSECOND, (gint) flxdec->frame_time / 1000, NULL); gst_pad_set_caps (flxdec->srcpad, caps); gst_caps_unref (caps); if (flxh->depth <= 8) flxdec->converter = flx_colorspace_converter_new (flxh->width, flxh->height); if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) { GST_LOG ("(FLC) aspect_dx : %d", flxh->aspect_dx); GST_LOG ("(FLC) aspect_dy : %d", flxh->aspect_dy); GST_LOG ("(FLC) oframe1 : 0x%08x", flxh->oframe1); GST_LOG ("(FLC) oframe2 : 0x%08x", flxh->oframe2); } flxdec->size = ((guint) flxh->width * (guint) flxh->height); /* create delta and output frame */ flxdec->frame_data = g_malloc (flxdec->size); flxdec->delta_data = g_malloc (flxdec->size); flxdec->state = GST_FLXDEC_PLAYING; } } else if (flxdec->state == GST_FLXDEC_PLAYING) { GstBuffer *out; /* while we have enough data in the adapter */ while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) { FlxFrameChunk flxfh; guchar *chunk; const guint8 *data; GstMapInfo map; chunk = NULL; data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize); memcpy (&flxfh, data, FlxFrameChunkSize); FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh); gst_adapter_unmap (flxdec->adapter); switch (flxfh.id) { case FLX_FRAME_TYPE: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; /* flush header */ gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize); chunk = gst_adapter_take (flxdec->adapter, flxfh.size - FlxFrameChunkSize); FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk); if (((FlxFrameType *) chunk)->chunks == 0) break; /* create 32 bits output frame */ // res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad, // GST_BUFFER_OFFSET_NONE, // flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out); // if (res != GST_FLOW_OK) // break; out = gst_buffer_new_and_alloc (flxdec->size * 4); /* decode chunks */ if (!flx_decode_chunks (flxdec, ((FlxFrameType *) chunk)->chunks, chunk + FlxFrameTypeSize, flxdec->frame_data)) { GST_ELEMENT_ERROR (flxdec, STREAM, DECODE, ("%s", "Could not decode chunk"), NULL); return GST_FLOW_ERROR; } /* save copy of the current frame for possible delta. */ memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size); gst_buffer_map (out, &map, GST_MAP_WRITE); /* convert current frame. */ flx_colorspace_convert (flxdec->converter, flxdec->frame_data, map.data); gst_buffer_unmap (out, &map); GST_BUFFER_TIMESTAMP (out) = flxdec->next_time; flxdec->next_time += flxdec->frame_time; res = gst_pad_push (flxdec->srcpad, out); break; default: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; gst_adapter_flush (flxdec->adapter, flxfh.size); break; } g_free (chunk); avail = gst_adapter_available (flxdec->adapter); } } need_more_data: return res; /* ERRORS */ wrong_type: { GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL), ("not a flx file (type %x)", flxh->type)); gst_object_unref (flxdec); return GST_FLOW_ERROR; } }
293682781429111556527181973502820056353
gstflxdec.c
257993996858330004218595538099349772474
CWE-125
CVE-2016-9810
The gst_decode_chain_free_internal function in the flxdex decoder in gst-plugins-good in GStreamer before 1.10.2 allows remote attackers to cause a denial of service (invalid memory read and crash) via an invalid file, which triggers an incorrect unref call.
https://nvd.nist.gov/vuln/detail/CVE-2016-9810
482,692
gst-plugins-good
b31c504645a814c59d91d49e4fe218acaf93f4ca
https://github.com/GStreamer/gst-plugins-good
https://github.com/GStreamer/gst-plugins-good/commit/b31c504645a814c59d91d49e4fe218acaf93f4ca
flxdec: Don't unref() parent in the chain function We don't own the reference here, it is owned by the caller and given to us for the scope of this function. Leftover mistake from 0.10 porting. https://bugzilla.gnome.org/show_bug.cgi?id=774897
0
gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf) { GstCaps *caps; guint avail; GstFlowReturn res = GST_FLOW_OK; GstFlxDec *flxdec; FlxHeader *flxh; g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR); flxdec = (GstFlxDec *) parent; g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR); gst_adapter_push (flxdec->adapter, buf); avail = gst_adapter_available (flxdec->adapter); if (flxdec->state == GST_FLXDEC_READ_HEADER) { if (avail >= FlxHeaderSize) { const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize); GstCaps *templ; memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize); FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr)); gst_adapter_unmap (flxdec->adapter); gst_adapter_flush (flxdec->adapter, FlxHeaderSize); flxh = &flxdec->hdr; /* check header */ if (flxh->type != FLX_MAGICHDR_FLI && flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX) goto wrong_type; GST_LOG ("size : %d", flxh->size); GST_LOG ("frames : %d", flxh->frames); GST_LOG ("width : %d", flxh->width); GST_LOG ("height : %d", flxh->height); GST_LOG ("depth : %d", flxh->depth); GST_LOG ("speed : %d", flxh->speed); flxdec->next_time = 0; if (flxh->type == FLX_MAGICHDR_FLI) { flxdec->frame_time = JIFFIE * flxh->speed; } else if (flxh->speed == 0) { flxdec->frame_time = GST_SECOND / 70; } else { flxdec->frame_time = flxh->speed * GST_MSECOND; } flxdec->duration = flxh->frames * flxdec->frame_time; GST_LOG ("duration : %" GST_TIME_FORMAT, GST_TIME_ARGS (flxdec->duration)); templ = gst_pad_get_pad_template_caps (flxdec->srcpad); caps = gst_caps_copy (templ); gst_caps_unref (templ); gst_caps_set_simple (caps, "width", G_TYPE_INT, flxh->width, "height", G_TYPE_INT, flxh->height, "framerate", GST_TYPE_FRACTION, (gint) GST_MSECOND, (gint) flxdec->frame_time / 1000, NULL); gst_pad_set_caps (flxdec->srcpad, caps); gst_caps_unref (caps); if (flxh->depth <= 8) flxdec->converter = flx_colorspace_converter_new (flxh->width, flxh->height); if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) { GST_LOG ("(FLC) aspect_dx : %d", flxh->aspect_dx); GST_LOG ("(FLC) aspect_dy : %d", flxh->aspect_dy); GST_LOG ("(FLC) oframe1 : 0x%08x", flxh->oframe1); GST_LOG ("(FLC) oframe2 : 0x%08x", flxh->oframe2); } flxdec->size = ((guint) flxh->width * (guint) flxh->height); /* create delta and output frame */ flxdec->frame_data = g_malloc (flxdec->size); flxdec->delta_data = g_malloc (flxdec->size); flxdec->state = GST_FLXDEC_PLAYING; } } else if (flxdec->state == GST_FLXDEC_PLAYING) { GstBuffer *out; /* while we have enough data in the adapter */ while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) { FlxFrameChunk flxfh; guchar *chunk; const guint8 *data; GstMapInfo map; chunk = NULL; data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize); memcpy (&flxfh, data, FlxFrameChunkSize); FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh); gst_adapter_unmap (flxdec->adapter); switch (flxfh.id) { case FLX_FRAME_TYPE: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; /* flush header */ gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize); chunk = gst_adapter_take (flxdec->adapter, flxfh.size - FlxFrameChunkSize); FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk); if (((FlxFrameType *) chunk)->chunks == 0) break; /* create 32 bits output frame */ // res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad, // GST_BUFFER_OFFSET_NONE, // flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out); // if (res != GST_FLOW_OK) // break; out = gst_buffer_new_and_alloc (flxdec->size * 4); /* decode chunks */ if (!flx_decode_chunks (flxdec, ((FlxFrameType *) chunk)->chunks, chunk + FlxFrameTypeSize, flxdec->frame_data)) { GST_ELEMENT_ERROR (flxdec, STREAM, DECODE, ("%s", "Could not decode chunk"), NULL); return GST_FLOW_ERROR; } /* save copy of the current frame for possible delta. */ memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size); gst_buffer_map (out, &map, GST_MAP_WRITE); /* convert current frame. */ flx_colorspace_convert (flxdec->converter, flxdec->frame_data, map.data); gst_buffer_unmap (out, &map); GST_BUFFER_TIMESTAMP (out) = flxdec->next_time; flxdec->next_time += flxdec->frame_time; res = gst_pad_push (flxdec->srcpad, out); break; default: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; gst_adapter_flush (flxdec->adapter, flxfh.size); break; } g_free (chunk); avail = gst_adapter_available (flxdec->adapter); } } need_more_data: return res; /* ERRORS */ wrong_type: { GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL), ("not a flx file (type %x)", flxh->type)); return GST_FLOW_ERROR; } }
307699482792832838844638071066338187796
gstflxdec.c
15220895690601023240129213899493293437
CWE-125
CVE-2016-9810
The gst_decode_chain_free_internal function in the flxdex decoder in gst-plugins-good in GStreamer before 1.10.2 allows remote attackers to cause a denial of service (invalid memory read and crash) via an invalid file, which triggers an incorrect unref call.
https://nvd.nist.gov/vuln/detail/CVE-2016-9810
215,073
linux
24f6008564183aa120d07c03d9289519c2fe02af
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/24f6008564183aa120d07c03d9289519c2fe02af
cgroup-v1: Require capabilities to set release_agent The cgroup release_agent is called with call_usermodehelper. The function call_usermodehelper starts the release_agent with a full set fo capabilities. Therefore require capabilities when setting the release_agaent. Reported-by: Tabitha Sable <[email protected]> Tested-by: Tabitha Sable <[email protected]> Fixes: 81a6a5cdd2c5 ("Task Control Groups: automatic userspace notification of idle cgroups") Cc: [email protected] # v2.6.24+ Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Tejun Heo <[email protected]>
1
static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { struct cgroup *cgrp; BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX); cgrp = cgroup_kn_lock_live(of->kn, false); if (!cgrp) return -ENODEV; spin_lock(&release_agent_path_lock); strlcpy(cgrp->root->release_agent_path, strstrip(buf), sizeof(cgrp->root->release_agent_path)); spin_unlock(&release_agent_path_lock); cgroup_kn_unlock(of->kn); return nbytes; }
62903931031364372249216035169426622389
cgroup-v1.c
159693224935670518088988394061249784059
CWE-269
CVE-2022-0492
A vulnerability was found in the Linux kernel’s cgroup_release_agent_write in the kernel/cgroup/cgroup-v1.c function. This flaw, under certain circumstances, allows the use of the cgroups v1 release_agent feature to escalate privileges and bypass the namespace isolation unexpectedly.
https://nvd.nist.gov/vuln/detail/CVE-2022-0492
483,053
linux
24f6008564183aa120d07c03d9289519c2fe02af
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/24f6008564183aa120d07c03d9289519c2fe02af
cgroup-v1: Require capabilities to set release_agent The cgroup release_agent is called with call_usermodehelper. The function call_usermodehelper starts the release_agent with a full set fo capabilities. Therefore require capabilities when setting the release_agaent. Reported-by: Tabitha Sable <[email protected]> Tested-by: Tabitha Sable <[email protected]> Fixes: 81a6a5cdd2c5 ("Task Control Groups: automatic userspace notification of idle cgroups") Cc: [email protected] # v2.6.24+ Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Tejun Heo <[email protected]>
0
static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { struct cgroup *cgrp; BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX); /* * Release agent gets called with all capabilities, * require capabilities to set release agent. */ if ((of->file->f_cred->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN)) return -EPERM; cgrp = cgroup_kn_lock_live(of->kn, false); if (!cgrp) return -ENODEV; spin_lock(&release_agent_path_lock); strlcpy(cgrp->root->release_agent_path, strstrip(buf), sizeof(cgrp->root->release_agent_path)); spin_unlock(&release_agent_path_lock); cgroup_kn_unlock(of->kn); return nbytes; }
43963490668592516286761666416958152261
cgroup-v1.c
124298823051510119794232043748065237512
CWE-269
CVE-2022-0492
A vulnerability was found in the Linux kernel’s cgroup_release_agent_write in the kernel/cgroup/cgroup-v1.c function. This flaw, under certain circumstances, allows the use of the cgroups v1 release_agent feature to escalate privileges and bypass the namespace isolation unexpectedly.
https://nvd.nist.gov/vuln/detail/CVE-2022-0492