source
stringclasses 3
values | pair_id
stringlengths 24
88
| commit_id
stringlengths 7
40
| project
stringlengths 2
42
| project_url
stringclasses 998
values | vuln_func
stringlengths 61
482k
| patched_func
stringlengths 28
484k
| cve
stringlengths 13
16
⌀ | cve_desc
stringlengths 35
2.26k
⌀ | cwe
listlengths 1
6
| deleted_lines
listlengths 0
981
| added_lines
listlengths 0
1.09k
| source_row_idx
int64 0
218k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
primevul
|
primevul_openssl_ca989269a2876bae79393bd54c3e72d49975fc75
|
ca989269a2876bae79393bd54c3e72d49975fc75
|
openssl
|
https://github.com/openssl/openssl
|
long ssl_get_algorithm2(SSL *s)
{
long alg2 = s->s3->tmp.new_cipher->algorithm2;
if (TLS1_get_version(s) >= TLS1_2_VERSION &&
alg2 == (SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF))
return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256;
return alg2;
}
|
long ssl_get_algorithm2(SSL *s)
{
long alg2 = s->s3->tmp.new_cipher->algorithm2;
if (s->method->version == TLS1_2_VERSION &&
alg2 == (SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF))
return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256;
return alg2;
}
|
CVE-2013-6449
|
The ssl_get_algorithm2 function in ssl/s3_lib.c in OpenSSL before 1.0.2 obtains a certain version number from an incorrect data structure, which allows remote attackers to cause a denial of service (daemon crash) via crafted traffic from a TLS 1.2 client.
|
[
"CWE-310"
] |
[
{
"line_no": 4,
"text": " if (TLS1_get_version(s) >= TLS1_2_VERSION &&",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 4,
"text": " if (s->method->version == TLS1_2_VERSION &&",
"char_start": null,
"char_end": null
}
] | 0
|
primevul
|
primevul_savannah_190cef6eed37d0e73a73c1e205eb31d45ab60a3c
|
190cef6eed37d0e73a73c1e205eb31d45ab60a3c
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
*session_data_size = psession.size;
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
|
gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
*session_data_size = psession.size;
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
|
CVE-2011-4128
|
Buffer overflow in the gnutls_session_get_data function in lib/gnutls_session.c in GnuTLS 2.12.x before 2.12.14 and 3.x before 3.0.7, when used on a client that performs nonstandard session resumption, allows remote TLS servers to cause a denial of service (application crash) via a large SessionTicket.
|
[
"CWE-119"
] |
[
{
"line_no": 19,
"text": " *session_data_size = psession.size;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 25,
"text": " *session_data_size = psession.size;",
"char_start": null,
"char_end": null
}
] | 1
|
primevul
|
primevul_savannah_e82ef4545e9e98cbcb032f55d7c750b81e3a0450
|
e82ef4545e9e98cbcb032f55d7c750b81e3a0450
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
|
gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
*session_data_size = psession.size;
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
|
CVE-2011-4128
|
Buffer overflow in the gnutls_session_get_data function in lib/gnutls_session.c in GnuTLS 2.12.x before 2.12.14 and 3.x before 3.0.7, when used on a client that performs nonstandard session resumption, allows remote TLS servers to cause a denial of service (application crash) via a large SessionTicket.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 22,
"text": " *session_data_size = psession.size;",
"char_start": null,
"char_end": null
}
] | 2
|
primevul
|
primevul_savannah_075d7556964f5a871a73c22ac4b69f5361295099
|
075d7556964f5a871a73c22ac4b69f5361295099
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread,
wgint restval, ccon *con, int count, wgint *last_expected_bytes,
FILE *warc_tmp)
{
int csock, dtsock, local_sock, res;
uerr_t err = RETROK; /* appease the compiler */
FILE *fp;
char *respline, *tms;
const char *user, *passwd, *tmrate;
int cmd = con->cmd;
bool pasv_mode_open = false;
wgint expected_bytes = 0;
bool got_expected_bytes = false;
bool rest_failed = false;
bool rest_failed = false;
int flags;
wgint rd_size, previous_rd_size = 0;
char type_char;
bool try_again;
bool list_a_used = false;
assert (con != NULL);
assert (con->target != NULL);
/* Debug-check of the sanity of the request by making sure that LIST
and RETR are never both requested (since we can handle only one
at a time. */
assert (!((cmd & DO_LIST) && (cmd & DO_RETR)));
/* Make sure that at least *something* is requested. */
assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0);
*qtyread = restval;
user = u->user;
passwd = u->passwd;
search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1);
user = user ? user : (opt.ftp_user ? opt.ftp_user : opt.user);
if (!user) user = "anonymous";
passwd = passwd ? passwd : (opt.ftp_passwd ? opt.ftp_passwd : opt.passwd);
if (!passwd) passwd = "-wget@";
dtsock = -1;
local_sock = -1;
con->dltime = 0;
if (!(cmd & DO_LOGIN))
csock = con->csock;
else /* cmd & DO_LOGIN */
{
char *host = con->proxy ? con->proxy->host : u->host;
int port = con->proxy ? con->proxy->port : u->port;
/* Login to the server: */
/* First: Establish the control connection. */
csock = connect_to_host (host, port);
if (csock == E_HOST)
return HOSTERR;
else if (csock < 0)
return (retryable_socket_connect_error (errno)
? CONERROR : CONIMPOSSIBLE);
if (cmd & LEAVE_PENDING)
con->csock = csock;
else
con->csock = -1;
/* Second: Login with proper USER/PASS sequence. */
logprintf (LOG_VERBOSE, _("Logging in as %s ... "),
quotearg_style (escape_quoting_style, user));
if (opt.server_response)
logputs (LOG_ALWAYS, "\n");
if (con->proxy)
{
/* If proxy is in use, log in as username@target-site. */
char *logname = concat_strings (user, "@", u->host, (char *) 0);
err = ftp_login (csock, logname, passwd);
xfree (logname);
}
else
err = ftp_login (csock, user, passwd);
/* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Error in server greeting.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPLOGREFUSED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("The server refuses login.\n"));
fd_close (csock);
con->csock = -1;
return FTPLOGREFUSED;
case FTPLOGINC:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Login incorrect.\n"));
fd_close (csock);
con->csock = -1;
return FTPLOGINC;
case FTPOK:
if (!opt.server_response)
logputs (LOG_VERBOSE, _("Logged in!\n"));
break;
default:
abort ();
}
/* Third: Get the system type */
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> SYST ... ");
err = ftp_syst (csock, &con->rs, &con->rsu);
/* FTPRERR */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Server error, can't determine system type.\n"));
break;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response && err != FTPSRVERR)
logputs (LOG_VERBOSE, _("done. "));
/* 2013-10-17 Andrea Urbani (matfanjol)
According to the system type I choose which
list command will be used.
If I don't know that system, I will try, the
first time of each session, "LIST -a" and
"LIST". (see __LIST_A_EXPLANATION__ below) */
switch (con->rs)
{
case ST_VMS:
/* About ST_VMS there is an old note:
2008-01-29 SMS. For a VMS FTP server, where "LIST -a" may not
fail, but will never do what is desired here,
skip directly to the simple "LIST" command
(assumed to be the last one in the list). */
DEBUGP (("\nVMS: I know it and I will use \"LIST\" as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST_A;
break;
case ST_UNIX:
if (con->rsu == UST_MULTINET)
{
DEBUGP (("\nUNIX MultiNet: I know it and I will use \"LIST\" "
"as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST_A;
}
else if (con->rsu == UST_TYPE_L8)
{
DEBUGP (("\nUNIX TYPE L8: I know it and I will use \"LIST -a\" "
"as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST;
}
break;
default:
break;
}
/* Fourth: Find the initial ftp directory */
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> PWD ... ");
err = ftp_pwd (csock, &con->id);
/* FTPRERR */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR :
/* PWD unsupported -- assume "/". */
xfree (con->id);
con->id = xstrdup ("/");
break;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
#if 0
/* 2004-09-17 SMS.
Don't help me out. Please.
A reasonably recent VMS FTP server will cope just fine with
UNIX file specifications. This code just spoils things.
Discarding the device name, for example, is not a wise move.
This code was disabled but left in as an example of what not
to do.
*/
/* VMS will report something like "PUB$DEVICE:[INITIAL.FOLDER]".
Convert it to "/INITIAL/FOLDER" */
if (con->rs == ST_VMS)
{
char *path = strchr (con->id, '[');
char *pathend = path ? strchr (path + 1, ']') : NULL;
if (!path || !pathend)
DEBUGP (("Initial VMS directory not in the form [...]!\n"));
else
{
char *idir = con->id;
DEBUGP (("Preprocessing the initial VMS directory\n"));
DEBUGP ((" old = '%s'\n", con->id));
/* We do the conversion in-place by copying the stuff
between [ and ] to the beginning, and changing dots
to slashes at the same time. */
*idir++ = '/';
for (++path; path < pathend; path++, idir++)
*idir = *path == '.' ? '/' : *path;
*idir = '\0';
DEBUGP ((" new = '%s'\n\n", con->id));
}
}
#endif /* 0 */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
/* Fifth: Set the FTP type. */
type_char = ftp_process_type (u->params);
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> TYPE %c ... ", type_char);
err = ftp_type (csock, type_char);
/* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPUNKNOWNTYPE:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET,
_("Unknown type `%c', closing control connection.\n"),
type_char);
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* do login */
if (cmd & DO_CWD)
{
if (!*u->dir)
logputs (LOG_VERBOSE, _("==> CWD not needed.\n"));
else
{
const char *targ = NULL;
int cwd_count;
int cwd_end;
int cwd_start;
char *target = u->dir;
DEBUGP (("changing working directory\n"));
/* Change working directory. To change to a non-absolute
Unix directory, we need to prepend initial directory
(con->id) to it. Absolute directories "just work".
A relative directory is one that does not begin with '/'
and, on non-Unix OS'es, one that doesn't begin with
"[a-z]:".
This is not done for OS400, which doesn't use
"/"-delimited directories, nor does it support directory
hierarchies. "CWD foo" followed by "CWD bar" leaves us
in "bar", not in "foo/bar", as would be customary
elsewhere. */
/* 2004-09-20 SMS.
Why is this wise even on UNIX? It certainly fouls VMS.
See below for a more reliable, more universal method.
*/
/* 2008-04-22 MJC.
I'm not crazy about it either. I'm informed it's useful
for misconfigured servers that have some dirs in the path
with +x but -r, but this method is not RFC-conformant. I
understand the need to deal with crappy server
configurations, but it's far better to use the canonical
method first, and fall back to kludges second.
*/
if (target[0] != '/'
&& !(con->rs != ST_UNIX
&& c_isalpha (target[0])
&& target[1] == ':')
&& (con->rs != ST_OS400)
&& (con->rs != ST_VMS))
{
int idlen = strlen (con->id);
char *ntarget, *p;
/* Strip trailing slash(es) from con->id. */
while (idlen > 0 && con->id[idlen - 1] == '/')
--idlen;
p = ntarget = (char *)alloca (idlen + 1 + strlen (u->dir) + 1);
memcpy (p, con->id, idlen);
p += idlen;
*p++ = '/';
strcpy (p, target);
DEBUGP (("Prepended initial PWD to relative path:\n"));
DEBUGP ((" pwd: '%s'\n old: '%s'\n new: '%s'\n",
con->id, target, ntarget));
target = ntarget;
}
#if 0
/* 2004-09-17 SMS.
Don't help me out. Please.
A reasonably recent VMS FTP server will cope just fine with
UNIX file specifications. This code just spoils things.
Discarding the device name, for example, is not a wise
move.
This code was disabled but left in as an example of what
not to do.
*/
/* If the FTP host runs VMS, we will have to convert the absolute
directory path in UNIX notation to absolute directory path in
VMS notation as VMS FTP servers do not like UNIX notation of
absolute paths. "VMS notation" is [dir.subdir.subsubdir]. */
if (con->rs == ST_VMS)
{
char *tmpp;
char *ntarget = (char *)alloca (strlen (target) + 2);
/* We use a converted initial dir, so directories in
TARGET will be separated with slashes, something like
"/INITIAL/FOLDER/DIR/SUBDIR". Convert that to
"[INITIAL.FOLDER.DIR.SUBDIR]". */
strcpy (ntarget, target);
assert (*ntarget == '/');
*ntarget = '[';
for (tmpp = ntarget + 1; *tmpp; tmpp++)
if (*tmpp == '/')
*tmpp = '.';
*tmpp++ = ']';
*tmpp = '\0';
DEBUGP (("Changed file name to VMS syntax:\n"));
DEBUGP ((" Unix: '%s'\n VMS: '%s'\n", target, ntarget));
target = ntarget;
}
#endif /* 0 */
/* 2004-09-20 SMS.
A relative directory is relative to the initial directory.
Thus, what _is_ useful on VMS (and probably elsewhere) is
to CWD to the initial directory (ideally, whatever the
server reports, _exactly_, NOT badly UNIX-ixed), and then
CWD to the (new) relative directory. This should probably
be restructured as a function, called once or twice, but
I'm lazy enough to take the badly indented loop short-cut
for now.
*/
/* Decide on one pass (absolute) or two (relative).
The VMS restriction may be relaxed when the squirrely code
above is reformed.
*/
if ((con->rs == ST_VMS) && (target[0] != '/'))
{
cwd_start = 0;
DEBUGP (("Using two-step CWD for relative path.\n"));
}
else
{
/* Go straight to the target. */
cwd_start = 1;
}
/* At least one VMS FTP server (TCPware V5.6-2) can switch to
a UNIX emulation mode when given a UNIX-like directory
specification (like "a/b/c"). If allowed to continue this
way, LIST interpretation will be confused, because the
system type (SYST response) will not be re-checked, and
future UNIX-format directory listings (for multiple URLs or
"-r") will be horribly misinterpreted.
The cheap and nasty work-around is to do a "CWD []" after a
UNIX-like directory specification is used. (A single-level
directory is harmless.) This puts the TCPware server back
into VMS mode, and does no harm on other servers.
Unlike the rest of this block, this particular behavior
_is_ VMS-specific, so it gets its own VMS test.
*/
if ((con->rs == ST_VMS) && (strchr( target, '/') != NULL))
{
cwd_end = 3;
DEBUGP (("Using extra \"CWD []\" step for VMS server.\n"));
}
else
{
cwd_end = 2;
}
/* 2004-09-20 SMS. */
/* Sorry about the deviant indenting. Laziness. */
for (cwd_count = cwd_start; cwd_count < cwd_end; cwd_count++)
{
switch (cwd_count)
{
case 0:
/* Step one (optional): Go to the initial directory,
exactly as reported by the server.
*/
targ = con->id;
break;
case 1:
/* Step two: Go to the target directory. (Absolute or
relative will work now.)
*/
targ = target;
break;
case 2:
/* Step three (optional): "CWD []" to restore server
VMS-ness.
*/
targ = "[]";
break;
default:
logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()"));
logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"),
cwd_count, cwd_start, cwd_end);
abort ();
}
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> CWD (%d) %s ... ", cwd_count,
quotearg_style (escape_quoting_style, target));
err = ftp_cwd (csock, targ);
/* FTPRERR, WRITEFAILED, FTPNSFOD */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such directory %s.\n\n"),
quote (u->dir));
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
} /* for */
/* 2004-09-20 SMS. */
} /* else */
}
else /* do not CWD */
logputs (LOG_VERBOSE, _("==> CWD not required.\n"));
if ((cmd & DO_RETR) && passed_expected_bytes == 0)
{
if (opt.verbose)
{
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> SIZE %s ... ",
quotearg_style (escape_quoting_style, u->file));
}
err = ftp_size (csock, u->file, &expected_bytes);
/* FTPRERR */
switch (err)
{
case FTPRERR:
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
got_expected_bytes = true;
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response)
{
logprintf (LOG_VERBOSE, "%s\n",
expected_bytes ?
number_to_static_string (expected_bytes) :
_("done.\n"));
}
}
if (cmd & DO_RETR && restval > 0 && restval == expected_bytes)
{
/* Server confirms that file has length restval. We should stop now.
Some servers (f.e. NcFTPd) return error when receive REST 0 */
logputs (LOG_VERBOSE, _("File has already been retrieved.\n"));
fd_close (csock);
con->csock = -1;
return RETRFINISHED;
}
do
{
try_again = false;
/* If anything is to be retrieved, PORT (or PASV) must be sent. */
if (cmd & (DO_LIST | DO_RETR))
{
if (opt.ftp_pasv)
{
ip_address passive_addr;
int passive_port;
err = ftp_do_pasv (csock, &passive_addr, &passive_port);
/* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPNOPASV:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n"));
break;
case FTPINVPASV:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n"));
break;
case FTPOK:
break;
default:
abort ();
} /* switch (err) */
if (err==FTPOK)
{
DEBUGP (("trying to connect to %s port %d\n",
print_address (&passive_addr), passive_port));
dtsock = connect_to_ip (&passive_addr, passive_port, NULL);
if (dtsock < 0)
{
int save_errno = errno;
fd_close (csock);
con->csock = -1;
logprintf (LOG_VERBOSE, _("couldn't connect to %s port %d: %s\n"),
print_address (&passive_addr), passive_port,
strerror (save_errno));
? CONERROR : CONIMPOSSIBLE);
}
pasv_mode_open = true; /* Flag to avoid accept port */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* err==FTP_OK */
}
if (!pasv_mode_open) /* Try to use a port command if PASV failed */
{
err = ftp_do_port (csock, &local_sock);
/* FTPRERR, WRITEFAILED, bindport (FTPSYSERR), HOSTERR,
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case CONSOCKERR:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPSYSERR:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"),
strerror (errno));
fd_close (dtsock);
return err;
case FTPPORTERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Invalid PORT.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
} /* port switch */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* dtsock == -1 */
} /* cmd & (DO_LIST | DO_RETR) */
/* Restart if needed. */
if (restval && (cmd & DO_RETR))
{
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> REST %s ... ",
number_to_static_string (restval));
err = ftp_rest (csock, restval);
/* FTPRERR, WRITEFAILED, FTPRESTFAIL */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPRESTFAIL:
logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n"));
rest_failed = true;
break;
case FTPOK:
break;
default:
abort ();
}
if (err != FTPRESTFAIL && !opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* restval && cmd & DO_RETR */
if (cmd & DO_RETR)
{
/* If we're in spider mode, don't really retrieve anything except
the directory listing and verify whether the given "file" exists. */
if (opt.spider)
{
bool exists = false;
struct fileinfo *f;
uerr_t _res = ftp_get_listing (u, con, &f);
/* Set the DO_RETR command flag again, because it gets unset when
calling ftp_get_listing() and would otherwise cause an assertion
failure earlier on when this function gets repeatedly called
(e.g., when recursing). */
con->cmd |= DO_RETR;
if (_res == RETROK)
{
while (f)
{
if (!strcmp (f->name, u->file))
{
exists = true;
break;
}
f = f->next;
}
if (exists)
{
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("File %s exists.\n"),
quote (u->file));
}
else
{
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file %s.\n"),
quote (u->file));
}
}
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return RETRFINISHED;
}
if (opt.verbose)
{
if (!opt.server_response)
{
if (restval)
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_VERBOSE, "==> RETR %s ... ",
quotearg_style (escape_quoting_style, u->file));
}
}
err = ftp_retr (csock, u->file);
/* FTPRERR, WRITEFAILED, FTPNSFOD */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file %s.\n\n"),
quote (u->file));
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
if (! got_expected_bytes)
expected_bytes = *last_expected_bytes;
} /* do retrieve */
if (cmd & DO_LIST)
{
if (!opt.server_response)
logputs (LOG_VERBOSE, "==> LIST ... ");
/* As Maciej W. Rozycki (macro@ds2.pg.gda.pl) says, `LIST'
without arguments is better than `LIST .'; confirmed by
RFC959. */
err = ftp_list (csock, NULL, con->st&AVOID_LIST_A, con->st&AVOID_LIST, &list_a_used);
/* FTPRERR, WRITEFAILED */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file or directory %s.\n\n"),
quote ("."));
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
if (! got_expected_bytes)
expected_bytes = *last_expected_bytes;
} /* cmd & DO_LIST */
if (!(cmd & (DO_LIST | DO_RETR)) || (opt.spider && !(cmd & DO_LIST)))
return RETRFINISHED;
/* Some FTP servers return the total length of file after REST
command, others just return the remaining size. */
if (passed_expected_bytes && restval && expected_bytes
&& (expected_bytes == passed_expected_bytes - restval))
{
DEBUGP (("Lying FTP server found, adjusting.\n"));
expected_bytes = passed_expected_bytes;
}
/* If no transmission was required, then everything is OK. */
if (!pasv_mode_open) /* we are not using pasive mode so we need
to accept */
}
|
getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread,
wgint restval, ccon *con, int count, wgint *last_expected_bytes,
FILE *warc_tmp)
{
int csock, dtsock, local_sock, res;
uerr_t err = RETROK; /* appease the compiler */
FILE *fp;
char *respline, *tms;
const char *user, *passwd, *tmrate;
int cmd = con->cmd;
wgint expected_bytes = 0;
bool got_expected_bytes = false;
bool rest_failed = false;
bool rest_failed = false;
int flags;
wgint rd_size, previous_rd_size = 0;
char type_char;
bool try_again;
bool list_a_used = false;
assert (con != NULL);
assert (con->target != NULL);
/* Debug-check of the sanity of the request by making sure that LIST
and RETR are never both requested (since we can handle only one
at a time. */
assert (!((cmd & DO_LIST) && (cmd & DO_RETR)));
/* Make sure that at least *something* is requested. */
assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0);
*qtyread = restval;
user = u->user;
passwd = u->passwd;
search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1);
user = user ? user : (opt.ftp_user ? opt.ftp_user : opt.user);
if (!user) user = "anonymous";
passwd = passwd ? passwd : (opt.ftp_passwd ? opt.ftp_passwd : opt.passwd);
if (!passwd) passwd = "-wget@";
dtsock = -1;
local_sock = -1;
con->dltime = 0;
if (!(cmd & DO_LOGIN))
csock = con->csock;
else /* cmd & DO_LOGIN */
{
char *host = con->proxy ? con->proxy->host : u->host;
int port = con->proxy ? con->proxy->port : u->port;
/* Login to the server: */
/* First: Establish the control connection. */
csock = connect_to_host (host, port);
if (csock == E_HOST)
return HOSTERR;
else if (csock < 0)
return (retryable_socket_connect_error (errno)
? CONERROR : CONIMPOSSIBLE);
if (cmd & LEAVE_PENDING)
con->csock = csock;
else
con->csock = -1;
/* Second: Login with proper USER/PASS sequence. */
logprintf (LOG_VERBOSE, _("Logging in as %s ... "),
quotearg_style (escape_quoting_style, user));
if (opt.server_response)
logputs (LOG_ALWAYS, "\n");
if (con->proxy)
{
/* If proxy is in use, log in as username@target-site. */
char *logname = concat_strings (user, "@", u->host, (char *) 0);
err = ftp_login (csock, logname, passwd);
xfree (logname);
}
else
err = ftp_login (csock, user, passwd);
/* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Error in server greeting.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPLOGREFUSED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("The server refuses login.\n"));
fd_close (csock);
con->csock = -1;
return FTPLOGREFUSED;
case FTPLOGINC:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Login incorrect.\n"));
fd_close (csock);
con->csock = -1;
return FTPLOGINC;
case FTPOK:
if (!opt.server_response)
logputs (LOG_VERBOSE, _("Logged in!\n"));
break;
default:
abort ();
}
/* Third: Get the system type */
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> SYST ... ");
err = ftp_syst (csock, &con->rs, &con->rsu);
/* FTPRERR */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Server error, can't determine system type.\n"));
break;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response && err != FTPSRVERR)
logputs (LOG_VERBOSE, _("done. "));
/* 2013-10-17 Andrea Urbani (matfanjol)
According to the system type I choose which
list command will be used.
If I don't know that system, I will try, the
first time of each session, "LIST -a" and
"LIST". (see __LIST_A_EXPLANATION__ below) */
switch (con->rs)
{
case ST_VMS:
/* About ST_VMS there is an old note:
2008-01-29 SMS. For a VMS FTP server, where "LIST -a" may not
fail, but will never do what is desired here,
skip directly to the simple "LIST" command
(assumed to be the last one in the list). */
DEBUGP (("\nVMS: I know it and I will use \"LIST\" as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST_A;
break;
case ST_UNIX:
if (con->rsu == UST_MULTINET)
{
DEBUGP (("\nUNIX MultiNet: I know it and I will use \"LIST\" "
"as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST_A;
}
else if (con->rsu == UST_TYPE_L8)
{
DEBUGP (("\nUNIX TYPE L8: I know it and I will use \"LIST -a\" "
"as standard list command\n"));
con->st |= LIST_AFTER_LIST_A_CHECK_DONE;
con->st |= AVOID_LIST;
}
break;
default:
break;
}
/* Fourth: Find the initial ftp directory */
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> PWD ... ");
err = ftp_pwd (csock, &con->id);
/* FTPRERR */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPSRVERR :
/* PWD unsupported -- assume "/". */
xfree (con->id);
con->id = xstrdup ("/");
break;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
#if 0
/* 2004-09-17 SMS.
Don't help me out. Please.
A reasonably recent VMS FTP server will cope just fine with
UNIX file specifications. This code just spoils things.
Discarding the device name, for example, is not a wise move.
This code was disabled but left in as an example of what not
to do.
*/
/* VMS will report something like "PUB$DEVICE:[INITIAL.FOLDER]".
Convert it to "/INITIAL/FOLDER" */
if (con->rs == ST_VMS)
{
char *path = strchr (con->id, '[');
char *pathend = path ? strchr (path + 1, ']') : NULL;
if (!path || !pathend)
DEBUGP (("Initial VMS directory not in the form [...]!\n"));
else
{
char *idir = con->id;
DEBUGP (("Preprocessing the initial VMS directory\n"));
DEBUGP ((" old = '%s'\n", con->id));
/* We do the conversion in-place by copying the stuff
between [ and ] to the beginning, and changing dots
to slashes at the same time. */
*idir++ = '/';
for (++path; path < pathend; path++, idir++)
*idir = *path == '.' ? '/' : *path;
*idir = '\0';
DEBUGP ((" new = '%s'\n\n", con->id));
}
}
#endif /* 0 */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
/* Fifth: Set the FTP type. */
type_char = ftp_process_type (u->params);
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> TYPE %c ... ", type_char);
err = ftp_type (csock, type_char);
/* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPUNKNOWNTYPE:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET,
_("Unknown type `%c', closing control connection.\n"),
type_char);
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* do login */
if (cmd & DO_CWD)
{
if (!*u->dir)
logputs (LOG_VERBOSE, _("==> CWD not needed.\n"));
else
{
const char *targ = NULL;
int cwd_count;
int cwd_end;
int cwd_start;
char *target = u->dir;
DEBUGP (("changing working directory\n"));
/* Change working directory. To change to a non-absolute
Unix directory, we need to prepend initial directory
(con->id) to it. Absolute directories "just work".
A relative directory is one that does not begin with '/'
and, on non-Unix OS'es, one that doesn't begin with
"[a-z]:".
This is not done for OS400, which doesn't use
"/"-delimited directories, nor does it support directory
hierarchies. "CWD foo" followed by "CWD bar" leaves us
in "bar", not in "foo/bar", as would be customary
elsewhere. */
/* 2004-09-20 SMS.
Why is this wise even on UNIX? It certainly fouls VMS.
See below for a more reliable, more universal method.
*/
/* 2008-04-22 MJC.
I'm not crazy about it either. I'm informed it's useful
for misconfigured servers that have some dirs in the path
with +x but -r, but this method is not RFC-conformant. I
understand the need to deal with crappy server
configurations, but it's far better to use the canonical
method first, and fall back to kludges second.
*/
if (target[0] != '/'
&& !(con->rs != ST_UNIX
&& c_isalpha (target[0])
&& target[1] == ':')
&& (con->rs != ST_OS400)
&& (con->rs != ST_VMS))
{
int idlen = strlen (con->id);
char *ntarget, *p;
/* Strip trailing slash(es) from con->id. */
while (idlen > 0 && con->id[idlen - 1] == '/')
--idlen;
p = ntarget = (char *)alloca (idlen + 1 + strlen (u->dir) + 1);
memcpy (p, con->id, idlen);
p += idlen;
*p++ = '/';
strcpy (p, target);
DEBUGP (("Prepended initial PWD to relative path:\n"));
DEBUGP ((" pwd: '%s'\n old: '%s'\n new: '%s'\n",
con->id, target, ntarget));
target = ntarget;
}
#if 0
/* 2004-09-17 SMS.
Don't help me out. Please.
A reasonably recent VMS FTP server will cope just fine with
UNIX file specifications. This code just spoils things.
Discarding the device name, for example, is not a wise
move.
This code was disabled but left in as an example of what
not to do.
*/
/* If the FTP host runs VMS, we will have to convert the absolute
directory path in UNIX notation to absolute directory path in
VMS notation as VMS FTP servers do not like UNIX notation of
absolute paths. "VMS notation" is [dir.subdir.subsubdir]. */
if (con->rs == ST_VMS)
{
char *tmpp;
char *ntarget = (char *)alloca (strlen (target) + 2);
/* We use a converted initial dir, so directories in
TARGET will be separated with slashes, something like
"/INITIAL/FOLDER/DIR/SUBDIR". Convert that to
"[INITIAL.FOLDER.DIR.SUBDIR]". */
strcpy (ntarget, target);
assert (*ntarget == '/');
*ntarget = '[';
for (tmpp = ntarget + 1; *tmpp; tmpp++)
if (*tmpp == '/')
*tmpp = '.';
*tmpp++ = ']';
*tmpp = '\0';
DEBUGP (("Changed file name to VMS syntax:\n"));
DEBUGP ((" Unix: '%s'\n VMS: '%s'\n", target, ntarget));
target = ntarget;
}
#endif /* 0 */
/* 2004-09-20 SMS.
A relative directory is relative to the initial directory.
Thus, what _is_ useful on VMS (and probably elsewhere) is
to CWD to the initial directory (ideally, whatever the
server reports, _exactly_, NOT badly UNIX-ixed), and then
CWD to the (new) relative directory. This should probably
be restructured as a function, called once or twice, but
I'm lazy enough to take the badly indented loop short-cut
for now.
*/
/* Decide on one pass (absolute) or two (relative).
The VMS restriction may be relaxed when the squirrely code
above is reformed.
*/
if ((con->rs == ST_VMS) && (target[0] != '/'))
{
cwd_start = 0;
DEBUGP (("Using two-step CWD for relative path.\n"));
}
else
{
/* Go straight to the target. */
cwd_start = 1;
}
/* At least one VMS FTP server (TCPware V5.6-2) can switch to
a UNIX emulation mode when given a UNIX-like directory
specification (like "a/b/c"). If allowed to continue this
way, LIST interpretation will be confused, because the
system type (SYST response) will not be re-checked, and
future UNIX-format directory listings (for multiple URLs or
"-r") will be horribly misinterpreted.
The cheap and nasty work-around is to do a "CWD []" after a
UNIX-like directory specification is used. (A single-level
directory is harmless.) This puts the TCPware server back
into VMS mode, and does no harm on other servers.
Unlike the rest of this block, this particular behavior
_is_ VMS-specific, so it gets its own VMS test.
*/
if ((con->rs == ST_VMS) && (strchr( target, '/') != NULL))
{
cwd_end = 3;
DEBUGP (("Using extra \"CWD []\" step for VMS server.\n"));
}
else
{
cwd_end = 2;
}
/* 2004-09-20 SMS. */
/* Sorry about the deviant indenting. Laziness. */
for (cwd_count = cwd_start; cwd_count < cwd_end; cwd_count++)
{
switch (cwd_count)
{
case 0:
/* Step one (optional): Go to the initial directory,
exactly as reported by the server.
*/
targ = con->id;
break;
case 1:
/* Step two: Go to the target directory. (Absolute or
relative will work now.)
*/
targ = target;
break;
case 2:
/* Step three (optional): "CWD []" to restore server
VMS-ness.
*/
targ = "[]";
break;
default:
logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()"));
logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"),
cwd_count, cwd_start, cwd_end);
abort ();
}
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> CWD (%d) %s ... ", cwd_count,
quotearg_style (escape_quoting_style, target));
err = ftp_cwd (csock, targ);
/* FTPRERR, WRITEFAILED, FTPNSFOD */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such directory %s.\n\n"),
quote (u->dir));
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
} /* for */
/* 2004-09-20 SMS. */
} /* else */
}
else /* do not CWD */
logputs (LOG_VERBOSE, _("==> CWD not required.\n"));
if ((cmd & DO_RETR) && passed_expected_bytes == 0)
{
if (opt.verbose)
{
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> SIZE %s ... ",
quotearg_style (escape_quoting_style, u->file));
}
err = ftp_size (csock, u->file, &expected_bytes);
/* FTPRERR */
switch (err)
{
case FTPRERR:
case FTPSRVERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPOK:
got_expected_bytes = true;
/* Everything is OK. */
break;
default:
abort ();
}
if (!opt.server_response)
{
logprintf (LOG_VERBOSE, "%s\n",
expected_bytes ?
number_to_static_string (expected_bytes) :
_("done.\n"));
}
}
if (cmd & DO_RETR && restval > 0 && restval == expected_bytes)
{
/* Server confirms that file has length restval. We should stop now.
Some servers (f.e. NcFTPd) return error when receive REST 0 */
logputs (LOG_VERBOSE, _("File has already been retrieved.\n"));
fd_close (csock);
con->csock = -1;
return RETRFINISHED;
}
do
{
try_again = false;
/* If anything is to be retrieved, PORT (or PASV) must be sent. */
if (cmd & (DO_LIST | DO_RETR))
{
if (opt.ftp_pasv)
{
ip_address passive_addr;
int passive_port;
err = ftp_do_pasv (csock, &passive_addr, &passive_port);
/* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
return err;
case FTPNOPASV:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n"));
break;
case FTPINVPASV:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n"));
break;
case FTPOK:
break;
default:
abort ();
} /* switch (err) */
if (err==FTPOK)
{
DEBUGP (("trying to connect to %s port %d\n",
print_address (&passive_addr), passive_port));
dtsock = connect_to_ip (&passive_addr, passive_port, NULL);
if (dtsock < 0)
{
int save_errno = errno;
fd_close (csock);
con->csock = -1;
logprintf (LOG_VERBOSE, _("couldn't connect to %s port %d: %s\n"),
print_address (&passive_addr), passive_port,
strerror (save_errno));
? CONERROR : CONIMPOSSIBLE);
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
}
else
return err;
/*
* We do not want to fall back from PASSIVE mode to ACTIVE mode !
* The reason is the PORT command exposes the client's real IP address
* to the server. Bad for someone who relies on privacy via a ftp proxy.
*/
}
else
{
err = ftp_do_port (csock, &local_sock);
/* FTPRERR, WRITEFAILED, bindport (FTPSYSERR), HOSTERR,
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case CONSOCKERR:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPSYSERR:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"),
strerror (errno));
fd_close (dtsock);
return err;
case FTPPORTERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("Invalid PORT.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
} /* port switch */
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* dtsock == -1 */
} /* cmd & (DO_LIST | DO_RETR) */
/* Restart if needed. */
if (restval && (cmd & DO_RETR))
{
if (!opt.server_response)
logprintf (LOG_VERBOSE, "==> REST %s ... ",
number_to_static_string (restval));
err = ftp_rest (csock, restval);
/* FTPRERR, WRITEFAILED, FTPRESTFAIL */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPRESTFAIL:
logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n"));
rest_failed = true;
break;
case FTPOK:
break;
default:
abort ();
}
if (err != FTPRESTFAIL && !opt.server_response)
logputs (LOG_VERBOSE, _("done. "));
} /* restval && cmd & DO_RETR */
if (cmd & DO_RETR)
{
/* If we're in spider mode, don't really retrieve anything except
the directory listing and verify whether the given "file" exists. */
if (opt.spider)
{
bool exists = false;
struct fileinfo *f;
uerr_t _res = ftp_get_listing (u, con, &f);
/* Set the DO_RETR command flag again, because it gets unset when
calling ftp_get_listing() and would otherwise cause an assertion
failure earlier on when this function gets repeatedly called
(e.g., when recursing). */
con->cmd |= DO_RETR;
if (_res == RETROK)
{
while (f)
{
if (!strcmp (f->name, u->file))
{
exists = true;
break;
}
f = f->next;
}
if (exists)
{
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("File %s exists.\n"),
quote (u->file));
}
else
{
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file %s.\n"),
quote (u->file));
}
}
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return RETRFINISHED;
}
if (opt.verbose)
{
if (!opt.server_response)
{
if (restval)
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_VERBOSE, "==> RETR %s ... ",
quotearg_style (escape_quoting_style, u->file));
}
}
err = ftp_retr (csock, u->file);
/* FTPRERR, WRITEFAILED, FTPNSFOD */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file %s.\n\n"),
quote (u->file));
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
if (! got_expected_bytes)
expected_bytes = *last_expected_bytes;
} /* do retrieve */
if (cmd & DO_LIST)
{
if (!opt.server_response)
logputs (LOG_VERBOSE, "==> LIST ... ");
/* As Maciej W. Rozycki (macro@ds2.pg.gda.pl) says, `LIST'
without arguments is better than `LIST .'; confirmed by
RFC959. */
err = ftp_list (csock, NULL, con->st&AVOID_LIST_A, con->st&AVOID_LIST, &list_a_used);
/* FTPRERR, WRITEFAILED */
switch (err)
{
case FTPRERR:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET, _("\
Error in server response, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case WRITEFAILED:
logputs (LOG_VERBOSE, "\n");
logputs (LOG_NOTQUIET,
_("Write failed, closing control connection.\n"));
fd_close (csock);
con->csock = -1;
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPNSFOD:
logputs (LOG_VERBOSE, "\n");
logprintf (LOG_NOTQUIET, _("No such file or directory %s.\n\n"),
quote ("."));
fd_close (dtsock);
fd_close (local_sock);
return err;
case FTPOK:
break;
default:
abort ();
}
if (!opt.server_response)
logputs (LOG_VERBOSE, _("done.\n"));
if (! got_expected_bytes)
expected_bytes = *last_expected_bytes;
} /* cmd & DO_LIST */
if (!(cmd & (DO_LIST | DO_RETR)) || (opt.spider && !(cmd & DO_LIST)))
return RETRFINISHED;
/* Some FTP servers return the total length of file after REST
command, others just return the remaining size. */
if (passed_expected_bytes && restval && expected_bytes
&& (expected_bytes == passed_expected_bytes - restval))
{
DEBUGP (("Lying FTP server found, adjusting.\n"));
expected_bytes = passed_expected_bytes;
}
/* If no transmission was required, then everything is OK. */
if (!pasv_mode_open) /* we are not using pasive mode so we need
to accept */
}
|
CVE-2015-7665
|
Tails before 1.7 includes the wget program but does not prevent automatic fallback from passive FTP to active FTP, which allows remote FTP servers to discover the Tor client IP address by reading a (1) PORT or (2) EPRT command. NOTE: within wget itself, the automatic fallback is not considered a vulnerability by CVE.
|
[
"CWE-200"
] |
[
{
"line_no": 11,
"text": " bool pasv_mode_open = false;",
"char_start": null,
"char_end": null
},
{
"line_no": 642,
"text": " pasv_mode_open = true; /* Flag to avoid accept port */",
"char_start": null,
"char_end": null
},
{
"line_no": 645,
"text": " } /* err==FTP_OK */",
"char_start": null,
"char_end": null
},
{
"line_no": 646,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 648,
"text": " if (!pasv_mode_open) /* Try to use a port command if PASV failed */",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 643,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 644,
"text": " else",
"char_start": null,
"char_end": null
},
{
"line_no": 645,
"text": " return err;",
"char_start": null,
"char_end": null
},
{
"line_no": 647,
"text": " /*",
"char_start": null,
"char_end": null
},
{
"line_no": 648,
"text": " * We do not want to fall back from PASSIVE mode to ACTIVE mode !",
"char_start": null,
"char_end": null
},
{
"line_no": 649,
"text": " * The reason is the PORT command exposes the client's real IP address",
"char_start": null,
"char_end": null
},
{
"line_no": 650,
"text": " * to the server. Bad for someone who relies on privacy via a ftp proxy.",
"char_start": null,
"char_end": null
},
{
"line_no": 651,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 652,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 653,
"text": " else",
"char_start": null,
"char_end": null
}
] | 3
|
primevul
|
primevul_ghostscript_f597300439e62f5e921f0d7b1e880b5c1a1f1607
|
f597300439e62f5e921f0d7b1e880b5c1a1f1607
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
|
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);
tree = cmap->tree;
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
|
CVE-2018-1000039
|
In MuPDF 1.12.0 and earlier, multiple heap use after free bugs in the PDF parser could allow an attacker to execute arbitrary code, read memory, or cause a denial of service via a crafted file.
|
[
"CWE-416"
] |
[] |
[
{
"line_no": 59,
"text": " tree = cmap->tree;",
"char_start": null,
"char_end": null
}
] | 6
|
primevul
|
primevul_ghostscript_71ceebcf56e682504da22c4035b39a2d451e8ffd
|
71ceebcf56e682504da22c4035b39a2d451e8ffd
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
|
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
|
CVE-2018-1000039
|
In MuPDF 1.12.0 and earlier, multiple heap use after free bugs in the PDF parser could allow an attacker to execute arbitrary code, read memory, or cause a denial of service via a crafted file.
|
[
"CWE-416"
] |
[
{
"line_no": 58,
"text": " add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, many);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 58,
"text": " add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);",
"char_start": null,
"char_end": null
}
] | 8
|
primevul
|
primevul_ghostscript_b2e7d38e845c7d4922d05e6e41f3a2dc1bc1b14a
|
b2e7d38e845c7d4922d05e6e41f3a2dc1bc1b14a
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image)
{
pdf_gstate *gstate = pr->gstate + pr->gtop;
fz_matrix image_ctm;
fz_rect bbox;
softmask_save softmask = { NULL };
if (pr->super.hidden)
return;
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
bbox = fz_unit_rect;
fz_transform_rect(&bbox, &image_ctm);
if (image->mask)
{
/* apply blend group even though we skip the soft mask */
if (gstate->blendmode)
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1);
fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);
}
else
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
if (!image->colorspace)
{
switch (gstate->fill.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_fill_image_mask(ctx, pr->dev, image, &image_ctm,
gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->fill.pattern)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
else
{
fz_fill_image(ctx, pr->dev, image, &image_ctm, gstate->fill.alpha, &gstate->fill.color_params);
}
if (image->mask)
{
fz_pop_clip(ctx, pr->dev);
if (gstate->blendmode)
fz_end_group(ctx, pr->dev);
}
else
pdf_end_group(ctx, pr, &softmask);
}
static void
if (pr->clip)
{
gstate->clip_depth++;
fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox);
pr->clip = 0;
}
if (pr->super.hidden)
dostroke = dofill = 0;
if (dofill || dostroke)
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
if (dofill && dostroke)
{
/* We may need to push a knockout group */
if (gstate->stroke.alpha == 0)
{
/* No need for group, as stroke won't do anything */
}
else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL)
{
/* No need for group, as stroke won't show up */
}
else
{
knockout_group = 1;
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1);
}
}
if (dofill)
{
switch (gstate->fill.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm,
gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->fill.pattern)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
/* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */
fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (dostroke)
{
switch (gstate->stroke.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm,
gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->stroke.pattern)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->stroke.shade)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (knockout_group)
fz_end_group(ctx, pr->dev);
if (dofill || dostroke)
pdf_end_group(ctx, pr, &softmask);
}
|
pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image)
{
pdf_gstate *gstate = pr->gstate + pr->gtop;
fz_matrix image_ctm;
fz_rect bbox;
if (pr->super.hidden)
return;
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
bbox = fz_unit_rect;
fz_transform_rect(&bbox, &image_ctm);
if (image->mask && gstate->blendmode)
{
/* apply blend group even though we skip the soft mask */
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1);
fz_try(ctx)
fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);
fz_catch(ctx)
{
fz_end_group(ctx, pr->dev);
fz_rethrow(ctx);
}
fz_try(ctx)
pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);
fz_always(ctx)
{
fz_pop_clip(ctx, pr->dev);
fz_end_group(ctx, pr->dev);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
else if (image->mask)
{
fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);
fz_try(ctx)
pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);
fz_always(ctx)
fz_pop_clip(ctx, pr->dev);
fz_catch(ctx)
fz_rethrow(ctx);
}
else
{
softmask_save softmask = { NULL };
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
fz_try(ctx)
pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);
fz_always(ctx)
pdf_end_group(ctx, pr, &softmask);
fz_catch(ctx)
fz_rethrow(ctx);
}
}
static void
if (pr->clip)
{
gstate->clip_depth++;
fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox);
pr->clip = 0;
}
if (pr->super.hidden)
dostroke = dofill = 0;
if (dofill || dostroke)
gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);
if (dofill && dostroke)
{
/* We may need to push a knockout group */
if (gstate->stroke.alpha == 0)
{
/* No need for group, as stroke won't do anything */
}
else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL)
{
/* No need for group, as stroke won't show up */
}
else
{
knockout_group = 1;
fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1);
}
}
if (dofill)
{
switch (gstate->fill.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm,
gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->fill.pattern)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->fill.shade)
{
fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox);
/* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */
fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (dostroke)
{
switch (gstate->stroke.kind)
{
case PDF_MAT_NONE:
break;
case PDF_MAT_COLOR:
fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm,
gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params);
break;
case PDF_MAT_PATTERN:
if (gstate->stroke.pattern)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE);
fz_pop_clip(ctx, pr->dev);
}
break;
case PDF_MAT_SHADE:
if (gstate->stroke.shade)
{
fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox);
fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params);
fz_pop_clip(ctx, pr->dev);
}
break;
}
}
if (knockout_group)
fz_end_group(ctx, pr->dev);
if (dofill || dostroke)
pdf_end_group(ctx, pr, &softmask);
}
|
CVE-2018-1000037
|
In MuPDF 1.12.0 and earlier, multiple reachable assertions in the PDF parser allow an attacker to cause a denial of service (assert crash) via a crafted file.
|
[
"CWE-20"
] |
[
{
"line_no": 6,
"text": " softmask_save softmask = { NULL };",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " if (image->mask)",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " if (gstate->blendmode)",
"char_start": null,
"char_end": null
},
{
"line_no": 22,
"text": " fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1);",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " else",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " ",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " if (!image->colorspace)",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " switch (gstate->fill.kind)",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " case PDF_MAT_NONE:",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " break;",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " case PDF_MAT_COLOR:",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " fz_fill_image_mask(ctx, pr->dev, image, &image_ctm,",
"char_start": null,
"char_end": null
},
{
"line_no": 36,
"text": " gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": " break;",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " case PDF_MAT_PATTERN:",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": " if (gstate->fill.pattern)",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": " pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": " fz_pop_clip(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": " break;",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " case PDF_MAT_SHADE:",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": " if (gstate->fill.shade)",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": " fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);",
"char_start": null,
"char_end": null
},
{
"line_no": 50,
"text": " fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);",
"char_start": null,
"char_end": null
},
{
"line_no": 51,
"text": " fz_pop_clip(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": " break;",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 58,
"text": " fz_fill_image(ctx, pr->dev, image, &image_ctm, gstate->fill.alpha, &gstate->fill.color_params);",
"char_start": null,
"char_end": null
},
{
"line_no": 60,
"text": " if (image->mask)",
"char_start": null,
"char_end": null
},
{
"line_no": 61,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 62,
"text": " fz_pop_clip(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 63,
"text": " if (gstate->blendmode)",
"char_start": null,
"char_end": null
},
{
"line_no": 64,
"text": " fz_end_group(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 65,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 66,
"text": " else",
"char_start": null,
"char_end": null
},
{
"line_no": 67,
"text": " pdf_end_group(ctx, pr, &softmask);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 17,
"text": " if (image->mask && gstate->blendmode)",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": " fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1);",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " ",
"char_start": null,
"char_end": null
},
{
"line_no": 22,
"text": " fz_try(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " fz_catch(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " fz_end_group(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " fz_rethrow(ctx);",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " fz_try(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": " pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " fz_always(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " fz_pop_clip(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " fz_end_group(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 36,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": " fz_catch(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " fz_rethrow(ctx);",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": " else if (image->mask)",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": " fz_try(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": " fz_always(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " fz_pop_clip(ctx, pr->dev);",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": " fz_catch(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": " fz_rethrow(ctx);",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " softmask_save softmask = { NULL };",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);",
"char_start": null,
"char_end": null
},
{
"line_no": 55,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": " fz_try(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 57,
"text": " pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox);",
"char_start": null,
"char_end": null
},
{
"line_no": 58,
"text": " fz_always(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 59,
"text": " pdf_end_group(ctx, pr, &softmask);",
"char_start": null,
"char_end": null
},
{
"line_no": 60,
"text": " fz_catch(ctx)",
"char_start": null,
"char_end": null
},
{
"line_no": 61,
"text": " fz_rethrow(ctx);",
"char_start": null,
"char_end": null
}
] | 9
|
primevul
|
primevul_savannah_c15c42ccd1e2377945fd0414eca1a49294bff454
|
c15c42ccd1e2377945fd0414eca1a49294bff454
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
sparse_dump_region (struct tar_sparse_file *file, size_t i)
{
union block *blk;
off_t bytes_left = file->stat_info->sparse_map[i].numbytes;
if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset))
return false;
while (bytes_left > 0)
{
size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left;
size_t bytes_read;
blk = find_next_block ();
bytes_read = safe_read (file->fd, blk->buffer, bufsize);
if (bytes_read == SAFE_READ_ERROR)
{
read_diag_details (file->stat_info->orig_file_name,
(file->stat_info->sparse_map[i].offset
+ file->stat_info->sparse_map[i].numbytes
- bytes_left),
bufsize);
return false;
}
memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read);
bytes_left -= bytes_read;
{
size_t count;
size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size;
union block *blk = find_next_block ();
if (!blk)
{
ERROR ((0, 0, _("Unexpected EOF in archive")));
return false;
}
set_next_block_after (blk);
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
file->dumped_size += count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
{
write_error_details (file->stat_info->orig_file_name,
count, wrbytes);
return false;
}
}
return true;
}
/* Interface functions */
enum dump_status
sparse_dump_file (int fd, struct tar_stat_info *st)
{
return false;
}
set_next_block_after (blk);
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
file->dumped_size += count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
rc = sparse_scan_file (&file);
if (rc && file.optab->dump_region)
{
tar_sparse_dump_header (&file);
if (fd >= 0)
{
size_t i;
mv_begin_write (file.stat_info->file_name,
file.stat_info->stat.st_size,
file.stat_info->archive_file_size - file.dumped_size);
for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++)
rc = tar_sparse_dump_region (&file, i);
}
}
pad_archive (file.stat_info->archive_file_size - file.dumped_size);
return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short;
}
|
sparse_dump_region (struct tar_sparse_file *file, size_t i)
{
union block *blk;
off_t bytes_left = file->stat_info->sparse_map[i].numbytes;
if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset))
return false;
while (bytes_left > 0)
{
size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left;
size_t bytes_read;
blk = find_next_block ();
bytes_read = safe_read (file->fd, blk->buffer, bufsize);
if (bytes_read == SAFE_READ_ERROR)
{
read_diag_details (file->stat_info->orig_file_name,
(file->stat_info->sparse_map[i].offset
+ file->stat_info->sparse_map[i].numbytes
- bytes_left),
bufsize);
return false;
}
else if (bytes_read == 0)
{
char buf[UINTMAX_STRSIZE_BOUND];
struct stat st;
size_t n;
if (fstat (file->fd, &st) == 0)
n = file->stat_info->stat.st_size - st.st_size;
else
n = file->stat_info->stat.st_size
- (file->stat_info->sparse_map[i].offset
+ file->stat_info->sparse_map[i].numbytes
- bytes_left);
WARNOPT (WARN_FILE_SHRANK,
(0, 0,
ngettext ("%s: File shrank by %s byte; padding with zeros",
"%s: File shrank by %s bytes; padding with zeros",
n),
quotearg_colon (file->stat_info->orig_file_name),
STRINGIFY_BIGINT (n, buf)));
if (! ignore_failed_read_option)
set_exit_status (TAREXIT_DIFFERS);
return false;
}
memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read);
bytes_left -= bytes_read;
{
size_t count;
size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size;
union block *blk = find_next_block ();
if (!blk)
{
ERROR ((0, 0, _("Unexpected EOF in archive")));
return false;
}
set_next_block_after (blk);
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
file->dumped_size += count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
{
write_error_details (file->stat_info->orig_file_name,
count, wrbytes);
return false;
}
}
return true;
}
/* Interface functions */
enum dump_status
sparse_dump_file (int fd, struct tar_stat_info *st)
{
return false;
}
set_next_block_after (blk);
file->dumped_size += BLOCKSIZE;
count = blocking_write (file->fd, blk->buffer, wrbytes);
write_size -= count;
mv_size_left (file->stat_info->archive_file_size - file->dumped_size);
file->offset += count;
if (count != wrbytes)
rc = sparse_scan_file (&file);
if (rc && file.optab->dump_region)
{
tar_sparse_dump_header (&file);
if (fd >= 0)
{
size_t i;
mv_begin_write (file.stat_info->file_name,
file.stat_info->stat.st_size,
file.stat_info->archive_file_size - file.dumped_size);
for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++)
rc = tar_sparse_dump_region (&file, i);
}
}
pad_archive (file.stat_info->archive_file_size - file.dumped_size);
return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short;
}
|
CVE-2018-20482
|
GNU Tar through 1.30, when --sparse is used, mishandles file shrinkage during read access, which allows local users to cause a denial of service (infinite read loop in sparse_dump_region in sparse.c) by modifying a file that is supposed to be archived by a different user's process (e.g., a system backup running as root).
|
[
"CWE-835"
] |
[
{
"line_no": 65,
"text": " file->dumped_size += count;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 25,
"text": " else if (bytes_read == 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": "\t{",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": "\t char buf[UINTMAX_STRSIZE_BOUND];",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": "\t struct stat st;",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": "\t size_t n;",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": "\t if (fstat (file->fd, &st) == 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": "\t n = file->stat_info->stat.st_size - st.st_size;",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": "\t else",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": "\t n = file->stat_info->stat.st_size",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": "\t - (file->stat_info->sparse_map[i].offset",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": "\t\t + file->stat_info->sparse_map[i].numbytes",
"char_start": null,
"char_end": null
},
{
"line_no": 36,
"text": "\t\t - bytes_left);",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": "\t ",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": "\t WARNOPT (WARN_FILE_SHRANK,",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": "\t\t (0, 0,",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": "\t\t ngettext (\"%s: File shrank by %s byte; padding with zeros\",",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": "\t\t\t \"%s: File shrank by %s bytes; padding with zeros\",",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": "\t\t\t n),",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": "\t\t quotearg_colon (file->stat_info->orig_file_name),",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": "\t\t STRINGIFY_BIGINT (n, buf)));",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": "\t if (! ignore_failed_read_option)",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": "\t set_exit_status (TAREXIT_DIFFERS);",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": "\t return false;",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": "\t}",
"char_start": null,
"char_end": null
},
{
"line_no": 87,
"text": " file->dumped_size += BLOCKSIZE;",
"char_start": null,
"char_end": null
}
] | 23
|
primevul
|
primevul_haproxy_58df5aea0a0c926b2238f65908f5e9f83d1cca25
|
58df5aea0a0c926b2238f65908f5e9f83d1cca25
|
haproxy
|
https://github.com/haproxy/haproxy
|
int dns_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
n = dns_read_name(buffer, bufend, buffer + reader[1],
dest, dest_len - nb_bytes, offset);
if (n == 0)
goto err;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
|
int dns_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset, unsigned int depth)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
if (depth++ > 100)
goto err;
n = dns_read_name(buffer, bufend, buffer + reader[1],
dest, dest_len - nb_bytes, offset, depth);
if (n == 0)
goto err;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
|
CVE-2018-20103
|
An issue was discovered in dns.c in HAProxy through 1.8.14. In the case of a compressed pointer, a crafted packet can trigger infinite recursion by making the pointer point to itself, or create a long chain of valid pointers resulting in stack exhaustion.
|
[
"CWE-835"
] |
[
{
"line_no": 3,
"text": " int *offset)",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " dest, dest_len - nb_bytes, offset);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 3,
"text": " int *offset, unsigned int depth)",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": " if (depth++ > 100)",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " goto err;",
"char_start": null,
"char_end": null
},
{
"line_no": 19,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " dest, dest_len - nb_bytes, offset, depth);",
"char_start": null,
"char_end": null
}
] | 26
|
primevul
|
primevul_poppler_284a92899602daa4a7f429e61849e794569310b5
|
284a92899602daa4a7f429e61849e794569310b5
|
poppler
|
https://github.com/freedesktop/poppler
|
void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
|
void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
|
CVE-2009-3605
|
Multiple integer overflows in Poppler 0.10.5 and earlier allow remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted PDF file, related to (1) glib/poppler-page.cc; (2) ArthurOutputDev.cc, (3) CairoOutputDev.cc, (4) GfxState.cc, (5) JBIG2Stream.cc, (6) PSOutputDev.cc, and (7) SplashOutputDev.cc in poppler/; and (8) SplashBitmap.cc, (9) Splash.cc, and (10) SplashFTFont.cc in splash/. NOTE: this may overlap CVE-2009-0791.
|
[
"CWE-189"
] |
[
{
"line_no": 62,
"text": " imgData.lookup = (SplashColorPtr)gmallocn(n, 3);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 62,
"text": " imgData.lookup = (SplashColorPtr)gmallocn(n, 4);",
"char_start": null,
"char_end": null
}
] | 27
|
primevul
|
primevul_poppler_7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
|
7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
|
poppler
|
https://github.com/freedesktop/poppler
|
void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg)
{
unsigned char *buffer;
unsigned int *dest;
int x, y;
ImageStream *imgStr;
Guchar *pix;
int i;
double *ctm;
QMatrix matrix;
int is_identity_transform;
buffer = (unsigned char *)gmalloc (width * height * 4);
/* TODO: Do we want to cache these? */
imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgStr->reset();
/* ICCBased color space doesn't do any color correction
* so check its underlying color space as well */
is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB ||
(colorMap->getColorSpace()->getMode() == csICCBased &&
((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB);
if (maskColors) {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
for (x = 0; x < width; x++) {
for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
if (pix[i] < maskColors[2*i] * 255||
pix[i] > maskColors[2*i+1] * 255) {
*dest = *dest | 0xff000000;
break;
}
}
pix += colorMap->getNumPixelComps();
dest++;
}
}
m_image = new QImage(buffer, width, height, QImage::Format_ARGB32);
}
else {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
}
m_image = new QImage(buffer, width, height, QImage::Format_RGB32);
}
if (m_image == NULL || m_image->isNull()) {
qDebug() << "Null image";
delete imgStr;
return;
}
ctm = state->getCTM();
matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]);
m_painter->setMatrix(matrix, true);
m_painter->drawImage( QPoint(0,0), *m_image );
delete m_image;
m_image = 0;
free (buffer);
delete imgStr;
}
|
void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg)
{
unsigned char *buffer;
unsigned int *dest;
int x, y;
ImageStream *imgStr;
Guchar *pix;
int i;
double *ctm;
QMatrix matrix;
int is_identity_transform;
buffer = (unsigned char *)gmallocn3(width, height, 4);
/* TODO: Do we want to cache these? */
imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgStr->reset();
/* ICCBased color space doesn't do any color correction
* so check its underlying color space as well */
is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB ||
(colorMap->getColorSpace()->getMode() == csICCBased &&
((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB);
if (maskColors) {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
for (x = 0; x < width; x++) {
for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
if (pix[i] < maskColors[2*i] * 255||
pix[i] > maskColors[2*i+1] * 255) {
*dest = *dest | 0xff000000;
break;
}
}
pix += colorMap->getNumPixelComps();
dest++;
}
}
m_image = new QImage(buffer, width, height, QImage::Format_ARGB32);
}
else {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
}
m_image = new QImage(buffer, width, height, QImage::Format_RGB32);
}
if (m_image == NULL || m_image->isNull()) {
qDebug() << "Null image";
delete imgStr;
return;
}
ctm = state->getCTM();
matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]);
m_painter->setMatrix(matrix, true);
m_painter->drawImage( QPoint(0,0), *m_image );
delete m_image;
m_image = 0;
free (buffer);
delete imgStr;
}
|
CVE-2009-3605
|
Multiple integer overflows in Poppler 0.10.5 and earlier allow remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted PDF file, related to (1) glib/poppler-page.cc; (2) ArthurOutputDev.cc, (3) CairoOutputDev.cc, (4) GfxState.cc, (5) JBIG2Stream.cc, (6) PSOutputDev.cc, and (7) SplashOutputDev.cc in poppler/; and (8) SplashBitmap.cc, (9) Splash.cc, and (10) SplashFTFont.cc in splash/. NOTE: this may overlap CVE-2009-0791.
|
[
"CWE-189"
] |
[
{
"line_no": 16,
"text": " buffer = (unsigned char *)gmalloc (width * height * 4);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 16,
"text": " buffer = (unsigned char *)gmallocn3(width, height, 4);",
"char_start": null,
"char_end": null
}
] | 28
|
primevul
|
primevul_shibboleth_b66cceb0e992c351ad5e2c665229ede82f261b16
|
b66cceb0e992c351ad5e2c665229ede82f261b16
|
shibboleth
|
https://git.shibboleth.net/view/?p=cpp-opensaml
|
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
: saml2md::DynamicMetadataProvider(e),
m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)),
m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)),
m_encoded(true), m_trust(nullptr)
{
const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst);
if (child && child->hasChildNodes()) {
auto_ptr_char s(child->getFirstChild()->getNodeValue());
if (s.get() && *s.get()) {
m_subst = s.get();
m_encoded = XMLHelper::getAttrBool(child, true, encoded);
m_hashed = XMLHelper::getAttrString(child, nullptr, hashed);
}
}
if (m_subst.empty()) {
child = XMLHelper::getFirstChildElement(e, Regex);
if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) {
m_match = XMLHelper::getAttrString(child, nullptr, match);
auto_ptr_char repl(child->getFirstChild()->getNodeValue());
if (repl.get() && *repl.get())
m_regex = repl.get();
}
}
if (!m_ignoreTransport) {
child = XMLHelper::getFirstChildElement(e, _TrustEngine);
string t = XMLHelper::getAttrString(child, nullptr, _type);
if (!t.empty()) {
TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
if (!dynamic_cast<X509TrustEngine*>(trust)) {
delete trust;
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
}
m_trust.reset(dynamic_cast<X509TrustEngine*>(trust));
m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr));
}
if (!m_trust.get() || !m_dummyCR.get())
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
}
}
|
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
: saml2md::DynamicMetadataProvider(e), MetadataProvider(e),
m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)),
m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)),
m_encoded(true), m_trust(nullptr)
{
const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst);
if (child && child->hasChildNodes()) {
auto_ptr_char s(child->getFirstChild()->getNodeValue());
if (s.get() && *s.get()) {
m_subst = s.get();
m_encoded = XMLHelper::getAttrBool(child, true, encoded);
m_hashed = XMLHelper::getAttrString(child, nullptr, hashed);
}
}
if (m_subst.empty()) {
child = XMLHelper::getFirstChildElement(e, Regex);
if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) {
m_match = XMLHelper::getAttrString(child, nullptr, match);
auto_ptr_char repl(child->getFirstChild()->getNodeValue());
if (repl.get() && *repl.get())
m_regex = repl.get();
}
}
if (!m_ignoreTransport) {
child = XMLHelper::getFirstChildElement(e, _TrustEngine);
string t = XMLHelper::getAttrString(child, nullptr, _type);
if (!t.empty()) {
TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
if (!dynamic_cast<X509TrustEngine*>(trust)) {
delete trust;
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
}
m_trust.reset(dynamic_cast<X509TrustEngine*>(trust));
m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr));
}
if (!m_trust.get() || !m_dummyCR.get())
throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
}
}
|
CVE-2017-16852
|
shibsp/metadata/DynamicMetadataProvider.cpp in the Dynamic MetadataProvider plugin in Shibboleth Service Provider before 2.6.1 fails to properly configure itself with the MetadataFilter plugins and does not perform critical security checks such as signature verification, enforcement of validity periods, and other checks specific to deployments, aka SSPCPP-763.
|
[
"CWE-347"
] |
[
{
"line_no": 2,
"text": " : saml2md::DynamicMetadataProvider(e),",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 2,
"text": " : saml2md::DynamicMetadataProvider(e), MetadataProvider(e),",
"char_start": null,
"char_end": null
}
] | 40
|
primevul
|
primevul_pengutronix_574ce994016107ad8ab0f845a785f28d7eaa5208
|
574ce994016107ad8ab0f845a785f28d7eaa5208
|
pengutronix
|
https://git.pengutronix.de/cgit/barebox/commit/fs/nfs.c?h=next&id=574ce994016107ad8ab0f845a785f28d7eaa5208
|
static int nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh,
char **target)
{
uint32_t data[1024];
uint32_t *p;
uint32_t len;
struct packet *nfs_packet;
/*
* struct READLINK3args {
* nfs_fh3 symlink;
* };
*
* struct READLINK3resok {
* post_op_attr symlink_attributes;
* nfspath3 data;
* };
*
* struct READLINK3resfail {
* post_op_attr symlink_attributes;
* }
*
* union READLINK3res switch (nfsstat3 status) {
* case NFS3_OK:
* READLINK3resok resok;
* default:
* READLINK3resfail resfail;
* };
*/
p = &(data[0]);
p = rpc_add_credentials(p);
p = nfs_add_fh3(p, fh);
len = p - &(data[0]);
nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len);
if (IS_ERR(nfs_packet))
return PTR_ERR(nfs_packet);
p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4;
p = nfs_read_post_op_attr(p, NULL);
len = ntoh32(net_read_uint32(p)); /* new path length */
p++;
*target = xzalloc(len + 1);
return 0;
}
|
static int nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh,
char **target)
{
uint32_t data[1024];
uint32_t *p;
uint32_t len;
struct packet *nfs_packet;
/*
* struct READLINK3args {
* nfs_fh3 symlink;
* };
*
* struct READLINK3resok {
* post_op_attr symlink_attributes;
* nfspath3 data;
* };
*
* struct READLINK3resfail {
* post_op_attr symlink_attributes;
* }
*
* union READLINK3res switch (nfsstat3 status) {
* case NFS3_OK:
* READLINK3resok resok;
* default:
* READLINK3resfail resfail;
* };
*/
p = &(data[0]);
p = rpc_add_credentials(p);
p = nfs_add_fh3(p, fh);
len = p - &(data[0]);
nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len);
if (IS_ERR(nfs_packet))
return PTR_ERR(nfs_packet);
p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4;
p = nfs_read_post_op_attr(p, NULL);
len = ntoh32(net_read_uint32(p)); /* new path length */
len = max_t(unsigned int, len,
nfs_packet->len - sizeof(struct rpc_reply) - sizeof(uint32_t));
p++;
*target = xzalloc(len + 1);
return 0;
}
|
CVE-2019-15938
|
Pengutronix barebox through 2019.08.1 has a remote buffer overflow in nfs_readlink_req in fs/nfs.c because a length field is directly used for a memcpy.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 46,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": "\tlen = max_t(unsigned int, len,",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": "\t\t nfs_packet->len - sizeof(struct rpc_reply) - sizeof(uint32_t));",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": "",
"char_start": null,
"char_end": null
}
] | 41
|
primevul
|
primevul_pengutronix_84986ca024462058574432b5483f4bf9136c538d
|
84986ca024462058574432b5483f4bf9136c538d
|
pengutronix
|
https://git.pengutronix.de/cgit/barebox/commit/fs/nfs.c?h=next&id=574ce994016107ad8ab0f845a785f28d7eaa5208
|
static int nfs_readlink_reply(unsigned char *pkt, unsigned len)
{
uint32_t *data;
char *path;
int rlen;
int ret;
ret = rpc_check_reply(pkt, 1);
if (ret)
return ret;
data = (uint32_t *)(pkt + sizeof(struct rpc_reply));
data++;
rlen = ntohl(net_read_uint32(data)); /* new path length */
data++;
path = (char *)data;
} else {
memcpy(nfs_path, path, rlen);
nfs_path[rlen] = 0;
}
|
static int nfs_readlink_reply(unsigned char *pkt, unsigned len)
{
uint32_t *data;
char *path;
unsigned int rlen;
int ret;
ret = rpc_check_reply(pkt, 1);
if (ret)
return ret;
data = (uint32_t *)(pkt + sizeof(struct rpc_reply));
data++;
rlen = ntohl(net_read_uint32(data)); /* new path length */
rlen = max_t(unsigned int, rlen,
len - sizeof(struct rpc_reply) - sizeof(uint32_t));
data++;
path = (char *)data;
} else {
memcpy(nfs_path, path, rlen);
nfs_path[rlen] = 0;
}
|
CVE-2019-15937
|
Pengutronix barebox through 2019.08.1 has a remote buffer overflow in nfs_readlink_reply in net/nfs.c because a length field is directly used for a memcpy.
|
[
"CWE-119"
] |
[
{
"line_no": 5,
"text": "\tint rlen;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 5,
"text": "\tunsigned int rlen;",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": "\trlen = max_t(unsigned int, rlen,",
"char_start": null,
"char_end": null
},
{
"line_no": 19,
"text": "\t\t len - sizeof(struct rpc_reply) - sizeof(uint32_t));",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": "",
"char_start": null,
"char_end": null
}
] | 42
|
primevul
|
primevul_samba_c252546ceeb0925eb8a4061315e3ff0a8c55b48b
|
c252546ceeb0925eb8a4061315e3ff0a8c55b48b
|
samba
|
https://github.com/samba-team/samba
|
void sum_update(const char *p, int32 len)
{
switch (cursum_type) {
case CSUM_MD5:
md5_update(&md, (uchar *)p, len);
break;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
if (len + sumresidue < CSUM_CHUNK) {
memcpy(md.buffer + sumresidue, p, len);
sumresidue += len;
}
if (sumresidue) {
int32 i = CSUM_CHUNK - sumresidue;
memcpy(md.buffer + sumresidue, p, i);
mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK);
len -= i;
p += i;
}
while (len >= CSUM_CHUNK) {
mdfour_update(&md, (uchar *)p, CSUM_CHUNK);
len -= CSUM_CHUNK;
p += CSUM_CHUNK;
}
sumresidue = len;
if (sumresidue)
memcpy(md.buffer, p, sumresidue);
break;
case CSUM_NONE:
break;
}
}
|
void sum_update(const char *p, int32 len)
{
switch (cursum_type) {
case CSUM_MD5:
md5_update(&md, (uchar *)p, len);
break;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
case CSUM_MD4_ARCHAIC:
if (len + sumresidue < CSUM_CHUNK) {
memcpy(md.buffer + sumresidue, p, len);
sumresidue += len;
}
if (sumresidue) {
int32 i = CSUM_CHUNK - sumresidue;
memcpy(md.buffer + sumresidue, p, i);
mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK);
len -= i;
p += i;
}
while (len >= CSUM_CHUNK) {
mdfour_update(&md, (uchar *)p, CSUM_CHUNK);
len -= CSUM_CHUNK;
p += CSUM_CHUNK;
}
sumresidue = len;
if (sumresidue)
memcpy(md.buffer, p, sumresidue);
break;
case CSUM_NONE:
break;
}
}
|
CVE-2017-15994
|
rsync 3.1.3-development before 2017-10-24 mishandles archaic checksums, which makes it easier for remote attackers to bypass intended access restrictions. NOTE: the rsync development branch has significant use beyond the rsync developers, e.g., the code has been copied for use in various GitHub projects.
|
[
"CWE-354"
] |
[] |
[
{
"line_no": 10,
"text": " case CSUM_MD4_ARCHAIC:",
"char_start": null,
"char_end": null
}
] | 54
|
primevul
|
primevul_busybox_0402cb32df015d9372578e3db27db47b33d5c7b0
|
0402cb32df015d9372578e3db27db47b33d5c7b0
|
busybox
|
http://git.busybox.net/busybox
|
static int get_next_block(bunzip_data *bd)
{
struct group_data *hufGroup;
int dbufCount, dbufSize, groupCount, *base, *limit, selector,
i, j, runPos, symCount, symTotal, nSelectors, byteCount[256];
int runCnt = runCnt; /* for compiler */
uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
uint32_t *dbuf;
unsigned origPtr, t;
dbuf = bd->dbuf;
dbufSize = bd->dbufSize;
selectors = bd->selectors;
/* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */
#if 0
/* Reset longjmp I/O error handling */
i = setjmp(bd->jmpbuf);
if (i) return i;
#endif
/* Read in header signature and CRC, then validate signature.
(last block signature means CRC is for whole file, return now) */
i = get_bits(bd, 24);
j = get_bits(bd, 24);
bd->headerCRC = get_bits(bd, 32);
if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;
if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;
/* We can add support for blockRandomised if anybody complains. There was
some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
it didn't actually work. */
if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
origPtr = get_bits(bd, 24);
if ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR;
/* mapping table: if some byte values are never used (encoding things
like ascii text), the compression code removes the gaps to have fewer
symbols to deal with, and writes a sparse bitfield indicating which
values were present. We make a translation table to convert the symbols
back to the corresponding bytes. */
symTotal = 0;
i = 0;
t = get_bits(bd, 16);
do {
if (t & (1 << 15)) {
unsigned inner_map = get_bits(bd, 16);
do {
if (inner_map & (1 << 15))
symToByte[symTotal++] = i;
inner_map <<= 1;
i++;
} while (i & 15);
i -= 16;
}
t <<= 1;
i += 16;
} while (i < 256);
/* How many different Huffman coding groups does this block use? */
groupCount = get_bits(bd, 3);
if (groupCount < 2 || groupCount > MAX_GROUPS)
return RETVAL_DATA_ERROR;
/* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
group. Read in the group selector list, which is stored as MTF encoded
bit runs. (MTF=Move To Front, as each value is used it's moved to the
start of the list.) */
for (i = 0; i < groupCount; i++)
mtfSymbol[i] = i;
nSelectors = get_bits(bd, 15);
if (!nSelectors)
return RETVAL_DATA_ERROR;
for (i = 0; i < nSelectors; i++) {
uint8_t tmp_byte;
/* Get next value */
int n = 0;
while (get_bits(bd, 1)) {
if (n >= groupCount) return RETVAL_DATA_ERROR;
n++;
}
/* Decode MTF to get the next selector */
tmp_byte = mtfSymbol[n];
while (--n >= 0)
mtfSymbol[n + 1] = mtfSymbol[n];
mtfSymbol[0] = selectors[i] = tmp_byte;
}
/* Read the Huffman coding tables for each group, which code for symTotal
literal symbols, plus two run symbols (RUNA, RUNB) */
symCount = symTotal + 2;
for (j = 0; j < groupCount; j++) {
uint8_t length[MAX_SYMBOLS];
/* 8 bits is ALMOST enough for temp[], see below */
unsigned temp[MAX_HUFCODE_BITS+1];
int minLen, maxLen, pp, len_m1;
/* Read Huffman code lengths for each symbol. They're stored in
a way similar to mtf; record a starting value for the first symbol,
and an offset from the previous value for every symbol after that.
(Subtracting 1 before the loop and then adding it back at the end is
an optimization that makes the test inside the loop simpler: symbol
length 0 becomes negative, so an unsigned inequality catches it.) */
len_m1 = get_bits(bd, 5) - 1;
for (i = 0; i < symCount; i++) {
for (;;) {
int two_bits;
if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1))
return RETVAL_DATA_ERROR;
/* If first bit is 0, stop. Else second bit indicates whether
to increment or decrement the value. Optimization: grab 2
bits and unget the second if the first was 0. */
two_bits = get_bits(bd, 2);
if (two_bits < 2) {
bd->inbufBitCount++;
break;
}
/* Add one if second bit 1, else subtract 1. Avoids if/else */
len_m1 += (((two_bits+1) & 2) - 1);
}
/* Correct for the initial -1, to get the final symbol length */
length[i] = len_m1 + 1;
}
/* Find largest and smallest lengths in this group */
minLen = maxLen = length[0];
for (i = 1; i < symCount; i++) {
if (length[i] > maxLen) maxLen = length[i];
else if (length[i] < minLen) minLen = length[i];
}
/* Calculate permute[], base[], and limit[] tables from length[].
*
* permute[] is the lookup table for converting Huffman coded symbols
* into decoded symbols. base[] is the amount to subtract from the
* value of a Huffman symbol of a given length when using permute[].
*
* limit[] indicates the largest numerical value a symbol with a given
* number of bits can have. This is how the Huffman codes can vary in
* length: each code with a value>limit[length] needs another bit.
*/
hufGroup = bd->groups + j;
hufGroup->minLen = minLen;
hufGroup->maxLen = maxLen;
/* Note that minLen can't be smaller than 1, so we adjust the base
and limit array pointers so we're not always wasting the first
entry. We do this again when using them (during symbol decoding). */
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
/* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */
pp = 0;
for (i = minLen; i <= maxLen; i++) {
int k;
temp[i] = limit[i] = 0;
for (k = 0; k < symCount; k++)
if (length[k] == i)
hufGroup->permute[pp++] = k;
}
/* Count symbols coded for at each bit length */
/* NB: in pathological cases, temp[8] can end ip being 256.
* That's why uint8_t is too small for temp[]. */
for (i = 0; i < symCount; i++) temp[length[i]]++;
/* Calculate limit[] (the largest symbol-coding value at each bit
* length, which is (previous limit<<1)+symbols at this level), and
* base[] (number of symbols to ignore at each bit length, which is
* limit minus the cumulative count of symbols coded for already). */
pp = t = 0;
for (i = minLen; i < maxLen;) {
unsigned temp_i = temp[i];
pp += temp_i;
/* We read the largest possible symbol size and then unget bits
after determining how many we need, and those extra bits could
be set to anything. (They're noise from future symbols.) At
each level we're really only interested in the first few bits,
so here we set all the trailing to-be-ignored bits to 1 so they
don't affect the value>limit[length] comparison. */
limit[i] = (pp << (maxLen - i)) - 1;
pp <<= 1;
t += temp_i;
base[++i] = pp - t;
}
limit[maxLen] = pp + temp[maxLen] - 1;
limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
base[minLen] = 0;
}
/* We've finished reading and digesting the block header. Now read this
block's Huffman coded symbols from the file and undo the Huffman coding
and run length encoding, saving the result into dbuf[dbufCount++] = uc */
/* Initialize symbol occurrence counters and symbol Move To Front table */
/*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */
for (i = 0; i < 256; i++) {
byteCount[i] = 0;
mtfSymbol[i] = (uint8_t)i;
}
/* Loop through compressed symbols. */
runPos = dbufCount = selector = 0;
for (;;) {
int nextSym;
/* Fetch next Huffman coding group from list. */
symCount = GROUP_SIZE - 1;
if (selector >= nSelectors) return RETVAL_DATA_ERROR;
hufGroup = bd->groups + selectors[selector++];
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
continue_this_group:
/* Read next Huffman-coded symbol. */
/* Note: It is far cheaper to read maxLen bits and back up than it is
to read minLen bits and then add additional bit at a time, testing
as we go. Because there is a trailing last block (with file CRC),
there is no danger of the overread causing an unexpected EOF for a
valid compressed file.
*/
if (1) {
/* As a further optimization, we do the read inline
(falling back to a call to get_bits if the buffer runs dry).
*/
int new_cnt;
while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) {
/* bd->inbufBitCount < hufGroup->maxLen */
if (bd->inbufPos == bd->inbufCount) {
nextSym = get_bits(bd, hufGroup->maxLen);
goto got_huff_bits;
}
bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
bd->inbufBitCount += 8;
};
bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */
nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1);
got_huff_bits: ;
} else { /* unoptimized equivalent */
nextSym = get_bits(bd, hufGroup->maxLen);
}
/* Figure how many bits are in next symbol and unget extras */
i = hufGroup->minLen;
while (nextSym > limit[i]) ++i;
j = hufGroup->maxLen - i;
if (j < 0)
return RETVAL_DATA_ERROR;
bd->inbufBitCount += j;
/* Huffman decode value to get nextSym (with bounds checking) */
nextSym = (nextSym >> j) - base[i];
if ((unsigned)nextSym >= MAX_SYMBOLS)
return RETVAL_DATA_ERROR;
nextSym = hufGroup->permute[nextSym];
/* We have now decoded the symbol, which indicates either a new literal
byte, or a repeated run of the most recent literal byte. First,
check if nextSym indicates a repeated run, and if so loop collecting
how many times to repeat the last literal. */
if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
/* If this is the start of a new run, zero out counter */
if (runPos == 0) {
runPos = 1;
runCnt = 0;
}
/* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
each bit position, add 1 or 2 instead. For example,
1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
You can make any bit pattern that way using 1 less symbol than
the basic or 0/1 method (except all bits 0, which would use no
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
if (runPos < dbufSize) runPos <<= 1;
////The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
////This would be the fix (catches too large count way before it can overflow):
//// if (runCnt > bd->dbufSize) {
//// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
//// runCnt, bd->dbufSize);
//// return RETVAL_DATA_ERROR;
//// }
goto end_of_huffman_loop;
}
dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, dbufSize);
return RETVAL_DATA_ERROR;
literal used is the one at the head of the mtfSymbol array.) */
if (runPos != 0) {
uint8_t tmp_byte;
if (dbufCount + runCnt > dbufSize) {
dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, dbufSize);
return RETVAL_DATA_ERROR;
}
tmp_byte = symToByte[mtfSymbol[0]];
byteCount[tmp_byte] += runCnt;
while (--runCnt >= 0) dbuf[dbufCount++] = (uint32_t)tmp_byte;
runPos = 0;
}
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
/* Adjust the MTF array. Since we typically expect to move only a
first symbol in the mtf array, position 0, would have been handled
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
uc = symToByte[uc];
/* We have our literal byte. Save it into dbuf. */
byteCount[uc]++;
dbuf[dbufCount++] = (uint32_t)uc;
/* Skip group initialization if we're not done with this group. Done
* this way to avoid compiler warning. */
end_of_huffman_loop:
if (--symCount >= 0) goto continue_this_group;
}
/* At this point, we've read all the Huffman-coded symbols (and repeated
runs) for this block from the input stream, and decoded them into the
intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
Now undo the Burrows-Wheeler transform on dbuf.
See http://dogma.net/markn/articles/bwt/bwt.htm
*/
/* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
j = 0;
for (i = 0; i < 256; i++) {
int tmp_count = j + byteCount[i];
byteCount[i] = j;
j = tmp_count;
}
/* Figure out what order dbuf would be in if we sorted it. */
for (i = 0; i < dbufCount; i++) {
uint8_t tmp_byte = (uint8_t)dbuf[i];
int tmp_count = byteCount[tmp_byte];
dbuf[tmp_count] |= (i << 8);
byteCount[tmp_byte] = tmp_count + 1;
}
/* Decode first byte by hand to initialize "previous" byte. Note that it
doesn't get output, and if the first three characters are identical
it doesn't qualify as a run (hence writeRunCountdown=5). */
if (dbufCount) {
uint32_t tmp;
if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
tmp = dbuf[origPtr];
bd->writeCurrent = (uint8_t)tmp;
bd->writePos = (tmp >> 8);
bd->writeRunCountdown = 5;
}
bd->writeCount = dbufCount;
return RETVAL_OK;
}
|
static int get_next_block(bunzip_data *bd)
{
struct group_data *hufGroup;
int groupCount, *base, *limit, selector,
i, j, symCount, symTotal, nSelectors, byteCount[256];
uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
uint32_t *dbuf;
unsigned origPtr, t;
unsigned dbufCount, runPos;
unsigned runCnt = runCnt; /* for compiler */
dbuf = bd->dbuf;
selectors = bd->selectors;
/* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */
#if 0
/* Reset longjmp I/O error handling */
i = setjmp(bd->jmpbuf);
if (i) return i;
#endif
/* Read in header signature and CRC, then validate signature.
(last block signature means CRC is for whole file, return now) */
i = get_bits(bd, 24);
j = get_bits(bd, 24);
bd->headerCRC = get_bits(bd, 32);
if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;
if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;
/* We can add support for blockRandomised if anybody complains. There was
some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
it didn't actually work. */
if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
origPtr = get_bits(bd, 24);
if (origPtr > bd->dbufSize) return RETVAL_DATA_ERROR;
/* mapping table: if some byte values are never used (encoding things
like ascii text), the compression code removes the gaps to have fewer
symbols to deal with, and writes a sparse bitfield indicating which
values were present. We make a translation table to convert the symbols
back to the corresponding bytes. */
symTotal = 0;
i = 0;
t = get_bits(bd, 16);
do {
if (t & (1 << 15)) {
unsigned inner_map = get_bits(bd, 16);
do {
if (inner_map & (1 << 15))
symToByte[symTotal++] = i;
inner_map <<= 1;
i++;
} while (i & 15);
i -= 16;
}
t <<= 1;
i += 16;
} while (i < 256);
/* How many different Huffman coding groups does this block use? */
groupCount = get_bits(bd, 3);
if (groupCount < 2 || groupCount > MAX_GROUPS)
return RETVAL_DATA_ERROR;
/* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
group. Read in the group selector list, which is stored as MTF encoded
bit runs. (MTF=Move To Front, as each value is used it's moved to the
start of the list.) */
for (i = 0; i < groupCount; i++)
mtfSymbol[i] = i;
nSelectors = get_bits(bd, 15);
if (!nSelectors)
return RETVAL_DATA_ERROR;
for (i = 0; i < nSelectors; i++) {
uint8_t tmp_byte;
/* Get next value */
int n = 0;
while (get_bits(bd, 1)) {
if (n >= groupCount) return RETVAL_DATA_ERROR;
n++;
}
/* Decode MTF to get the next selector */
tmp_byte = mtfSymbol[n];
while (--n >= 0)
mtfSymbol[n + 1] = mtfSymbol[n];
mtfSymbol[0] = selectors[i] = tmp_byte;
}
/* Read the Huffman coding tables for each group, which code for symTotal
literal symbols, plus two run symbols (RUNA, RUNB) */
symCount = symTotal + 2;
for (j = 0; j < groupCount; j++) {
uint8_t length[MAX_SYMBOLS];
/* 8 bits is ALMOST enough for temp[], see below */
unsigned temp[MAX_HUFCODE_BITS+1];
int minLen, maxLen, pp, len_m1;
/* Read Huffman code lengths for each symbol. They're stored in
a way similar to mtf; record a starting value for the first symbol,
and an offset from the previous value for every symbol after that.
(Subtracting 1 before the loop and then adding it back at the end is
an optimization that makes the test inside the loop simpler: symbol
length 0 becomes negative, so an unsigned inequality catches it.) */
len_m1 = get_bits(bd, 5) - 1;
for (i = 0; i < symCount; i++) {
for (;;) {
int two_bits;
if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1))
return RETVAL_DATA_ERROR;
/* If first bit is 0, stop. Else second bit indicates whether
to increment or decrement the value. Optimization: grab 2
bits and unget the second if the first was 0. */
two_bits = get_bits(bd, 2);
if (two_bits < 2) {
bd->inbufBitCount++;
break;
}
/* Add one if second bit 1, else subtract 1. Avoids if/else */
len_m1 += (((two_bits+1) & 2) - 1);
}
/* Correct for the initial -1, to get the final symbol length */
length[i] = len_m1 + 1;
}
/* Find largest and smallest lengths in this group */
minLen = maxLen = length[0];
for (i = 1; i < symCount; i++) {
if (length[i] > maxLen) maxLen = length[i];
else if (length[i] < minLen) minLen = length[i];
}
/* Calculate permute[], base[], and limit[] tables from length[].
*
* permute[] is the lookup table for converting Huffman coded symbols
* into decoded symbols. base[] is the amount to subtract from the
* value of a Huffman symbol of a given length when using permute[].
*
* limit[] indicates the largest numerical value a symbol with a given
* number of bits can have. This is how the Huffman codes can vary in
* length: each code with a value>limit[length] needs another bit.
*/
hufGroup = bd->groups + j;
hufGroup->minLen = minLen;
hufGroup->maxLen = maxLen;
/* Note that minLen can't be smaller than 1, so we adjust the base
and limit array pointers so we're not always wasting the first
entry. We do this again when using them (during symbol decoding). */
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
/* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */
pp = 0;
for (i = minLen; i <= maxLen; i++) {
int k;
temp[i] = limit[i] = 0;
for (k = 0; k < symCount; k++)
if (length[k] == i)
hufGroup->permute[pp++] = k;
}
/* Count symbols coded for at each bit length */
/* NB: in pathological cases, temp[8] can end ip being 256.
* That's why uint8_t is too small for temp[]. */
for (i = 0; i < symCount; i++) temp[length[i]]++;
/* Calculate limit[] (the largest symbol-coding value at each bit
* length, which is (previous limit<<1)+symbols at this level), and
* base[] (number of symbols to ignore at each bit length, which is
* limit minus the cumulative count of symbols coded for already). */
pp = t = 0;
for (i = minLen; i < maxLen;) {
unsigned temp_i = temp[i];
pp += temp_i;
/* We read the largest possible symbol size and then unget bits
after determining how many we need, and those extra bits could
be set to anything. (They're noise from future symbols.) At
each level we're really only interested in the first few bits,
so here we set all the trailing to-be-ignored bits to 1 so they
don't affect the value>limit[length] comparison. */
limit[i] = (pp << (maxLen - i)) - 1;
pp <<= 1;
t += temp_i;
base[++i] = pp - t;
}
limit[maxLen] = pp + temp[maxLen] - 1;
limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
base[minLen] = 0;
}
/* We've finished reading and digesting the block header. Now read this
block's Huffman coded symbols from the file and undo the Huffman coding
and run length encoding, saving the result into dbuf[dbufCount++] = uc */
/* Initialize symbol occurrence counters and symbol Move To Front table */
/*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */
for (i = 0; i < 256; i++) {
byteCount[i] = 0;
mtfSymbol[i] = (uint8_t)i;
}
/* Loop through compressed symbols. */
runPos = dbufCount = selector = 0;
for (;;) {
int nextSym;
/* Fetch next Huffman coding group from list. */
symCount = GROUP_SIZE - 1;
if (selector >= nSelectors) return RETVAL_DATA_ERROR;
hufGroup = bd->groups + selectors[selector++];
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
continue_this_group:
/* Read next Huffman-coded symbol. */
/* Note: It is far cheaper to read maxLen bits and back up than it is
to read minLen bits and then add additional bit at a time, testing
as we go. Because there is a trailing last block (with file CRC),
there is no danger of the overread causing an unexpected EOF for a
valid compressed file.
*/
if (1) {
/* As a further optimization, we do the read inline
(falling back to a call to get_bits if the buffer runs dry).
*/
int new_cnt;
while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) {
/* bd->inbufBitCount < hufGroup->maxLen */
if (bd->inbufPos == bd->inbufCount) {
nextSym = get_bits(bd, hufGroup->maxLen);
goto got_huff_bits;
}
bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
bd->inbufBitCount += 8;
};
bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */
nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1);
got_huff_bits: ;
} else { /* unoptimized equivalent */
nextSym = get_bits(bd, hufGroup->maxLen);
}
/* Figure how many bits are in next symbol and unget extras */
i = hufGroup->minLen;
while (nextSym > limit[i]) ++i;
j = hufGroup->maxLen - i;
if (j < 0)
return RETVAL_DATA_ERROR;
bd->inbufBitCount += j;
/* Huffman decode value to get nextSym (with bounds checking) */
nextSym = (nextSym >> j) - base[i];
if ((unsigned)nextSym >= MAX_SYMBOLS)
return RETVAL_DATA_ERROR;
nextSym = hufGroup->permute[nextSym];
/* We have now decoded the symbol, which indicates either a new literal
byte, or a repeated run of the most recent literal byte. First,
check if nextSym indicates a repeated run, and if so loop collecting
how many times to repeat the last literal. */
if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
/* If this is the start of a new run, zero out counter */
if (runPos == 0) {
runPos = 1;
runCnt = 0;
}
/* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
each bit position, add 1 or 2 instead. For example,
1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
You can make any bit pattern that way using 1 less symbol than
the basic or 0/1 method (except all bits 0, which would use no
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
////The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
////This would be the fix (catches too large count way before it can overflow):
//// if (runCnt > bd->dbufSize) {
//// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
//// runCnt, bd->dbufSize);
//// return RETVAL_DATA_ERROR;
//// }
if (runPos < bd->dbufSize) runPos <<= 1;
goto end_of_huffman_loop;
}
dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, dbufSize);
return RETVAL_DATA_ERROR;
literal used is the one at the head of the mtfSymbol array.) */
if (runPos != 0) {
uint8_t tmp_byte;
if (dbufCount + runCnt > bd->dbufSize) {
dbg("dbufCount:%u+runCnt:%u %u > dbufSize:%u RETVAL_DATA_ERROR",
dbufCount, runCnt, dbufCount + runCnt, bd->dbufSize);
return RETVAL_DATA_ERROR;
}
tmp_byte = symToByte[mtfSymbol[0]];
byteCount[tmp_byte] += runCnt;
while ((int)--runCnt >= 0)
dbuf[dbufCount++] = (uint32_t)tmp_byte;
runPos = 0;
}
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
/* Adjust the MTF array. Since we typically expect to move only a
first symbol in the mtf array, position 0, would have been handled
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= bd->dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
uc = symToByte[uc];
/* We have our literal byte. Save it into dbuf. */
byteCount[uc]++;
dbuf[dbufCount++] = (uint32_t)uc;
/* Skip group initialization if we're not done with this group. Done
* this way to avoid compiler warning. */
end_of_huffman_loop:
if (--symCount >= 0) goto continue_this_group;
}
/* At this point, we've read all the Huffman-coded symbols (and repeated
runs) for this block from the input stream, and decoded them into the
intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
Now undo the Burrows-Wheeler transform on dbuf.
See http://dogma.net/markn/articles/bwt/bwt.htm
*/
/* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
j = 0;
for (i = 0; i < 256; i++) {
int tmp_count = j + byteCount[i];
byteCount[i] = j;
j = tmp_count;
}
/* Figure out what order dbuf would be in if we sorted it. */
for (i = 0; i < dbufCount; i++) {
uint8_t tmp_byte = (uint8_t)dbuf[i];
int tmp_count = byteCount[tmp_byte];
dbuf[tmp_count] |= (i << 8);
byteCount[tmp_byte] = tmp_count + 1;
}
/* Decode first byte by hand to initialize "previous" byte. Note that it
doesn't get output, and if the first three characters are identical
it doesn't qualify as a run (hence writeRunCountdown=5). */
if (dbufCount) {
uint32_t tmp;
if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
tmp = dbuf[origPtr];
bd->writeCurrent = (uint8_t)tmp;
bd->writePos = (tmp >> 8);
bd->writeRunCountdown = 5;
}
bd->writeCount = dbufCount;
return RETVAL_OK;
}
|
CVE-2017-15873
|
The get_next_block function in archival/libarchive/decompress_bunzip2.c in BusyBox 1.27.2 has an Integer Overflow that may lead to a write access violation.
|
[
"CWE-190"
] |
[
{
"line_no": 4,
"text": "\tint dbufCount, dbufSize, groupCount, *base, *limit, selector,",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": "\t\ti, j, runPos, symCount, symTotal, nSelectors, byteCount[256];",
"char_start": null,
"char_end": null
},
{
"line_no": 6,
"text": "\tint runCnt = runCnt; /* for compiler */",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": "\tdbufSize = bd->dbufSize;",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": "\tif ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR;",
"char_start": null,
"char_end": null
},
{
"line_no": 283,
"text": "\t\t\tif (runPos < dbufSize) runPos <<= 1;",
"char_start": null,
"char_end": null
},
{
"line_no": 300,
"text": "\t\t\tif (dbufCount + runCnt > dbufSize) {",
"char_start": null,
"char_end": null
},
{
"line_no": 301,
"text": "\t\t\t\tdbg(\"dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR\",",
"char_start": null,
"char_end": null
},
{
"line_no": 302,
"text": "\t\t\t\t\t\tdbufCount, runCnt, dbufCount + runCnt, dbufSize);",
"char_start": null,
"char_end": null
},
{
"line_no": 307,
"text": "\t\t\twhile (--runCnt >= 0) dbuf[dbufCount++] = (uint32_t)tmp_byte;",
"char_start": null,
"char_end": null
},
{
"line_no": 321,
"text": "\t\tif (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 4,
"text": "\tint groupCount, *base, *limit, selector,",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": "\t\ti, j, symCount, symTotal, nSelectors, byteCount[256];",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": "\tunsigned dbufCount, runPos;",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": "\tunsigned runCnt = runCnt; /* for compiler */",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": "\tif (origPtr > bd->dbufSize) return RETVAL_DATA_ERROR;",
"char_start": null,
"char_end": null
},
{
"line_no": 290,
"text": "\t\t\tif (runPos < bd->dbufSize) runPos <<= 1;",
"char_start": null,
"char_end": null
},
{
"line_no": 300,
"text": "\t\t\tif (dbufCount + runCnt > bd->dbufSize) {",
"char_start": null,
"char_end": null
},
{
"line_no": 301,
"text": "\t\t\t\tdbg(\"dbufCount:%u+runCnt:%u %u > dbufSize:%u RETVAL_DATA_ERROR\",",
"char_start": null,
"char_end": null
},
{
"line_no": 302,
"text": "\t\t\t\t\t\tdbufCount, runCnt, dbufCount + runCnt, bd->dbufSize);",
"char_start": null,
"char_end": null
},
{
"line_no": 307,
"text": "\t\t\twhile ((int)--runCnt >= 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 308,
"text": "\t\t\t\tdbuf[dbufCount++] = (uint32_t)tmp_byte;",
"char_start": null,
"char_end": null
},
{
"line_no": 322,
"text": "\t\tif (dbufCount >= bd->dbufSize) return RETVAL_DATA_ERROR;",
"char_start": null,
"char_end": null
}
] | 62
|
primevul
|
primevul_libxfont_d11ee5886e9d9ec610051a206b135a4cdc1e09a0
|
d11ee5886e9d9ec610051a206b135a4cdc1e09a0
|
libxfont
|
https://cgit.freedesktop.org/xorg/lib/libXfont/commit/?id=d11ee5886e9d9ec610051a206b135a4cdc1e09a0
|
BufCompressedFill (BufFilePtr f)
{
CompressedFile *file;
register char_type *stackp, *de_stack;
register char_type finchar;
register code_int code, oldcode, incode;
BufChar *buf, *bufend;
file = (CompressedFile *) f->private;
buf = f->buffer;
bufend = buf + BUFFILESIZE;
stackp = file->stackp;
de_stack = file->de_stack;
finchar = file->finchar;
oldcode = file->oldcode;
while (buf < bufend) {
while (stackp > de_stack && buf < bufend)
*buf++ = *--stackp;
if (buf == bufend)
break;
if (oldcode == -1)
break;
code = getcode (file);
if (code == -1)
break;
if ( (code == CLEAR) && file->block_compress ) {
for ( code = 255; code >= 0; code-- )
file->tab_prefix[code] = 0;
file->clear_flg = 1;
file->free_ent = FIRST - 1;
if ( (code = getcode (file)) == -1 ) /* O, untimely death! */
break;
}
incode = code;
/*
* Special case for KwKwK string.
*/
if ( code >= file->free_ent ) {
*stackp++ = finchar;
code = oldcode;
}
/*
* Generate output characters in reverse order
*/
while ( code >= 256 )
{
*stackp++ = file->tab_suffix[code];
code = file->tab_prefix[code];
}
/*
* Generate the new entry.
*/
if ( (code=file->free_ent) < file->maxmaxcode ) {
file->tab_prefix[code] = (unsigned short)oldcode;
file->tab_suffix[code] = finchar;
file->free_ent = code+1;
}
/*
* Remember previous code.
*/
oldcode = incode;
}
file->oldcode = oldcode;
file->stackp = stackp;
file->finchar = finchar;
if (buf == f->buffer) {
f->left = 0;
return BUFFILEEOF;
}
f->bufp = f->buffer + 1;
f->left = (buf - f->buffer) - 1;
return f->buffer[0];
}
|
BufCompressedFill (BufFilePtr f)
{
CompressedFile *file;
register char_type *stackp, *de_stack;
register char_type finchar;
register code_int code, oldcode, incode;
BufChar *buf, *bufend;
file = (CompressedFile *) f->private;
buf = f->buffer;
bufend = buf + BUFFILESIZE;
stackp = file->stackp;
de_stack = file->de_stack;
finchar = file->finchar;
oldcode = file->oldcode;
while (buf < bufend) {
while (stackp > de_stack && buf < bufend)
*buf++ = *--stackp;
if (buf == bufend)
break;
if (oldcode == -1)
break;
code = getcode (file);
if (code == -1)
break;
if ( (code == CLEAR) && file->block_compress ) {
for ( code = 255; code >= 0; code-- )
file->tab_prefix[code] = 0;
file->clear_flg = 1;
file->free_ent = FIRST - 1;
if ( (code = getcode (file)) == -1 ) /* O, untimely death! */
break;
}
incode = code;
/*
* Special case for KwKwK string.
*/
if ( code >= file->free_ent ) {
*stackp++ = finchar;
code = oldcode;
}
/*
* Generate output characters in reverse order
*/
while ( code >= 256 )
{
if (stackp - de_stack >= STACK_SIZE - 1)
return BUFFILEEOF;
*stackp++ = file->tab_suffix[code];
code = file->tab_prefix[code];
}
/*
* Generate the new entry.
*/
if ( (code=file->free_ent) < file->maxmaxcode ) {
file->tab_prefix[code] = (unsigned short)oldcode;
file->tab_suffix[code] = finchar;
file->free_ent = code+1;
}
/*
* Remember previous code.
*/
oldcode = incode;
}
file->oldcode = oldcode;
file->stackp = stackp;
file->finchar = finchar;
if (buf == f->buffer) {
f->left = 0;
return BUFFILEEOF;
}
f->bufp = f->buffer + 1;
f->left = (buf - f->buffer) - 1;
return f->buffer[0];
}
|
CVE-2011-2895
|
The LZW decompressor in (1) the BufCompressedFill function in fontfile/decompress.c in X.Org libXfont before 1.4.4 and (2) compress/compress.c in 4.3BSD, as used in zopen.c in OpenBSD before 3.8, FreeBSD, NetBSD 4.0.x and 5.0.x before 5.0.3 and 5.1.x before 5.1.1, FreeType 2.1.9, and other products, does not properly handle code words that are absent from the decompression table when encountered, which allows context-dependent attackers to trigger an infinite loop or a heap-based buffer overflow, and possibly execute arbitrary code, via a crafted compressed stream, a related issue to CVE-2006-1168 and CVE-2011-2896.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 53,
"text": "\t if (stackp - de_stack >= STACK_SIZE - 1)",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": "\t\treturn BUFFILEEOF;",
"char_start": null,
"char_end": null
}
] | 63
|
primevul
|
primevul_musl_45ca5d3fcb6f874bf5ba55d0e9651cef68515395
|
45ca5d3fcb6f874bf5ba55d0e9651cef68515395
|
musl
|
https://git.musl-libc.org/cgit/musl/commit/?id=45ca5d3fcb6f874bf5ba55d0e9651cef68515395
|
static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
{
char tmp[256];
struct dpc_ctx *ctx = c;
switch (rr) {
case RR_A:
if (len != 4) return -1;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
break;
case RR_AAAA:
if (len != 16) return -1;
ctx->addrs[ctx->cnt].family = AF_INET6;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
break;
case RR_CNAME:
if (__dn_expand(packet, (const unsigned char *)packet + 512,
data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
strcpy(ctx->canon, tmp);
break;
}
return 0;
}
|
static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
{
char tmp[256];
struct dpc_ctx *ctx = c;
if (ctx->cnt >= MAXADDRS) return -1;
switch (rr) {
case RR_A:
if (len != 4) return -1;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
break;
case RR_AAAA:
if (len != 16) return -1;
ctx->addrs[ctx->cnt].family = AF_INET6;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
break;
case RR_CNAME:
if (__dn_expand(packet, (const unsigned char *)packet + 512,
data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
strcpy(ctx->canon, tmp);
break;
}
return 0;
}
|
CVE-2017-15650
|
musl libc before 1.1.17 has a buffer overflow via crafted DNS replies because dns_parse_callback in network/lookup_name.c does not restrict the number of addresses, and thus an attacker can provide an unexpected number by sending A records in a reply to an AAAA query.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 5,
"text": "\tif (ctx->cnt >= MAXADDRS) return -1;",
"char_start": null,
"char_end": null
}
] | 64
|
primevul
|
primevul_poppler_61f79b8447c3ac8ab5a26e79e0c28053ffdccf75
|
61f79b8447c3ac8ab5a26e79e0c28053ffdccf75
|
poppler
|
https://github.com/freedesktop/poppler
|
bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
{
printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
globalParams = new GlobalParams();
ok = extractPages (argv[1], argv[2]);
if (ok) {
exitCode = 0;
}
delete globalParams;
err0:
return exitCode;
}
|
bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%d' if more than one page should be extracted", destFileName);
return false;
}
// destFileName can have multiple %% and one %d
// We use auxDestFileName to replace all the valid % appearances
// by 'A' (random char that is not %), if at the end of replacing
// any of the valid appearances there is still any % around, the
// pattern is wrong
char *auxDestFileName = strdup(destFileName);
// %% can appear as many times as you want
char *p = strstr(auxDestFileName, "%%");
while (p != NULL) {
*p = 'A';
*(p + 1) = 'A';
p = strstr(p, "%%");
}
// %d can appear only one time
p = strstr(auxDestFileName, "%d");
if (p != NULL) {
*p = 'A';
}
// at this point any other % is wrong
p = strstr(auxDestFileName, "%");
if (p != NULL) {
error(errSyntaxError, -1, "'{0:s}' can only contain one '%d' pattern", destFileName);
free(auxDestFileName);
return false;
}
free(auxDestFileName);
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
{
printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
globalParams = new GlobalParams();
ok = extractPages (argv[1], argv[2]);
if (ok) {
exitCode = 0;
}
delete globalParams;
err0:
return exitCode;
}
|
CVE-2013-4474
|
Format string vulnerability in the extractPages function in utils/pdfseparate.cc in poppler before 0.24.3 allows remote attackers to cause a denial of service (crash) via format string specifiers in a destination filename.
|
[
"CWE-20"
] |
[
{
"line_no": 21,
"text": " error(errSyntaxError, -1, \"'{0:s}' must contain '%%d' if more than one page should be extracted\", destFileName);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 21,
"text": " error(errSyntaxError, -1, \"'{0:s}' must contain '%d' if more than one page should be extracted\", destFileName);",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " ",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " // destFileName can have multiple %% and one %d",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " // We use auxDestFileName to replace all the valid % appearances",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " // by 'A' (random char that is not %), if at the end of replacing",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " // any of the valid appearances there is still any % around, the",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " // pattern is wrong",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " char *auxDestFileName = strdup(destFileName);",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": " // %% can appear as many times as you want",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " char *p = strstr(auxDestFileName, \"%%\");",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " while (p != NULL) {",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " *p = 'A';",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " *(p + 1) = 'A';",
"char_start": null,
"char_end": null
},
{
"line_no": 36,
"text": " p = strstr(p, \"%%\"); ",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " // %d can appear only one time",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": " p = strstr(auxDestFileName, \"%d\");",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": " if (p != NULL) {",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " *p = 'A';",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": " // at this point any other % is wrong",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " p = strstr(auxDestFileName, \"%\");",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": " if (p != NULL) {",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " error(errSyntaxError, -1, \"'{0:s}' can only contain one '%d' pattern\", destFileName);",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": " free(auxDestFileName);",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": " return false;",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 50,
"text": " free(auxDestFileName);",
"char_start": null,
"char_end": null
},
{
"line_no": 51,
"text": " ",
"char_start": null,
"char_end": null
}
] | 65
|
primevul
|
primevul_poppler_b8682d868ddf7f741e93b791588af0932893f95c
|
b8682d868ddf7f741e93b791588af0932893f95c
|
poppler
|
https://github.com/freedesktop/poppler
|
bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[1024];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
sprintf (pathName, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
int errCode = doc->savePageAs(gpageName, pageNo);
if ( errCode != errNone) {
delete gpageName;
delete gfileName;
return false;
}
delete gpageName;
}
delete gfileName;
return true;
}
|
bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
int errCode = doc->savePageAs(gpageName, pageNo);
if ( errCode != errNone) {
delete gpageName;
delete gfileName;
return false;
}
delete gpageName;
}
delete gfileName;
return true;
}
|
CVE-2013-4473
|
Stack-based buffer overflow in the extractPages function in utils/pdfseparate.cc in poppler before 0.24.2 allows remote attackers to cause a denial of service (crash) and possibly execute arbitrary code via a source filename.
|
[
"CWE-119"
] |
[
{
"line_no": 2,
"text": " char pathName[1024];",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " sprintf (pathName, destFileName, pageNo);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 2,
"text": " char pathName[4096];",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);",
"char_start": null,
"char_end": null
}
] | 66
|
primevul
|
primevul_ghostscript_97096297d409ec6f206298444ba00719607e8ba8
|
97096297d409ec6f206298444ba00719607e8ba8
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
walk_string(fz_context *ctx, int uni, int remove, editable_str *str)
{
int rune;
if (str->utf8 == NULL)
return;
do
{
char *s = &str->utf8[str->pos];
size_t len;
int n = fz_chartorune(&rune, s);
if (rune == uni)
{
/* Match. Skip over that one. */
str->pos += n;
}
else if (uni == 32) {
/* We don't care if we're given whitespace
* and it doesn't match the string. Don't
* skip forward. Nothing to remove. */
break;
}
else if (rune == 32) {
/* The string has a whitespace, and we
* don't match it; that's forgivable as
* PDF often misses out spaces. Remove this
* if we are removing stuff. */
}
else
{
/* Mismatch. No point in tracking through any more. */
str->pos = -1;
break;
}
if (remove)
{
len = strlen(s+n);
memmove(s, s+n, len+1);
str->edited = 1;
}
}
while (rune != uni);
}
|
walk_string(fz_context *ctx, int uni, int remove, editable_str *str)
{
int rune;
if (str->utf8 == NULL || str->pos == -1)
return;
do
{
char *s = &str->utf8[str->pos];
size_t len;
int n = fz_chartorune(&rune, s);
if (rune == uni)
{
/* Match. Skip over that one. */
str->pos += n;
}
else if (uni == 32) {
/* We don't care if we're given whitespace
* and it doesn't match the string. Don't
* skip forward. Nothing to remove. */
break;
}
else if (rune == 32) {
/* The string has a whitespace, and we
* don't match it; that's forgivable as
* PDF often misses out spaces. Remove this
* if we are removing stuff. */
}
else
{
/* Mismatch. No point in tracking through any more. */
str->pos = -1;
break;
}
if (remove)
{
len = strlen(s+n);
memmove(s, s+n, len+1);
str->edited = 1;
}
}
while (rune != uni);
}
|
CVE-2019-14975
|
Artifex MuPDF before 1.16.0 has a heap-based buffer over-read in fz_chartorune in fitz/string.c because pdf/pdf-op-filter.c does not check for a missing string.
|
[
"CWE-125"
] |
[
{
"line_no": 5,
"text": " if (str->utf8 == NULL)",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 5,
"text": " if (str->utf8 == NULL || str->pos == -1)",
"char_start": null,
"char_end": null
}
] | 70
|
primevul
|
primevul_mindrot_1bf477d3cdf1a864646d59820878783d42357a1d
|
1bf477d3cdf1a864646d59820878783d42357a1d
|
mindrot
|
https://anongit.mindrot.org/openssh
|
x11_open_helper(Buffer *b)
{
u_char *ucp;
u_int proto_len, data_len;
u_char *ucp;
u_int proto_len, data_len;
/* Check if the fixed size part of the packet is in buffer. */
if (buffer_len(b) < 12)
return 0;
debug2("Initial X11 packet contains bad byte order byte: 0x%x",
ucp[0]);
return -1;
}
|
x11_open_helper(Buffer *b)
{
u_char *ucp;
u_int proto_len, data_len;
u_char *ucp;
u_int proto_len, data_len;
/* Is this being called after the refusal deadline? */
if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
verbose("Rejected X11 connection after ForwardX11Timeout "
"expired");
return -1;
}
/* Check if the fixed size part of the packet is in buffer. */
if (buffer_len(b) < 12)
return 0;
debug2("Initial X11 packet contains bad byte order byte: 0x%x",
ucp[0]);
return -1;
}
|
CVE-2015-5352
|
The x11_open_helper function in channels.c in ssh in OpenSSH before 6.9, when ForwardX11Trusted mode is not used, lacks a check of the refusal deadline for X connections, which makes it easier for remote attackers to bypass intended access restrictions via a connection outside of the permitted time window.
|
[
"CWE-264"
] |
[] |
[
{
"line_no": 9,
"text": "\t/* Is this being called after the refusal deadline? */",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": "\tif (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": "\t\tverbose(\"Rejected X11 connection after ForwardX11Timeout \"",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": "\t\t \"expired\");",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": "\t\treturn -1;",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": "\t}",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": "",
"char_start": null,
"char_end": null
}
] | 73
|
primevul
|
primevul_samba_538d305de91e34a2938f5f219f18bf0e1918763f
|
538d305de91e34a2938f5f219f18bf0e1918763f
|
samba
|
https://github.com/samba-team/samba
|
_PUBLIC_ codepoint_t next_codepoint_handle_ext(
struct smb_iconv_handle *ic,
const char *str, size_t len,
charset_t src_charset,
size_t *bytes_consumed)
{
/* it cannot occupy more than 4 bytes in UTF16 format */
uint8_t buf[4];
smb_iconv_t descriptor;
size_t ilen_orig;
size_t ilen;
size_t olen;
char *outbuf;
if ((str[0] & 0x80) == 0) {
*bytes_consumed = 1;
return (codepoint_t)str[0];
}
* This is OK as we only support codepoints up to 1M (U+100000)
*/
ilen_orig = MIN(len, 5);
ilen = ilen_orig;
descriptor = get_conv_handle(ic, src_charset, CH_UTF16);
if (descriptor == (smb_iconv_t)-1) {
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
/*
* this looks a little strange, but it is needed to cope with
* codepoints above 64k (U+1000) which are encoded as per RFC2781.
*/
olen = 2;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 2) {
olen = 4;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 4) {
/* we didn't convert any bytes */
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
olen = 4 - olen;
} else {
olen = 2 - olen;
}
*bytes_consumed = ilen_orig - ilen;
if (olen == 2) {
return (codepoint_t)SVAL(buf, 0);
}
if (olen == 4) {
/* decode a 4 byte UTF16 character manually */
return (codepoint_t)0x10000 +
(buf[2] | ((buf[3] & 0x3)<<8) |
(buf[0]<<10) | ((buf[1] & 0x3)<<18));
}
/* no other length is valid */
return INVALID_CODEPOINT;
}
|
_PUBLIC_ codepoint_t next_codepoint_handle_ext(
struct smb_iconv_handle *ic,
const char *str, size_t len,
charset_t src_charset,
size_t *bytes_consumed)
{
/* it cannot occupy more than 4 bytes in UTF16 format */
uint8_t buf[4];
smb_iconv_t descriptor;
size_t ilen_orig;
size_t ilen;
size_t olen;
char *outbuf;
if (((str[0] & 0x80) == 0) && (src_charset == CH_DOS ||
src_charset == CH_UNIX ||
src_charset == CH_UTF8)) {
*bytes_consumed = 1;
return (codepoint_t)str[0];
}
* This is OK as we only support codepoints up to 1M (U+100000)
*/
ilen_orig = MIN(len, 5);
ilen = ilen_orig;
descriptor = get_conv_handle(ic, src_charset, CH_UTF16);
if (descriptor == (smb_iconv_t)-1) {
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
/*
* this looks a little strange, but it is needed to cope with
* codepoints above 64k (U+1000) which are encoded as per RFC2781.
*/
olen = 2;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 2) {
olen = 4;
outbuf = (char *)buf;
smb_iconv(descriptor, &str, &ilen, &outbuf, &olen);
if (olen == 4) {
/* we didn't convert any bytes */
*bytes_consumed = 1;
return INVALID_CODEPOINT;
}
olen = 4 - olen;
} else {
olen = 2 - olen;
}
*bytes_consumed = ilen_orig - ilen;
if (olen == 2) {
return (codepoint_t)SVAL(buf, 0);
}
if (olen == 4) {
/* decode a 4 byte UTF16 character manually */
return (codepoint_t)0x10000 +
(buf[2] | ((buf[3] & 0x3)<<8) |
(buf[0]<<10) | ((buf[1] & 0x3)<<18));
}
/* no other length is valid */
return INVALID_CODEPOINT;
}
|
CVE-2015-5330
|
ldb before 1.1.24, as used in the AD LDAP server in Samba 4.x before 4.1.22, 4.2.x before 4.2.7, and 4.3.x before 4.3.3, mishandles string lengths, which allows remote attackers to obtain sensitive information from daemon heap memory by sending crafted packets and then reading (1) an error message or (2) a database value.
|
[
"CWE-200"
] |
[
{
"line_no": 15,
"text": " if ((str[0] & 0x80) == 0) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 15,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " if (((str[0] & 0x80) == 0) && (src_charset == CH_DOS ||",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": " src_charset == CH_UNIX ||",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " src_charset == CH_UTF8)) {",
"char_start": null,
"char_end": null
}
] | 74
|
primevul
|
primevul_samba_7f51ec8c4ed9ba1f53d722e44fb6fb3cde933b72
|
7f51ec8c4ed9ba1f53d722e44fb6fb3cde933b72
|
samba
|
https://github.com/samba-team/samba
|
static int ldb_dn_escape_internal(char *dst, const char *src, int len)
{
const char *p, *s;
char *d;
size_t l;
p = s = src;
d = dst;
while (p - src < len) {
p += strcspn(p, ",=\n\r+<>#;\\\" ");
if (p - src == len) /* found no escapable chars */
break;
/* copy the part of the string before the stop */
memcpy(d, s, p - s);
d += (p - s); /* move to current position */
switch (*p) {
case ' ':
if (p == src || (p-src)==(len-1)) {
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = *p++;
} else {
/* otherwise don't escape */
*d++ = *p++;
}
break;
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = *p++;
} else {
/* otherwise don't escape */
*d++ = *p++;
}
break;
case '?':
/* these must be escaped using \c form */
*d++ = '\\';
*d++ = *p++;
break;
default: {
/* any others get \XX form */
unsigned char v;
const char *hexbytes = "0123456789ABCDEF";
v = *(const unsigned char *)p;
*d++ = '\\';
*d++ = hexbytes[v>>4];
*d++ = hexbytes[v&0xF];
p++;
break;
}
}
s = p; /* move forward */
}
|
static int ldb_dn_escape_internal(char *dst, const char *src, int len)
{
char c;
char *d;
int i;
d = dst;
for (i = 0; i < len; i++){
c = src[i];
switch (c) {
case ' ':
if (i == 0 || i == len - 1) {
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = c;
} else {
/* otherwise don't escape */
*d++ = c;
}
break;
/* if at the beginning or end
* of the string then escape */
*d++ = '\\';
*d++ = *p++;
} else {
/* otherwise don't escape */
*d++ = *p++;
}
break;
case '?':
/* these must be escaped using \c form */
*d++ = '\\';
*d++ = c;
break;
case ';':
case '\r':
case '\n':
case '=':
case '\0': {
/* any others get \XX form */
unsigned char v;
const char *hexbytes = "0123456789ABCDEF";
v = (const unsigned char)c;
*d++ = '\\';
*d++ = hexbytes[v>>4];
*d++ = hexbytes[v&0xF];
break;
}
default:
*d++ = c;
}
}
|
CVE-2015-5330
|
ldb before 1.1.24, as used in the AD LDAP server in Samba 4.x before 4.1.22, 4.2.x before 4.2.7, and 4.3.x before 4.3.3, mishandles string lengths, which allows remote attackers to obtain sensitive information from daemon heap memory by sending crafted packets and then reading (1) an error message or (2) a database value.
|
[
"CWE-200"
] |
[
{
"line_no": 3,
"text": " const char *p, *s;",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": " size_t l;",
"char_start": null,
"char_end": null
},
{
"line_no": 6,
"text": " p = s = src;",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " while (p - src < len) {",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " p += strcspn(p, \",=\\n\\r+<>#;\\\\\\\" \");",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " if (p - src == len) /* found no escapable chars */",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " break;",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " /* copy the part of the string before the stop */",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " memcpy(d, s, p - s);",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": " d += (p - s); /* move to current position */",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " switch (*p) {",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " if (p == src || (p-src)==(len-1)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 22,
"text": " *d++ = *p++; ",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " *d++ = *p++;",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " *d++ = *p++;",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " default: {",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": " v = *(const unsigned char *)p;",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " p++;",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": " s = p; /* move forward */",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 3,
"text": " char c;",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": " int i;",
"char_start": null,
"char_end": null
},
{
"line_no": 8,
"text": " for (i = 0; i < len; i++){",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " c = src[i];",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " switch (c) {",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " if (i == 0 || i == len - 1) {",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " *d++ = c;",
"char_start": null,
"char_end": null
},
{
"line_no": 19,
"text": " *d++ = c;",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " *d++ = c;",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " case ';':",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": " case '\\r':",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": " case '\\n':",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " case '=':",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": " case '\\0': {",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " v = (const unsigned char)c;",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " default:",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": " *d++ = c;",
"char_start": null,
"char_end": null
}
] | 75
|
primevul
|
primevul_samba_a118d4220ed85749c07fb43c1229d9e2fecbea6b
|
a118d4220ed85749c07fb43c1229d9e2fecbea6b
|
samba
|
https://github.com/samba-team/samba
|
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle,
TALLOC_CTX *ctx, const char *src, size_t n)
{
size_t size=0;
char *dest;
if (!src) {
return NULL;
}
/* this takes advantage of the fact that upper/lower can't
change the length of a character by more than 1 byte */
dest = talloc_array(ctx, char, 2*(n+1));
if (dest == NULL) {
return NULL;
}
while (n-- && *src) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n,
CH_UNIX, &c_size);
src += c_size;
c = toupper_m(c);
if (c_size == -1) {
talloc_free(dest);
return NULL;
}
size += c_size;
}
dest[size] = 0;
/* trim it so talloc_append_string() works */
dest = talloc_realloc(ctx, dest, char, size+1);
talloc_set_name_const(dest, dest);
return dest;
}
|
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle,
TALLOC_CTX *ctx, const char *src, size_t n)
{
size_t size=0;
char *dest;
if (!src) {
return NULL;
}
/* this takes advantage of the fact that upper/lower can't
change the length of a character by more than 1 byte */
dest = talloc_array(ctx, char, 2*(n+1));
if (dest == NULL) {
return NULL;
}
while (n && *src) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n,
CH_UNIX, &c_size);
src += c_size;
n -= c_size;
c = toupper_m(c);
if (c_size == -1) {
talloc_free(dest);
return NULL;
}
size += c_size;
}
dest[size] = 0;
/* trim it so talloc_append_string() works */
dest = talloc_realloc(ctx, dest, char, size+1);
talloc_set_name_const(dest, dest);
return dest;
}
|
CVE-2015-5330
|
ldb before 1.1.24, as used in the AD LDAP server in Samba 4.x before 4.1.22, 4.2.x before 4.2.7, and 4.3.x before 4.3.3, mishandles string lengths, which allows remote attackers to obtain sensitive information from daemon heap memory by sending crafted packets and then reading (1) an error message or (2) a database value.
|
[
"CWE-200"
] |
[
{
"line_no": 18,
"text": " while (n-- && *src) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 18,
"text": " while (n && *src) {",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " n -= c_size;",
"char_start": null,
"char_end": null
}
] | 76
|
primevul
|
primevul_samba_f36cb71c330a52106e36028b3029d952257baf15
|
f36cb71c330a52106e36028b3029d952257baf15
|
samba
|
https://github.com/samba-team/samba
|
static bool ldb_dn_explode(struct ldb_dn *dn)
{
char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t;
bool trim = true;
bool in_extended = true;
bool in_ex_name = false;
bool in_ex_value = false;
bool in_attr = false;
bool in_value = false;
bool in_quote = false;
bool is_oid = false;
bool escape = false;
unsigned int x;
size_t l = 0;
int ret;
char *parse_dn;
bool is_index;
if ( ! dn || dn->invalid) return false;
if (dn->components) {
return true;
}
if (dn->ext_linearized) {
parse_dn = dn->ext_linearized;
} else {
parse_dn = dn->linearized;
}
if ( ! parse_dn ) {
return false;
}
is_index = (strncmp(parse_dn, "DN=@INDEX:", 10) == 0);
/* Empty DNs */
if (parse_dn[0] == '\0') {
return true;
}
/* Special DNs case */
if (dn->special) {
return true;
}
/* make sure we free this if allocated previously before replacing */
LDB_FREE(dn->components);
dn->comp_num = 0;
LDB_FREE(dn->ext_components);
dn->ext_comp_num = 0;
/* in the common case we have 3 or more components */
/* make sure all components are zeroed, other functions depend on it */
dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3);
if ( ! dn->components) {
return false;
}
/* Components data space is allocated here once */
data = talloc_array(dn->components, char, strlen(parse_dn) + 1);
if (!data) {
return false;
}
p = parse_dn;
t = NULL;
d = dt = data;
while (*p) {
if (in_extended) {
if (!in_ex_name && !in_ex_value) {
if (p[0] == '<') {
p++;
ex_name = d;
in_ex_name = true;
continue;
} else if (p[0] == '\0') {
p++;
continue;
} else {
in_extended = false;
in_attr = true;
dt = d;
continue;
}
}
if (in_ex_name && *p == '=') {
*d++ = '\0';
p++;
ex_value = d;
in_ex_name = false;
in_ex_value = true;
continue;
}
if (in_ex_value && *p == '>') {
const struct ldb_dn_extended_syntax *ext_syntax;
struct ldb_val ex_val = {
.data = (uint8_t *)ex_value,
.length = d - ex_value
};
*d++ = '\0';
p++;
in_ex_value = false;
/* Process name and ex_value */
dn->ext_components = talloc_realloc(dn,
dn->ext_components,
struct ldb_dn_ext_component,
dn->ext_comp_num + 1);
if ( ! dn->ext_components) {
/* ouch ! */
goto failed;
}
ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name);
if (!ext_syntax) {
/* We don't know about this type of extended DN */
goto failed;
}
dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name);
if (!dn->ext_components[dn->ext_comp_num].name) {
/* ouch */
goto failed;
}
ret = ext_syntax->read_fn(dn->ldb, dn->ext_components,
&ex_val, &dn->ext_components[dn->ext_comp_num].value);
if (ret != LDB_SUCCESS) {
ldb_dn_mark_invalid(dn);
goto failed;
}
dn->ext_comp_num++;
if (*p == '\0') {
/* We have reached the end (extended component only)! */
talloc_free(data);
return true;
} else if (*p == ';') {
p++;
continue;
} else {
ldb_dn_mark_invalid(dn);
goto failed;
}
}
*d++ = *p++;
continue;
}
if (in_attr) {
if (trim) {
if (*p == ' ') {
p++;
continue;
}
/* first char */
trim = false;
if (!isascii(*p)) {
/* attr names must be ascii only */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (isdigit(*p)) {
is_oid = true;
} else
if ( ! isalpha(*p)) {
/* not a digit nor an alpha,
* invalid attribute name */
ldb_dn_mark_invalid(dn);
goto failed;
}
/* Copy this character across from parse_dn,
* now we have trimmed out spaces */
*d++ = *p++;
continue;
}
if (*p == ' ') {
p++;
/* valid only if we are at the end */
trim = true;
continue;
}
if (trim && (*p != '=')) {
/* spaces/tabs are not allowed */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (*p == '=') {
/* attribute terminated */
in_attr = false;
in_value = true;
trim = true;
l = 0;
/* Terminate this string in d
* (which is a copy of parse_dn
* with spaces trimmed) */
*d++ = '\0';
dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt);
if ( ! dn->components[dn->comp_num].name) {
/* ouch */
goto failed;
}
dt = d;
p++;
continue;
}
if (!isascii(*p)) {
/* attr names must be ascii only */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) {
/* not a digit nor a dot,
* invalid attribute oid */
ldb_dn_mark_invalid(dn);
goto failed;
} else
if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) {
/* not ALPHA, DIGIT or HYPHEN */
ldb_dn_mark_invalid(dn);
goto failed;
}
*d++ = *p++;
continue;
}
if (in_value) {
if (in_quote) {
if (*p == '\"') {
if (p[-1] != '\\') {
p++;
in_quote = false;
continue;
}
}
*d++ = *p++;
l++;
continue;
}
if (trim) {
if (*p == ' ') {
p++;
continue;
}
/* first char */
trim = false;
if (*p == '\"') {
in_quote = true;
p++;
continue;
}
}
switch (*p) {
/* TODO: support ber encoded values
case '#':
*/
case ',':
if (escape) {
*d++ = *p++;
l++;
escape = false;
continue;
}
/* ok found value terminator */
if ( t ) {
/* trim back */
d -= (p - t);
l -= (p - t);
}
in_attr = true;
in_value = false;
trim = true;
p++;
*d++ = '\0';
dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt);
dn->components[dn->comp_num].value.length = l;
if ( ! dn->components[dn->comp_num].value.data) {
/* ouch ! */
goto failed;
}
dt = d;
dn->components,
struct ldb_dn_component,
dn->comp_num + 1);
if ( ! dn->components) {
/* ouch ! */
goto failed;
}
/* make sure all components are zeroed, other functions depend on this */
memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component));
}
continue;
case '+':
case '=':
/* to main compatibility with earlier
versions of ldb indexing, we have to
accept the base64 encoded binary index
values, which contain a '+' or '='
which should normally be escaped */
if (is_index) {
if ( t ) t = NULL;
*d++ = *p++;
l++;
break;
}
/* fall through */
case '\"':
case '<':
case '>':
case ';':
/* a string with not escaped specials is invalid (tested) */
if ( ! escape) {
ldb_dn_mark_invalid(dn);
goto failed;
}
escape = false;
*d++ = *p++;
l++;
if ( t ) t = NULL;
break;
case '\\':
if ( ! escape) {
escape = true;
p++;
continue;
}
escape = false;
*d++ = *p++;
l++;
if ( t ) t = NULL;
break;
default:
if (escape) {
if (isxdigit(p[0]) && isxdigit(p[1])) {
if (sscanf(p, "%02x", &x) != 1) {
/* invalid escaping sequence */
ldb_dn_mark_invalid(dn);
goto failed;
}
p += 2;
*d++ = (unsigned char)x;
} else {
*d++ = *p++;
}
escape = false;
l++;
if ( t ) t = NULL;
break;
}
if (*p == ' ') {
if ( ! t) t = p;
} else {
if ( t ) t = NULL;
}
*d++ = *p++;
l++;
break;
}
}
}
|
static bool ldb_dn_explode(struct ldb_dn *dn)
{
char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t;
bool trim = true;
bool in_extended = true;
bool in_ex_name = false;
bool in_ex_value = false;
bool in_attr = false;
bool in_value = false;
bool in_quote = false;
bool is_oid = false;
bool escape = false;
unsigned int x;
size_t l = 0;
int ret;
char *parse_dn;
bool is_index;
if ( ! dn || dn->invalid) return false;
if (dn->components) {
return true;
}
if (dn->ext_linearized) {
parse_dn = dn->ext_linearized;
} else {
parse_dn = dn->linearized;
}
if ( ! parse_dn ) {
return false;
}
is_index = (strncmp(parse_dn, "DN=@INDEX:", 10) == 0);
/* Empty DNs */
if (parse_dn[0] == '\0') {
return true;
}
/* Special DNs case */
if (dn->special) {
return true;
}
/* make sure we free this if allocated previously before replacing */
LDB_FREE(dn->components);
dn->comp_num = 0;
LDB_FREE(dn->ext_components);
dn->ext_comp_num = 0;
/* in the common case we have 3 or more components */
/* make sure all components are zeroed, other functions depend on it */
dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3);
if ( ! dn->components) {
return false;
}
/* Components data space is allocated here once */
data = talloc_array(dn->components, char, strlen(parse_dn) + 1);
if (!data) {
return false;
}
p = parse_dn;
t = NULL;
d = dt = data;
while (*p) {
if (in_extended) {
if (!in_ex_name && !in_ex_value) {
if (p[0] == '<') {
p++;
ex_name = d;
in_ex_name = true;
continue;
} else if (p[0] == '\0') {
p++;
continue;
} else {
in_extended = false;
in_attr = true;
dt = d;
continue;
}
}
if (in_ex_name && *p == '=') {
*d++ = '\0';
p++;
ex_value = d;
in_ex_name = false;
in_ex_value = true;
continue;
}
if (in_ex_value && *p == '>') {
const struct ldb_dn_extended_syntax *ext_syntax;
struct ldb_val ex_val = {
.data = (uint8_t *)ex_value,
.length = d - ex_value
};
*d++ = '\0';
p++;
in_ex_value = false;
/* Process name and ex_value */
dn->ext_components = talloc_realloc(dn,
dn->ext_components,
struct ldb_dn_ext_component,
dn->ext_comp_num + 1);
if ( ! dn->ext_components) {
/* ouch ! */
goto failed;
}
ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name);
if (!ext_syntax) {
/* We don't know about this type of extended DN */
goto failed;
}
dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name);
if (!dn->ext_components[dn->ext_comp_num].name) {
/* ouch */
goto failed;
}
ret = ext_syntax->read_fn(dn->ldb, dn->ext_components,
&ex_val, &dn->ext_components[dn->ext_comp_num].value);
if (ret != LDB_SUCCESS) {
ldb_dn_mark_invalid(dn);
goto failed;
}
dn->ext_comp_num++;
if (*p == '\0') {
/* We have reached the end (extended component only)! */
talloc_free(data);
return true;
} else if (*p == ';') {
p++;
continue;
} else {
ldb_dn_mark_invalid(dn);
goto failed;
}
}
*d++ = *p++;
continue;
}
if (in_attr) {
if (trim) {
if (*p == ' ') {
p++;
continue;
}
/* first char */
trim = false;
if (!isascii(*p)) {
/* attr names must be ascii only */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (isdigit(*p)) {
is_oid = true;
} else
if ( ! isalpha(*p)) {
/* not a digit nor an alpha,
* invalid attribute name */
ldb_dn_mark_invalid(dn);
goto failed;
}
/* Copy this character across from parse_dn,
* now we have trimmed out spaces */
*d++ = *p++;
continue;
}
if (*p == ' ') {
p++;
/* valid only if we are at the end */
trim = true;
continue;
}
if (trim && (*p != '=')) {
/* spaces/tabs are not allowed */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (*p == '=') {
/* attribute terminated */
in_attr = false;
in_value = true;
trim = true;
l = 0;
/* Terminate this string in d
* (which is a copy of parse_dn
* with spaces trimmed) */
*d++ = '\0';
dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt);
if ( ! dn->components[dn->comp_num].name) {
/* ouch */
goto failed;
}
dt = d;
p++;
continue;
}
if (!isascii(*p)) {
/* attr names must be ascii only */
ldb_dn_mark_invalid(dn);
goto failed;
}
if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) {
/* not a digit nor a dot,
* invalid attribute oid */
ldb_dn_mark_invalid(dn);
goto failed;
} else
if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) {
/* not ALPHA, DIGIT or HYPHEN */
ldb_dn_mark_invalid(dn);
goto failed;
}
*d++ = *p++;
continue;
}
if (in_value) {
if (in_quote) {
if (*p == '\"') {
if (p[-1] != '\\') {
p++;
in_quote = false;
continue;
}
}
*d++ = *p++;
l++;
continue;
}
if (trim) {
if (*p == ' ') {
p++;
continue;
}
/* first char */
trim = false;
if (*p == '\"') {
in_quote = true;
p++;
continue;
}
}
switch (*p) {
/* TODO: support ber encoded values
case '#':
*/
case ',':
if (escape) {
*d++ = *p++;
l++;
escape = false;
continue;
}
/* ok found value terminator */
if ( t ) {
/* trim back */
d -= (p - t);
l -= (p - t);
}
in_attr = true;
in_value = false;
trim = true;
p++;
*d++ = '\0';
dn->components[dn->comp_num].value.data = \
(uint8_t *)talloc_memdup(dn->components, dt, l + 1);
dn->components[dn->comp_num].value.length = l;
if ( ! dn->components[dn->comp_num].value.data) {
/* ouch ! */
goto failed;
}
talloc_set_name_const(dn->components[dn->comp_num].value.data,
(const char *)dn->components[dn->comp_num].value.data);
dt = d;
dn->components,
struct ldb_dn_component,
dn->comp_num + 1);
if ( ! dn->components) {
/* ouch ! */
goto failed;
}
/* make sure all components are zeroed, other functions depend on this */
memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component));
}
continue;
case '+':
case '=':
/* to main compatibility with earlier
versions of ldb indexing, we have to
accept the base64 encoded binary index
values, which contain a '+' or '='
which should normally be escaped */
if (is_index) {
if ( t ) t = NULL;
*d++ = *p++;
l++;
break;
}
/* fall through */
case '\"':
case '<':
case '>':
case ';':
/* a string with not escaped specials is invalid (tested) */
if ( ! escape) {
ldb_dn_mark_invalid(dn);
goto failed;
}
escape = false;
*d++ = *p++;
l++;
if ( t ) t = NULL;
break;
case '\\':
if ( ! escape) {
escape = true;
p++;
continue;
}
escape = false;
*d++ = *p++;
l++;
if ( t ) t = NULL;
break;
default:
if (escape) {
if (isxdigit(p[0]) && isxdigit(p[1])) {
if (sscanf(p, "%02x", &x) != 1) {
/* invalid escaping sequence */
ldb_dn_mark_invalid(dn);
goto failed;
}
p += 2;
*d++ = (unsigned char)x;
} else {
*d++ = *p++;
}
escape = false;
l++;
if ( t ) t = NULL;
break;
}
if (*p == ' ') {
if ( ! t) t = p;
} else {
if ( t ) t = NULL;
}
*d++ = *p++;
l++;
break;
}
}
}
|
CVE-2015-5330
|
ldb before 1.1.24, as used in the AD LDAP server in Samba 4.x before 4.1.22, 4.2.x before 4.2.7, and 4.3.x before 4.3.3, mishandles string lengths, which allows remote attackers to obtain sensitive information from daemon heap memory by sending crafted packets and then reading (1) an error message or (2) a database value.
|
[
"CWE-200"
] |
[
{
"line_no": 308,
"text": " dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 308,
"text": " dn->components[dn->comp_num].value.data = \\",
"char_start": null,
"char_end": null
},
{
"line_no": 309,
"text": " (uint8_t *)talloc_memdup(dn->components, dt, l + 1);",
"char_start": null,
"char_end": null
},
{
"line_no": 315,
"text": " talloc_set_name_const(dn->components[dn->comp_num].value.data,",
"char_start": null,
"char_end": null
},
{
"line_no": 316,
"text": " (const char *)dn->components[dn->comp_num].value.data);",
"char_start": null,
"char_end": null
}
] | 80
|
primevul
|
primevul_ghostscript_a6807394bd94b708be24758287b606154daaaed9
|
a6807394bd94b708be24758287b606154daaaed9
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors,
int *pexit_code, ref * perror_object)
{
ref *epref = pref;
ref doref;
ref *perrordict;
ref error_name;
int code, ccode;
ref saref;
i_ctx_t *i_ctx_p = *pi_ctx_p;
int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal;
*pexit_code = 0;
*gc_signal = 0;
ialloc_reset_requested(idmemory);
again:
/* Avoid a dangling error object that might get traced by a future GC. */
make_null(perror_object);
o_stack.requested = e_stack.requested = d_stack.requested = 0;
while (*gc_signal) { /* Some routine below triggered a GC. */
gs_gc_root_t epref_root;
*gc_signal = 0;
/* Make sure that doref will get relocated properly if */
/* a garbage collection happens with epref == &doref. */
gs_register_ref_root(imemory_system, &epref_root,
(void **)&epref, "gs_call_interp(epref)");
code = interp_reclaim(pi_ctx_p, -1);
i_ctx_p = *pi_ctx_p;
gs_unregister_root(imemory_system, &epref_root,
"gs_call_interp(epref)");
if (code < 0)
return code;
}
code = interp(pi_ctx_p, epref, perror_object);
i_ctx_p = *pi_ctx_p;
if (!r_has_type(&i_ctx_p->error_object, t__invalid)) {
*perror_object = i_ctx_p->error_object;
make_t(&i_ctx_p->error_object, t__invalid);
}
/* Prevent a dangling reference to the GC signal in ticks_left */
/* in the frame of interp, but be prepared to do a GC if */
/* an allocation in this routine asks for it. */
*gc_signal = 0;
set_gc_signal(i_ctx_p, 1);
if (esp < esbot) /* popped guard entry */
esp = esbot;
switch (code) {
case gs_error_Fatal:
*pexit_code = 255;
return code;
case gs_error_Quit:
*perror_object = osp[-1];
*pexit_code = code = osp->value.intval;
osp -= 2;
return
(code == 0 ? gs_error_Quit :
code < 0 && code > -100 ? code : gs_error_Fatal);
case gs_error_InterpreterExit:
return 0;
case gs_error_ExecStackUnderflow:
/****** WRONG -- must keep mark blocks intact ******/
ref_stack_pop_block(&e_stack);
doref = *perror_object;
epref = &doref;
goto again;
case gs_error_VMreclaim:
/* Do the GC and continue. */
/* We ignore the return value here, if it fails here
* we'll call it again having jumped to the "again" label.
* Where, assuming it fails again, we'll handle the error.
*/
(void)interp_reclaim(pi_ctx_p,
(osp->value.intval == 2 ?
avm_global : avm_local));
i_ctx_p = *pi_ctx_p;
make_oper(&doref, 0, zpop);
epref = &doref;
goto again;
case gs_error_NeedInput:
case gs_error_interrupt:
return code;
}
/* Adjust osp in case of operand stack underflow */
if (osp < osbot - 1)
osp = osbot - 1;
/* We have to handle stack over/underflow specially, because */
/* we might be able to recover by adding or removing a block. */
switch (code) {
case gs_error_dictstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_dstack, which does a ref_stack_extend, */
/* so if` we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
/* Skip system dictionaries for CET 20-02-02 */
ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref);
if (ccode < 0)
return ccode;
ref_stack_pop_to(&d_stack, min_dstack_size);
dict_set_top();
*++osp = saref;
break;
case gs_error_dictstackunderflow:
if (ref_stack_pop_block(&d_stack) >= 0) {
dict_set_top();
doref = *perror_object;
epref = &doref;
goto again;
}
break;
case gs_error_execstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_estack, which does a ref_stack_extend, */
/* so if we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref);
if (ccode < 0)
return ccode;
{
uint count = ref_stack_count(&e_stack);
uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM;
if (count > limit) {
/*
* If there is an e-stack mark within MIN_BLOCK_ESTACK of
* the new top, cut the stack back to remove the mark.
*/
int skip = count - limit;
int i;
for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) {
const ref *ep = ref_stack_index(&e_stack, i);
if (r_has_type_attrs(ep, t_null, a_executable)) {
skip = i + 1;
break;
}
}
pop_estack(i_ctx_p, skip);
}
}
*++osp = saref;
break;
case gs_error_stackoverflow:
if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */
/* it might be a procedure being pushed as a */
/* literal. We check for this case specially. */
doref = *perror_object;
if (r_is_proc(&doref)) {
*++osp = doref;
make_null_proc(&doref);
}
epref = &doref;
goto again;
}
ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref);
if (ccode < 0)
return ccode;
ref_stack_clear(&o_stack);
*++osp = saref;
break;
case gs_error_stackunderflow:
if (ref_stack_pop_block(&o_stack) >= 0) {
doref = *perror_object;
epref = &doref;
goto again;
}
break;
}
if (user_errors < 0)
return code;
if (gs_errorname(i_ctx_p, code, &error_name) < 0)
return code; /* out-of-range error code! */
/* We refer to gserrordict first, which is not accessible to Postcript jobs
* If we're running with SAFERERRORS all the handlers are copied to gserrordict
* so we'll always find the default one. If not SAFERERRORS, only gs specific
* errors are in gserrordict.
*/
if (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
(dict_find(perrordict, &error_name, &epref) <= 0 &&
(dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
dict_find(perrordict, &error_name, &epref) <= 0))
)
return code; /* error name not in errordict??? */
doref = *epref;
epref = &doref;
/* Push the error object on the operand stack if appropriate. */
if (!GS_ERROR_IS_INTERRUPT(code)) {
/* Replace the error object if within an oparray or .errorexec. */
osp++;
if (osp >= ostop) {
}
*osp = *perror_object;
}
*osp = *perror_object;
errorexec_find(i_ctx_p, osp);
/* If using SAFER, hand a name object to the error handler, rather than the executable
* object/operator itself.
*/
if (i_ctx_p->LockFilePermissions) {
code = obj_cvs(imemory, osp, buf + 2, 256, &rlen, (const byte **)&bufptr);
if (code < 0) {
const char *unknownstr = "--unknown--";
rlen = strlen(unknownstr);
memcpy(buf, unknownstr, rlen);
}
else {
buf[0] = buf[1] = buf[rlen + 2] = buf[rlen + 3] = '-';
rlen += 4;
}
code = name_ref(imemory, buf, rlen, osp, 1);
if (code < 0)
make_null(osp);
}
}
|
gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors,
int *pexit_code, ref * perror_object)
{
ref *epref = pref;
ref doref;
ref *perrordict;
ref error_name;
int code, ccode;
ref saref;
i_ctx_t *i_ctx_p = *pi_ctx_p;
int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal;
*pexit_code = 0;
*gc_signal = 0;
ialloc_reset_requested(idmemory);
again:
/* Avoid a dangling error object that might get traced by a future GC. */
make_null(perror_object);
o_stack.requested = e_stack.requested = d_stack.requested = 0;
while (*gc_signal) { /* Some routine below triggered a GC. */
gs_gc_root_t epref_root;
*gc_signal = 0;
/* Make sure that doref will get relocated properly if */
/* a garbage collection happens with epref == &doref. */
gs_register_ref_root(imemory_system, &epref_root,
(void **)&epref, "gs_call_interp(epref)");
code = interp_reclaim(pi_ctx_p, -1);
i_ctx_p = *pi_ctx_p;
gs_unregister_root(imemory_system, &epref_root,
"gs_call_interp(epref)");
if (code < 0)
return code;
}
code = interp(pi_ctx_p, epref, perror_object);
i_ctx_p = *pi_ctx_p;
if (!r_has_type(&i_ctx_p->error_object, t__invalid)) {
*perror_object = i_ctx_p->error_object;
make_t(&i_ctx_p->error_object, t__invalid);
}
/* Prevent a dangling reference to the GC signal in ticks_left */
/* in the frame of interp, but be prepared to do a GC if */
/* an allocation in this routine asks for it. */
*gc_signal = 0;
set_gc_signal(i_ctx_p, 1);
if (esp < esbot) /* popped guard entry */
esp = esbot;
switch (code) {
case gs_error_Fatal:
*pexit_code = 255;
return code;
case gs_error_Quit:
*perror_object = osp[-1];
*pexit_code = code = osp->value.intval;
osp -= 2;
return
(code == 0 ? gs_error_Quit :
code < 0 && code > -100 ? code : gs_error_Fatal);
case gs_error_InterpreterExit:
return 0;
case gs_error_ExecStackUnderflow:
/****** WRONG -- must keep mark blocks intact ******/
ref_stack_pop_block(&e_stack);
doref = *perror_object;
epref = &doref;
goto again;
case gs_error_VMreclaim:
/* Do the GC and continue. */
/* We ignore the return value here, if it fails here
* we'll call it again having jumped to the "again" label.
* Where, assuming it fails again, we'll handle the error.
*/
(void)interp_reclaim(pi_ctx_p,
(osp->value.intval == 2 ?
avm_global : avm_local));
i_ctx_p = *pi_ctx_p;
make_oper(&doref, 0, zpop);
epref = &doref;
goto again;
case gs_error_NeedInput:
case gs_error_interrupt:
return code;
}
/* Adjust osp in case of operand stack underflow */
if (osp < osbot - 1)
osp = osbot - 1;
/* We have to handle stack over/underflow specially, because */
/* we might be able to recover by adding or removing a block. */
switch (code) {
case gs_error_dictstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_dstack, which does a ref_stack_extend, */
/* so if` we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
/* Skip system dictionaries for CET 20-02-02 */
ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref);
if (ccode < 0)
return ccode;
ref_stack_pop_to(&d_stack, min_dstack_size);
dict_set_top();
*++osp = saref;
break;
case gs_error_dictstackunderflow:
if (ref_stack_pop_block(&d_stack) >= 0) {
dict_set_top();
doref = *perror_object;
epref = &doref;
goto again;
}
break;
case gs_error_execstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_estack, which does a ref_stack_extend, */
/* so if we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref);
if (ccode < 0)
return ccode;
{
uint count = ref_stack_count(&e_stack);
uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM;
if (count > limit) {
/*
* If there is an e-stack mark within MIN_BLOCK_ESTACK of
* the new top, cut the stack back to remove the mark.
*/
int skip = count - limit;
int i;
for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) {
const ref *ep = ref_stack_index(&e_stack, i);
if (r_has_type_attrs(ep, t_null, a_executable)) {
skip = i + 1;
break;
}
}
pop_estack(i_ctx_p, skip);
}
}
*++osp = saref;
break;
case gs_error_stackoverflow:
if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */
/* it might be a procedure being pushed as a */
/* literal. We check for this case specially. */
doref = *perror_object;
if (r_is_proc(&doref)) {
*++osp = doref;
make_null_proc(&doref);
}
epref = &doref;
goto again;
}
ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref);
if (ccode < 0)
return ccode;
ref_stack_clear(&o_stack);
*++osp = saref;
break;
case gs_error_stackunderflow:
if (ref_stack_pop_block(&o_stack) >= 0) {
doref = *perror_object;
epref = &doref;
goto again;
}
break;
}
if (user_errors < 0)
return code;
if (gs_errorname(i_ctx_p, code, &error_name) < 0)
return code; /* out-of-range error code! */
/* We refer to gserrordict first, which is not accessible to Postcript jobs
* If we're running with SAFERERRORS all the handlers are copied to gserrordict
* so we'll always find the default one. If not SAFERERRORS, only gs specific
* errors are in gserrordict.
*/
if (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
(dict_find(perrordict, &error_name, &epref) <= 0 &&
(dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
dict_find(perrordict, &error_name, &epref) <= 0))
)
return code; /* error name not in errordict??? */
doref = *epref;
epref = &doref;
/* Push the error object on the operand stack if appropriate. */
if (!GS_ERROR_IS_INTERRUPT(code)) {
byte buf[260], *bufptr;
uint rlen;
/* Replace the error object if within an oparray or .errorexec. */
osp++;
if (osp >= ostop) {
}
*osp = *perror_object;
}
*osp = *perror_object;
errorexec_find(i_ctx_p, osp);
if (!r_has_type(osp, t_string) && !r_has_type(osp, t_name)) {
code = obj_cvs(imemory, osp, buf + 2, 256, &rlen, (const byte **)&bufptr);
if (code < 0) {
const char *unknownstr = "--unknown--";
rlen = strlen(unknownstr);
memcpy(buf, unknownstr, rlen);
bufptr = buf;
}
else {
ref *tobj;
bufptr[rlen] = '\0';
/* Only pass a name object if the operator doesn't exist in systemdict
* i.e. it's an internal operator we have hidden
*/
code = dict_find_string(systemdict, (const char *)bufptr, &tobj);
if (code < 0) {
buf[0] = buf[1] = buf[rlen + 2] = buf[rlen + 3] = '-';
rlen += 4;
bufptr = buf;
}
else {
bufptr = NULL;
}
}
if (bufptr) {
code = name_ref(imemory, buf, rlen, osp, 1);
if (code < 0)
make_null(osp);
}
}
}
|
CVE-2018-17961
|
Artifex Ghostscript 9.25 and earlier allows attackers to bypass a sandbox protection mechanism via vectors involving errorhandler setup. NOTE: this issue exists because of an incomplete fix for CVE-2018-17183.
|
[
"CWE-209"
] |
[
{
"line_no": 207,
"text": " /* If using SAFER, hand a name object to the error handler, rather than the executable",
"char_start": null,
"char_end": null
},
{
"line_no": 208,
"text": " * object/operator itself.",
"char_start": null,
"char_end": null
},
{
"line_no": 209,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 210,
"text": " if (i_ctx_p->LockFilePermissions) {",
"char_start": null,
"char_end": null
},
{
"line_no": 218,
"text": " buf[0] = buf[1] = buf[rlen + 2] = buf[rlen + 3] = '-';",
"char_start": null,
"char_end": null
},
{
"line_no": 219,
"text": " rlen += 4;",
"char_start": null,
"char_end": null
},
{
"line_no": 221,
"text": " code = name_ref(imemory, buf, rlen, osp, 1);",
"char_start": null,
"char_end": null
},
{
"line_no": 222,
"text": " if (code < 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 223,
"text": " make_null(osp);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 199,
"text": " byte buf[260], *bufptr;",
"char_start": null,
"char_end": null
},
{
"line_no": 200,
"text": " uint rlen;",
"char_start": null,
"char_end": null
},
{
"line_no": 209,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 210,
"text": " if (!r_has_type(osp, t_string) && !r_has_type(osp, t_name)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 216,
"text": " bufptr = buf;",
"char_start": null,
"char_end": null
},
{
"line_no": 219,
"text": " ref *tobj;",
"char_start": null,
"char_end": null
},
{
"line_no": 220,
"text": " bufptr[rlen] = '\\0';",
"char_start": null,
"char_end": null
},
{
"line_no": 221,
"text": " /* Only pass a name object if the operator doesn't exist in systemdict",
"char_start": null,
"char_end": null
},
{
"line_no": 222,
"text": " * i.e. it's an internal operator we have hidden",
"char_start": null,
"char_end": null
},
{
"line_no": 223,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 224,
"text": " code = dict_find_string(systemdict, (const char *)bufptr, &tobj);",
"char_start": null,
"char_end": null
},
{
"line_no": 225,
"text": " if (code < 0) {",
"char_start": null,
"char_end": null
},
{
"line_no": 226,
"text": " buf[0] = buf[1] = buf[rlen + 2] = buf[rlen + 3] = '-';",
"char_start": null,
"char_end": null
},
{
"line_no": 227,
"text": " rlen += 4;",
"char_start": null,
"char_end": null
},
{
"line_no": 228,
"text": " bufptr = buf;",
"char_start": null,
"char_end": null
},
{
"line_no": 229,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 230,
"text": " else {",
"char_start": null,
"char_end": null
},
{
"line_no": 231,
"text": " bufptr = NULL;",
"char_start": null,
"char_end": null
},
{
"line_no": 232,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 233,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 234,
"text": " if (bufptr) {",
"char_start": null,
"char_end": null
},
{
"line_no": 235,
"text": " code = name_ref(imemory, buf, rlen, osp, 1);",
"char_start": null,
"char_end": null
},
{
"line_no": 236,
"text": " if (code < 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 237,
"text": " make_null(osp);",
"char_start": null,
"char_end": null
}
] | 81
|
primevul
|
primevul_samba_4278ef25f64d5fdbf432ff1534e275416ec9561e
|
4278ef25f64d5fdbf432ff1534e275416ec9561e
|
samba
|
https://github.com/samba-team/samba
|
NTSTATUS check_reduced_name_with_privilege(connection_struct *conn,
const char *fname,
struct smb_request *smbreq)
{
NTSTATUS status;
TALLOC_CTX *ctx = talloc_tos();
const char *conn_rootdir;
size_t rootdir_len;
char *dir_name = NULL;
const char *last_component = NULL;
char *resolved_name = NULL;
char *saved_dir = NULL;
struct smb_filename *smb_fname_cwd = NULL;
struct privilege_paths *priv_paths = NULL;
int ret;
DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n",
fname,
priv_paths = talloc_zero(smbreq, struct privilege_paths);
if (!priv_paths) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (!parent_dirname(ctx, fname, &dir_name, &last_component)) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name);
priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component);
if (priv_paths->parent_name.base_name == NULL ||
priv_paths->file_name.base_name == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Remember where we were. */
saved_dir = vfs_GetWd(ctx, conn);
if (!saved_dir) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Go to the parent directory to lock in memory. */
if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Get the absolute path of the parent directory. */
resolved_name = SMB_VFS_REALPATH(conn,".");
if (!resolved_name) {
status = map_nt_error_from_unix(errno);
goto err;
}
if (*resolved_name != '/') {
DEBUG(0,("check_reduced_name_with_privilege: realpath "
"doesn't return absolute paths !\n"));
status = NT_STATUS_OBJECT_NAME_INVALID;
goto err;
}
DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n",
priv_paths->parent_name.base_name,
resolved_name));
/* Now check the stat value is the same. */
smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL);
if (smb_fname_cwd == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Ensure we're pointing at the same place. */
if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) {
DEBUG(0,("check_reduced_name_with_privilege: "
"device/inode/uid/gid on directory %s changed. "
"Denying access !\n",
priv_paths->parent_name.base_name));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
/* Ensure we're below the connect path. */
conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
if (conn_rootdir == NULL) {
DEBUG(2, ("check_reduced_name_with_privilege: Could not get "
"conn_rootdir\n"));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
}
|
NTSTATUS check_reduced_name_with_privilege(connection_struct *conn,
const char *fname,
struct smb_request *smbreq)
{
NTSTATUS status;
TALLOC_CTX *ctx = talloc_tos();
const char *conn_rootdir;
size_t rootdir_len;
char *dir_name = NULL;
const char *last_component = NULL;
char *resolved_name = NULL;
char *saved_dir = NULL;
struct smb_filename *smb_fname_cwd = NULL;
struct privilege_paths *priv_paths = NULL;
int ret;
bool matched;
DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n",
fname,
priv_paths = talloc_zero(smbreq, struct privilege_paths);
if (!priv_paths) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (!parent_dirname(ctx, fname, &dir_name, &last_component)) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name);
priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component);
if (priv_paths->parent_name.base_name == NULL ||
priv_paths->file_name.base_name == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Remember where we were. */
saved_dir = vfs_GetWd(ctx, conn);
if (!saved_dir) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Go to the parent directory to lock in memory. */
if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Get the absolute path of the parent directory. */
resolved_name = SMB_VFS_REALPATH(conn,".");
if (!resolved_name) {
status = map_nt_error_from_unix(errno);
goto err;
}
if (*resolved_name != '/') {
DEBUG(0,("check_reduced_name_with_privilege: realpath "
"doesn't return absolute paths !\n"));
status = NT_STATUS_OBJECT_NAME_INVALID;
goto err;
}
DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n",
priv_paths->parent_name.base_name,
resolved_name));
/* Now check the stat value is the same. */
smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL);
if (smb_fname_cwd == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Ensure we're pointing at the same place. */
if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) {
DEBUG(0,("check_reduced_name_with_privilege: "
"device/inode/uid/gid on directory %s changed. "
"Denying access !\n",
priv_paths->parent_name.base_name));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
/* Ensure we're below the connect path. */
conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
if (conn_rootdir == NULL) {
DEBUG(2, ("check_reduced_name_with_privilege: Could not get "
"conn_rootdir\n"));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
}
|
CVE-2015-5252
|
vfs.c in smbd in Samba 3.x and 4.x before 4.1.22, 4.2.x before 4.2.7, and 4.3.x before 4.3.3, when share names with certain substring relationships exist, allows remote attackers to bypass intended file-access restrictions via a symlink that points outside of a share.
|
[
"CWE-264"
] |
[] |
[
{
"line_no": 16,
"text": " bool matched;",
"char_start": null,
"char_end": null
}
] | 82
|
primevul
|
primevul_savannah_dce4683cbbe107a95f1f0d45fabc304acfb5d71a
|
dce4683cbbe107a95f1f0d45fabc304acfb5d71a
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
plan_a (char const *filename)
{
char const *s;
char const *lim;
char const **ptr;
char *buffer;
lin iline;
size_t size = instat.st_size;
/* Fail if the file size doesn't fit in a size_t,
or if storage isn't available. */
if (! (size == instat.st_size
&& (buffer = malloc (size ? size : (size_t) 1))))
return false;
/* Read the input file, but don't bother reading it if it's empty.
When creating files, the files do not actually exist. */
if (size)
{
if (S_ISREG (instat.st_mode))
{
int ifd = safe_open (filename, O_RDONLY|binary_transput, 0);
size_t buffered = 0, n;
if (ifd < 0)
pfatal ("can't open file %s", quotearg (filename));
/* Some non-POSIX hosts exaggerate st_size in text mode;
or the file may have shrunk! */
size = buffered;
break;
}
if (n == (size_t) -1)
{
/* Perhaps size is too large for this host. */
close (ifd);
free (buffer);
return false;
}
buffered += n;
}
if (close (ifd) != 0)
read_fatal ();
}
|
plan_a (char const *filename)
{
char const *s;
char const *lim;
char const **ptr;
char *buffer;
lin iline;
size_t size = instat.st_size;
/* Fail if the file size doesn't fit in a size_t,
or if storage isn't available. */
if (! (size == instat.st_size
&& (buffer = malloc (size ? size : (size_t) 1))))
return false;
/* Read the input file, but don't bother reading it if it's empty.
When creating files, the files do not actually exist. */
if (size)
{
if (S_ISREG (instat.st_mode))
{
int flags = O_RDONLY | binary_transput;
size_t buffered = 0, n;
int ifd;
if (! follow_symlinks)
flags |= O_NOFOLLOW;
ifd = safe_open (filename, flags, 0);
if (ifd < 0)
pfatal ("can't open file %s", quotearg (filename));
/* Some non-POSIX hosts exaggerate st_size in text mode;
or the file may have shrunk! */
size = buffered;
break;
}
if (n == (size_t) -1)
{
/* Perhaps size is too large for this host. */
close (ifd);
free (buffer);
return false;
}
buffered += n;
}
if (close (ifd) != 0)
read_fatal ();
}
|
CVE-2019-13636
|
In GNU patch through 2.7.6, the following of symlinks is mishandled in certain cases other than input files. This affects inp.c and util.c.
|
[
"CWE-59"
] |
[
{
"line_no": 22,
"text": "\t int ifd = safe_open (filename, O_RDONLY|binary_transput, 0);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 22,
"text": "\t int flags = O_RDONLY | binary_transput;",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": "\t int ifd;",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": "\t if (! follow_symlinks)",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": "\t flags |= O_NOFOLLOW;",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": "\t ifd = safe_open (filename, flags, 0);",
"char_start": null,
"char_end": null
}
] | 83
|
primevul
|
primevul_dbus_c3223ba6c401ba81df1305851312a47c485e6cd7
|
c3223ba6c401ba81df1305851312a47c485e6cd7
|
dbus
|
http://gitweb.freedesktop.org/?p=dbus/dbus
|
_dbus_header_byteswap (DBusHeader *header,
int new_order)
{
if (header->byte_order == new_order)
return;
_dbus_marshal_byteswap (&_dbus_header_signature_str,
0, header->byte_order,
new_order,
&header->data, 0);
header->byte_order = new_order;
}
|
_dbus_header_byteswap (DBusHeader *header,
int new_order)
{
unsigned char byte_order;
if (header->byte_order == new_order)
return;
byte_order = _dbus_string_get_byte (&header->data, BYTE_ORDER_OFFSET);
_dbus_assert (header->byte_order == byte_order);
_dbus_marshal_byteswap (&_dbus_header_signature_str,
0, header->byte_order,
new_order,
&header->data, 0);
_dbus_string_set_byte (&header->data, BYTE_ORDER_OFFSET, new_order);
header->byte_order = new_order;
}
|
CVE-2011-2200
|
The _dbus_header_byteswap function in dbus-marshal-header.c in D-Bus (aka DBus) 1.2.x before 1.2.28, 1.4.x before 1.4.12, and 1.5.x before 1.5.4 does not properly handle a non-native byte order, which allows local users to cause a denial of service (connection loss), obtain potentially sensitive information, or conduct unspecified state-modification attacks via crafted messages.
|
[
"CWE-20"
] |
[] |
[
{
"line_no": 4,
"text": " unsigned char byte_order;",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " byte_order = _dbus_string_get_byte (&header->data, BYTE_ORDER_OFFSET);",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " _dbus_assert (header->byte_order == byte_order);",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": " _dbus_string_set_byte (&header->data, BYTE_ORDER_OFFSET, new_order);",
"char_start": null,
"char_end": null
}
] | 84
|
primevul
|
primevul_ghostscript_79cccf641486a6595c43f1de1cd7ade696020a31
|
79cccf641486a6595c43f1de1cd7ade696020a31
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
gs_nulldevice(gs_gstate * pgs)
{
int code = 0;
if (pgs->device == 0 || !gx_device_is_null(pgs->device)) {
gx_device *ndev;
code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device,
pgs->memory);
if (code < 0)
return code;
/*
* Internal devices have a reference count of 0, not 1,
* aside from references from graphics states.
to sort out how the icc profile is best handled with this device.
It seems to inherit properties from the current device if there
is one */
rc_init(ndev, pgs->memory, 0);
if (pgs->device != NULL) {
if ((code = dev_proc(pgs->device, get_profile)(pgs->device,
&(ndev->icc_struct))) < 0)
return code;
rc_increment(ndev->icc_struct);
set_dev_proc(ndev, get_profile, gx_default_get_profile);
}
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
gs_free_object(pgs->memory, ndev, "gs_copydevice(device)");
}
return code;
}
|
gs_nulldevice(gs_gstate * pgs)
{
int code = 0;
bool saveLockSafety = false;
if (pgs->device == 0 || !gx_device_is_null(pgs->device)) {
gx_device *ndev;
code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device,
pgs->memory);
if (code < 0)
return code;
if (gs_currentdevice_inline(pgs) != NULL)
saveLockSafety = gs_currentdevice_inline(pgs)->LockSafetyParams;
/*
* Internal devices have a reference count of 0, not 1,
* aside from references from graphics states.
to sort out how the icc profile is best handled with this device.
It seems to inherit properties from the current device if there
is one */
rc_init(ndev, pgs->memory, 0);
if (pgs->device != NULL) {
if ((code = dev_proc(pgs->device, get_profile)(pgs->device,
&(ndev->icc_struct))) < 0)
return code;
rc_increment(ndev->icc_struct);
set_dev_proc(ndev, get_profile, gx_default_get_profile);
}
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
gs_free_object(pgs->memory, ndev, "gs_copydevice(device)");
gs_currentdevice_inline(pgs)->LockSafetyParams = saveLockSafety;
}
return code;
}
|
CVE-2018-16863
|
It was found that RHSA-2018:2918 did not fully fix CVE-2018-16509. An attacker could possibly exploit another variant of the flaw and bypass the -dSAFER protection to, for example, execute arbitrary shell commands via a specially crafted PostScript document. This only affects ghostscript 9.07 as shipped with Red Hat Enterprise Linux 7.
|
[
"CWE-78"
] |
[] |
[
{
"line_no": 4,
"text": " bool saveLockSafety = false;",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " if (gs_currentdevice_inline(pgs) != NULL)",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " saveLockSafety = gs_currentdevice_inline(pgs)->LockSafetyParams;",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " gs_currentdevice_inline(pgs)->LockSafetyParams = saveLockSafety;",
"char_start": null,
"char_end": null
}
] | 85
|
primevul
|
primevul_ghostscript_5516c614dc33662a2afdc377159f70218e67bde5
|
5516c614dc33662a2afdc377159f70218e67bde5
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
zrestore(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
alloc_save_t *asave;
bool last;
vm_save_t *vmsave;
int code = restore_check_operand(op, &asave, idmemory);
if (code < 0)
return code;
if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n",
(ulong) alloc_save_client_data(asave),
(ulong) op->value.saveid);
if (I_VALIDATE_BEFORE_RESTORE)
ivalidate_clean_spaces(i_ctx_p);
ivalidate_clean_spaces(i_ctx_p);
/* Check the contents of the stacks. */
{
int code;
if ((code = restore_check_stack(i_ctx_p, &o_stack, asave, false)) < 0 ||
(code = restore_check_stack(i_ctx_p, &e_stack, asave, true)) < 0 ||
(code = restore_check_stack(i_ctx_p, &d_stack, asave, false)) < 0
) {
osp++;
return code;
}
}
/* Reset l_new in all stack entries if the new save level is zero. */
/* Also do some special fixing on the e-stack. */
restore_fix_stack(i_ctx_p, &o_stack, asave, false);
}
|
zrestore(i_ctx_t *i_ctx_p)
restore_check_save(i_ctx_t *i_ctx_p, alloc_save_t **asave)
{
os_ptr op = osp;
int code = restore_check_operand(op, asave, idmemory);
if (code < 0)
return code;
if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n",
(ulong) alloc_save_client_data(*asave),
(ulong) op->value.saveid);
if (I_VALIDATE_BEFORE_RESTORE)
ivalidate_clean_spaces(i_ctx_p);
ivalidate_clean_spaces(i_ctx_p);
/* Check the contents of the stacks. */
{
int code;
if ((code = restore_check_stack(i_ctx_p, &o_stack, *asave, false)) < 0 ||
(code = restore_check_stack(i_ctx_p, &e_stack, *asave, true)) < 0 ||
(code = restore_check_stack(i_ctx_p, &d_stack, *asave, false)) < 0
) {
osp++;
return code;
}
}
osp++;
return 0;
}
/* the semantics of restore differ slightly between Level 1 and
Level 2 and later - the latter includes restoring the device
state (whilst Level 1 didn't have "page devices" as such).
Hence we have two restore operators - one here (Level 1)
and one in zdevice2.c (Level 2+). For that reason, the
operand checking and guts of the restore operation are
separated so both implementations can use them to best
effect.
*/
int
dorestore(i_ctx_t *i_ctx_p, alloc_save_t *asave)
{
os_ptr op = osp;
bool last;
vm_save_t *vmsave;
int code;
osp--;
/* Reset l_new in all stack entries if the new save level is zero. */
/* Also do some special fixing on the e-stack. */
restore_fix_stack(i_ctx_p, &o_stack, asave, false);
}
|
CVE-2018-16863
|
It was found that RHSA-2018:2918 did not fully fix CVE-2018-16509. An attacker could possibly exploit another variant of the flaw and bypass the -dSAFER protection to, for example, execute arbitrary shell commands via a specially crafted PostScript document. This only affects ghostscript 9.07 as shipped with Red Hat Enterprise Linux 7.
|
[
"CWE-78"
] |
[
{
"line_no": 4,
"text": " alloc_save_t *asave;",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": " bool last;",
"char_start": null,
"char_end": null
},
{
"line_no": 6,
"text": " vm_save_t *vmsave;",
"char_start": null,
"char_end": null
},
{
"line_no": 7,
"text": " int code = restore_check_operand(op, &asave, idmemory);",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " (ulong) alloc_save_client_data(asave),",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " if ((code = restore_check_stack(i_ctx_p, &o_stack, asave, false)) < 0 ||",
"char_start": null,
"char_end": null
},
{
"line_no": 22,
"text": " (code = restore_check_stack(i_ctx_p, &e_stack, asave, true)) < 0 ||",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " (code = restore_check_stack(i_ctx_p, &d_stack, asave, false)) < 0",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 2,
"text": "restore_check_save(i_ctx_t *i_ctx_p, alloc_save_t **asave)",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": " int code = restore_check_operand(op, asave, idmemory);",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " (ulong) alloc_save_client_data(*asave),",
"char_start": null,
"char_end": null
},
{
"line_no": 19,
"text": " if ((code = restore_check_stack(i_ctx_p, &o_stack, *asave, false)) < 0 ||",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": " (code = restore_check_stack(i_ctx_p, &e_stack, *asave, true)) < 0 ||",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " (code = restore_check_stack(i_ctx_p, &d_stack, *asave, false)) < 0",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " osp++;",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " return 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": "}",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": "/* the semantics of restore differ slightly between Level 1 and",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " Level 2 and later - the latter includes restoring the device",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " state (whilst Level 1 didn't have \"page devices\" as such).",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " Hence we have two restore operators - one here (Level 1)",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " and one in zdevice2.c (Level 2+). For that reason, the",
"char_start": null,
"char_end": null
},
{
"line_no": 36,
"text": " operand checking and guts of the restore operation are",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": " separated so both implementations can use them to best",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " effect.",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": "int",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": "dorestore(i_ctx_t *i_ctx_p, alloc_save_t *asave)",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": "{",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": " os_ptr op = osp;",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " bool last;",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": " vm_save_t *vmsave;",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " int code;",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": " osp--;",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": "",
"char_start": null,
"char_end": null
}
] | 86
|
primevul
|
primevul_NetworkManager_78ce088843d59d4494965bfc40b30a2e63d065f6
|
78ce088843d59d4494965bfc40b30a2e63d065f6
|
NetworkManager
|
https://gitlab.freedesktop.org/NetworkManager/NetworkManager
|
destroy_one_secret (gpointer data)
{
char *secret = (char *) data;
/* Don't leave the secret lying around in memory */
g_message ("%s: destroying %s", __func__, secret);
memset (secret, 0, strlen (secret));
g_free (secret);
}
|
destroy_one_secret (gpointer data)
{
char *secret = (char *) data;
/* Don't leave the secret lying around in memory */
memset (secret, 0, strlen (secret));
g_free (secret);
}
|
CVE-2011-1943
|
The destroy_one_secret function in nm-setting-vpn.c in libnm-util in the NetworkManager package 0.8.999-3.git20110526 in Fedora 15 creates a log entry containing a certificate password, which allows local users to obtain sensitive information by reading a log file.
|
[
"CWE-200"
] |
[
{
"line_no": 6,
"text": "g_message (\"%s: destroying %s\", __func__, secret);",
"char_start": null,
"char_end": null
}
] |
[] | 87
|
primevul
|
primevul_libxfont_d1e670a4a8704b8708e493ab6155589bcd570608
|
d1e670a4a8704b8708e493ab6155589bcd570608
|
libxfont
|
https://cgit.freedesktop.org/xorg/lib/libXfont/commit/?id=d11ee5886e9d9ec610051a206b135a4cdc1e09a0
|
PatternMatch(char *pat, int patdashes, char *string, int stringdashes)
{
char c,
t;
if (stringdashes < patdashes)
return 0;
for (;;) {
switch (c = *pat++) {
case '*':
if (!(c = *pat++))
return 1;
if (c == XK_minus) {
patdashes--;
for (;;) {
while ((t = *string++) != XK_minus)
if (!t)
return 0;
stringdashes--;
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
if (stringdashes == patdashes)
return 0;
}
} else {
for (;;) {
while ((t = *string++) != c) {
if (!t)
return 0;
if (t == XK_minus) {
if (stringdashes-- < patdashes)
return 0;
}
}
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
}
}
case '?':
if (*string++ == XK_minus)
stringdashes--;
break;
case '\0':
return (*string == '\0');
patdashes--;
stringdashes--;
break;
}
return 0;
default:
if (c == *string++)
break;
return 0;
}
}
|
PatternMatch(char *pat, int patdashes, char *string, int stringdashes)
{
char c,
t;
if (stringdashes < patdashes)
return 0;
for (;;) {
switch (c = *pat++) {
case '*':
if (!(c = *pat++))
return 1;
if (c == XK_minus) {
patdashes--;
for (;;) {
while ((t = *string++) != XK_minus)
if (!t)
return 0;
stringdashes--;
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
if (stringdashes == patdashes)
return 0;
}
} else {
for (;;) {
while ((t = *string++) != c) {
if (!t)
return 0;
if (t == XK_minus) {
if (stringdashes-- < patdashes)
return 0;
}
}
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
}
}
case '?':
if ((t = *string++) == XK_minus)
stringdashes--;
if (!t)
return 0;
break;
case '\0':
return (*string == '\0');
patdashes--;
stringdashes--;
break;
}
return 0;
default:
if (c == *string++)
break;
return 0;
}
}
|
CVE-2017-13720
|
In the PatternMatch function in fontfile/fontdir.c in libXfont through 1.5.2 and 2.x before 2.0.2, an attacker with access to an X connection can cause a buffer over-read during pattern matching of fonts, leading to information disclosure or a crash (denial of service). This occurs because '\0' characters are incorrectly skipped in situations involving ? characters.
|
[
"CWE-125"
] |
[
{
"line_no": 40,
"text": "\t if (*string++ == XK_minus)",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 40,
"text": "\t if ((t = *string++) == XK_minus)",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": "\t if (!t)",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": "\t\treturn 0;",
"char_start": null,
"char_end": null
}
] | 90
|
primevul
|
primevul_ghostscript_b575e1ec42cc86f6a58c603f2a88fcc2af699cc8
|
b575e1ec42cc86f6a58c603f2a88fcc2af699cc8
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors,
int *pexit_code, ref * perror_object)
{
ref *epref = pref;
ref doref;
ref *perrordict;
ref error_name;
int code, ccode;
ref saref;
i_ctx_t *i_ctx_p = *pi_ctx_p;
int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal;
*pexit_code = 0;
*gc_signal = 0;
ialloc_reset_requested(idmemory);
again:
/* Avoid a dangling error object that might get traced by a future GC. */
make_null(perror_object);
o_stack.requested = e_stack.requested = d_stack.requested = 0;
while (*gc_signal) { /* Some routine below triggered a GC. */
gs_gc_root_t epref_root;
*gc_signal = 0;
/* Make sure that doref will get relocated properly if */
/* a garbage collection happens with epref == &doref. */
gs_register_ref_root(imemory_system, &epref_root,
(void **)&epref, "gs_call_interp(epref)");
code = interp_reclaim(pi_ctx_p, -1);
i_ctx_p = *pi_ctx_p;
gs_unregister_root(imemory_system, &epref_root,
"gs_call_interp(epref)");
if (code < 0)
return code;
}
code = interp(pi_ctx_p, epref, perror_object);
i_ctx_p = *pi_ctx_p;
if (!r_has_type(&i_ctx_p->error_object, t__invalid)) {
*perror_object = i_ctx_p->error_object;
make_t(&i_ctx_p->error_object, t__invalid);
}
/* Prevent a dangling reference to the GC signal in ticks_left */
/* in the frame of interp, but be prepared to do a GC if */
/* an allocation in this routine asks for it. */
*gc_signal = 0;
set_gc_signal(i_ctx_p, 1);
if (esp < esbot) /* popped guard entry */
esp = esbot;
switch (code) {
case gs_error_Fatal:
*pexit_code = 255;
return code;
case gs_error_Quit:
*perror_object = osp[-1];
*pexit_code = code = osp->value.intval;
osp -= 2;
return
(code == 0 ? gs_error_Quit :
code < 0 && code > -100 ? code : gs_error_Fatal);
case gs_error_InterpreterExit:
return 0;
case gs_error_ExecStackUnderflow:
/****** WRONG -- must keep mark blocks intact ******/
ref_stack_pop_block(&e_stack);
doref = *perror_object;
epref = &doref;
goto again;
case gs_error_VMreclaim:
/* Do the GC and continue. */
/* We ignore the return value here, if it fails here
* we'll call it again having jumped to the "again" label.
* Where, assuming it fails again, we'll handle the error.
*/
(void)interp_reclaim(pi_ctx_p,
(osp->value.intval == 2 ?
avm_global : avm_local));
i_ctx_p = *pi_ctx_p;
make_oper(&doref, 0, zpop);
epref = &doref;
goto again;
case gs_error_NeedInput:
case gs_error_interrupt:
return code;
}
/* Adjust osp in case of operand stack underflow */
if (osp < osbot - 1)
osp = osbot - 1;
/* We have to handle stack over/underflow specially, because */
/* we might be able to recover by adding or removing a block. */
switch (code) {
case gs_error_dictstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_dstack, which does a ref_stack_extend, */
/* so if` we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
/* Skip system dictionaries for CET 20-02-02 */
ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref);
if (ccode < 0)
return ccode;
ref_stack_pop_to(&d_stack, min_dstack_size);
dict_set_top();
*++osp = saref;
break;
case gs_error_dictstackunderflow:
if (ref_stack_pop_block(&d_stack) >= 0) {
dict_set_top();
doref = *perror_object;
epref = &doref;
goto again;
}
break;
case gs_error_execstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_estack, which does a ref_stack_extend, */
/* so if we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref);
if (ccode < 0)
return ccode;
{
uint count = ref_stack_count(&e_stack);
uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM;
if (count > limit) {
/*
* If there is an e-stack mark within MIN_BLOCK_ESTACK of
* the new top, cut the stack back to remove the mark.
*/
int skip = count - limit;
int i;
for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) {
const ref *ep = ref_stack_index(&e_stack, i);
if (r_has_type_attrs(ep, t_null, a_executable)) {
skip = i + 1;
break;
}
}
pop_estack(i_ctx_p, skip);
}
}
*++osp = saref;
break;
case gs_error_stackoverflow:
if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */
/* it might be a procedure being pushed as a */
/* literal. We check for this case specially. */
doref = *perror_object;
if (r_is_proc(&doref)) {
*++osp = doref;
make_null_proc(&doref);
}
epref = &doref;
goto again;
}
ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref);
if (ccode < 0)
return ccode;
ref_stack_clear(&o_stack);
*++osp = saref;
break;
case gs_error_stackunderflow:
if (ref_stack_pop_block(&o_stack) >= 0) {
doref = *perror_object;
epref = &doref;
goto again;
}
break;
}
if (user_errors < 0)
return code;
if (gs_errorname(i_ctx_p, code, &error_name) < 0)
return code; /* out-of-range error code! */
/*
* For greater Adobe compatibility, only the standard PostScript errors
* are defined in errordict; the rest are in gserrordict.
*/
if (dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
(dict_find(perrordict, &error_name, &epref) <= 0 &&
(dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
dict_find(perrordict, &error_name, &epref) <= 0))
)
return code; /* error name not in errordict??? */
doref = *epref;
epref = &doref;
/* Push the error object on the operand stack if appropriate. */
if (!GS_ERROR_IS_INTERRUPT(code)) {
/* Replace the error object if within an oparray or .errorexec. */
*++osp = *perror_object;
errorexec_find(i_ctx_p, osp);
}
goto again;
}
|
gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors,
int *pexit_code, ref * perror_object)
{
ref *epref = pref;
ref doref;
ref *perrordict;
ref error_name;
int code, ccode;
ref saref;
i_ctx_t *i_ctx_p = *pi_ctx_p;
int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal;
*pexit_code = 0;
*gc_signal = 0;
ialloc_reset_requested(idmemory);
again:
/* Avoid a dangling error object that might get traced by a future GC. */
make_null(perror_object);
o_stack.requested = e_stack.requested = d_stack.requested = 0;
while (*gc_signal) { /* Some routine below triggered a GC. */
gs_gc_root_t epref_root;
*gc_signal = 0;
/* Make sure that doref will get relocated properly if */
/* a garbage collection happens with epref == &doref. */
gs_register_ref_root(imemory_system, &epref_root,
(void **)&epref, "gs_call_interp(epref)");
code = interp_reclaim(pi_ctx_p, -1);
i_ctx_p = *pi_ctx_p;
gs_unregister_root(imemory_system, &epref_root,
"gs_call_interp(epref)");
if (code < 0)
return code;
}
code = interp(pi_ctx_p, epref, perror_object);
i_ctx_p = *pi_ctx_p;
if (!r_has_type(&i_ctx_p->error_object, t__invalid)) {
*perror_object = i_ctx_p->error_object;
make_t(&i_ctx_p->error_object, t__invalid);
}
/* Prevent a dangling reference to the GC signal in ticks_left */
/* in the frame of interp, but be prepared to do a GC if */
/* an allocation in this routine asks for it. */
*gc_signal = 0;
set_gc_signal(i_ctx_p, 1);
if (esp < esbot) /* popped guard entry */
esp = esbot;
switch (code) {
case gs_error_Fatal:
*pexit_code = 255;
return code;
case gs_error_Quit:
*perror_object = osp[-1];
*pexit_code = code = osp->value.intval;
osp -= 2;
return
(code == 0 ? gs_error_Quit :
code < 0 && code > -100 ? code : gs_error_Fatal);
case gs_error_InterpreterExit:
return 0;
case gs_error_ExecStackUnderflow:
/****** WRONG -- must keep mark blocks intact ******/
ref_stack_pop_block(&e_stack);
doref = *perror_object;
epref = &doref;
goto again;
case gs_error_VMreclaim:
/* Do the GC and continue. */
/* We ignore the return value here, if it fails here
* we'll call it again having jumped to the "again" label.
* Where, assuming it fails again, we'll handle the error.
*/
(void)interp_reclaim(pi_ctx_p,
(osp->value.intval == 2 ?
avm_global : avm_local));
i_ctx_p = *pi_ctx_p;
make_oper(&doref, 0, zpop);
epref = &doref;
goto again;
case gs_error_NeedInput:
case gs_error_interrupt:
return code;
}
/* Adjust osp in case of operand stack underflow */
if (osp < osbot - 1)
osp = osbot - 1;
/* We have to handle stack over/underflow specially, because */
/* we might be able to recover by adding or removing a block. */
switch (code) {
case gs_error_dictstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_dstack, which does a ref_stack_extend, */
/* so if` we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
/* Skip system dictionaries for CET 20-02-02 */
ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref);
if (ccode < 0)
return ccode;
ref_stack_pop_to(&d_stack, min_dstack_size);
dict_set_top();
*++osp = saref;
break;
case gs_error_dictstackunderflow:
if (ref_stack_pop_block(&d_stack) >= 0) {
dict_set_top();
doref = *perror_object;
epref = &doref;
goto again;
}
break;
case gs_error_execstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_estack, which does a ref_stack_extend, */
/* so if we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref);
if (ccode < 0)
return ccode;
{
uint count = ref_stack_count(&e_stack);
uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM;
if (count > limit) {
/*
* If there is an e-stack mark within MIN_BLOCK_ESTACK of
* the new top, cut the stack back to remove the mark.
*/
int skip = count - limit;
int i;
for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) {
const ref *ep = ref_stack_index(&e_stack, i);
if (r_has_type_attrs(ep, t_null, a_executable)) {
skip = i + 1;
break;
}
}
pop_estack(i_ctx_p, skip);
}
}
*++osp = saref;
break;
case gs_error_stackoverflow:
if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */
/* it might be a procedure being pushed as a */
/* literal. We check for this case specially. */
doref = *perror_object;
if (r_is_proc(&doref)) {
*++osp = doref;
make_null_proc(&doref);
}
epref = &doref;
goto again;
}
ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref);
if (ccode < 0)
return ccode;
ref_stack_clear(&o_stack);
*++osp = saref;
break;
case gs_error_stackunderflow:
if (ref_stack_pop_block(&o_stack) >= 0) {
doref = *perror_object;
epref = &doref;
goto again;
}
break;
}
if (user_errors < 0)
return code;
if (gs_errorname(i_ctx_p, code, &error_name) < 0)
return code; /* out-of-range error code! */
/*
* For greater Adobe compatibility, only the standard PostScript errors
* are defined in errordict; the rest are in gserrordict.
*/
if (dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
(dict_find(perrordict, &error_name, &epref) <= 0 &&
(dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
dict_find(perrordict, &error_name, &epref) <= 0))
)
return code; /* error name not in errordict??? */
doref = *epref;
epref = &doref;
/* Push the error object on the operand stack if appropriate. */
if (!GS_ERROR_IS_INTERRUPT(code)) {
/* Replace the error object if within an oparray or .errorexec. */
osp++;
if (osp >= ostop) {
*pexit_code = gs_error_Fatal;
return_error(gs_error_Fatal);
}
*osp = *perror_object;
errorexec_find(i_ctx_p, osp);
}
goto again;
}
|
CVE-2018-16542
|
In Artifex Ghostscript before 9.24, attackers able to supply crafted PostScript files could use insufficient interpreter stack-size checking during error handling to crash the interpreter.
|
[
"CWE-388"
] |
[
{
"line_no": 197,
"text": " *++osp = *perror_object;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 197,
"text": " osp++;",
"char_start": null,
"char_end": null
},
{
"line_no": 198,
"text": " if (osp >= ostop) {",
"char_start": null,
"char_end": null
},
{
"line_no": 199,
"text": " *pexit_code = gs_error_Fatal;",
"char_start": null,
"char_end": null
},
{
"line_no": 200,
"text": " return_error(gs_error_Fatal);",
"char_start": null,
"char_end": null
},
{
"line_no": 201,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 202,
"text": " *osp = *perror_object;",
"char_start": null,
"char_end": null
}
] | 91
|
primevul
|
primevul_ghostscript_241d91112771a6104de10b3948c3f350d6690c1d
|
241d91112771a6104de10b3948c3f350d6690c1d
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
gs_main_finit(gs_main_instance * minst, int exit_status, int code)
{
i_ctx_t *i_ctx_p = minst->i_ctx_p;
gs_dual_memory_t dmem = {0};
int exit_code;
ref error_object;
char *tempnames;
/* NB: need to free gs_name_table
*/
/*
* Previous versions of this code closed the devices in the
* device list here. Since these devices are now prototypes,
* they cannot be opened, so they do not need to be closed;
* alloc_restore_all will close dynamically allocated devices.
*/
tempnames = gs_main_tempnames(minst);
/* by the time we get here, we *must* avoid any random redefinitions of
* operators etc, so we push systemdict onto the top of the dict stack.
* We do this in C to avoid running into any other re-defininitions in the
* Postscript world.
*/
gs_finit_push_systemdict(i_ctx_p);
/* We have to disable BGPrint before we call interp_reclaim() to prevent the
* parent rendering thread initialising for the next page, whilst we are
* removing objects it may want to access - for example, the I/O device table.
* We also have to mess with the BeginPage/EndPage procs so that we don't
* trigger a spurious extra page to be emitted.
*/
if (minst->init_done >= 2) {
gs_main_run_string(minst,
"/BGPrint /GetDeviceParam .special_op \
{{ <</BeginPage {pop} /EndPage {pop pop //false } \
/BGPrint false /NumRenderingThreads 0>> setpagedevice} if} if \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse \
.systemvar exec",
0 , &exit_code, &error_object);
}
/*
* Close the "main" device, because it may need to write out
* data before destruction. pdfwrite needs so.
*/
if (minst->init_done >= 2) {
int code = 0;
if (idmemory->reclaim != 0) {
code = interp_reclaim(&minst->i_ctx_p, avm_global);
if (code < 0) {
ref error_name;
if (tempnames)
free(tempnames);
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf2(imemory, "ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n", err_str, code);
}
else {
emprintf1(imemory, "UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n", code);
}
#ifdef MEMENTO_SQUEEZE_BUILD
if (code != gs_error_VMerror ) return gs_error_Fatal;
#else
return gs_error_Fatal;
#endif
}
i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */
}
if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) {
gx_device *pdev = i_ctx_p->pgs->device;
const char * dname = pdev->dname;
if (code < 0) {
ref error_name;
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf3(imemory, "ERROR: %s (%d) on closing %s device.\n", err_str, code, dname);
}
else {
emprintf2(imemory, "UNKNOWN ERROR %d closing %s device.\n", code, dname);
}
}
rc_decrement(pdev, "gs_main_finit"); /* device might be freed */
if (exit_status == 0 || exit_status == gs_error_Quit)
exit_status = code;
}
/* Flush stdout and stderr */
gs_main_run_string(minst,
"(%stdout) (w) file closefile (%stderr) (w) file closefile \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \
systemdict /savedinitialgstate .forceundef",
0 , &exit_code, &error_object);
}
gp_readline_finit(minst->readline_data);
i_ctx_p = minst->i_ctx_p; /* get current interp context */
if (gs_debug_c(':')) {
print_resource_usage(minst, &gs_imemory, "Final");
dmprintf1(minst->heap, "%% Exiting instance 0x%p\n", minst);
}
/* Do the equivalent of a restore "past the bottom". */
/* This will release all memory, close all open files, etc. */
if (minst->init_done >= 1) {
gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory;
i_plugin_holder *h = i_ctx_p->plugin_list;
dmem = *idmemory;
code = alloc_restore_all(i_ctx_p);
if (code < 0)
emprintf1(mem_raw,
"ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n",
code);
i_iodev_finit(&dmem);
i_plugin_finit(mem_raw, h);
}
/* clean up redirected stdout */
if (minst->heap->gs_lib_ctx->fstdout2
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout)
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) {
fclose(minst->heap->gs_lib_ctx->fstdout2);
minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL;
}
minst->heap->gs_lib_ctx->stdout_is_redirected = 0;
minst->heap->gs_lib_ctx->stdout_to_stderr = 0;
/* remove any temporary files, after ghostscript has closed files */
if (tempnames) {
char *p = tempnames;
while (*p) {
unlink(p);
p += strlen(p) + 1;
}
free(tempnames);
}
gs_lib_finit(exit_status, code, minst->heap);
gs_free_object(minst->heap, minst->lib_path.container.value.refs, "lib_path array");
ialloc_finit(&dmem);
return exit_status;
}
|
gs_main_finit(gs_main_instance * minst, int exit_status, int code)
{
i_ctx_t *i_ctx_p = minst->i_ctx_p;
gs_dual_memory_t dmem = {0};
int exit_code;
ref error_object;
char *tempnames;
/* NB: need to free gs_name_table
*/
/*
* Previous versions of this code closed the devices in the
* device list here. Since these devices are now prototypes,
* they cannot be opened, so they do not need to be closed;
* alloc_restore_all will close dynamically allocated devices.
*/
tempnames = gs_main_tempnames(minst);
/* by the time we get here, we *must* avoid any random redefinitions of
* operators etc, so we push systemdict onto the top of the dict stack.
* We do this in C to avoid running into any other re-defininitions in the
* Postscript world.
*/
gs_finit_push_systemdict(i_ctx_p);
/* We have to disable BGPrint before we call interp_reclaim() to prevent the
* parent rendering thread initialising for the next page, whilst we are
* removing objects it may want to access - for example, the I/O device table.
* We also have to mess with the BeginPage/EndPage procs so that we don't
* trigger a spurious extra page to be emitted.
*/
if (minst->init_done >= 2) {
gs_main_run_string(minst,
"/BGPrint /GetDeviceParam .special_op \
{{ <</BeginPage {pop} /EndPage {pop pop //false } \
/BGPrint false /NumRenderingThreads 0>> setpagedevice} if} if \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse \
.systemvar exec",
0 , &exit_code, &error_object);
}
/*
* Close the "main" device, because it may need to write out
* data before destruction. pdfwrite needs so.
*/
if (minst->init_done >= 2) {
int code = 0;
if (idmemory->reclaim != 0) {
code = interp_reclaim(&minst->i_ctx_p, avm_global);
if (code < 0) {
ref error_name;
if (tempnames)
free(tempnames);
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf2(imemory, "ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n", err_str, code);
}
else {
emprintf1(imemory, "UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n", code);
}
#ifdef MEMENTO_SQUEEZE_BUILD
if (code != gs_error_VMerror ) return gs_error_Fatal;
#else
return gs_error_Fatal;
#endif
}
i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */
}
if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL &&
gx_device_is_null(i_ctx_p->pgs->device)) {
/* if the job replaced the device with the nulldevice, we we need to grestore
away that device, so the block below can properly dispense
with the default device.
*/
int code = gs_grestoreall(i_ctx_p->pgs);
if (code < 0) return_error(gs_error_Fatal);
}
if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) {
gx_device *pdev = i_ctx_p->pgs->device;
const char * dname = pdev->dname;
if (code < 0) {
ref error_name;
if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
char err_str[32] = {0};
name_string_ref(imemory, &error_name, &error_name);
memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
emprintf3(imemory, "ERROR: %s (%d) on closing %s device.\n", err_str, code, dname);
}
else {
emprintf2(imemory, "UNKNOWN ERROR %d closing %s device.\n", code, dname);
}
}
rc_decrement(pdev, "gs_main_finit"); /* device might be freed */
if (exit_status == 0 || exit_status == gs_error_Quit)
exit_status = code;
}
/* Flush stdout and stderr */
gs_main_run_string(minst,
"(%stdout) (w) file closefile (%stderr) (w) file closefile \
serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \
systemdict /savedinitialgstate .forceundef",
0 , &exit_code, &error_object);
}
gp_readline_finit(minst->readline_data);
i_ctx_p = minst->i_ctx_p; /* get current interp context */
if (gs_debug_c(':')) {
print_resource_usage(minst, &gs_imemory, "Final");
dmprintf1(minst->heap, "%% Exiting instance 0x%p\n", minst);
}
/* Do the equivalent of a restore "past the bottom". */
/* This will release all memory, close all open files, etc. */
if (minst->init_done >= 1) {
gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory;
i_plugin_holder *h = i_ctx_p->plugin_list;
dmem = *idmemory;
code = alloc_restore_all(i_ctx_p);
if (code < 0)
emprintf1(mem_raw,
"ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n",
code);
i_iodev_finit(&dmem);
i_plugin_finit(mem_raw, h);
}
/* clean up redirected stdout */
if (minst->heap->gs_lib_ctx->fstdout2
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout)
&& (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) {
fclose(minst->heap->gs_lib_ctx->fstdout2);
minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL;
}
minst->heap->gs_lib_ctx->stdout_is_redirected = 0;
minst->heap->gs_lib_ctx->stdout_to_stderr = 0;
/* remove any temporary files, after ghostscript has closed files */
if (tempnames) {
char *p = tempnames;
while (*p) {
unlink(p);
p += strlen(p) + 1;
}
free(tempnames);
}
gs_lib_finit(exit_status, code, minst->heap);
gs_free_object(minst->heap, minst->lib_path.container.value.refs, "lib_path array");
ialloc_finit(&dmem);
return exit_status;
}
|
CVE-2018-16541
|
In Artifex Ghostscript before 9.24, attackers able to supply crafted PostScript files could use incorrect free logic in pagedevice replacement to crash the interpreter.
|
[
"CWE-416"
] |
[] |
[
{
"line_no": 76,
"text": " if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL &&",
"char_start": null,
"char_end": null
},
{
"line_no": 77,
"text": " gx_device_is_null(i_ctx_p->pgs->device)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 78,
"text": " /* if the job replaced the device with the nulldevice, we we need to grestore",
"char_start": null,
"char_end": null
},
{
"line_no": 79,
"text": " away that device, so the block below can properly dispense",
"char_start": null,
"char_end": null
},
{
"line_no": 80,
"text": " with the default device.",
"char_start": null,
"char_end": null
},
{
"line_no": 81,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 82,
"text": " int code = gs_grestoreall(i_ctx_p->pgs);",
"char_start": null,
"char_end": null
},
{
"line_no": 83,
"text": " if (code < 0) return_error(gs_error_Fatal);",
"char_start": null,
"char_end": null
},
{
"line_no": 84,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 85,
"text": "",
"char_start": null,
"char_end": null
}
] | 92
|
primevul
|
primevul_ghostscript_b326a71659b7837d3acde954b18bda1a6f5e9498
|
b326a71659b7837d3acde954b18bda1a6f5e9498
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
zsetcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp;
es_ptr ep;
const gs_color_space * pcs = gs_currentcolorspace(igs);
gs_client_color cc;
int n_comps, n_numeric_comps, num_offset = 0, code, depth;
PS_colour_space_t *space;
/* initialize the client color pattern pointer for GC */
cc.pattern = 0;
/* check for a pattern color space */
if ((n_comps = cs_num_components(pcs)) < 0) {
n_comps = -n_comps;
if (r_has_type(op, t_dictionary)) {
ref *pImpl, pPatInst;
code = dict_find_string(op, "Implementation", &pImpl);
if (code != 0) {
code = array_get(imemory, pImpl, 0, &pPatInst);
if (code < 0)
return code;
n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern)
? n_comps - 1
: 0 );
} else
n_numeric_comps = 0;
} else
n_numeric_comps = 0;
num_offset = 1;
} else
n_numeric_comps = n_comps;
/* gather the numeric operands */
code = float_params(op - num_offset, n_numeric_comps, cc.paint.values);
if (code < 0)
return code;
/* The values are copied to graphic state and compared with */
/* other colors by memcmp() in gx_hld_saved_color_equal() */
/* This is the easiest way to avoid indeterminism */
memset(cc.paint.values + n_numeric_comps, 0,
sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps);
code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space);
if (code < 0)
return code;
if (space->validatecomponents) {
code = space->validatecomponents(i_ctx_p,
&istate->colorspace[0].array,
cc.paint.values, n_numeric_comps);
if (code < 0)
return code;
}
/* pass the color to the graphic library */
if ((code = gs_setcolor(igs, &cc)) >= 0) {
if (n_comps > n_numeric_comps) {
istate->pattern[0] = *op; /* save pattern dict or null */
}
}
/* Check the color spaces, to see if we need to run any tint transform
* procedures. Some Adobe applications *eg Photoshop) expect that the
* tint transform will be run and use this to set up duotone DeviceN
* spaces.
*/
code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth);
if (code < 0)
return code;
/* Set up for the continuation procedure which will do the work */
/* Make sure the exec stack has enough space */
check_estack(5);
/* A place holder for data potentially used by transform functions */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'depth' of the space returned during checking above */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'stage' of processing (initially 0) */
ep = esp += 1;
make_int(ep, 0);
/* Store a pointer to the color space stored on the operand stack
* as the stack may grow unpredictably making further access
* to the space difficult
*/
ep = esp += 1;
*ep = istate->colorspace[0].array;
/* Finally, the actual continuation routine */
push_op_estack(setcolor_cont);
return o_push_estack;
}
|
zsetcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp;
es_ptr ep;
const gs_color_space * pcs = gs_currentcolorspace(igs);
gs_client_color cc;
int n_comps, n_numeric_comps, num_offset = 0, code, depth;
PS_colour_space_t *space;
/* initialize the client color pattern pointer for GC */
cc.pattern = 0;
/* check for a pattern color space */
if ((n_comps = cs_num_components(pcs)) < 0) {
n_comps = -n_comps;
if (r_has_type(op, t_dictionary)) {
ref *pImpl, pPatInst;
if ((code = dict_find_string(op, "Implementation", &pImpl)) < 0)
return code;
if (code > 0) {
code = array_get(imemory, pImpl, 0, &pPatInst);
if (code < 0)
return code;
n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern)
? n_comps - 1
: 0 );
} else
n_numeric_comps = 0;
} else
n_numeric_comps = 0;
num_offset = 1;
} else
n_numeric_comps = n_comps;
/* gather the numeric operands */
code = float_params(op - num_offset, n_numeric_comps, cc.paint.values);
if (code < 0)
return code;
/* The values are copied to graphic state and compared with */
/* other colors by memcmp() in gx_hld_saved_color_equal() */
/* This is the easiest way to avoid indeterminism */
memset(cc.paint.values + n_numeric_comps, 0,
sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps);
code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space);
if (code < 0)
return code;
if (space->validatecomponents) {
code = space->validatecomponents(i_ctx_p,
&istate->colorspace[0].array,
cc.paint.values, n_numeric_comps);
if (code < 0)
return code;
}
/* pass the color to the graphic library */
if ((code = gs_setcolor(igs, &cc)) >= 0) {
if (n_comps > n_numeric_comps) {
istate->pattern[0] = *op; /* save pattern dict or null */
}
}
/* Check the color spaces, to see if we need to run any tint transform
* procedures. Some Adobe applications *eg Photoshop) expect that the
* tint transform will be run and use this to set up duotone DeviceN
* spaces.
*/
code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth);
if (code < 0)
return code;
/* Set up for the continuation procedure which will do the work */
/* Make sure the exec stack has enough space */
check_estack(5);
/* A place holder for data potentially used by transform functions */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'depth' of the space returned during checking above */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'stage' of processing (initially 0) */
ep = esp += 1;
make_int(ep, 0);
/* Store a pointer to the color space stored on the operand stack
* as the stack may grow unpredictably making further access
* to the space difficult
*/
ep = esp += 1;
*ep = istate->colorspace[0].array;
/* Finally, the actual continuation routine */
push_op_estack(setcolor_cont);
return o_push_estack;
}
|
CVE-2018-16513
|
In Artifex Ghostscript before 9.24, attackers able to supply crafted PostScript files could use a type confusion in the setcolor function to crash the interpreter or possibly have unspecified other impact.
|
[
"CWE-704"
] |
[
{
"line_no": 19,
"text": " code = dict_find_string(op, \"Implementation\", &pImpl);",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": " if (code != 0) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 19,
"text": " if ((code = dict_find_string(op, \"Implementation\", &pImpl)) < 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": " return code;",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " if (code > 0) {",
"char_start": null,
"char_end": null
}
] | 93
|
primevul
|
primevul_drm_9f1f1a2dab38d4ce87a13565cf4dc1b73bef3a5f
|
9f1f1a2dab38d4ce87a13565cf4dc1b73bef3a5f
|
drm
|
https://cgit.freedesktop.org/drm/drm-misc/commit/?id=9f1f1a2dab38d4ce87a13565cf4dc1b73bef3a5f
|
struct edid *drm_load_edid_firmware(struct drm_connector *connector)
{
const char *connector_name = connector->name;
char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL;
struct edid *edid;
if (edid_firmware[0] == '\0')
return ERR_PTR(-ENOENT);
/*
* If there are multiple edid files specified and separated
* by commas, search through the list looking for one that
* matches the connector.
*
* If there's one or more that doesn't specify a connector, keep
* the last one found one as a fallback.
*/
fwstr = kstrdup(edid_firmware, GFP_KERNEL);
edidstr = fwstr;
while ((edidname = strsep(&edidstr, ","))) {
if (strncmp(connector_name, edidname, colon - edidname))
continue;
edidname = colon + 1;
break;
}
if (*edidname != '\0') /* corner case: multiple ',' */
fallback = edidname;
}
|
struct edid *drm_load_edid_firmware(struct drm_connector *connector)
{
const char *connector_name = connector->name;
char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL;
struct edid *edid;
if (edid_firmware[0] == '\0')
return ERR_PTR(-ENOENT);
/*
* If there are multiple edid files specified and separated
* by commas, search through the list looking for one that
* matches the connector.
*
* If there's one or more that doesn't specify a connector, keep
* the last one found one as a fallback.
*/
fwstr = kstrdup(edid_firmware, GFP_KERNEL);
if (!fwstr)
return ERR_PTR(-ENOMEM);
edidstr = fwstr;
while ((edidname = strsep(&edidstr, ","))) {
if (strncmp(connector_name, edidname, colon - edidname))
continue;
edidname = colon + 1;
break;
}
if (*edidname != '\0') /* corner case: multiple ',' */
fallback = edidname;
}
|
CVE-2019-12382
|
An issue was discovered in drm_load_edid_firmware in drivers/gpu/drm/drm_edid_load.c in the Linux kernel through 5.1.5. There is an unchecked kstrdup of fwstr, which might allow an attacker to cause a denial of service (NULL pointer dereference and system crash). NOTE: The vendor disputes this issues as not being a vulnerability because kstrdup() returning NULL is handled sufficiently and there is no chance for a NULL pointer dereference
|
[
"CWE-476"
] |
[] |
[
{
"line_no": 19,
"text": "\tif (!fwstr)",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": "\t\treturn ERR_PTR(-ENOMEM);",
"char_start": null,
"char_end": null
}
] | 102
|
primevul
|
primevul_haproxy_7ec765568883b2d4e5a2796adbeb492a22ec9bd4
|
7ec765568883b2d4e5a2796adbeb492a22ec9bd4
|
haproxy
|
https://github.com/haproxy/haproxy
|
void buffer_slow_realign(struct buffer *buf)
{
/* two possible cases :
* - the buffer is in one contiguous block, we move it in-place
* - the buffer is in two blocks, we move it via the swap_buffer
*/
if (buf->i) {
int block1 = buf->i;
int block2 = 0;
if (buf->p + buf->i > buf->data + buf->size) {
/* non-contiguous block */
block1 = buf->data + buf->size - buf->p;
block2 = buf->p + buf->i - (buf->data + buf->size);
}
if (block2)
memcpy(swap_buffer, buf->data, block2);
memmove(buf->data, buf->p, block1);
if (block2)
memcpy(buf->data + block1, swap_buffer, block2);
}
buf->p = buf->data;
}
|
void buffer_slow_realign(struct buffer *buf)
{
int block1 = buf->o;
int block2 = 0;
/* process output data in two steps to cover wrapping */
if (block1 > buf->p - buf->data) {
block2 = buf->p - buf->data;
block1 -= block2;
}
memcpy(swap_buffer + buf->size - buf->o, bo_ptr(buf), block1);
memcpy(swap_buffer + buf->size - block2, buf->data, block2);
/* process input data in two steps to cover wrapping */
block1 = buf->i;
block2 = 0;
if (block1 > buf->data + buf->size - buf->p) {
block1 = buf->data + buf->size - buf->p;
block2 = buf->i - block1;
}
memcpy(swap_buffer, bi_ptr(buf), block1);
memcpy(swap_buffer + block1, buf->data, block2);
/* reinject changes into the buffer */
memcpy(buf->data, swap_buffer, buf->i);
memcpy(buf->data + buf->size - buf->o, swap_buffer + buf->size - buf->o, buf->o);
buf->p = buf->data;
}
|
CVE-2015-3281
|
The buffer_slow_realign function in HAProxy 1.5.x before 1.5.14 and 1.6-dev does not properly realign a buffer that is used for pending outgoing data, which allows remote attackers to obtain sensitive information (uninitialized memory contents of previous requests) via a crafted request.
|
[
"CWE-119"
] |
[
{
"line_no": 3,
"text": " /* two possible cases :",
"char_start": null,
"char_end": null
},
{
"line_no": 4,
"text": " * - the buffer is in one contiguous block, we move it in-place",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": " * - the buffer is in two blocks, we move it via the swap_buffer",
"char_start": null,
"char_end": null
},
{
"line_no": 6,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 7,
"text": " if (buf->i) {",
"char_start": null,
"char_end": null
},
{
"line_no": 8,
"text": " int block1 = buf->i;",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " int block2 = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " if (buf->p + buf->i > buf->data + buf->size) {",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " /* non-contiguous block */",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " block1 = buf->data + buf->size - buf->p;",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " block2 = buf->p + buf->i - (buf->data + buf->size);",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": " if (block2)",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " memcpy(swap_buffer, buf->data, block2);",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": " memmove(buf->data, buf->p, block1);",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " if (block2)",
"char_start": null,
"char_end": null
},
{
"line_no": 19,
"text": " memcpy(buf->data + block1, swap_buffer, block2);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 3,
"text": " int block1 = buf->o;",
"char_start": null,
"char_end": null
},
{
"line_no": 4,
"text": " int block2 = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 6,
"text": " /* process output data in two steps to cover wrapping */",
"char_start": null,
"char_end": null
},
{
"line_no": 7,
"text": " if (block1 > buf->p - buf->data) {",
"char_start": null,
"char_end": null
},
{
"line_no": 8,
"text": " block2 = buf->p - buf->data;",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " block1 -= block2;",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " memcpy(swap_buffer + buf->size - buf->o, bo_ptr(buf), block1);",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " memcpy(swap_buffer + buf->size - block2, buf->data, block2);",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " /* process input data in two steps to cover wrapping */",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": " block1 = buf->i;",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " block2 = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " if (block1 > buf->data + buf->size - buf->p) {",
"char_start": null,
"char_end": null
},
{
"line_no": 19,
"text": " block1 = buf->data + buf->size - buf->p;",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": " block2 = buf->i - block1;",
"char_start": null,
"char_end": null
},
{
"line_no": 22,
"text": " memcpy(swap_buffer, bi_ptr(buf), block1);",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " memcpy(swap_buffer + block1, buf->data, block2);",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " /* reinject changes into the buffer */",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " memcpy(buf->data, swap_buffer, buf->i);",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " memcpy(buf->data + buf->size - buf->o, swap_buffer + buf->size - buf->o, buf->o);",
"char_start": null,
"char_end": null
}
] | 106
|
primevul
|
primevul_openssl_cc598f321fbac9c04da5766243ed55d55948637d
|
cc598f321fbac9c04da5766243ed55d55948637d
|
openssl
|
https://github.com/openssl/openssl
|
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx)
{
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
const unsigned char *p = NULL, *q;
unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */
unsigned char imphack = 0, oclass;
char seq_eoc, seq_nolen, cst, isopt;
long tmplen;
int i;
int otag;
int ret = 0;
ASN1_VALUE **pchptr, *ptmpval;
if (!pval)
return 0;
if (aux && aux->asn1_cb)
asn1_cb = 0;
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
/*
* tagging or OPTIONAL is currently illegal on an item template
* because the flags can't get passed down. In practice this
* isn't a problem: we include the relevant flags from the item
* template in the template itself.
*/
if ((tag != -1) || opt) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len,
it->templates, opt, ctx);
}
return asn1_d2i_ex_primitive(pval, in, len, it,
tag, aclass, opt, ctx);
break;
case ASN1_ITYPE_MSTRING:
p = *in;
/* Just read in tag and class */
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
&p, len, -1, 0, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Must be UNIVERSAL class */
if (oclass != V_ASN1_UNIVERSAL) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
goto err;
}
/* Check tag matches bit map */
if (!(ASN1_tag2bit(otag) & it->utype)) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
goto err;
}
return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
case ASN1_ITYPE_EXTERN:
/* Use new style d2i */
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
case ASN1_ITYPE_COMPAT:
/* we must resort to old style evil hackery */
cf = it->funcs;
/* If OPTIONAL see if it is there */
if (opt) {
int exptag;
p = *in;
if (tag == -1)
exptag = it->utype;
else
exptag = tag;
/*
* Don't care about anything other than presence of expected tag
*/
ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
&p, len, exptag, aclass, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (ret == -1)
return -1;
}
/*
* This is the old style evil hack IMPLICIT handling: since the
* underlying code is expecting a tag and class other than the one
* present we change the buffer temporarily then change it back
* afterwards. This doesn't and never did work for tags > 30. Yes
* this is *horrible* but it is only needed for old style d2i which
* will hopefully not be around for much longer. FIXME: should copy
* the buffer then modify it so the input buffer can be const: we
* should *always* copy because the old style d2i might modify the
* buffer.
*/
if (tag != -1) {
wp = *(unsigned char **)in;
imphack = *wp;
if (p == NULL) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
| it->utype);
}
ptmpval = cf->asn1_d2i(pval, in, len);
if (tag != -1)
*wp = imphack;
if (ptmpval)
return 1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
case ASN1_ITYPE_CHOICE:
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
if (*pval) {
/* Free up and zero CHOICE value if initialised */
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
tt = it->templates + i;
pchptr = asn1_get_field_ptr(pval, tt);
ASN1_template_free(pchptr, tt);
asn1_set_choice_selector(pval, -1, it);
}
} else if (!ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* CHOICE type, try each possibility in turn */
p = *in;
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
pchptr = asn1_get_field_ptr(pval, tt);
/*
* We mark field as OPTIONAL so its absence can be recognised.
*/
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
/* If field not present, try the next one */
if (ret == -1)
continue;
/* If positive return, read OK, break loop */
if (ret > 0)
break;
/* Otherwise must be an ASN1 parsing error */
errtt = tt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Did we fall off the end without reading anything? */
if (i == it->tcount) {
/* If OPTIONAL, this is OK */
if (opt) {
/* Free and zero it */
ASN1_item_ex_free(pval, it);
return -1;
}
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
goto err;
}
asn1_set_choice_selector(pval, i, it);
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
p = *in;
tmplen = len;
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
aclass = V_ASN1_UNIVERSAL;
}
/* Get SEQUENCE length and update len, p */
ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
&p, len, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
len = tmplen - (p - *in);
seq_nolen = 1;
}
/* If indefinite we don't do a length check */
else
seq_nolen = seq_eoc;
if (!cst) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
goto err;
}
if (!*pval && !ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Free up and zero any ADB found */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
if (tt->flags & ASN1_TFLG_ADB_MASK) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
}
}
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
pseqval = asn1_get_field_ptr(pval, seqtt);
/* Have we ran out of data? */
if (!len)
break;
q = p;
if (asn1_check_eoc(&p, len)) {
if (!seq_eoc) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);
goto err;
}
len -= p - q;
seq_eoc = 0;
q = p;
break;
}
/*
* This determines the OPTIONAL flag value. The field cannot be
* omitted if it is the last of a SEQUENCE and there is still
* data to be read. This isn't strictly necessary but it
* increases efficiency in some cases.
*/
if (i == (it->tcount - 1))
isopt = 0;
else
isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
/*
* attempt to read in field, allowing each to be OPTIONAL
*/
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
if (!ret) {
errtt = seqtt;
goto err;
} else if (ret == -1) {
/*
* OPTIONAL component absent. Free and zero the field.
*/
ASN1_template_free(pseqval, seqtt);
continue;
}
/* Update length */
len -= p - q;
}
/* Check for EOC if expecting one */
if (seq_eoc && !asn1_check_eoc(&p, len)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
goto err;
}
/* Check all data read */
if (!seq_nolen && len) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
goto err;
}
/*
* If we get here we've got no more data in the SEQUENCE, however we
* may not have read all fields so check all remaining are OPTIONAL
* and clear any that are.
*/
for (; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
ASN1_VALUE **pseqval;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
} else {
errtt = seqtt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
goto err;
}
}
/* Save encoding */
if (!asn1_enc_save(pval, *in, p - *in, it))
goto auxerr;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
default:
return 0;
}
auxerr:
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
auxerr:
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
err:
ASN1_item_ex_free(pval, it);
if (errtt)
ERR_add_error_data(4, "Field=", errtt->field_name,
", Type=", it->sname);
}
|
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx)
{
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
const unsigned char *p = NULL, *q;
unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */
unsigned char imphack = 0, oclass;
char seq_eoc, seq_nolen, cst, isopt;
long tmplen;
int i;
int otag;
int ret = 0;
ASN1_VALUE **pchptr, *ptmpval;
int combine = aclass & ASN1_TFLG_COMBINE;
aclass &= ~ASN1_TFLG_COMBINE;
if (!pval)
return 0;
if (aux && aux->asn1_cb)
asn1_cb = 0;
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
/*
* tagging or OPTIONAL is currently illegal on an item template
* because the flags can't get passed down. In practice this
* isn't a problem: we include the relevant flags from the item
* template in the template itself.
*/
if ((tag != -1) || opt) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len,
it->templates, opt, ctx);
}
return asn1_d2i_ex_primitive(pval, in, len, it,
tag, aclass, opt, ctx);
break;
case ASN1_ITYPE_MSTRING:
p = *in;
/* Just read in tag and class */
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
&p, len, -1, 0, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Must be UNIVERSAL class */
if (oclass != V_ASN1_UNIVERSAL) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
goto err;
}
/* Check tag matches bit map */
if (!(ASN1_tag2bit(otag) & it->utype)) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
goto err;
}
return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
case ASN1_ITYPE_EXTERN:
/* Use new style d2i */
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
case ASN1_ITYPE_COMPAT:
/* we must resort to old style evil hackery */
cf = it->funcs;
/* If OPTIONAL see if it is there */
if (opt) {
int exptag;
p = *in;
if (tag == -1)
exptag = it->utype;
else
exptag = tag;
/*
* Don't care about anything other than presence of expected tag
*/
ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
&p, len, exptag, aclass, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (ret == -1)
return -1;
}
/*
* This is the old style evil hack IMPLICIT handling: since the
* underlying code is expecting a tag and class other than the one
* present we change the buffer temporarily then change it back
* afterwards. This doesn't and never did work for tags > 30. Yes
* this is *horrible* but it is only needed for old style d2i which
* will hopefully not be around for much longer. FIXME: should copy
* the buffer then modify it so the input buffer can be const: we
* should *always* copy because the old style d2i might modify the
* buffer.
*/
if (tag != -1) {
wp = *(unsigned char **)in;
imphack = *wp;
if (p == NULL) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
| it->utype);
}
ptmpval = cf->asn1_d2i(pval, in, len);
if (tag != -1)
*wp = imphack;
if (ptmpval)
return 1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
case ASN1_ITYPE_CHOICE:
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
if (*pval) {
/* Free up and zero CHOICE value if initialised */
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
tt = it->templates + i;
pchptr = asn1_get_field_ptr(pval, tt);
ASN1_template_free(pchptr, tt);
asn1_set_choice_selector(pval, -1, it);
}
} else if (!ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* CHOICE type, try each possibility in turn */
p = *in;
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
pchptr = asn1_get_field_ptr(pval, tt);
/*
* We mark field as OPTIONAL so its absence can be recognised.
*/
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
/* If field not present, try the next one */
if (ret == -1)
continue;
/* If positive return, read OK, break loop */
if (ret > 0)
break;
/* Otherwise must be an ASN1 parsing error */
errtt = tt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Did we fall off the end without reading anything? */
if (i == it->tcount) {
/* If OPTIONAL, this is OK */
if (opt) {
/* Free and zero it */
ASN1_item_ex_free(pval, it);
return -1;
}
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
goto err;
}
asn1_set_choice_selector(pval, i, it);
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
p = *in;
tmplen = len;
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
aclass = V_ASN1_UNIVERSAL;
}
/* Get SEQUENCE length and update len, p */
ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
&p, len, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
len = tmplen - (p - *in);
seq_nolen = 1;
}
/* If indefinite we don't do a length check */
else
seq_nolen = seq_eoc;
if (!cst) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
goto err;
}
if (!*pval && !ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Free up and zero any ADB found */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
if (tt->flags & ASN1_TFLG_ADB_MASK) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
}
}
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
pseqval = asn1_get_field_ptr(pval, seqtt);
/* Have we ran out of data? */
if (!len)
break;
q = p;
if (asn1_check_eoc(&p, len)) {
if (!seq_eoc) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);
goto err;
}
len -= p - q;
seq_eoc = 0;
q = p;
break;
}
/*
* This determines the OPTIONAL flag value. The field cannot be
* omitted if it is the last of a SEQUENCE and there is still
* data to be read. This isn't strictly necessary but it
* increases efficiency in some cases.
*/
if (i == (it->tcount - 1))
isopt = 0;
else
isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
/*
* attempt to read in field, allowing each to be OPTIONAL
*/
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
if (!ret) {
errtt = seqtt;
goto err;
} else if (ret == -1) {
/*
* OPTIONAL component absent. Free and zero the field.
*/
ASN1_template_free(pseqval, seqtt);
continue;
}
/* Update length */
len -= p - q;
}
/* Check for EOC if expecting one */
if (seq_eoc && !asn1_check_eoc(&p, len)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
goto err;
}
/* Check all data read */
if (!seq_nolen && len) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
goto err;
}
/*
* If we get here we've got no more data in the SEQUENCE, however we
* may not have read all fields so check all remaining are OPTIONAL
* and clear any that are.
*/
for (; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
ASN1_VALUE **pseqval;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
} else {
errtt = seqtt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
goto err;
}
}
/* Save encoding */
if (!asn1_enc_save(pval, *in, p - *in, it))
goto auxerr;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
default:
return 0;
}
auxerr:
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
auxerr:
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
err:
if (combine == 0)
ASN1_item_ex_free(pval, it);
if (errtt)
ERR_add_error_data(4, "Field=", errtt->field_name,
", Type=", it->sname);
}
|
CVE-2015-3195
|
The ASN1_TFLG_COMBINE implementation in crypto/asn1/tasn_dec.c in OpenSSL before 0.9.8zh, 1.0.0 before 1.0.0t, 1.0.1 before 1.0.1q, and 1.0.2 before 1.0.2e mishandles errors caused by malformed X509_ATTRIBUTE data, which allows remote attackers to obtain sensitive information from process memory by triggering a decoding failure in a PKCS#7 or CMS application.
|
[
"CWE-200"
] |
[
{
"line_no": 339,
"text": " ASN1_item_ex_free(pval, it);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 19,
"text": " int combine = aclass & ASN1_TFLG_COMBINE;",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": " aclass &= ~ASN1_TFLG_COMBINE;",
"char_start": null,
"char_end": null
},
{
"line_no": 341,
"text": " if (combine == 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 342,
"text": " ASN1_item_ex_free(pval, it);",
"char_start": null,
"char_end": null
}
] | 108
|
primevul
|
primevul_openssl_d8541d7e9e63bf5f343af24644046c8d96498c17
|
d8541d7e9e63bf5f343af24644046c8d96498c17
|
openssl
|
https://github.com/openssl/openssl
|
static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
|
static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param && param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
|
CVE-2015-3194
|
crypto/rsa/rsa_ameth.c in OpenSSL 1.0.1 before 1.0.1q and 1.0.2 before 1.0.2e allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via an RSA PSS ASN.1 signature that lacks a mask generation function parameter.
|
[
"CWE-476"
] |
[
{
"line_no": 22,
"text": " && param->type == V_ASN1_SEQUENCE) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 22,
"text": " && param && param->type == V_ASN1_SEQUENCE) {",
"char_start": null,
"char_end": null
}
] | 109
|
primevul
|
primevul_openssl_c394a488942387246653833359a5c94b5832674e
|
c394a488942387246653833359a5c94b5832674e
|
openssl
|
https://github.com/openssl/openssl
|
static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
{
const unsigned char *p;
int plen;
if (alg == NULL)
return NULL;
if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
return NULL;
if (alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
return d2i_X509_ALGOR(NULL, &p, plen);
}
|
static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
{
const unsigned char *p;
int plen;
if (alg == NULL || alg->parameter == NULL)
return NULL;
if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
return NULL;
if (alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
return d2i_X509_ALGOR(NULL, &p, plen);
}
|
CVE-2015-3194
|
crypto/rsa/rsa_ameth.c in OpenSSL 1.0.1 before 1.0.1q and 1.0.2 before 1.0.2e allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via an RSA PSS ASN.1 signature that lacks a mask generation function parameter.
|
[
"CWE-476"
] |
[
{
"line_no": 5,
"text": " if (alg == NULL)",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 5,
"text": " if (alg == NULL || alg->parameter == NULL)",
"char_start": null,
"char_end": null
}
] | 110
|
primevul
|
primevul_openssl_d73cc256c8e256c32ed959456101b73ba9842f72
|
d73cc256c8e256c32ed959456101b73ba9842f72
|
openssl
|
https://github.com/openssl/openssl
|
int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp(d, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp(d, a, b, c, ctx))
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_zero(c);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
"succeeded\n");
return 0;
}
BN_set_word(c, 16);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
"succeeded\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
return (00);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
|
int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp(d, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp(d, a, b, c, ctx))
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
/* Regression test for carry propagation bug in sqr8x_reduction */
BN_hex2bn(&a, "050505050505");
BN_hex2bn(&b, "02");
BN_hex2bn(&c,
"4141414141414141414141274141414141414141414141414141414141414141"
"4141414141414141414141414141414141414141414141414141414141414141"
"4141414141414141414141800000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000001");
BN_mod_exp(d, a, b, c, ctx);
BN_mul(e, a, a, ctx);
if (BN_cmp(d, e)) {
fprintf(stderr, "BN_mod_exp and BN_mul produce different results!\n");
return 0;
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_zero(c);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
"succeeded\n");
return 0;
}
BN_set_word(c, 16);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
"succeeded\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
return (00);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
|
CVE-2015-3193
|
The Montgomery squaring implementation in crypto/bn/asm/x86_64-mont5.pl in OpenSSL 1.0.2 before 1.0.2e on the x86_64 platform, as used by the BN_mod_exp function, mishandles carry propagation and produces incorrect output, which makes it easier for remote attackers to obtain sensitive private-key information via an attack against use of a (1) Diffie-Hellman (DH) or (2) Diffie-Hellman Ephemeral (DHE) ciphersuite.
|
[
"CWE-200"
] |
[] |
[
{
"line_no": 48,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": " /* Regression test for carry propagation bug in sqr8x_reduction */",
"char_start": null,
"char_end": null
},
{
"line_no": 50,
"text": " BN_hex2bn(&a, \"050505050505\");",
"char_start": null,
"char_end": null
},
{
"line_no": 51,
"text": " BN_hex2bn(&b, \"02\");",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " BN_hex2bn(&c,",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": " \"4141414141414141414141274141414141414141414141414141414141414141\"",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " \"4141414141414141414141414141414141414141414141414141414141414141\"",
"char_start": null,
"char_end": null
},
{
"line_no": 55,
"text": " \"4141414141414141414141800000000000000000000000000000000000000000\"",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": " \"0000000000000000000000000000000000000000000000000000000000000000\"",
"char_start": null,
"char_end": null
},
{
"line_no": 57,
"text": " \"0000000000000000000000000000000000000000000000000000000000000000\"",
"char_start": null,
"char_end": null
},
{
"line_no": 58,
"text": " \"0000000000000000000000000000000000000000000000000000000001\");",
"char_start": null,
"char_end": null
},
{
"line_no": 59,
"text": " BN_mod_exp(d, a, b, c, ctx);",
"char_start": null,
"char_end": null
},
{
"line_no": 60,
"text": " BN_mul(e, a, a, ctx);",
"char_start": null,
"char_end": null
},
{
"line_no": 61,
"text": " if (BN_cmp(d, e)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 62,
"text": " fprintf(stderr, \"BN_mod_exp and BN_mul produce different results!\\n\");",
"char_start": null,
"char_end": null
},
{
"line_no": 63,
"text": " return 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 64,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 65,
"text": "",
"char_start": null,
"char_end": null
}
] | 111
|
primevul
|
primevul_ghostscript_671fd59eb657743aa86fbc1895cb15872a317caa
|
671fd59eb657743aa86fbc1895cb15872a317caa
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save)
{
os_ptr op = osp;
int code;
ref token;
/* Note that gs_scan_token may change osp! */
pop(1); /* remove the file or scanner state */
again:
gs_scanner_error_object(i_ctx_p, pstate, &i_ctx_p->error_object);
break;
case scan_BOS:
code = 0;
case 0: /* read a token */
push(2);
ref_assign(op - 1, &token);
make_true(op);
break;
case scan_EOF: /* no tokens */
push(1);
make_false(op);
code = 0;
break;
case scan_Refill: /* need more data */
code = gs_scan_handle_refill(i_ctx_p, pstate, save,
ztoken_continue);
switch (code) {
case 0: /* state is not copied to the heap */
goto again;
case o_push_estack:
return code;
}
break; /* error */
}
|
token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save)
{
os_ptr op = osp;
int code;
ref token;
/* Since we might free pstate below, and we're dealing with
* gc memory referenced by the stack, we need to explicitly
* remove the reference to pstate from the stack, otherwise
* the garbager will fall over
*/
make_null(osp);
/* Note that gs_scan_token may change osp! */
pop(1); /* remove the file or scanner state */
again:
gs_scanner_error_object(i_ctx_p, pstate, &i_ctx_p->error_object);
break;
case scan_BOS:
code = 0;
case 0: /* read a token */
push(2);
ref_assign(op - 1, &token);
make_true(op);
break;
case scan_EOF: /* no tokens */
push(1);
make_false(op);
code = 0;
break;
case scan_Refill: /* need more data */
code = gs_scan_handle_refill(i_ctx_p, pstate, save,
ztoken_continue);
switch (code) {
case 0: /* state is not copied to the heap */
goto again;
case o_push_estack:
return code;
}
break; /* error */
}
|
CVE-2017-11714
|
psi/ztoken.c in Artifex Ghostscript 9.21 mishandles references to the scanner state structure, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted PostScript document, related to an out-of-bounds read in the igc_reloc_struct_ptr function in psi/igc.c.
|
[
"CWE-125"
] |
[] |
[
{
"line_no": 7,
"text": " /* Since we might free pstate below, and we're dealing with",
"char_start": null,
"char_end": null
},
{
"line_no": 8,
"text": " * gc memory referenced by the stack, we need to explicitly",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " * remove the reference to pstate from the stack, otherwise",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " * the garbager will fall over",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " make_null(osp);",
"char_start": null,
"char_end": null
}
] | 117
|
primevul
|
primevul_savannah_79972af4f0485a11dcb19551356c45245749fc5b
|
79972af4f0485a11dcb19551356c45245749fc5b
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
ft_smooth_render_generic( FT_Renderer render,
FT_GlyphSlot slot,
FT_Render_Mode mode,
const FT_Vector* origin,
FT_Render_Mode required_mode )
{
FT_Error error;
FT_Outline* outline = NULL;
FT_BBox cbox;
FT_UInt width, height, height_org, width_org, pitch;
FT_Bitmap* bitmap;
FT_Memory memory;
FT_Int hmul = mode == FT_RENDER_MODE_LCD;
FT_Int vmul = mode == FT_RENDER_MODE_LCD_V;
FT_Pos x_shift, y_shift, x_left, y_top;
FT_Raster_Params params;
/* check glyph image format */
if ( slot->format != render->glyph_format )
{
error = Smooth_Err_Invalid_Argument;
goto Exit;
}
/* check mode */
if ( mode != required_mode )
return Smooth_Err_Cannot_Render_Glyph;
outline = &slot->outline;
/* translate the outline to the new origin if needed */
if ( origin )
FT_Outline_Translate( outline, origin->x, origin->y );
/* compute the control box, and grid fit it */
FT_Outline_Get_CBox( outline, &cbox );
cbox.xMin = FT_PIX_FLOOR( cbox.xMin );
cbox.yMin = FT_PIX_FLOOR( cbox.yMin );
cbox.xMax = FT_PIX_CEIL( cbox.xMax );
cbox.yMax = FT_PIX_CEIL( cbox.yMax );
width = (FT_UInt)( ( cbox.xMax - cbox.xMin ) >> 6 );
height = (FT_UInt)( ( cbox.yMax - cbox.yMin ) >> 6 );
bitmap = &slot->bitmap;
memory = render->root.memory;
width_org = width;
height_org = height;
/* release old bitmap buffer */
if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP )
{
FT_FREE( bitmap->buffer );
slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP;
}
/* allocate new one, depends on pixel format */
pitch = width;
if ( hmul )
{
width = width * 3;
pitch = FT_PAD_CEIL( width, 4 );
}
if ( vmul )
height *= 3;
x_shift = (FT_Int) cbox.xMin;
y_shift = (FT_Int) cbox.yMin;
x_left = (FT_Int)( cbox.xMin >> 6 );
y_top = (FT_Int)( cbox.yMax >> 6 );
#ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING
if ( slot->library->lcd_filter_func )
{
FT_Int extra = slot->library->lcd_extra;
if ( hmul )
{
x_shift -= 64 * ( extra >> 1 );
width += 3 * extra;
pitch = FT_PAD_CEIL( width, 4 );
x_left -= extra >> 1;
}
if ( vmul )
{
y_shift -= 64 * ( extra >> 1 );
height += 3 * extra;
y_top += extra >> 1;
}
}
#endif
bitmap->pixel_mode = FT_PIXEL_MODE_GRAY;
bitmap->num_grays = 256;
bitmap->width = width;
goto Exit;
slot->internal->flags |= FT_GLYPH_OWN_BITMAP;
/* set up parameters */
params.target = bitmap;
params.source = outline;
params.flags = FT_RASTER_FLAG_AA;
#ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING
/* implode outline if needed */
{
FT_Vector* points = outline->points;
FT_Vector* points_end = points + outline->n_points;
FT_Vector* vec;
if ( hmul )
for ( vec = points; vec < points_end; vec++ )
vec->x *= 3;
if ( vmul )
for ( vec = points; vec < points_end; vec++ )
vec->y *= 3;
}
/* render outline into the bitmap */
error = render->raster_render( render->raster, ¶ms );
/* deflate outline if needed */
{
FT_Vector* points = outline->points;
FT_Vector* points_end = points + outline->n_points;
FT_Vector* vec;
if ( hmul )
for ( vec = points; vec < points_end; vec++ )
vec->x /= 3;
if ( vmul )
for ( vec = points; vec < points_end; vec++ )
vec->y /= 3;
}
if ( slot->library->lcd_filter_func )
slot->library->lcd_filter_func( bitmap, mode, slot->library );
#else /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */
/* render outline into bitmap */
error = render->raster_render( render->raster, ¶ms );
/* expand it horizontally */
if ( hmul )
{
FT_Byte* line = bitmap->buffer;
FT_UInt hh;
for ( hh = height_org; hh > 0; hh--, line += pitch )
{
FT_UInt xx;
FT_Byte* end = line + width;
for ( xx = width_org; xx > 0; xx-- )
{
FT_UInt pixel = line[xx-1];
end[-3] = (FT_Byte)pixel;
end[-2] = (FT_Byte)pixel;
end[-1] = (FT_Byte)pixel;
end -= 3;
}
}
}
/* expand it vertically */
if ( vmul )
{
FT_Byte* read = bitmap->buffer + ( height - height_org ) * pitch;
FT_Byte* write = bitmap->buffer;
FT_UInt hh;
for ( hh = height_org; hh > 0; hh-- )
{
ft_memcpy( write, read, pitch );
write += pitch;
ft_memcpy( write, read, pitch );
write += pitch;
ft_memcpy( write, read, pitch );
write += pitch;
read += pitch;
}
}
#endif /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */
FT_Outline_Translate( outline, x_shift, y_shift );
if ( error )
goto Exit;
slot->format = FT_GLYPH_FORMAT_BITMAP;
slot->bitmap_left = x_left;
slot->bitmap_top = y_top;
Exit:
if ( outline && origin )
FT_Outline_Translate( outline, -origin->x, -origin->y );
return error;
}
|
ft_smooth_render_generic( FT_Renderer render,
FT_GlyphSlot slot,
FT_Render_Mode mode,
const FT_Vector* origin,
FT_Render_Mode required_mode )
{
FT_Error error;
FT_Outline* outline = NULL;
FT_BBox cbox;
FT_UInt width, height, height_org, width_org, pitch;
FT_Bitmap* bitmap;
FT_Memory memory;
FT_Int hmul = mode == FT_RENDER_MODE_LCD;
FT_Int vmul = mode == FT_RENDER_MODE_LCD_V;
FT_Pos x_shift, y_shift, x_left, y_top;
FT_Raster_Params params;
/* check glyph image format */
if ( slot->format != render->glyph_format )
{
error = Smooth_Err_Invalid_Argument;
goto Exit;
}
/* check mode */
if ( mode != required_mode )
return Smooth_Err_Cannot_Render_Glyph;
outline = &slot->outline;
/* translate the outline to the new origin if needed */
if ( origin )
FT_Outline_Translate( outline, origin->x, origin->y );
/* compute the control box, and grid fit it */
FT_Outline_Get_CBox( outline, &cbox );
cbox.xMin = FT_PIX_FLOOR( cbox.xMin );
cbox.yMin = FT_PIX_FLOOR( cbox.yMin );
cbox.xMax = FT_PIX_CEIL( cbox.xMax );
cbox.yMax = FT_PIX_CEIL( cbox.yMax );
width = (FT_UInt)( ( cbox.xMax - cbox.xMin ) >> 6 );
height = (FT_UInt)( ( cbox.yMax - cbox.yMin ) >> 6 );
bitmap = &slot->bitmap;
memory = render->root.memory;
width_org = width;
height_org = height;
/* release old bitmap buffer */
if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP )
{
FT_FREE( bitmap->buffer );
slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP;
}
/* allocate new one */
pitch = width;
if ( hmul )
{
width = width * 3;
pitch = FT_PAD_CEIL( width, 4 );
}
if ( vmul )
height *= 3;
x_shift = (FT_Int) cbox.xMin;
y_shift = (FT_Int) cbox.yMin;
x_left = (FT_Int)( cbox.xMin >> 6 );
y_top = (FT_Int)( cbox.yMax >> 6 );
#ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING
if ( slot->library->lcd_filter_func )
{
FT_Int extra = slot->library->lcd_extra;
if ( hmul )
{
x_shift -= 64 * ( extra >> 1 );
width += 3 * extra;
pitch = FT_PAD_CEIL( width, 4 );
x_left -= extra >> 1;
}
if ( vmul )
{
y_shift -= 64 * ( extra >> 1 );
height += 3 * extra;
y_top += extra >> 1;
}
}
#endif
if ( pitch > 0xFFFF || height > 0xFFFF )
{
FT_ERROR(( "ft_smooth_render_generic: glyph too large: %d x %d\n",
width, height ));
return Smooth_Err_Raster_Overflow;
}
bitmap->pixel_mode = FT_PIXEL_MODE_GRAY;
bitmap->num_grays = 256;
bitmap->width = width;
goto Exit;
slot->internal->flags |= FT_GLYPH_OWN_BITMAP;
/* set up parameters */
params.target = bitmap;
params.source = outline;
params.flags = FT_RASTER_FLAG_AA;
#ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING
/* implode outline if needed */
{
FT_Vector* points = outline->points;
FT_Vector* points_end = points + outline->n_points;
FT_Vector* vec;
if ( hmul )
for ( vec = points; vec < points_end; vec++ )
vec->x *= 3;
if ( vmul )
for ( vec = points; vec < points_end; vec++ )
vec->y *= 3;
}
/* render outline into the bitmap */
error = render->raster_render( render->raster, ¶ms );
/* deflate outline if needed */
{
FT_Vector* points = outline->points;
FT_Vector* points_end = points + outline->n_points;
FT_Vector* vec;
if ( hmul )
for ( vec = points; vec < points_end; vec++ )
vec->x /= 3;
if ( vmul )
for ( vec = points; vec < points_end; vec++ )
vec->y /= 3;
}
if ( slot->library->lcd_filter_func )
slot->library->lcd_filter_func( bitmap, mode, slot->library );
#else /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */
/* render outline into bitmap */
error = render->raster_render( render->raster, ¶ms );
/* expand it horizontally */
if ( hmul )
{
FT_Byte* line = bitmap->buffer;
FT_UInt hh;
for ( hh = height_org; hh > 0; hh--, line += pitch )
{
FT_UInt xx;
FT_Byte* end = line + width;
for ( xx = width_org; xx > 0; xx-- )
{
FT_UInt pixel = line[xx-1];
end[-3] = (FT_Byte)pixel;
end[-2] = (FT_Byte)pixel;
end[-1] = (FT_Byte)pixel;
end -= 3;
}
}
}
/* expand it vertically */
if ( vmul )
{
FT_Byte* read = bitmap->buffer + ( height - height_org ) * pitch;
FT_Byte* write = bitmap->buffer;
FT_UInt hh;
for ( hh = height_org; hh > 0; hh-- )
{
ft_memcpy( write, read, pitch );
write += pitch;
ft_memcpy( write, read, pitch );
write += pitch;
ft_memcpy( write, read, pitch );
write += pitch;
read += pitch;
}
}
#endif /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */
FT_Outline_Translate( outline, x_shift, y_shift );
if ( error )
goto Exit;
slot->format = FT_GLYPH_FORMAT_BITMAP;
slot->bitmap_left = x_left;
slot->bitmap_top = y_top;
Exit:
if ( outline && origin )
FT_Outline_Translate( outline, -origin->x, -origin->y );
return error;
}
|
CVE-2009-0946
|
Multiple integer overflows in FreeType 2.3.9 and earlier allow remote attackers to execute arbitrary code via vectors related to large values in certain inputs in (1) smooth/ftsmooth.c, (2) sfnt/ttcmap.c, and (3) cff/cffload.c.
|
[
"CWE-189"
] |
[
{
"line_no": 60,
"text": " /* allocate new one, depends on pixel format */",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 60,
"text": " /* allocate new one */",
"char_start": null,
"char_end": null
},
{
"line_no": 101,
"text": " if ( pitch > 0xFFFF || height > 0xFFFF )",
"char_start": null,
"char_end": null
},
{
"line_no": 102,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 103,
"text": " FT_ERROR(( \"ft_smooth_render_generic: glyph too large: %d x %d\\n\",",
"char_start": null,
"char_end": null
},
{
"line_no": 104,
"text": " width, height ));",
"char_start": null,
"char_end": null
},
{
"line_no": 105,
"text": " return Smooth_Err_Raster_Overflow;",
"char_start": null,
"char_end": null
},
{
"line_no": 106,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 107,
"text": "",
"char_start": null,
"char_end": null
}
] | 121
|
primevul
|
primevul_savannah_0545ec1ca36b27cb928128870a83e5f668980bc5
|
0545ec1ca36b27cb928128870a83e5f668980bc5
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
cff_charset_load( CFF_Charset charset,
FT_UInt num_glyphs,
FT_Stream stream,
FT_ULong base_offset,
FT_ULong offset,
FT_Bool invert )
{
FT_Memory memory = stream->memory;
FT_Error error = CFF_Err_Ok;
FT_UShort glyph_sid;
/* If the the offset is greater than 2, we have to parse the */
/* charset table. */
if ( offset > 2 )
{
FT_UInt j;
charset->offset = base_offset + offset;
/* Get the format of the table. */
if ( FT_STREAM_SEEK( charset->offset ) ||
FT_READ_BYTE( charset->format ) )
goto Exit;
/* Allocate memory for sids. */
if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) )
goto Exit;
/* assign the .notdef glyph */
charset->sids[0] = 0;
switch ( charset->format )
{
case 0:
if ( num_glyphs > 0 )
{
if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) )
goto Exit;
for ( j = 1; j < num_glyphs; j++ )
charset->sids[j] = FT_GET_USHORT();
FT_FRAME_EXIT();
}
/* Read the first glyph sid of the range. */
if ( FT_READ_USHORT( glyph_sid ) )
goto Exit;
/* Read the number of glyphs in the range. */
if ( charset->format == 2 )
{
if ( FT_READ_USHORT( nleft ) )
goto Exit;
}
else
{
if ( FT_READ_BYTE( nleft ) )
goto Exit;
}
/* Fill in the range of sids -- `nleft + 1' glyphs. */
for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ )
charset->sids[j] = glyph_sid;
}
}
break;
default:
FT_ERROR(( "cff_charset_load: invalid table format!\n" ));
error = CFF_Err_Invalid_File_Format;
goto Exit;
}
|
cff_charset_load( CFF_Charset charset,
FT_UInt num_glyphs,
FT_Stream stream,
FT_ULong base_offset,
FT_ULong offset,
FT_Bool invert )
{
FT_Memory memory = stream->memory;
FT_Error error = CFF_Err_Ok;
FT_UShort glyph_sid;
/* If the the offset is greater than 2, we have to parse the */
/* charset table. */
if ( offset > 2 )
{
FT_UInt j;
charset->offset = base_offset + offset;
/* Get the format of the table. */
if ( FT_STREAM_SEEK( charset->offset ) ||
FT_READ_BYTE( charset->format ) )
goto Exit;
/* Allocate memory for sids. */
if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) )
goto Exit;
/* assign the .notdef glyph */
charset->sids[0] = 0;
switch ( charset->format )
{
case 0:
if ( num_glyphs > 0 )
{
if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) )
goto Exit;
for ( j = 1; j < num_glyphs; j++ )
{
FT_UShort sid = FT_GET_USHORT();
/* this constant is given in the CFF specification */
if ( sid < 65000 )
charset->sids[j] = sid;
else
{
FT_ERROR(( "cff_charset_load:"
" invalid SID value %d set to zero\n", sid ));
charset->sids[j] = 0;
}
}
FT_FRAME_EXIT();
}
/* Read the first glyph sid of the range. */
if ( FT_READ_USHORT( glyph_sid ) )
goto Exit;
/* Read the number of glyphs in the range. */
if ( charset->format == 2 )
{
if ( FT_READ_USHORT( nleft ) )
goto Exit;
}
else
{
if ( FT_READ_BYTE( nleft ) )
goto Exit;
}
/* Fill in the range of sids -- `nleft + 1' glyphs. */
for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ )
charset->sids[j] = glyph_sid;
}
}
break;
default:
FT_ERROR(( "cff_charset_load: invalid table format!\n" ));
error = CFF_Err_Invalid_File_Format;
goto Exit;
}
|
CVE-2009-0946
|
Multiple integer overflows in FreeType 2.3.9 and earlier allow remote attackers to execute arbitrary code via vectors related to large values in certain inputs in (1) smooth/ftsmooth.c, (2) sfnt/ttcmap.c, and (3) cff/cffload.c.
|
[
"CWE-189"
] |
[
{
"line_no": 43,
"text": " charset->sids[j] = FT_GET_USHORT();",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 43,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " FT_UShort sid = FT_GET_USHORT();",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": " /* this constant is given in the CFF specification */",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": " if ( sid < 65000 )",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": " charset->sids[j] = sid;",
"char_start": null,
"char_end": null
},
{
"line_no": 50,
"text": " else",
"char_start": null,
"char_end": null
},
{
"line_no": 51,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " FT_ERROR(( \"cff_charset_load:\"",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": " \" invalid SID value %d set to zero\\n\", sid ));",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " charset->sids[j] = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 55,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": " }",
"char_start": null,
"char_end": null
}
] | 122
|
primevul
|
primevul_netfilter_2ae1099a42e6a0f06de305ca13a842ac83d4683e
|
2ae1099a42e6a0f06de305ca13a842ac83d4683e
|
netfilter
|
https://git.netfilter.org/conntrack-tools
|
void add_param_to_argv(char *parsestart, int line)
{
int quote_open = 0, escaped = 0, param_len = 0;
char param_buffer[1024], *curchar;
/* After fighting with strtok enough, here's now
* a 'real' parser. According to Rusty I'm now no
} else {
param_buffer[param_len++] = *curchar;
for (curchar = parsestart; *curchar; curchar++) {
if (quote_open) {
if (escaped) {
param_buffer[param_len++] = *curchar;
escaped = 0;
continue;
} else if (*curchar == '\\') {
}
switch (*curchar) {
quote_open = 0;
*curchar = '"';
} else {
param_buffer[param_len++] = *curchar;
continue;
}
} else {
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
case ' ':
case '\t':
case '\n':
if (!param_len) {
/* two spaces? */
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
"Parameter too long!");
continue;
}
param_buffer[param_len] = '\0';
/* check if table name specified */
if ((param_buffer[0] == '-' &&
param_buffer[1] != '-' &&
strchr(param_buffer, 't')) ||
(!strncmp(param_buffer, "--t", 3) &&
!strncmp(param_buffer, "--table", strlen(param_buffer)))) {
xtables_error(PARAMETER_PROBLEM,
"The -t option (seen in line %u) cannot be used in %s.\n",
line, xt_params->program_name);
}
add_argv(param_buffer, 0);
param_len = 0;
}
|
void add_param_to_argv(char *parsestart, int line)
{
int quote_open = 0, escaped = 0;
struct xt_param_buf param = {};
char *curchar;
/* After fighting with strtok enough, here's now
* a 'real' parser. According to Rusty I'm now no
} else {
param_buffer[param_len++] = *curchar;
for (curchar = parsestart; *curchar; curchar++) {
if (quote_open) {
if (escaped) {
add_param(¶m, curchar);
escaped = 0;
continue;
} else if (*curchar == '\\') {
}
switch (*curchar) {
quote_open = 0;
*curchar = '"';
} else {
add_param(¶m, curchar);
continue;
}
} else {
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
case ' ':
case '\t':
case '\n':
if (!param.len) {
/* two spaces? */
continue;
}
break;
default:
/* regular character, copy to buffer */
add_param(¶m, curchar);
continue;
}
param.buffer[param.len] = '\0';
/* check if table name specified */
if ((param.buffer[0] == '-' &&
param.buffer[1] != '-' &&
strchr(param.buffer, 't')) ||
(!strncmp(param.buffer, "--t", 3) &&
!strncmp(param.buffer, "--table", strlen(param.buffer)))) {
xtables_error(PARAMETER_PROBLEM,
"The -t option (seen in line %u) cannot be used in %s.\n",
line, xt_params->program_name);
}
add_argv(param.buffer, 0);
param.len = 0;
}
|
CVE-2019-11360
|
A buffer overflow in iptables-restore in netfilter iptables 1.8.2 allows an attacker to (at least) crash the program or potentially gain code execution via a specially crafted iptables-save file. This is related to add_param_to_argv in xshared.c.
|
[
"CWE-119"
] |
[
{
"line_no": 3,
"text": "\tint quote_open = 0, escaped = 0, param_len = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 4,
"text": "\tchar param_buffer[1024], *curchar;",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": "\t\t\t\tparam_buffer[param_len++] = *curchar;",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": "\t\t\t\tparam_buffer[param_len++] = *curchar;",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": "\t\t\tif (!param_len) {",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": "\t\t\tparam_buffer[param_len++] = *curchar;",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": "\t\t\tif (param_len >= sizeof(param_buffer))",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": "\t\t\t\txtables_error(PARAMETER_PROBLEM,",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": "\t\t\t\t\t \"Parameter too long!\");",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": "\t\tparam_buffer[param_len] = '\\0';",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": "\t\tif ((param_buffer[0] == '-' &&",
"char_start": null,
"char_end": null
},
{
"line_no": 57,
"text": "\t\t param_buffer[1] != '-' &&",
"char_start": null,
"char_end": null
},
{
"line_no": 58,
"text": "\t\t strchr(param_buffer, 't')) ||",
"char_start": null,
"char_end": null
},
{
"line_no": 59,
"text": "\t\t (!strncmp(param_buffer, \"--t\", 3) &&",
"char_start": null,
"char_end": null
},
{
"line_no": 60,
"text": "\t\t !strncmp(param_buffer, \"--table\", strlen(param_buffer)))) {",
"char_start": null,
"char_end": null
},
{
"line_no": 66,
"text": "\t\tadd_argv(param_buffer, 0);",
"char_start": null,
"char_end": null
},
{
"line_no": 67,
"text": "\t\tparam_len = 0;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 3,
"text": "\tint quote_open = 0, escaped = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 4,
"text": "\tstruct xt_param_buf param = {};",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": "\tchar *curchar;",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": "\t\t\t\tadd_param(¶m, curchar);",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": "\t\t\t\tadd_param(¶m, curchar);",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": "\t\t\tif (!param.len) {",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": "\t\t\tadd_param(¶m, curchar);",
"char_start": null,
"char_end": null
},
{
"line_no": 51,
"text": "\t\tparam.buffer[param.len] = '\\0';",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": "\t\tif ((param.buffer[0] == '-' &&",
"char_start": null,
"char_end": null
},
{
"line_no": 55,
"text": "\t\t param.buffer[1] != '-' &&",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": "\t\t strchr(param.buffer, 't')) ||",
"char_start": null,
"char_end": null
},
{
"line_no": 57,
"text": "\t\t (!strncmp(param.buffer, \"--t\", 3) &&",
"char_start": null,
"char_end": null
},
{
"line_no": 58,
"text": "\t\t !strncmp(param.buffer, \"--table\", strlen(param.buffer)))) {",
"char_start": null,
"char_end": null
},
{
"line_no": 64,
"text": "\t\tadd_argv(param.buffer, 0);",
"char_start": null,
"char_end": null
},
{
"line_no": 65,
"text": "\t\tparam.len = 0;",
"char_start": null,
"char_end": null
}
] | 123
|
primevul
|
primevul_accountsservice_f9abd359f71a5bce421b9ae23432f539a067847a
|
f9abd359f71a5bce421b9ae23432f539a067847a
|
accountsservice
|
https://cgit.freedesktop.org/accountsservice/commit/?id=f9abd359f71a5bce421b9ae23432f539a067847a
|
user_change_icon_file_authorized_cb (Daemon *daemon,
User *user,
GDBusMethodInvocation *context,
gpointer data)
{
g_autofree gchar *filename = NULL;
g_autoptr(GFile) file = NULL;
g_autoptr(GFileInfo) info = NULL;
guint32 mode;
GFileType type;
guint64 size;
filename = g_strdup (data);
if (filename == NULL ||
*filename == '\0') {
g_autofree gchar *dest_path = NULL;
g_autoptr(GFile) dest = NULL;
g_autoptr(GError) error = NULL;
g_clear_pointer (&filename, g_free);
dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL);
dest = g_file_new_for_path (dest_path);
if (!g_file_delete (dest, NULL, &error) &&
!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message);
return;
}
goto icon_saved;
}
file = g_file_new_for_path (filename);
info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
return;
}
|
user_change_icon_file_authorized_cb (Daemon *daemon,
User *user,
GDBusMethodInvocation *context,
gpointer data)
{
g_autofree gchar *filename = NULL;
g_autoptr(GFile) file = NULL;
g_autoptr(GFileInfo) info = NULL;
guint32 mode;
GFileType type;
guint64 size;
filename = g_strdup (data);
if (filename == NULL ||
*filename == '\0') {
g_autofree gchar *dest_path = NULL;
g_autoptr(GFile) dest = NULL;
g_autoptr(GError) error = NULL;
g_clear_pointer (&filename, g_free);
dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL);
dest = g_file_new_for_path (dest_path);
if (!g_file_delete (dest, NULL, &error) &&
!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message);
return;
}
goto icon_saved;
}
file = g_file_new_for_path (filename);
g_clear_pointer (&filename, g_free);
/* Canonicalize path so we can call g_str_has_prefix on it
* below without concern for ../ path components moving outside
* the prefix
*/
filename = g_file_get_path (file);
info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
return;
}
|
CVE-2018-14036
|
Directory Traversal with ../ sequences occurs in AccountsService before 0.6.50 because of an insufficient path check in user_change_icon_file_authorized_cb() in user.c.
|
[
"CWE-22"
] |
[] |
[
{
"line_no": 36,
"text": " g_clear_pointer (&filename, g_free);",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " /* Canonicalize path so we can call g_str_has_prefix on it",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": " * below without concern for ../ path components moving outside",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": " * the prefix",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": " filename = g_file_get_path (file);",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": "",
"char_start": null,
"char_end": null
}
] | 124
|
primevul
|
primevul_xserver_215f894965df5fb0bb45b107d84524e700d2073c
|
215f894965df5fb0bb45b107d84524e700d2073c
|
xserver
|
http://gitweb.freedesktop.org/?p=xorg/xserver
|
ProcSendEvent(ClientPtr client)
{
WindowPtr pWin;
WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */
DeviceIntPtr dev = PickPointer(client);
DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD);
SpritePtr pSprite = dev->spriteInfo->sprite;
REQUEST(xSendEventReq);
REQUEST_SIZE_MATCH(xSendEventReq);
/* libXext and other extension libraries may set the bit indicating
* that this event came from a SendEvent request so remove it
* since otherwise the event type may fail the range checks
* and cause an invalid BadValue error to be returned.
*
* This is safe to do since we later add the SendEvent bit (0x80)
* back in once we send the event to the client */
stuff->event.u.u.type &= ~(SEND_EVENT_BIT);
/* The client's event type must be a core event type or one defined by an
extension. */
if (!((stuff->event.u.u.type > X_Reply &&
stuff->event.u.u.type < LASTEvent) ||
(stuff->event.u.u.type >= EXTENSION_EVENT_BASE &&
stuff->event.u.u.type < (unsigned) lastEvent))) {
client->errorValue = stuff->event.u.u.type;
return BadValue;
}
if (stuff->event.u.u.type == ClientMessage &&
stuff->event.u.u.detail != 8 &&
stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) {
}
if (stuff->destination == PointerWindow)
pWin = pSprite->win;
else if (stuff->destination == InputFocus) {
WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin;
if (inputFocus == NoneWin)
return Success;
/* If the input focus is PointerRootWin, send the event to where
the pointer is if possible, then perhaps propogate up to root. */
if (inputFocus == PointerRootWin)
inputFocus = GetCurrentRootWindow(dev);
if (IsParent(inputFocus, pSprite->win)) {
effectiveFocus = inputFocus;
pWin = pSprite->win;
}
else
effectiveFocus = pWin = inputFocus;
}
else
dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess);
if (!pWin)
return BadWindow;
if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) {
client->errorValue = stuff->propagate;
return BadValue;
}
stuff->event.u.u.type |= SEND_EVENT_BIT;
if (stuff->propagate) {
for (; pWin; pWin = pWin->parent) {
if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin,
&stuff->event, 1))
return Success;
if (DeliverEventsToWindow(dev, pWin,
&stuff->event, 1, stuff->eventMask,
NullGrab))
return Success;
if (pWin == effectiveFocus)
return Success;
stuff->eventMask &= ~wDontPropagateMask(pWin);
if (!stuff->eventMask)
break;
}
}
else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1))
DeliverEventsToWindow(dev, pWin, &stuff->event,
1, stuff->eventMask, NullGrab);
return Success;
}
|
ProcSendEvent(ClientPtr client)
{
WindowPtr pWin;
WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */
DeviceIntPtr dev = PickPointer(client);
DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD);
SpritePtr pSprite = dev->spriteInfo->sprite;
REQUEST(xSendEventReq);
REQUEST_SIZE_MATCH(xSendEventReq);
/* libXext and other extension libraries may set the bit indicating
* that this event came from a SendEvent request so remove it
* since otherwise the event type may fail the range checks
* and cause an invalid BadValue error to be returned.
*
* This is safe to do since we later add the SendEvent bit (0x80)
* back in once we send the event to the client */
stuff->event.u.u.type &= ~(SEND_EVENT_BIT);
/* The client's event type must be a core event type or one defined by an
extension. */
if (!((stuff->event.u.u.type > X_Reply &&
stuff->event.u.u.type < LASTEvent) ||
(stuff->event.u.u.type >= EXTENSION_EVENT_BASE &&
stuff->event.u.u.type < (unsigned) lastEvent))) {
client->errorValue = stuff->event.u.u.type;
return BadValue;
}
/* Generic events can have variable size, but SendEvent request holds
exactly 32B of event data. */
if (stuff->event.u.u.type == GenericEvent) {
client->errorValue = stuff->event.u.u.type;
return BadValue;
}
if (stuff->event.u.u.type == ClientMessage &&
stuff->event.u.u.detail != 8 &&
stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) {
}
if (stuff->destination == PointerWindow)
pWin = pSprite->win;
else if (stuff->destination == InputFocus) {
WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin;
if (inputFocus == NoneWin)
return Success;
/* If the input focus is PointerRootWin, send the event to where
the pointer is if possible, then perhaps propogate up to root. */
if (inputFocus == PointerRootWin)
inputFocus = GetCurrentRootWindow(dev);
if (IsParent(inputFocus, pSprite->win)) {
effectiveFocus = inputFocus;
pWin = pSprite->win;
}
else
effectiveFocus = pWin = inputFocus;
}
else
dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess);
if (!pWin)
return BadWindow;
if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) {
client->errorValue = stuff->propagate;
return BadValue;
}
stuff->event.u.u.type |= SEND_EVENT_BIT;
if (stuff->propagate) {
for (; pWin; pWin = pWin->parent) {
if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin,
&stuff->event, 1))
return Success;
if (DeliverEventsToWindow(dev, pWin,
&stuff->event, 1, stuff->eventMask,
NullGrab))
return Success;
if (pWin == effectiveFocus)
return Success;
stuff->eventMask &= ~wDontPropagateMask(pWin);
if (!stuff->eventMask)
break;
}
}
else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1))
DeliverEventsToWindow(dev, pWin, &stuff->event,
1, stuff->eventMask, NullGrab);
return Success;
}
|
CVE-2017-10971
|
In the X.Org X server before 2017-06-19, a user authenticated to an X Session could crash or execute code in the context of the X Server by exploiting a stack overflow in the endianness conversion of X Events.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 33,
"text": " /* Generic events can have variable size, but SendEvent request holds",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " exactly 32B of event data. */",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " if (stuff->event.u.u.type == GenericEvent) {",
"char_start": null,
"char_end": null
},
{
"line_no": 36,
"text": " client->errorValue = stuff->event.u.u.type;",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": " return BadValue;",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " }",
"char_start": null,
"char_end": null
}
] | 128
|
primevul
|
primevul_xserver_8caed4df36b1f802b4992edcfd282cbeeec35d9d
|
8caed4df36b1f802b4992edcfd282cbeeec35d9d
|
xserver
|
http://gitweb.freedesktop.org/?p=xorg/xserver
|
ProcXSendExtensionEvent(ClientPtr client)
{
int ret;
DeviceIntPtr dev;
xEvent *first;
XEventClass *list;
struct tmask tmp[EMASKSIZE];
REQUEST(xSendExtensionEventReq);
REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq);
if (stuff->length !=
bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count +
(stuff->num_events * bytes_to_int32(sizeof(xEvent))))
return BadLength;
ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess);
if (ret != Success)
return ret;
if (stuff->num_events == 0)
return ret;
/* The client's event type must be one defined by an extension. */
first = ((xEvent *) &stuff[1]);
if (!((EXTENSION_EVENT_BASE <= first->u.u.type) &&
(first->u.u.type < lastEvent))) {
client->errorValue = first->u.u.type;
return BadValue;
}
list = (XEventClass *) (first + stuff->num_events);
return ret;
ret = (SendEvent(client, dev, stuff->destination,
stuff->propagate, (xEvent *) &stuff[1],
tmp[stuff->deviceid].mask, stuff->num_events));
return ret;
}
|
ProcXSendExtensionEvent(ClientPtr client)
{
int ret, i;
DeviceIntPtr dev;
xEvent *first;
XEventClass *list;
struct tmask tmp[EMASKSIZE];
REQUEST(xSendExtensionEventReq);
REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq);
if (stuff->length !=
bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count +
(stuff->num_events * bytes_to_int32(sizeof(xEvent))))
return BadLength;
ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess);
if (ret != Success)
return ret;
if (stuff->num_events == 0)
return ret;
/* The client's event type must be one defined by an extension. */
first = ((xEvent *) &stuff[1]);
for (i = 0; i < stuff->num_events; i++) {
if (!((EXTENSION_EVENT_BASE <= first[i].u.u.type) &&
(first[i].u.u.type < lastEvent))) {
client->errorValue = first[i].u.u.type;
return BadValue;
}
}
list = (XEventClass *) (first + stuff->num_events);
return ret;
ret = (SendEvent(client, dev, stuff->destination,
stuff->propagate, (xEvent *) &stuff[1],
tmp[stuff->deviceid].mask, stuff->num_events));
return ret;
}
|
CVE-2017-10971
|
In the X.Org X server before 2017-06-19, a user authenticated to an X Session could crash or execute code in the context of the X Server by exploiting a stack overflow in the endianness conversion of X Events.
|
[
"CWE-119"
] |
[
{
"line_no": 3,
"text": " int ret;",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " if (!((EXTENSION_EVENT_BASE <= first->u.u.type) &&",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " (first->u.u.type < lastEvent))) {",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " client->errorValue = first->u.u.type;",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " return BadValue;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 3,
"text": " int ret, i;",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " for (i = 0; i < stuff->num_events; i++) {",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " if (!((EXTENSION_EVENT_BASE <= first[i].u.u.type) &&",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " (first[i].u.u.type < lastEvent))) {",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " client->errorValue = first[i].u.u.type;",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": " return BadValue;",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " }",
"char_start": null,
"char_end": null
}
] | 129
|
primevul
|
primevul_openssl_9a0db453ba017ebcaccbee933ee6511a9ae4d1c8
|
9a0db453ba017ebcaccbee933ee6511a9ae4d1c8
|
openssl
|
https://github.com/openssl/openssl
|
int X509_verify_cert(X509_STORE_CTX *ctx)
{
X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;
int bad_chain = 0;
X509_VERIFY_PARAM *param = ctx->param;
int depth, i, ok = 0;
int num, j, retry;
int (*cb) (int xok, X509_STORE_CTX *xctx);
STACK_OF(X509) *sktmp = NULL;
if (ctx->cert == NULL) {
X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
return -1;
}
cb = ctx->verify_cb;
/*
* first we make sure the chain we are going to build is present and that
* the first entry is in place
*/
if (ctx->chain == NULL) {
if (((ctx->chain = sk_X509_new_null()) == NULL) ||
(!sk_X509_push(ctx->chain, ctx->cert))) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
ctx->last_untrusted = 1;
}
/* We use a temporary STACK so we can chop and hack at it */
if (ctx->untrusted != NULL
&& (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
num = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, num - 1);
depth = param->depth;
for (;;) {
/* If we have enough, we break */
if (depth < num)
break; /* FIXME: If this happens, we should take
* note of it and, if appropriate, use the
* X509_V_ERR_CERT_CHAIN_TOO_LONG error code
* later. */
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
/* If we were passed a cert chain, use it first */
if (ctx->untrusted != NULL) {
xtmp = find_issuer(ctx, sktmp, x);
if (xtmp != NULL) {
if (!sk_X509_push(ctx->chain, xtmp)) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
(void)sk_X509_delete_ptr(sktmp, xtmp);
ctx->last_untrusted++;
x = xtmp;
num++;
/*
* reparse the full chain for the next one
*/
continue;
}
}
break;
}
/* Remember how many untrusted certs we have */
j = num;
/*
* at this point, chain should contain a list of untrusted certificates.
* We now need to add at least one trusted one, if possible, otherwise we
* complain.
*/
do {
/*
* Examine last certificate in chain and see if it is self signed.
*/
i = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, i - 1);
if (ctx->check_issued(ctx, x, x)) {
/* we have a self signed certificate */
if (sk_X509_num(ctx->chain) == 1) {
/*
* We have a single self signed certificate: see if we can
* find it in the store. We must have an exact match to avoid
* possible impersonation.
*/
ok = ctx->get_issuer(&xtmp, ctx, x);
if ((ok <= 0) || X509_cmp(x, xtmp)) {
ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
ctx->current_cert = x;
ctx->error_depth = i - 1;
if (ok == 1)
X509_free(xtmp);
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
} else {
/*
* We have a match: replace certificate with store
* version so we get any trust settings.
*/
X509_free(x);
x = xtmp;
(void)sk_X509_set(ctx->chain, i - 1, x);
ctx->last_untrusted = 0;
}
} else {
/*
* extract and save self signed certificate for later use
*/
chain_ss = sk_X509_pop(ctx->chain);
ctx->last_untrusted--;
num--;
j--;
x = sk_X509_value(ctx->chain, num - 1);
}
}
/* We now lookup certs from the certificate store */
for (;;) {
/* If we have enough, we break */
if (depth < num)
break;
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
ok = ctx->get_issuer(&xtmp, ctx, x);
if (ok < 0)
return ok;
if (ok == 0)
break;
x = xtmp;
if (!sk_X509_push(ctx->chain, x)) {
X509_free(xtmp);
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
return 0;
}
num++;
}
/*
* If we haven't got a least one certificate from our store then check
* if there is an alternative chain that could be used. We only do this
* if the user hasn't switched off alternate chain checking
*/
retry = 0;
if (j == ctx->last_untrusted &&
!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {
while (j-- > 1) {
xtmp2 = sk_X509_value(ctx->chain, j - 1);
ok = ctx->get_issuer(&xtmp, ctx, xtmp2);
if (ok < 0)
goto end;
/* Check if we found an alternate chain */
if (ok > 0) {
/*
* Free up the found cert we'll add it again later
*/
X509_free(xtmp);
/*
* Dump all the certs above this point - we've found an
* alternate chain
*/
while (num > j) {
xtmp = sk_X509_pop(ctx->chain);
X509_free(xtmp);
num--;
ctx->last_untrusted--;
}
retry = 1;
break;
}
}
}
} while (retry);
/* Is last certificate looked up self signed? */
if (!ctx->check_issued(ctx, x, x)) {
if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
if (ctx->last_untrusted >= num)
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
else
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
ctx->current_cert = x;
} else {
sk_X509_push(ctx->chain, chain_ss);
num++;
ctx->last_untrusted = num;
ctx->current_cert = chain_ss;
ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
chain_ss = NULL;
}
ctx->error_depth = num - 1;
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
}
/* We have the chain complete: now we need to check its purpose */
ok = check_chain_extensions(ctx);
if (!ok)
goto end;
/* Check name constraints */
ok = check_name_constraints(ctx);
if (!ok)
goto end;
/* The chain extensions are OK: check trust */
if (param->trust > 0)
ok = check_trust(ctx);
if (!ok)
goto end;
/* We may as well copy down any DSA parameters that are required */
X509_get_pubkey_parameters(NULL, ctx->chain);
/*
* Check revocation status: we do this after copying parameters because
* they may be needed for CRL signature verification.
*/
ok = ctx->check_revocation(ctx);
if (!ok)
goto end;
/* At this point, we have a chain and need to verify it */
if (ctx->verify != NULL)
ok = ctx->verify(ctx);
else
ok = internal_verify(ctx);
if (!ok)
goto end;
#ifndef OPENSSL_NO_RFC3779
/* RFC 3779 path validation, now that CRL check has been done */
ok = v3_asid_validate_path(ctx);
if (!ok)
goto end;
ok = v3_addr_validate_path(ctx);
if (!ok)
goto end;
#endif
/* If we get this far evaluate policies */
if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
ok = ctx->check_policy(ctx);
if (!ok)
goto end;
if (0) {
end:
X509_get_pubkey_parameters(NULL, ctx->chain);
}
if (sktmp != NULL)
sk_X509_free(sktmp);
if (chain_ss != NULL)
X509_free(chain_ss);
return ok;
}
|
int X509_verify_cert(X509_STORE_CTX *ctx)
{
X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;
int bad_chain = 0;
X509_VERIFY_PARAM *param = ctx->param;
int depth, i, ok = 0;
int num, j, retry;
int (*cb) (int xok, X509_STORE_CTX *xctx);
STACK_OF(X509) *sktmp = NULL;
if (ctx->cert == NULL) {
X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
return -1;
}
cb = ctx->verify_cb;
/*
* first we make sure the chain we are going to build is present and that
* the first entry is in place
*/
if (ctx->chain == NULL) {
if (((ctx->chain = sk_X509_new_null()) == NULL) ||
(!sk_X509_push(ctx->chain, ctx->cert))) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
ctx->last_untrusted = 1;
}
/* We use a temporary STACK so we can chop and hack at it */
if (ctx->untrusted != NULL
&& (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
num = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, num - 1);
depth = param->depth;
for (;;) {
/* If we have enough, we break */
if (depth < num)
break; /* FIXME: If this happens, we should take
* note of it and, if appropriate, use the
* X509_V_ERR_CERT_CHAIN_TOO_LONG error code
* later. */
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
/* If we were passed a cert chain, use it first */
if (ctx->untrusted != NULL) {
xtmp = find_issuer(ctx, sktmp, x);
if (xtmp != NULL) {
if (!sk_X509_push(ctx->chain, xtmp)) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
(void)sk_X509_delete_ptr(sktmp, xtmp);
ctx->last_untrusted++;
x = xtmp;
num++;
/*
* reparse the full chain for the next one
*/
continue;
}
}
break;
}
/* Remember how many untrusted certs we have */
j = num;
/*
* at this point, chain should contain a list of untrusted certificates.
* We now need to add at least one trusted one, if possible, otherwise we
* complain.
*/
do {
/*
* Examine last certificate in chain and see if it is self signed.
*/
i = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, i - 1);
if (ctx->check_issued(ctx, x, x)) {
/* we have a self signed certificate */
if (sk_X509_num(ctx->chain) == 1) {
/*
* We have a single self signed certificate: see if we can
* find it in the store. We must have an exact match to avoid
* possible impersonation.
*/
ok = ctx->get_issuer(&xtmp, ctx, x);
if ((ok <= 0) || X509_cmp(x, xtmp)) {
ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
ctx->current_cert = x;
ctx->error_depth = i - 1;
if (ok == 1)
X509_free(xtmp);
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
} else {
/*
* We have a match: replace certificate with store
* version so we get any trust settings.
*/
X509_free(x);
x = xtmp;
(void)sk_X509_set(ctx->chain, i - 1, x);
ctx->last_untrusted = 0;
}
} else {
/*
* extract and save self signed certificate for later use
*/
chain_ss = sk_X509_pop(ctx->chain);
ctx->last_untrusted--;
num--;
j--;
x = sk_X509_value(ctx->chain, num - 1);
}
}
/* We now lookup certs from the certificate store */
for (;;) {
/* If we have enough, we break */
if (depth < num)
break;
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
ok = ctx->get_issuer(&xtmp, ctx, x);
if (ok < 0)
return ok;
if (ok == 0)
break;
x = xtmp;
if (!sk_X509_push(ctx->chain, x)) {
X509_free(xtmp);
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
return 0;
}
num++;
}
/*
* If we haven't got a least one certificate from our store then check
* if there is an alternative chain that could be used. We only do this
* if the user hasn't switched off alternate chain checking
*/
retry = 0;
if (j == ctx->last_untrusted &&
!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {
while (j-- > 1) {
xtmp2 = sk_X509_value(ctx->chain, j - 1);
ok = ctx->get_issuer(&xtmp, ctx, xtmp2);
if (ok < 0)
goto end;
/* Check if we found an alternate chain */
if (ok > 0) {
/*
* Free up the found cert we'll add it again later
*/
X509_free(xtmp);
/*
* Dump all the certs above this point - we've found an
* alternate chain
*/
while (num > j) {
xtmp = sk_X509_pop(ctx->chain);
X509_free(xtmp);
num--;
}
ctx->last_untrusted = sk_X509_num(ctx->chain);
retry = 1;
break;
}
}
}
} while (retry);
/* Is last certificate looked up self signed? */
if (!ctx->check_issued(ctx, x, x)) {
if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
if (ctx->last_untrusted >= num)
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
else
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
ctx->current_cert = x;
} else {
sk_X509_push(ctx->chain, chain_ss);
num++;
ctx->last_untrusted = num;
ctx->current_cert = chain_ss;
ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
chain_ss = NULL;
}
ctx->error_depth = num - 1;
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
}
/* We have the chain complete: now we need to check its purpose */
ok = check_chain_extensions(ctx);
if (!ok)
goto end;
/* Check name constraints */
ok = check_name_constraints(ctx);
if (!ok)
goto end;
/* The chain extensions are OK: check trust */
if (param->trust > 0)
ok = check_trust(ctx);
if (!ok)
goto end;
/* We may as well copy down any DSA parameters that are required */
X509_get_pubkey_parameters(NULL, ctx->chain);
/*
* Check revocation status: we do this after copying parameters because
* they may be needed for CRL signature verification.
*/
ok = ctx->check_revocation(ctx);
if (!ok)
goto end;
/* At this point, we have a chain and need to verify it */
if (ctx->verify != NULL)
ok = ctx->verify(ctx);
else
ok = internal_verify(ctx);
if (!ok)
goto end;
#ifndef OPENSSL_NO_RFC3779
/* RFC 3779 path validation, now that CRL check has been done */
ok = v3_asid_validate_path(ctx);
if (!ok)
goto end;
ok = v3_addr_validate_path(ctx);
if (!ok)
goto end;
#endif
/* If we get this far evaluate policies */
if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
ok = ctx->check_policy(ctx);
if (!ok)
goto end;
if (0) {
end:
X509_get_pubkey_parameters(NULL, ctx->chain);
}
if (sktmp != NULL)
sk_X509_free(sktmp);
if (chain_ss != NULL)
X509_free(chain_ss);
return ok;
}
|
CVE-2015-1793
|
The X509_verify_cert function in crypto/x509/x509_vfy.c in OpenSSL 1.0.1n, 1.0.1o, 1.0.2b, and 1.0.2c does not properly process X.509 Basic Constraints cA values during identification of alternative certificate chains, which allows remote attackers to spoof a Certification Authority role and trigger unintended certificate verifications via a valid leaf certificate.
|
[
"CWE-254"
] |
[
{
"line_no": 180,
"text": " ctx->last_untrusted--;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 181,
"text": " ctx->last_untrusted = sk_X509_num(ctx->chain);",
"char_start": null,
"char_end": null
}
] | 130
|
primevul
|
primevul_savannah_cb07844454d8cc9fb21f53ace75975f91185a120
|
cb07844454d8cc9fb21f53ace75975f91185a120
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
pax_decode_header (struct tar_sparse_file *file)
{
if (file->stat_info->sparse_major > 0)
{
uintmax_t u;
char nbuf[UINTMAX_STRSIZE_BOUND];
union block *blk;
char *p;
size_t i;
off_t start;
#define COPY_BUF(b,buf,src) do \
{ \
char *endp = b->buffer + BLOCKSIZE; \
char *dst = buf; \
do \
{ \
if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \
{ \
ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \
file->stat_info->orig_file_name)); \
return false; \
} \
if (src == endp) \
{ \
set_next_block_after (b); \
b = find_next_block (); \
src = b->buffer; \
endp = b->buffer + BLOCKSIZE; \
} \
while (*dst++ != '\n'); \
dst[-1] = 0; \
} while (0)
start = current_block_ordinal ();
set_next_block_after (current_header);
start = current_block_ordinal ();
set_next_block_after (current_header);
blk = find_next_block ();
p = blk->buffer;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))
}
file->stat_info->sparse_map_size = u;
file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,
sizeof (*file->stat_info->sparse_map));
file->stat_info->sparse_map_avail = 0;
for (i = 0; i < file->stat_info->sparse_map_size; i++)
{
struct sp_array sp;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.offset = u;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.numbytes = u;
sparse_add_map (file->stat_info, &sp);
}
set_next_block_after (blk);
file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);
}
return true;
}
|
pax_decode_header (struct tar_sparse_file *file)
{
if (file->stat_info->sparse_major > 0)
{
uintmax_t u;
char nbuf[UINTMAX_STRSIZE_BOUND];
union block *blk;
char *p;
size_t i;
off_t start;
#define COPY_BUF(b,buf,src) do \
{ \
char *endp = b->buffer + BLOCKSIZE; \
char *dst = buf; \
do \
{ \
if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \
{ \
ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \
file->stat_info->orig_file_name)); \
return false; \
} \
if (src == endp) \
{ \
set_next_block_after (b); \
b = find_next_block (); \
if (!b) \
FATAL_ERROR ((0, 0, _("Unexpected EOF in archive"))); \
src = b->buffer; \
endp = b->buffer + BLOCKSIZE; \
} \
while (*dst++ != '\n'); \
dst[-1] = 0; \
} while (0)
start = current_block_ordinal ();
set_next_block_after (current_header);
start = current_block_ordinal ();
set_next_block_after (current_header);
blk = find_next_block ();
if (!blk)
FATAL_ERROR ((0, 0, _("Unexpected EOF in archive")));
p = blk->buffer;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))
}
file->stat_info->sparse_map_size = u;
file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,
sizeof (*file->stat_info->sparse_map));
file->stat_info->sparse_map_avail = 0;
for (i = 0; i < file->stat_info->sparse_map_size; i++)
{
struct sp_array sp;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.offset = u;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.numbytes = u;
sparse_add_map (file->stat_info, &sp);
}
set_next_block_after (blk);
file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);
}
return true;
}
|
CVE-2019-9923
|
pax_decode_header in sparse.c in GNU Tar before 1.32 had a NULL pointer dereference when parsing certain archives that have malformed extended headers.
|
[
"CWE-476"
] |
[] |
[
{
"line_no": 28,
"text": " if (!b) \\",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " FATAL_ERROR ((0, 0, _(\"Unexpected EOF in archive\"))); \\",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": " if (!blk)",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": " FATAL_ERROR ((0, 0, _(\"Unexpected EOF in archive\")));",
"char_start": null,
"char_end": null
}
] | 132
|
primevul
|
primevul_ghostscript_7755e67116e8973ee0e3b22d653df026a84fa01b
|
7755e67116e8973ee0e3b22d653df026a84fa01b
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
static void Ins_MDRP( INS_ARG )
{
Int point;
TT_F26Dot6 distance,
org_dist;
point = (Int)args[0];
if ( BOUNDS( args[0], CUR.zp1.n_points ) )
{
/* Current version of FreeType silently ignores this out of bounds error
* and drops the instruction, see bug #691121
return;
}
/* XXX: Is there some undocumented feature while in the */
/* twilight zone? */
org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] -
CUR.zp0.org_x[CUR.GS.rp0],
CUR.zp1.org_y[point] -
CUR.zp0.org_y[CUR.GS.rp0] );
/* single width cutin test */
if ( ABS(org_dist) < CUR.GS.single_width_cutin )
{
if ( org_dist >= 0 )
org_dist = CUR.GS.single_width_value;
else
org_dist = -CUR.GS.single_width_value;
}
/* round flag */
if ( (CUR.opcode & 4) != 0 )
distance = CUR_Func_round( org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
else
distance = Round_None( EXEC_ARGS
org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
/* minimum distance flag */
if ( (CUR.opcode & 8) != 0 )
{
if ( org_dist >= 0 )
{
if ( distance < CUR.GS.minimum_distance )
distance = CUR.GS.minimum_distance;
}
else
{
if ( distance > -CUR.GS.minimum_distance )
distance = -CUR.GS.minimum_distance;
}
}
/* now move the point */
org_dist = CUR_Func_project( CUR.zp1.cur_x[point] -
CUR.zp0.cur_x[CUR.GS.rp0],
CUR.zp1.cur_y[point] -
CUR.zp0.cur_y[CUR.GS.rp0] );
CUR_Func_move( &CUR.zp1, point, distance - org_dist );
CUR.GS.rp1 = CUR.GS.rp0;
CUR.GS.rp2 = point;
if ( (CUR.opcode & 16) != 0 )
CUR.GS.rp0 = point;
}
|
static void Ins_MDRP( INS_ARG )
{
Int point;
TT_F26Dot6 distance,
org_dist;
point = (Int)args[0];
if ( BOUNDS( args[0], CUR.zp1.n_points ) ||
BOUNDS( CUR.GS.rp0, CUR.zp0.n_points) )
{
/* Current version of FreeType silently ignores this out of bounds error
* and drops the instruction, see bug #691121
return;
}
/* XXX: Is there some undocumented feature while in the */
/* twilight zone? */
org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] -
CUR.zp0.org_x[CUR.GS.rp0],
CUR.zp1.org_y[point] -
CUR.zp0.org_y[CUR.GS.rp0] );
/* single width cutin test */
if ( ABS(org_dist) < CUR.GS.single_width_cutin )
{
if ( org_dist >= 0 )
org_dist = CUR.GS.single_width_value;
else
org_dist = -CUR.GS.single_width_value;
}
/* round flag */
if ( (CUR.opcode & 4) != 0 )
distance = CUR_Func_round( org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
else
distance = Round_None( EXEC_ARGS
org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
/* minimum distance flag */
if ( (CUR.opcode & 8) != 0 )
{
if ( org_dist >= 0 )
{
if ( distance < CUR.GS.minimum_distance )
distance = CUR.GS.minimum_distance;
}
else
{
if ( distance > -CUR.GS.minimum_distance )
distance = -CUR.GS.minimum_distance;
}
}
/* now move the point */
org_dist = CUR_Func_project( CUR.zp1.cur_x[point] -
CUR.zp0.cur_x[CUR.GS.rp0],
CUR.zp1.cur_y[point] -
CUR.zp0.cur_y[CUR.GS.rp0] );
CUR_Func_move( &CUR.zp1, point, distance - org_dist );
CUR.GS.rp1 = CUR.GS.rp0;
CUR.GS.rp2 = point;
if ( (CUR.opcode & 16) != 0 )
CUR.GS.rp0 = point;
}
|
CVE-2017-9726
|
The Ins_MDRP function in base/ttinterp.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) or possibly have unspecified other impact via a crafted document.
|
[
"CWE-125"
] |
[
{
"line_no": 9,
"text": " if ( BOUNDS( args[0], CUR.zp1.n_points ) )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 9,
"text": " if ( BOUNDS( args[0], CUR.zp1.n_points ) ||",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " BOUNDS( CUR.GS.rp0, CUR.zp0.n_points) )",
"char_start": null,
"char_end": null
}
] | 135
|
primevul
|
primevul_dbus_166978a09cf5edff4028e670b6074215a4c75eca
|
166978a09cf5edff4028e670b6074215a4c75eca
|
dbus
|
http://gitweb.freedesktop.org/?p=dbus/dbus
|
dbus_g_proxy_manager_filter (DBusConnection *connection,
DBusMessage *message,
void *user_data)
{
DBusGProxyManager *manager;
if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
manager = user_data;
dbus_g_proxy_manager_ref (manager);
LOCK_MANAGER (manager);
if (dbus_message_is_signal (message,
DBUS_INTERFACE_LOCAL,
"Disconnected"))
{
/* Destroy all the proxies, quite possibly resulting in unreferencing
* the proxy manager and the connection as well.
*/
GSList *all;
GSList *tmp;
all = dbus_g_proxy_manager_list_all (manager);
tmp = all;
while (tmp != NULL)
{
DBusGProxy *proxy;
proxy = DBUS_G_PROXY (tmp->data);
UNLOCK_MANAGER (manager);
dbus_g_proxy_destroy (proxy);
g_object_unref (G_OBJECT (proxy));
LOCK_MANAGER (manager);
tmp = tmp->next;
}
g_slist_free (all);
#ifndef G_DISABLE_CHECKS
if (manager->proxy_lists != NULL)
g_warning ("Disconnection emitted \"destroy\" on all DBusGProxy, but somehow new proxies were created in response to one of those destroy signals. This will cause a memory leak.");
#endif
}
else
{
char *tri;
GSList *full_list;
GSList *owned_names;
GSList *tmp;
const char *sender;
/* First we handle NameOwnerChanged internally */
if (dbus_message_is_signal (message,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged"))
{
DBusError derr;
dbus_error_init (&derr);
if (!dbus_message_get_args (message,
&derr,
DBUS_TYPE_STRING,
&name,
DBUS_TYPE_STRING,
&prev_owner,
DBUS_TYPE_STRING,
&new_owner,
DBUS_TYPE_INVALID))
{
/* Ignore this error */
dbus_error_free (&derr);
}
else if (manager->owner_names != NULL)
{
dbus_g_proxy_manager_replace_name_owner (manager, name, prev_owner, new_owner);
}
}
}
}
|
dbus_g_proxy_manager_filter (DBusConnection *connection,
DBusMessage *message,
void *user_data)
{
DBusGProxyManager *manager;
if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
manager = user_data;
dbus_g_proxy_manager_ref (manager);
LOCK_MANAGER (manager);
if (dbus_message_is_signal (message,
DBUS_INTERFACE_LOCAL,
"Disconnected"))
{
/* Destroy all the proxies, quite possibly resulting in unreferencing
* the proxy manager and the connection as well.
*/
GSList *all;
GSList *tmp;
all = dbus_g_proxy_manager_list_all (manager);
tmp = all;
while (tmp != NULL)
{
DBusGProxy *proxy;
proxy = DBUS_G_PROXY (tmp->data);
UNLOCK_MANAGER (manager);
dbus_g_proxy_destroy (proxy);
g_object_unref (G_OBJECT (proxy));
LOCK_MANAGER (manager);
tmp = tmp->next;
}
g_slist_free (all);
#ifndef G_DISABLE_CHECKS
if (manager->proxy_lists != NULL)
g_warning ("Disconnection emitted \"destroy\" on all DBusGProxy, but somehow new proxies were created in response to one of those destroy signals. This will cause a memory leak.");
#endif
}
else
{
char *tri;
GSList *full_list;
GSList *owned_names;
GSList *tmp;
const char *sender;
sender = dbus_message_get_sender (message);
/* First we handle NameOwnerChanged internally */
if (g_strcmp0 (sender, DBUS_SERVICE_DBUS) == 0 &&
dbus_message_is_signal (message,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged"))
{
DBusError derr;
dbus_error_init (&derr);
if (!dbus_message_get_args (message,
&derr,
DBUS_TYPE_STRING,
&name,
DBUS_TYPE_STRING,
&prev_owner,
DBUS_TYPE_STRING,
&new_owner,
DBUS_TYPE_INVALID))
{
/* Ignore this error */
dbus_error_free (&derr);
}
else if (manager->owner_names != NULL)
{
dbus_g_proxy_manager_replace_name_owner (manager, name, prev_owner, new_owner);
}
}
}
}
|
CVE-2013-0292
|
The dbus_g_proxy_manager_filter function in dbus-gproxy in Dbus-glib before 0.100.1 does not properly verify the sender of NameOwnerChanged signals, which allows local users to gain privileges via a spoofed signal.
|
[
"CWE-20"
] |
[
{
"line_no": 59,
"text": " if (dbus_message_is_signal (message,",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 58,
"text": " sender = dbus_message_get_sender (message);",
"char_start": null,
"char_end": null
},
{
"line_no": 59,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 61,
"text": " if (g_strcmp0 (sender, DBUS_SERVICE_DBUS) == 0 &&",
"char_start": null,
"char_end": null
},
{
"line_no": 62,
"text": "\t dbus_message_is_signal (message,",
"char_start": null,
"char_end": null
}
] | 136
|
primevul
|
primevul_ghostscript_c53183d4e7103e87368b7cfa15367a47d559e323
|
c53183d4e7103e87368b7cfa15367a47d559e323
|
ghostscript
|
http://git.ghostscript.com/?p=mupdf
|
xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr)
{
/* This function is copied verbatim from plfont.c */
int table_length;
int table_offset;
ulong format;
uint numGlyphs;
uint glyph_name_index;
const byte *postp; /* post table pointer */
/* guess if the font type is not truetype */
if ( pfont->FontType != ft_TrueType )
{
pstr->size = strlen((char*)pstr->data);
return 0;
}
else
{
return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph);
}
}
|
xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr)
{
/* This function is copied verbatim from plfont.c */
int table_length;
int table_offset;
ulong format;
int numGlyphs;
uint glyph_name_index;
const byte *postp; /* post table pointer */
if (glyph >= GS_MIN_GLYPH_INDEX) {
glyph -= GS_MIN_GLYPH_INDEX;
}
/* guess if the font type is not truetype */
if ( pfont->FontType != ft_TrueType )
{
pstr->size = strlen((char*)pstr->data);
return 0;
}
else
{
return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph);
}
}
|
CVE-2017-9619
|
The xps_true_callback_glyph_name function in xps/xpsttf.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (Segmentation Violation and application crash) via a crafted file.
|
[
"CWE-119"
] |
[
{
"line_no": 9,
"text": " uint numGlyphs;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 9,
"text": " int numGlyphs;",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " if (glyph >= GS_MIN_GLYPH_INDEX) {",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " glyph -= GS_MIN_GLYPH_INDEX;",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": "",
"char_start": null,
"char_end": null
}
] | 139
|
primevul
|
primevul_altlinux_ffe7058c70253d574b1963c7c93002bd410fddc9
|
ffe7058c70253d574b1963c7c93002bd410fddc9
|
altlinux
|
http://git.altlinux.org/people/ldv/packages/?p=pam
|
check_acl(pam_handle_t *pamh,
const char *sense, const char *this_user, const char *other_user,
int noent_code, int debug)
{
char path[PATH_MAX];
struct passwd *pwd;
{
char path[PATH_MAX];
struct passwd *pwd;
FILE *fp;
int i, save_errno;
uid_t fsuid;
/* Check this user's <sense> file. */
pwd = pam_modutil_getpwnam(pamh, this_user);
if (pwd == NULL) {
}
/* Figure out what that file is really named. */
i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense);
if ((i >= (int)sizeof(path)) || (i < 0)) {
pam_syslog(pamh, LOG_ERR,
"name of user's home directory is too long");
return PAM_SESSION_ERR;
}
fsuid = setfsuid(pwd->pw_uid);
fp = fopen(path, "r");
return PAM_SESSION_ERR;
}
fsuid = setfsuid(pwd->pw_uid);
fp = fopen(path, "r");
save_errno = errno;
setfsuid(fsuid);
if (fp != NULL) {
char buf[LINE_MAX], *tmp;
/* Scan the file for a list of specs of users to "trust". */
while (fgets(buf, sizeof(buf), fp) != NULL) {
other_user, path);
}
fclose(fp);
return PAM_PERM_DENIED;
} else {
/* Default to okay if the file doesn't exist. */
errno = save_errno;
switch (errno) {
case ENOENT:
if (noent_code == PAM_SUCCESS) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, ignoring",
path);
}
} else {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, failing",
path);
}
}
return noent_code;
default:
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"error opening %s: %m", path);
}
return PAM_PERM_DENIED;
}
}
}
|
check_acl(pam_handle_t *pamh,
const char *sense, const char *this_user, const char *other_user,
int noent_code, int debug)
{
char path[PATH_MAX];
struct passwd *pwd;
{
char path[PATH_MAX];
struct passwd *pwd;
FILE *fp = NULL;
int i, fd = -1, save_errno;
uid_t fsuid;
struct stat st;
/* Check this user's <sense> file. */
pwd = pam_modutil_getpwnam(pamh, this_user);
if (pwd == NULL) {
}
/* Figure out what that file is really named. */
i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense);
if ((i >= (int)sizeof(path)) || (i < 0)) {
pam_syslog(pamh, LOG_ERR,
"name of user's home directory is too long");
return PAM_SESSION_ERR;
}
fsuid = setfsuid(pwd->pw_uid);
fp = fopen(path, "r");
return PAM_SESSION_ERR;
}
fsuid = setfsuid(pwd->pw_uid);
if (!stat(path, &st)) {
if (!S_ISREG(st.st_mode))
errno = EINVAL;
else
fd = open(path, O_RDONLY | O_NOCTTY);
}
save_errno = errno;
setfsuid(fsuid);
if (fd >= 0) {
if (!fstat(fd, &st)) {
if (!S_ISREG(st.st_mode))
errno = EINVAL;
else
fp = fdopen(fd, "r");
}
if (!fp) {
save_errno = errno;
close(fd);
}
}
if (fp) {
char buf[LINE_MAX], *tmp;
/* Scan the file for a list of specs of users to "trust". */
while (fgets(buf, sizeof(buf), fp) != NULL) {
other_user, path);
}
fclose(fp);
return PAM_PERM_DENIED;
} else {
/* Default to okay if the file doesn't exist. */
errno = save_errno;
switch (errno) {
case ENOENT:
if (noent_code == PAM_SUCCESS) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, ignoring",
path);
}
} else {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, failing",
path);
}
}
return noent_code;
default:
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"error opening %s: %m", path);
}
return PAM_PERM_DENIED;
}
}
}
|
CVE-2010-4707
|
The check_acl function in pam_xauth.c in the pam_xauth module in Linux-PAM (aka pam) 1.1.2 and earlier does not verify that a certain ACL file is a regular file, which might allow local users to cause a denial of service (resource consumption) via a special file.
|
[
"CWE-399"
] |
[
{
"line_no": 10,
"text": " FILE *fp;",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " int i, save_errno;",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " fp = fopen(path, \"r\");",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " if (fp != NULL) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 10,
"text": " FILE *fp = NULL;",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " int i, fd = -1, save_errno;",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " struct stat st;",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " if (!stat(path, &st)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": " if (!S_ISREG(st.st_mode))",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " errno = EINVAL;",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " else",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " fd = open(path, O_RDONLY | O_NOCTTY);",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": " if (fd >= 0) {",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": " if (!fstat(fd, &st)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": " if (!S_ISREG(st.st_mode))",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " errno = EINVAL;",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": " else",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": " fp = fdopen(fd, \"r\");",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": " if (!fp) {",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " save_errno = errno;",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": " close(fd);",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 50,
"text": " if (fp) {",
"char_start": null,
"char_end": null
}
] | 141
|
primevul
|
primevul_openssl_62e4506a7d4cec1c8e1ff687f6b220f6a62a57c7
|
62e4506a7d4cec1c8e1ff687f6b220f6a62a57c7
|
openssl
|
https://github.com/openssl/openssl
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
|
CVE-2013-0166
|
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
|
[
"CWE-310"
] |
[] |
[
{
"line_no": 10,
"text": " if (!pkey)",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " return -1;",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": "",
"char_start": null,
"char_end": null
}
] | 144
|
primevul
|
primevul_openssl_66e8211c0b1347970096e04b18aa52567c325200
|
66e8211c0b1347970096e04b18aa52567c325200
|
openssl
|
https://github.com/openssl/openssl
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *buf_in=NULL;
int ret= -1,i,inl;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
|
CVE-2013-0166
|
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
|
[
"CWE-310"
] |
[] |
[
{
"line_no": 9,
"text": " if (!pkey)",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " return -1;",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": "",
"char_start": null,
"char_end": null
}
] | 145
|
primevul
|
primevul_openssl_ebc71865f0506a293242bd4aec97cdc7a8ef24b0
|
ebc71865f0506a293242bd4aec97cdc7a8ef24b0
|
openssl
|
https://github.com/openssl/openssl
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type = NULL;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature,
void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type = NULL;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
|
CVE-2013-0166
|
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
|
[
"CWE-310"
] |
[] |
[
{
"line_no": 11,
"text": " if (!pkey)",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " return -1;",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": "",
"char_start": null,
"char_end": null
}
] | 146
|
primevul
|
primevul_samba_10c3e3923022485c720f322ca4f0aca5d7501310
|
10c3e3923022485c720f322ca4f0aca5d7501310
|
samba
|
https://github.com/samba-team/samba
|
static NTSTATUS fd_open_atomic(struct connection_struct *conn,
files_struct *fsp,
int flags,
mode_t mode,
bool *file_created)
{
NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
bool file_existed = VALID_STAT(fsp->fsp_name->st);
*file_created = false;
* We're not creating the file, just pass through.
*/
return fd_open(conn, fsp, flags, mode);
}
|
static NTSTATUS fd_open_atomic(struct connection_struct *conn,
files_struct *fsp,
int flags,
mode_t mode,
bool *file_created)
{
NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
NTSTATUS retry_status;
bool file_existed = VALID_STAT(fsp->fsp_name->st);
int curr_flags;
*file_created = false;
* We're not creating the file, just pass through.
*/
return fd_open(conn, fsp, flags, mode);
}
|
CVE-2017-9461
|
smbd in Samba before 4.4.10 and 4.5.x before 4.5.6 has a denial of service vulnerability (fd_open_atomic infinite loop with high CPU usage and memory consumption) due to wrongly handling dangling symlinks.
|
[
"CWE-835"
] |
[] |
[
{
"line_no": 8,
"text": " NTSTATUS retry_status;",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " int curr_flags;",
"char_start": null,
"char_end": null
}
] | 147
|
primevul
|
primevul_openssl_d0666f289ac013094bbbf547bfbcd616199b7d2d
|
d0666f289ac013094bbbf547bfbcd616199b7d2d
|
openssl
|
https://github.com/openssl/openssl
|
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int seof= -1,eof=0,rv= -1,ret=0,i,v,tmp,n,ln,exp_nl;
unsigned char *d;
n=ctx->num;
d=ctx->enc_data;
ln=ctx->line_num;
exp_nl=ctx->expect_nl;
/* last line of input. */
if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF)))
{ rv=0; goto end; }
/* We parse the input data */
for (i=0; i<inl; i++)
{
/* If the current line is > 80 characters, scream alot */
if (ln >= 80) { rv= -1; goto end; }
/* Get char and put it into the buffer */
tmp= *(in++);
v=conv_ascii2bin(tmp);
/* only save the good data :-) */
if (!B64_NOT_BASE64(v))
{
OPENSSL_assert(n < (int)sizeof(ctx->enc_data));
d[n++]=tmp;
ln++;
}
else if (v == B64_ERROR)
{
rv= -1;
goto end;
}
/* have we seen a '=' which is 'definitly' the last
* input line. seof will point to the character that
* holds it. and eof will hold how many characters to
* chop off. */
if (tmp == '=')
{
if (seof == -1) seof=n;
eof++;
}
if (v == B64_CR)
{
ln = 0;
if (exp_nl)
continue;
}
/* eoln */
if (v == B64_EOLN)
{
ln=0;
if (exp_nl)
{
exp_nl=0;
continue;
}
}
exp_nl=0;
/* If we are at the end of input and it looks like a
* line, process it. */
if (((i+1) == inl) && (((n&3) == 0) || eof))
{
v=B64_EOF;
/* In case things were given us in really small
records (so two '=' were given in separate
updates), eof may contain the incorrect number
of ending bytes to skip, so let's redo the count */
eof = 0;
if (d[n-1] == '=') eof++;
if (d[n-2] == '=') eof++;
/* There will never be more than two '=' */
}
if ((v == B64_EOF && (n&3) == 0) || (n >= 64))
{
/* This is needed to work correctly on 64 byte input
* lines. We process the line and then need to
* accept the '\n' */
if ((v != B64_EOF) && (n >= 64)) exp_nl=1;
if (n > 0)
{
v=EVP_DecodeBlock(out,d,n);
n=0;
if (v < 0) { rv=0; goto end; }
ret+=(v-eof);
}
else
eof=1;
v=0;
}
/* This is the case where we have had a short
* but valid input line */
if ((v < ctx->length) && eof)
{
rv=0;
goto end;
}
else
ctx->length=v;
if (seof >= 0) { rv=0; goto end; }
out+=v;
}
}
|
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int seof= -1,eof=0,rv= -1,ret=0,i,v,tmp,n,ln,exp_nl;
unsigned char *d;
n=ctx->num;
d=ctx->enc_data;
ln=ctx->line_num;
exp_nl=ctx->expect_nl;
/* last line of input. */
if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF)))
{ rv=0; goto end; }
/* We parse the input data */
for (i=0; i<inl; i++)
{
/* If the current line is > 80 characters, scream alot */
if (ln >= 80) { rv= -1; goto end; }
/* Get char and put it into the buffer */
tmp= *(in++);
v=conv_ascii2bin(tmp);
/* only save the good data :-) */
if (!B64_NOT_BASE64(v))
{
OPENSSL_assert(n < (int)sizeof(ctx->enc_data));
d[n++]=tmp;
ln++;
}
else if (v == B64_ERROR)
{
rv= -1;
goto end;
}
/* have we seen a '=' which is 'definitly' the last
* input line. seof will point to the character that
* holds it. and eof will hold how many characters to
* chop off. */
if (tmp == '=')
{
if (seof == -1) seof=n;
eof++;
}
if (v == B64_CR)
{
ln = 0;
if (exp_nl)
continue;
}
/* eoln */
if (v == B64_EOLN)
{
ln=0;
if (exp_nl)
{
exp_nl=0;
continue;
}
}
exp_nl=0;
/* If we are at the end of input and it looks like a
* line, process it. */
if (((i+1) == inl) && (((n&3) == 0) || eof))
{
v=B64_EOF;
/* In case things were given us in really small
records (so two '=' were given in separate
updates), eof may contain the incorrect number
of ending bytes to skip, so let's redo the count */
eof = 0;
if (d[n-1] == '=') eof++;
if (d[n-2] == '=') eof++;
/* There will never be more than two '=' */
}
if ((v == B64_EOF && (n&3) == 0) || (n >= 64))
{
/* This is needed to work correctly on 64 byte input
* lines. We process the line and then need to
* accept the '\n' */
if ((v != B64_EOF) && (n >= 64)) exp_nl=1;
if (n > 0)
{
v=EVP_DecodeBlock(out,d,n);
n=0;
if (v < 0) { rv=0; goto end; }
if (eof > v) { rv=-1; goto end; }
ret+=(v-eof);
}
else
eof=1;
v=0;
}
/* This is the case where we have had a short
* but valid input line */
if ((v < ctx->length) && eof)
{
rv=0;
goto end;
}
else
ctx->length=v;
if (seof >= 0) { rv=0; goto end; }
out+=v;
}
}
|
CVE-2015-0292
|
Integer underflow in the EVP_DecodeUpdate function in crypto/evp/encode.c in the base64-decoding implementation in OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via crafted base64 data that triggers a buffer overflow.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 93,
"text": " if (eof > v) { rv=-1; goto end; }",
"char_start": null,
"char_end": null
}
] | 150
|
primevul
|
primevul_openssl_77c77f0a1b9f15b869ca3342186dfbedd1119d0e
|
77c77f0a1b9f15b869ca3342186dfbedd1119d0e
|
openssl
|
https://github.com/openssl/openssl
|
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
{
const unsigned char *buf = buf_;
int tot;
unsigned int n, nw;
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
unsigned int max_send_fragment;
#endif
SSL3_BUFFER *wb = &(s->s3->wbuf);
int i;
s->rwstate = SSL_NOTHING;
OPENSSL_assert(s->s3->wnum <= INT_MAX);
tot = s->s3->wnum;
s->s3->wnum = 0;
if (SSL_in_init(s) && !s->in_handshake) {
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
/*
* ensure that if we end up with a smaller value of data to write out
* than the the original len from a write which didn't complete for
* non-blocking I/O and also somehow ended up avoiding the check for
* this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
* possible to end up with (len-tot) as a large number that will then
* promptly send beyond the end of the users buffer ... so we trap and
* report the error in a way the user will notice
*/
if (len < tot) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
return (-1);
}
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (wb->left != 0) {
i = ssl3_write_pending(s, type, &buf[tot], s->s3->wpend_tot);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->s3->wnum = tot;
return i;
}
tot += i; /* this might be last fragment */
}
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
/*
* Depending on platform multi-block can deliver several *times*
* better performance. Downside is that it has to allocate
* jumbo buffer to accomodate up to 8 records, but the
* compromise is considered worthy.
*/
if (type == SSL3_RT_APPLICATION_DATA &&
len >= 4 * (int)(max_send_fragment = s->max_send_fragment) &&
s->compress == NULL && s->msg_callback == NULL &&
SSL_USE_EXPLICIT_IV(s) &&
EVP_CIPHER_flags(s->enc_write_ctx->cipher) &
EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
unsigned char aad[13];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
int packlen;
/* minimize address aliasing conflicts */
if ((max_send_fragment & 0xfff) == 0)
max_send_fragment -= 512;
if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
ssl3_release_write_buffer(s);
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
max_send_fragment, NULL);
if (len >= 8 * (int)max_send_fragment)
packlen *= 8;
else
packlen *= 4;
wb->buf = OPENSSL_malloc(packlen);
if(!wb->buf) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
return -1;
}
wb->len = packlen;
} else if (tot == len) { /* done? */
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
return tot;
}
n = (len - tot);
for (;;) {
if (n < 4 * max_send_fragment) {
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
break;
}
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0) {
s->s3->wnum = tot;
return i;
}
}
if (n >= 8 * max_send_fragment)
nw = max_send_fragment * (mb_param.interleave = 8);
else
nw = max_send_fragment * (mb_param.interleave = 4);
memcpy(aad, s->s3->write_sequence, 8);
aad[8] = type;
aad[9] = (unsigned char)(s->version >> 8);
aad[10] = (unsigned char)(s->version);
aad[11] = 0;
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = nw;
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
break;
}
mb_param.out = wb->buf;
mb_param.inp = &buf[tot];
mb_param.len = nw;
if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param) <= 0)
return -1;
s->s3->write_sequence[7] += mb_param.interleave;
if (s->s3->write_sequence[7] < mb_param.interleave) {
int j = 6;
while (j >= 0 && (++s->s3->write_sequence[j--]) == 0) ;
}
wb->offset = 0;
wb->left = packlen;
s->s3->wpend_tot = nw;
s->s3->wpend_buf = &buf[tot];
s->s3->wpend_type = type;
s->s3->wpend_ret = nw;
i = ssl3_write_pending(s, type, &buf[tot], nw);
if (i <= 0) {
if (i < 0) {
OPENSSL_free(wb->buf);
wb->buf = NULL;
}
s->s3->wnum = tot;
return i;
}
if (i == (int)n) {
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
return tot + i;
}
n -= i;
tot += i;
}
} else
#endif
if (tot == len) { /* done? */
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot;
}
n = (len - tot);
for (;;) {
if (n > s->max_send_fragment)
nw = s->max_send_fragment;
else
nw = n;
i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->s3->wnum = tot;
return i;
}
if ((i == (int)n) ||
(type == SSL3_RT_APPLICATION_DATA &&
(s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
/*
* next chunk of data should get another prepended empty fragment
* in ciphersuites with known-IV weakness:
*/
s->s3->empty_fragment_done = 0;
if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
!SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot + i;
}
n -= i;
tot += i;
}
}
|
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
{
const unsigned char *buf = buf_;
int tot;
unsigned int n, nw;
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
unsigned int max_send_fragment;
#endif
SSL3_BUFFER *wb = &(s->s3->wbuf);
int i;
s->rwstate = SSL_NOTHING;
OPENSSL_assert(s->s3->wnum <= INT_MAX);
tot = s->s3->wnum;
s->s3->wnum = 0;
if (SSL_in_init(s) && !s->in_handshake) {
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
/*
* ensure that if we end up with a smaller value of data to write out
* than the the original len from a write which didn't complete for
* non-blocking I/O and also somehow ended up avoiding the check for
* this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
* possible to end up with (len-tot) as a large number that will then
* promptly send beyond the end of the users buffer ... so we trap and
* report the error in a way the user will notice
*/
if (len < tot) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
return (-1);
}
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (wb->left != 0) {
i = ssl3_write_pending(s, type, &buf[tot], s->s3->wpend_tot);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->s3->wnum = tot;
return i;
}
tot += i; /* this might be last fragment */
}
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
/*
* Depending on platform multi-block can deliver several *times*
* better performance. Downside is that it has to allocate
* jumbo buffer to accomodate up to 8 records, but the
* compromise is considered worthy.
*/
if (type == SSL3_RT_APPLICATION_DATA &&
len >= 4 * (int)(max_send_fragment = s->max_send_fragment) &&
s->compress == NULL && s->msg_callback == NULL &&
SSL_USE_EXPLICIT_IV(s) &&
EVP_CIPHER_flags(s->enc_write_ctx->cipher) &
EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
unsigned char aad[13];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
int packlen;
/* minimize address aliasing conflicts */
if ((max_send_fragment & 0xfff) == 0)
max_send_fragment -= 512;
if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
ssl3_release_write_buffer(s);
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
max_send_fragment, NULL);
if (len >= 8 * (int)max_send_fragment)
packlen *= 8;
else
packlen *= 4;
wb->buf = OPENSSL_malloc(packlen);
if(!wb->buf) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
return -1;
}
wb->len = packlen;
} else if (tot == len) { /* done? */
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
return tot;
}
n = (len - tot);
for (;;) {
if (n < 4 * max_send_fragment) {
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
break;
}
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0) {
s->s3->wnum = tot;
return i;
}
}
if (n >= 8 * max_send_fragment)
nw = max_send_fragment * (mb_param.interleave = 8);
else
nw = max_send_fragment * (mb_param.interleave = 4);
memcpy(aad, s->s3->write_sequence, 8);
aad[8] = type;
aad[9] = (unsigned char)(s->version >> 8);
aad[10] = (unsigned char)(s->version);
aad[11] = 0;
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = nw;
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
break;
}
mb_param.out = wb->buf;
mb_param.inp = &buf[tot];
mb_param.len = nw;
if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param) <= 0)
return -1;
s->s3->write_sequence[7] += mb_param.interleave;
if (s->s3->write_sequence[7] < mb_param.interleave) {
int j = 6;
while (j >= 0 && (++s->s3->write_sequence[j--]) == 0) ;
}
wb->offset = 0;
wb->left = packlen;
s->s3->wpend_tot = nw;
s->s3->wpend_buf = &buf[tot];
s->s3->wpend_type = type;
s->s3->wpend_ret = nw;
i = ssl3_write_pending(s, type, &buf[tot], nw);
if (i <= 0) {
if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
OPENSSL_free(wb->buf);
wb->buf = NULL;
}
s->s3->wnum = tot;
return i;
}
if (i == (int)n) {
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
return tot + i;
}
n -= i;
tot += i;
}
} else
#endif
if (tot == len) { /* done? */
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot;
}
n = (len - tot);
for (;;) {
if (n > s->max_send_fragment)
nw = s->max_send_fragment;
else
nw = n;
i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->s3->wnum = tot;
return i;
}
if ((i == (int)n) ||
(type == SSL3_RT_APPLICATION_DATA &&
(s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
/*
* next chunk of data should get another prepended empty fragment
* in ciphersuites with known-IV weakness:
*/
s->s3->empty_fragment_done = 0;
if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
!SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot + i;
}
n -= i;
tot += i;
}
}
|
CVE-2015-0290
|
The multi-block feature in the ssl3_write_bytes function in s3_pkt.c in OpenSSL 1.0.2 before 1.0.2a on 64-bit x86 platforms with AES NI support does not properly handle certain non-blocking I/O cases, which allows remote attackers to cause a denial of service (pointer corruption and application crash) via unspecified vectors.
|
[
"CWE-17"
] |
[
{
"line_no": 165,
"text": " if (i < 0) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 165,
"text": " if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {",
"char_start": null,
"char_end": null
}
] | 151
|
primevul
|
primevul_openssl_b717b083073b6cacc0a5e2397b661678aff7ae7f
|
b717b083073b6cacc0a5e2397b661678aff7ae7f
|
openssl
|
https://github.com/openssl/openssl
|
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx)
{
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
const unsigned char *p = NULL, *q;
unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */
unsigned char imphack = 0, oclass;
char seq_eoc, seq_nolen, cst, isopt;
long tmplen;
int i;
int otag;
int ret = 0;
ASN1_VALUE **pchptr, *ptmpval;
if (!pval)
return 0;
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
else
asn1_cb = 0;
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
/*
* tagging or OPTIONAL is currently illegal on an item template
* because the flags can't get passed down. In practice this
* isn't a problem: we include the relevant flags from the item
* template in the template itself.
*/
if ((tag != -1) || opt) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len,
it->templates, opt, ctx);
}
return asn1_d2i_ex_primitive(pval, in, len, it,
tag, aclass, opt, ctx);
break;
case ASN1_ITYPE_MSTRING:
p = *in;
/* Just read in tag and class */
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
&p, len, -1, 0, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Must be UNIVERSAL class */
if (oclass != V_ASN1_UNIVERSAL) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
goto err;
}
/* Check tag matches bit map */
if (!(ASN1_tag2bit(otag) & it->utype)) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
goto err;
}
return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
case ASN1_ITYPE_EXTERN:
/* Use new style d2i */
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
case ASN1_ITYPE_COMPAT:
/* we must resort to old style evil hackery */
cf = it->funcs;
/* If OPTIONAL see if it is there */
if (opt) {
int exptag;
p = *in;
if (tag == -1)
exptag = it->utype;
else
exptag = tag;
/*
* Don't care about anything other than presence of expected tag
*/
ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
&p, len, exptag, aclass, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (ret == -1)
return -1;
}
/*
* This is the old style evil hack IMPLICIT handling: since the
* underlying code is expecting a tag and class other than the one
* present we change the buffer temporarily then change it back
* afterwards. This doesn't and never did work for tags > 30. Yes
* this is *horrible* but it is only needed for old style d2i which
* will hopefully not be around for much longer. FIXME: should copy
* the buffer then modify it so the input buffer can be const: we
* should *always* copy because the old style d2i might modify the
* buffer.
*/
if (tag != -1) {
wp = *(unsigned char **)in;
imphack = *wp;
if (p == NULL) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
| it->utype);
}
ptmpval = cf->asn1_d2i(pval, in, len);
if (tag != -1)
*wp = imphack;
if (ptmpval)
return 1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
case ASN1_ITYPE_CHOICE:
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Allocate structure */
if (!*pval && !ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
/* If field not present, try the next one */
if (ret == -1)
continue;
/* If positive return, read OK, break loop */
if (ret > 0)
break;
/* Otherwise must be an ASN1 parsing error */
errtt = tt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Did we fall off the end without reading anything? */
if (i == it->tcount) {
/* If OPTIONAL, this is OK */
if (opt) {
/* Free and zero it */
ASN1_item_ex_free(pval, it);
return -1;
}
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
goto err;
}
asn1_set_choice_selector(pval, i, it);
*in = p;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
return 1;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
p = *in;
tmplen = len;
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
aclass = V_ASN1_UNIVERSAL;
}
/* Get SEQUENCE length and update len, p */
ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
&p, len, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
len = tmplen - (p - *in);
seq_nolen = 1;
}
/* If indefinite we don't do a length check */
else
seq_nolen = seq_eoc;
if (!cst) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
goto err;
}
if (!*pval && !ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
}
/*
* This determines the OPTIONAL flag value. The field cannot be
* omitted if it is the last of a SEQUENCE and there is still
* data to be read. This isn't strictly necessary but it
* increases efficiency in some cases.
*/
if (i == (it->tcount - 1))
isopt = 0;
else
isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
/*
* attempt to read in field, allowing each to be OPTIONAL
*/
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
if (!ret) {
errtt = seqtt;
goto err;
} else if (ret == -1) {
/*
* OPTIONAL component absent. Free and zero the field.
*/
ASN1_template_free(pseqval, seqtt);
continue;
}
/* Update length */
len -= p - q;
}
/* Check for EOC if expecting one */
if (seq_eoc && !asn1_check_eoc(&p, len)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
goto err;
}
/* Check all data read */
if (!seq_nolen && len) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
goto err;
}
/*
* If we get here we've got no more data in the SEQUENCE, however we
* may not have read all fields so check all remaining are OPTIONAL
* and clear any that are.
*/
for (; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
ASN1_VALUE **pseqval;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
} else {
errtt = seqtt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
goto err;
}
}
/* Save encoding */
if (!asn1_enc_save(pval, *in, p - *in, it))
goto auxerr;
*in = p;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
return 1;
default:
return 0;
}
|
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx)
{
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
const unsigned char *p = NULL, *q;
unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */
unsigned char imphack = 0, oclass;
char seq_eoc, seq_nolen, cst, isopt;
long tmplen;
int i;
int otag;
int ret = 0;
ASN1_VALUE **pchptr, *ptmpval;
if (!pval)
return 0;
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
else
asn1_cb = 0;
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
/*
* tagging or OPTIONAL is currently illegal on an item template
* because the flags can't get passed down. In practice this
* isn't a problem: we include the relevant flags from the item
* template in the template itself.
*/
if ((tag != -1) || opt) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len,
it->templates, opt, ctx);
}
return asn1_d2i_ex_primitive(pval, in, len, it,
tag, aclass, opt, ctx);
break;
case ASN1_ITYPE_MSTRING:
p = *in;
/* Just read in tag and class */
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
&p, len, -1, 0, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Must be UNIVERSAL class */
if (oclass != V_ASN1_UNIVERSAL) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
goto err;
}
/* Check tag matches bit map */
if (!(ASN1_tag2bit(otag) & it->utype)) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
goto err;
}
return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
case ASN1_ITYPE_EXTERN:
/* Use new style d2i */
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
case ASN1_ITYPE_COMPAT:
/* we must resort to old style evil hackery */
cf = it->funcs;
/* If OPTIONAL see if it is there */
if (opt) {
int exptag;
p = *in;
if (tag == -1)
exptag = it->utype;
else
exptag = tag;
/*
* Don't care about anything other than presence of expected tag
*/
ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
&p, len, exptag, aclass, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (ret == -1)
return -1;
}
/*
* This is the old style evil hack IMPLICIT handling: since the
* underlying code is expecting a tag and class other than the one
* present we change the buffer temporarily then change it back
* afterwards. This doesn't and never did work for tags > 30. Yes
* this is *horrible* but it is only needed for old style d2i which
* will hopefully not be around for much longer. FIXME: should copy
* the buffer then modify it so the input buffer can be const: we
* should *always* copy because the old style d2i might modify the
* buffer.
*/
if (tag != -1) {
wp = *(unsigned char **)in;
imphack = *wp;
if (p == NULL) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
| it->utype);
}
ptmpval = cf->asn1_d2i(pval, in, len);
if (tag != -1)
*wp = imphack;
if (ptmpval)
return 1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
case ASN1_ITYPE_CHOICE:
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
if (*pval) {
/* Free up and zero CHOICE value if initialised */
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
tt = it->templates + i;
pchptr = asn1_get_field_ptr(pval, tt);
ASN1_template_free(pchptr, tt);
asn1_set_choice_selector(pval, -1, it);
}
} else if (!ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
/* If field not present, try the next one */
if (ret == -1)
continue;
/* If positive return, read OK, break loop */
if (ret > 0)
break;
/* Otherwise must be an ASN1 parsing error */
errtt = tt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Did we fall off the end without reading anything? */
if (i == it->tcount) {
/* If OPTIONAL, this is OK */
if (opt) {
/* Free and zero it */
ASN1_item_ex_free(pval, it);
return -1;
}
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
goto err;
}
asn1_set_choice_selector(pval, i, it);
*in = p;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
return 1;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
p = *in;
tmplen = len;
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
aclass = V_ASN1_UNIVERSAL;
}
/* Get SEQUENCE length and update len, p */
ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
&p, len, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
len = tmplen - (p - *in);
seq_nolen = 1;
}
/* If indefinite we don't do a length check */
else
seq_nolen = seq_eoc;
if (!cst) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
goto err;
}
if (!*pval && !ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Free up and zero any ADB found */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
if (tt->flags & ASN1_TFLG_ADB_MASK) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
}
}
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
}
/*
* This determines the OPTIONAL flag value. The field cannot be
* omitted if it is the last of a SEQUENCE and there is still
* data to be read. This isn't strictly necessary but it
* increases efficiency in some cases.
*/
if (i == (it->tcount - 1))
isopt = 0;
else
isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
/*
* attempt to read in field, allowing each to be OPTIONAL
*/
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
if (!ret) {
errtt = seqtt;
goto err;
} else if (ret == -1) {
/*
* OPTIONAL component absent. Free and zero the field.
*/
ASN1_template_free(pseqval, seqtt);
continue;
}
/* Update length */
len -= p - q;
}
/* Check for EOC if expecting one */
if (seq_eoc && !asn1_check_eoc(&p, len)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
goto err;
}
/* Check all data read */
if (!seq_nolen && len) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
goto err;
}
/*
* If we get here we've got no more data in the SEQUENCE, however we
* may not have read all fields so check all remaining are OPTIONAL
* and clear any that are.
*/
for (; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
goto err;
if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
ASN1_VALUE **pseqval;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
} else {
errtt = seqtt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
goto err;
}
}
/* Save encoding */
if (!asn1_enc_save(pval, *in, p - *in, it))
goto auxerr;
*in = p;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
return 1;
default:
return 0;
}
|
CVE-2015-0287
|
The ASN1_item_ex_d2i function in crypto/asn1/tasn_dec.c in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not reinitialize CHOICE and ADB data structures, which might allow attackers to cause a denial of service (invalid write operation and memory corruption) by leveraging an application that relies on ASN.1 structure reuse.
|
[
"CWE-17"
] |
[
{
"line_no": 143,
"text": " /* Allocate structure */",
"char_start": null,
"char_end": null
},
{
"line_no": 144,
"text": " if (!*pval && !ASN1_item_ex_new(pval, it)) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 143,
"text": " if (*pval) {",
"char_start": null,
"char_end": null
},
{
"line_no": 144,
"text": " /* Free up and zero CHOICE value if initialised */",
"char_start": null,
"char_end": null
},
{
"line_no": 145,
"text": " i = asn1_get_choice_selector(pval, it);",
"char_start": null,
"char_end": null
},
{
"line_no": 146,
"text": " if ((i >= 0) && (i < it->tcount)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 147,
"text": " tt = it->templates + i;",
"char_start": null,
"char_end": null
},
{
"line_no": 148,
"text": " pchptr = asn1_get_field_ptr(pval, tt);",
"char_start": null,
"char_end": null
},
{
"line_no": 149,
"text": " ASN1_template_free(pchptr, tt);",
"char_start": null,
"char_end": null
},
{
"line_no": 150,
"text": " asn1_set_choice_selector(pval, -1, it);",
"char_start": null,
"char_end": null
},
{
"line_no": 151,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 152,
"text": " } else if (!ASN1_item_ex_new(pval, it)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 232,
"text": " /* Free up and zero any ADB found */",
"char_start": null,
"char_end": null
},
{
"line_no": 233,
"text": " for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {",
"char_start": null,
"char_end": null
},
{
"line_no": 234,
"text": " if (tt->flags & ASN1_TFLG_ADB_MASK) {",
"char_start": null,
"char_end": null
},
{
"line_no": 235,
"text": " const ASN1_TEMPLATE *seqtt;",
"char_start": null,
"char_end": null
},
{
"line_no": 236,
"text": " ASN1_VALUE **pseqval;",
"char_start": null,
"char_end": null
},
{
"line_no": 237,
"text": " seqtt = asn1_do_adb(pval, tt, 1);",
"char_start": null,
"char_end": null
},
{
"line_no": 238,
"text": " pseqval = asn1_get_field_ptr(pval, seqtt);",
"char_start": null,
"char_end": null
},
{
"line_no": 239,
"text": " ASN1_template_free(pseqval, seqtt);",
"char_start": null,
"char_end": null
},
{
"line_no": 240,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 241,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 242,
"text": "",
"char_start": null,
"char_end": null
}
] | 154
|
primevul
|
primevul_openssl_c3c7fb07dc975dc3c9de0eddb7d8fd79fc9c67c1
|
c3c7fb07dc975dc3c9de0eddb7d8fd79fc9c67c1
|
openssl
|
https://github.com/openssl/openssl
|
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
|
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
|
CVE-2015-0286
|
The ASN1_TYPE_cmp function in crypto/asn1/a_type.c in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not properly perform boolean-type comparisons, which allows remote attackers to cause a denial of service (invalid read operation and application crash) via a crafted X.509 certificate to an endpoint that uses the certificate-verification feature.
|
[
"CWE-17"
] |
[] |
[
{
"line_no": 12,
"text": " case V_ASN1_BOOLEAN:",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " result = a->value.boolean - b->value.boolean;",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " break;",
"char_start": null,
"char_end": null
}
] | 155
|
primevul
|
primevul_openssl_e1b568dd2462f7cacf98f3d117936c34e2849a6b
|
e1b568dd2462f7cacf98f3d117936c34e2849a6b
|
openssl
|
https://github.com/openssl/openssl
|
int ssl3_client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned long l;
int al = 0;
#ifndef OPENSSL_NO_COMP
int j;
SSL_COMP *comp;
#endif
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
SSL_SESSION *sess = s->session;
if ((sess == NULL) ||
(sess->ssl_version != s->version) ||
!sess->session_id_length || (sess->not_resumable)) {
if (!ssl_get_new_session(s, 0))
goto err;
}
if (s->method->version == DTLS_ANY_VERSION) {
/* Determine which DTLS version to use */
int options = s->options;
/* If DTLS 1.2 disabled correct the version number */
if (options & SSL_OP_NO_DTLSv1_2) {
if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
/*
* Disabling all versions is silly: return an error.
*/
if (options & SSL_OP_NO_DTLSv1) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION);
goto err;
}
/*
* Update method so we don't use any DTLS 1.2 features.
*/
s->method = DTLSv1_client_method();
s->version = DTLS1_VERSION;
} else {
/*
* We only support one version: update method
*/
if (options & SSL_OP_NO_DTLSv1)
s->method = DTLSv1_2_client_method();
s->version = DTLS1_2_VERSION;
}
s->client_version = s->version;
}
/* else use the pre-loaded session */
p = s->s3->client_random;
/*
* for DTLS if client_random is initialized, reuse it, we are
* required to use same upon reply to HelloVerify
*/
if (SSL_IS_DTLS(s)) {
size_t idx;
i = 1;
for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
if (p[idx]) {
i = 0;
break;
}
}
} else
i = 1;
if (i)
ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random));
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
/*-
* version indicates the negotiated version: for example from
* an SSLv2/v3 compatible client hello). The client_version
* field is the maximum version we permit and it is also
* used in RSA encrypted premaster secrets. Some servers can
* choke if we initially report a higher version then
* renegotiate to a lower one in the premaster secret. This
* didn't happen with TLS 1.0 as most servers supported it
* but it can with TLS 1.1 or later if the server only supports
* 1.0.
*
* Possible scenario with previous logic:
* 1. Client hello indicates TLS 1.2
* 2. Server hello says TLS 1.0
* 3. RSA encrypted premaster secret uses 1.2.
* 4. Handhaked proceeds using TLS 1.0.
* 5. Server sends hello request to renegotiate.
* 6. Client hello indicates TLS v1.0 as we now
* know that is maximum server supports.
* 7. Server chokes on RSA encrypted premaster secret
* containing version 1.0.
*
* For interoperability it should be OK to always use the
* maximum version we support in client hello and then rely
* on the checking of version to ensure the servers isn't
* being inconsistent: for example initially negotiating with
* TLS 1.0 and renegotiating with TLS 1.2. We do this by using
* client_version in client hello and not resetting it to
* the negotiated version.
*/
*(p++) = s->client_version >> 8;
*(p++) = s->client_version & 0xff;
/* Random stuff */
memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* Session ID */
if (s->new_session)
i = 0;
else
i = s->session->session_id_length;
*(p++) = i;
if (i != 0) {
if (i > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(p, s->session->session_id, i);
p += i;
}
/* cookie stuff for DTLS */
if (SSL_IS_DTLS(s)) {
if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
*(p++) = s->d1->cookie_len;
memcpy(p, s->d1->cookie, s->d1->cookie_len);
p += s->d1->cookie_len;
}
/* Ciphers supported */
i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
if (i == 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
goto err;
}
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
/*
* Some servers hang if client hello > 256 bytes as hack workaround
* chop number of supported ciphers to keep it well below this if we
* use TLS v1.2
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION
&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
#endif
s2n(i, p);
p += i;
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
*(p++) = 1;
#else
if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
j = 0;
else
j = sk_SSL_COMP_num(s->ctx->comp_methods);
*(p++) = 1 + j;
for (i = 0; i < j; i++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
*(p++) = comp->id;
}
#endif
*(p++) = 0; /* Add the NULL method */
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (ssl_prepare_clienthello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
if ((p =
ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
#endif
l = p - d;
ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
s->state = SSL3_ST_CW_CLNT_HELLO_B;
}
/* SSL3_ST_CW_CLNT_HELLO_B */
return ssl_do_write(s);
err:
return (-1);
}
|
int ssl3_client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned long l;
int al = 0;
#ifndef OPENSSL_NO_COMP
int j;
SSL_COMP *comp;
#endif
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
SSL_SESSION *sess = s->session;
if ((sess == NULL) ||
(sess->ssl_version != s->version) ||
!sess->session_id_length || (sess->not_resumable)) {
if (!ssl_get_new_session(s, 0))
goto err;
}
if (s->method->version == DTLS_ANY_VERSION) {
/* Determine which DTLS version to use */
int options = s->options;
/* If DTLS 1.2 disabled correct the version number */
if (options & SSL_OP_NO_DTLSv1_2) {
if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
/*
* Disabling all versions is silly: return an error.
*/
if (options & SSL_OP_NO_DTLSv1) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION);
goto err;
}
/*
* Update method so we don't use any DTLS 1.2 features.
*/
s->method = DTLSv1_client_method();
s->version = DTLS1_VERSION;
} else {
/*
* We only support one version: update method
*/
if (options & SSL_OP_NO_DTLSv1)
s->method = DTLSv1_2_client_method();
s->version = DTLS1_2_VERSION;
}
s->client_version = s->version;
}
/* else use the pre-loaded session */
p = s->s3->client_random;
/*
* for DTLS if client_random is initialized, reuse it, we are
* required to use same upon reply to HelloVerify
*/
if (SSL_IS_DTLS(s)) {
size_t idx;
i = 1;
for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
if (p[idx]) {
i = 0;
break;
}
}
} else
i = 1;
if (i && ssl_fill_hello_random(s, 0, p,
sizeof(s->s3->client_random)) <= 0)
goto err;
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
/*-
* version indicates the negotiated version: for example from
* an SSLv2/v3 compatible client hello). The client_version
* field is the maximum version we permit and it is also
* used in RSA encrypted premaster secrets. Some servers can
* choke if we initially report a higher version then
* renegotiate to a lower one in the premaster secret. This
* didn't happen with TLS 1.0 as most servers supported it
* but it can with TLS 1.1 or later if the server only supports
* 1.0.
*
* Possible scenario with previous logic:
* 1. Client hello indicates TLS 1.2
* 2. Server hello says TLS 1.0
* 3. RSA encrypted premaster secret uses 1.2.
* 4. Handhaked proceeds using TLS 1.0.
* 5. Server sends hello request to renegotiate.
* 6. Client hello indicates TLS v1.0 as we now
* know that is maximum server supports.
* 7. Server chokes on RSA encrypted premaster secret
* containing version 1.0.
*
* For interoperability it should be OK to always use the
* maximum version we support in client hello and then rely
* on the checking of version to ensure the servers isn't
* being inconsistent: for example initially negotiating with
* TLS 1.0 and renegotiating with TLS 1.2. We do this by using
* client_version in client hello and not resetting it to
* the negotiated version.
*/
*(p++) = s->client_version >> 8;
*(p++) = s->client_version & 0xff;
/* Random stuff */
memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* Session ID */
if (s->new_session)
i = 0;
else
i = s->session->session_id_length;
*(p++) = i;
if (i != 0) {
if (i > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(p, s->session->session_id, i);
p += i;
}
/* cookie stuff for DTLS */
if (SSL_IS_DTLS(s)) {
if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
*(p++) = s->d1->cookie_len;
memcpy(p, s->d1->cookie, s->d1->cookie_len);
p += s->d1->cookie_len;
}
/* Ciphers supported */
i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
if (i == 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
goto err;
}
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
/*
* Some servers hang if client hello > 256 bytes as hack workaround
* chop number of supported ciphers to keep it well below this if we
* use TLS v1.2
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION
&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
#endif
s2n(i, p);
p += i;
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
*(p++) = 1;
#else
if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
j = 0;
else
j = sk_SSL_COMP_num(s->ctx->comp_methods);
*(p++) = 1 + j;
for (i = 0; i < j; i++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
*(p++) = comp->id;
}
#endif
*(p++) = 0; /* Add the NULL method */
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (ssl_prepare_clienthello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
if ((p =
ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
#endif
l = p - d;
ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
s->state = SSL3_ST_CW_CLNT_HELLO_B;
}
/* SSL3_ST_CW_CLNT_HELLO_B */
return ssl_do_write(s);
err:
return (-1);
}
|
CVE-2015-0285
|
The ssl3_client_hello function in s3_clnt.c in OpenSSL 1.0.2 before 1.0.2a does not ensure that the PRNG is seeded before proceeding with a handshake, which makes it easier for remote attackers to defeat cryptographic protection mechanisms by sniffing the network and then conducting a brute-force attack.
|
[
"CWE-310"
] |
[
{
"line_no": 74,
"text": " if (i)",
"char_start": null,
"char_end": null
},
{
"line_no": 75,
"text": " ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random));",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 74,
"text": " if (i && ssl_fill_hello_random(s, 0, p,",
"char_start": null,
"char_end": null
},
{
"line_no": 75,
"text": " sizeof(s->s3->client_random)) <= 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 76,
"text": " goto err;",
"char_start": null,
"char_end": null
}
] | 156
|
primevul
|
primevul_lxde_bc8c3d871e9ecc67c47ff002b68cf049793faf08
|
bc8c3d871e9ecc67c47ff002b68cf049793faf08
|
lxde
|
https://git.lxde.org/gitweb/?p=lxde/pcmanfm
|
static void get_socket_name(SingleInstData* data, char* buf, int len)
{
const char* dpy = g_getenv("DISPLAY");
char* host = NULL;
int dpynum;
if(dpy)
{
const char* p = strrchr(dpy, ':');
host = g_strndup(dpy, (p - dpy));
dpynum = atoi(p + 1);
}
else
dpynum = 0;
g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s",
g_get_tmp_dir(),
data->prog_name,
host ? host : "",
dpynum,
g_get_user_name());
}
|
static void get_socket_name(SingleInstData* data, char* buf, int len)
{
const char* dpy = g_getenv("DISPLAY");
char* host = NULL;
int dpynum;
if(dpy)
{
const char* p = strrchr(dpy, ':');
host = g_strndup(dpy, (p - dpy));
dpynum = atoi(p + 1);
}
else
dpynum = 0;
#if GLIB_CHECK_VERSION(2, 28, 0)
g_snprintf(buf, len, "%s/%s-socket-%s-%d", g_get_user_runtime_dir(),
data->prog_name, host ? host : "", dpynum);
#else
g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s",
g_get_tmp_dir(),
data->prog_name,
host ? host : "",
dpynum,
g_get_user_name());
#endif
}
|
CVE-2017-8934
|
PCManFM 1.2.5 insecurely uses /tmp for a socket file, allowing a local user to cause a denial of service (application unavailability).
|
[
"CWE-20"
] |
[] |
[
{
"line_no": 14,
"text": "#if GLIB_CHECK_VERSION(2, 28, 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": " g_snprintf(buf, len, \"%s/%s-socket-%s-%d\", g_get_user_runtime_dir(),",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " data->prog_name, host ? host : \"\", dpynum);",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": "#else",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": "#endif",
"char_start": null,
"char_end": null
}
] | 159
|
primevul
|
primevul_savannah_7f2e4f4f553f6836be7683f66226afac3fa979b8
|
7f2e4f4f553f6836be7683f66226afac3fa979b8
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
_bdf_parse_glyphs( char* line,
unsigned long linelen,
unsigned long lineno,
void* call_data,
void* client_data )
{
int c, mask_index;
char* s;
unsigned char* bp;
unsigned long i, slen, nibbles;
_bdf_parse_t* p;
bdf_glyph_t* glyph;
bdf_font_t* font;
FT_Memory memory;
FT_Error error = BDF_Err_Ok;
FT_UNUSED( call_data );
FT_UNUSED( lineno ); /* only used in debug mode */
p = (_bdf_parse_t *)client_data;
font = p->font;
memory = font->memory;
/* Check for a comment. */
if ( ft_memcmp( line, "COMMENT", 7 ) == 0 )
{
linelen -= 7;
s = line + 7;
if ( *s != 0 )
{
s++;
linelen--;
}
error = _bdf_add_comment( p->font, s, linelen );
goto Exit;
}
/* The very first thing expected is the number of glyphs. */
if ( !( p->flags & _BDF_GLYPHS ) )
{
if ( ft_memcmp( line, "CHARS", 5 ) != 0 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" ));
error = BDF_Err_Missing_Chars_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 );
/* Make sure the number of glyphs is non-zero. */
if ( p->cnt == 0 )
font->glyphs_size = 64;
/* Limit ourselves to 1,114,112 glyphs in the font (this is the */
/* number of code points available in Unicode). */
if ( p->cnt >= 0x110000UL )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" ));
error = BDF_Err_Invalid_Argument;
goto Exit;
}
if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) )
goto Exit;
p->flags |= _BDF_GLYPHS;
goto Exit;
}
/* Check for the ENDFONT field. */
if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 )
{
/* Sort the glyphs by encoding. */
ft_qsort( (char *)font->glyphs,
font->glyphs_used,
sizeof ( bdf_glyph_t ),
by_encoding );
p->flags &= ~_BDF_START;
goto Exit;
}
/* Check for the ENDCHAR field. */
if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 )
{
p->glyph_enc = 0;
p->flags &= ~_BDF_GLYPH_BITS;
goto Exit;
}
/* Check whether a glyph is being scanned but should be */
/* ignored because it is an unencoded glyph. */
if ( ( p->flags & _BDF_GLYPH ) &&
p->glyph_enc == -1 &&
p->opts->keep_unencoded == 0 )
goto Exit;
/* Check for the STARTCHAR field. */
if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 )
{
/* Set the character name in the parse info first until the */
/* encoding can be checked for an unencoded character. */
FT_FREE( p->glyph_name );
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
_bdf_list_shift( &p->list, 1 );
s = _bdf_list_join( &p->list, ' ', &slen );
if ( !s )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) )
goto Exit;
FT_MEM_COPY( p->glyph_name, s, slen + 1 );
p->flags |= _BDF_GLYPH;
FT_TRACE4(( DBGMSG1, lineno, s ));
goto Exit;
}
/* Check for the ENCODING field. */
if ( ft_memcmp( line, "ENCODING", 8 ) == 0 )
{
if ( !( p->flags & _BDF_GLYPH ) )
{
/* Missing STARTCHAR field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" ));
error = BDF_Err_Missing_Startchar_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 );
/* Normalize negative encoding values. The specification only */
/* allows -1, but we can be more generous here. */
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
/* Check for alternative encoding format. */
if ( p->glyph_enc == -1 && p->list.used > 2 )
p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 );
FT_TRACE4(( DBGMSG2, p->glyph_enc ));
/* Check that the encoding is in the Unicode range because */
sizeof ( unsigned long ) * 32 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
/* Check whether this encoding has already been encountered. */
/* If it has then change it to unencoded so it gets added if */
/* indicated. */
if ( p->glyph_enc >= 0 )
{
if ( _bdf_glyph_modified( p->have, p->glyph_enc ) )
{
/* Emit a message saying a glyph has been moved to the */
/* unencoded area. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12,
p->glyph_enc, p->glyph_name ));
p->glyph_enc = -1;
font->modified = 1;
}
else
_bdf_set_glyph_modified( p->have, p->glyph_enc );
}
if ( p->glyph_enc >= 0 )
{
/* Make sure there are enough glyphs allocated in case the */
/* number of characters happen to be wrong. */
if ( font->glyphs_used == font->glyphs_size )
{
if ( FT_RENEW_ARRAY( font->glyphs,
font->glyphs_size,
font->glyphs_size + 64 ) )
goto Exit;
font->glyphs_size += 64;
}
glyph = font->glyphs + font->glyphs_used++;
glyph->name = p->glyph_name;
glyph->encoding = p->glyph_enc;
/* Reset the initial glyph info. */
p->glyph_name = 0;
}
else
{
/* Unencoded glyph. Check whether it should */
/* be added or not. */
if ( p->opts->keep_unencoded != 0 )
{
/* Allocate the next unencoded glyph. */
if ( font->unencoded_used == font->unencoded_size )
{
if ( FT_RENEW_ARRAY( font->unencoded ,
font->unencoded_size,
font->unencoded_size + 4 ) )
goto Exit;
font->unencoded_size += 4;
}
glyph = font->unencoded + font->unencoded_used;
glyph->name = p->glyph_name;
glyph->encoding = font->unencoded_used++;
}
else
/* Free up the glyph name if the unencoded shouldn't be */
/* kept. */
FT_FREE( p->glyph_name );
p->glyph_name = 0;
}
/* Clear the flags that might be added when width and height are */
/* checked for consistency. */
p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK );
p->flags |= _BDF_ENCODING;
goto Exit;
}
/* Point at the glyph being constructed. */
if ( p->glyph_enc == -1 )
glyph = font->unencoded + ( font->unencoded_used - 1 );
else
glyph = font->glyphs + ( font->glyphs_used - 1 );
/* Check whether a bitmap is being constructed. */
if ( p->flags & _BDF_BITMAP )
{
/* If there are more rows than are specified in the glyph metrics, */
/* ignore the remaining lines. */
if ( p->row >= (unsigned long)glyph->bbx.height )
{
if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding ));
p->flags |= _BDF_GLYPH_HEIGHT_CHECK;
font->modified = 1;
}
goto Exit;
}
/* Only collect the number of nibbles indicated by the glyph */
/* metrics. If there are more columns, they are simply ignored. */
nibbles = glyph->bpr << 1;
bp = glyph->bitmap + p->row * glyph->bpr;
for ( i = 0; i < nibbles; i++ )
{
c = line[i];
if ( !sbitset( hdigits, c ) )
break;
*bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] );
if ( i + 1 < nibbles && ( i & 1 ) )
*++bp = 0;
}
/* If any line has not enough columns, */
/* indicate they have been padded with zero bits. */
if ( i < nibbles &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
/* Remove possible garbage at the right. */
mask_index = ( glyph->bbx.width * p->font->bpp ) & 7;
if ( glyph->bbx.width )
*bp &= nibble_mask[mask_index];
/* If any line has extra columns, indicate they have been removed. */
if ( i == nibbles &&
sbitset( hdigits, line[nibbles] ) &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
p->row++;
goto Exit;
}
/* Expect the SWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
p->flags |= _BDF_SWIDTH;
goto Exit;
}
/* Expect the DWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
if ( !( p->flags & _BDF_SWIDTH ) )
{
/* Missing SWIDTH field. Emit an auto correction message and set */
/* the scalable width from the device width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno ));
glyph->swidth = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
}
p->flags |= _BDF_DWIDTH;
goto Exit;
}
/* Expect the BBX field next. */
if ( ft_memcmp( line, "BBX", 3 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 );
glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 );
glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 );
glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 );
/* Generate the ascent and descent of the character. */
glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset );
glyph->bbx.descent = (short)( -glyph->bbx.y_offset );
/* Determine the overall font bounding box as the characters are */
/* loaded so corrections can be done later if indicated. */
p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas );
p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds );
p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset );
p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb );
p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb );
p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb );
if ( !( p->flags & _BDF_DWIDTH ) )
{
/* Missing DWIDTH field. Emit an auto correction message and set */
/* the device width to the glyph width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno ));
glyph->dwidth = glyph->bbx.width;
}
/* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */
/* value if necessary. */
if ( p->opts->correct_metrics != 0 )
{
/* Determine the point size of the glyph. */
unsigned short sw = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
if ( sw != glyph->swidth )
{
glyph->swidth = sw;
if ( p->glyph_enc == -1 )
_bdf_set_glyph_modified( font->umod,
font->unencoded_used - 1 );
else
_bdf_set_glyph_modified( font->nmod, glyph->encoding );
p->flags |= _BDF_SWIDTH_ADJ;
font->modified = 1;
}
}
p->flags |= _BDF_BBX;
goto Exit;
}
/* And finally, gather up the bitmap. */
if ( ft_memcmp( line, "BITMAP", 6 ) == 0 )
{
unsigned long bitmap_size;
if ( !( p->flags & _BDF_BBX ) )
{
/* Missing BBX field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" ));
error = BDF_Err_Missing_Bbx_Field;
goto Exit;
}
/* Allocate enough space for the bitmap. */
glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3;
bitmap_size = glyph->bpr * glyph->bbx.height;
if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno ));
error = BDF_Err_Bbx_Too_Big;
goto Exit;
}
else
glyph->bytes = (unsigned short)bitmap_size;
if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) )
goto Exit;
p->row = 0;
p->flags |= _BDF_BITMAP;
goto Exit;
}
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
Missing_Encoding:
/* Missing ENCODING field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" ));
error = BDF_Err_Missing_Encoding_Field;
Exit:
if ( error && ( p->flags & _BDF_GLYPH ) )
FT_FREE( p->glyph_name );
return error;
}
|
_bdf_parse_glyphs( char* line,
unsigned long linelen,
unsigned long lineno,
void* call_data,
void* client_data )
{
int c, mask_index;
char* s;
unsigned char* bp;
unsigned long i, slen, nibbles;
_bdf_parse_t* p;
bdf_glyph_t* glyph;
bdf_font_t* font;
FT_Memory memory;
FT_Error error = BDF_Err_Ok;
FT_UNUSED( call_data );
FT_UNUSED( lineno ); /* only used in debug mode */
p = (_bdf_parse_t *)client_data;
font = p->font;
memory = font->memory;
/* Check for a comment. */
if ( ft_memcmp( line, "COMMENT", 7 ) == 0 )
{
linelen -= 7;
s = line + 7;
if ( *s != 0 )
{
s++;
linelen--;
}
error = _bdf_add_comment( p->font, s, linelen );
goto Exit;
}
/* The very first thing expected is the number of glyphs. */
if ( !( p->flags & _BDF_GLYPHS ) )
{
if ( ft_memcmp( line, "CHARS", 5 ) != 0 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" ));
error = BDF_Err_Missing_Chars_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 );
/* Make sure the number of glyphs is non-zero. */
if ( p->cnt == 0 )
font->glyphs_size = 64;
/* Limit ourselves to 1,114,112 glyphs in the font (this is the */
/* number of code points available in Unicode). */
if ( p->cnt >= 0x110000UL )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" ));
error = BDF_Err_Invalid_Argument;
goto Exit;
}
if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) )
goto Exit;
p->flags |= _BDF_GLYPHS;
goto Exit;
}
/* Check for the ENDFONT field. */
if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 )
{
/* Sort the glyphs by encoding. */
ft_qsort( (char *)font->glyphs,
font->glyphs_used,
sizeof ( bdf_glyph_t ),
by_encoding );
p->flags &= ~_BDF_START;
goto Exit;
}
/* Check for the ENDCHAR field. */
if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 )
{
p->glyph_enc = 0;
p->flags &= ~_BDF_GLYPH_BITS;
goto Exit;
}
/* Check whether a glyph is being scanned but should be */
/* ignored because it is an unencoded glyph. */
if ( ( p->flags & _BDF_GLYPH ) &&
p->glyph_enc == -1 &&
p->opts->keep_unencoded == 0 )
goto Exit;
/* Check for the STARTCHAR field. */
if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 )
{
/* Set the character name in the parse info first until the */
/* encoding can be checked for an unencoded character. */
FT_FREE( p->glyph_name );
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
_bdf_list_shift( &p->list, 1 );
s = _bdf_list_join( &p->list, ' ', &slen );
if ( !s )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) )
goto Exit;
FT_MEM_COPY( p->glyph_name, s, slen + 1 );
p->flags |= _BDF_GLYPH;
FT_TRACE4(( DBGMSG1, lineno, s ));
goto Exit;
}
/* Check for the ENCODING field. */
if ( ft_memcmp( line, "ENCODING", 8 ) == 0 )
{
if ( !( p->flags & _BDF_GLYPH ) )
{
/* Missing STARTCHAR field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" ));
error = BDF_Err_Missing_Startchar_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 );
/* Normalize negative encoding values. The specification only */
/* allows -1, but we can be more generous here. */
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
/* Check for alternative encoding format. */
if ( p->glyph_enc == -1 && p->list.used > 2 )
p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 );
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
FT_TRACE4(( DBGMSG2, p->glyph_enc ));
/* Check that the encoding is in the Unicode range because */
sizeof ( unsigned long ) * 32 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
/* Check whether this encoding has already been encountered. */
/* If it has then change it to unencoded so it gets added if */
/* indicated. */
if ( p->glyph_enc >= 0 )
{
if ( _bdf_glyph_modified( p->have, p->glyph_enc ) )
{
/* Emit a message saying a glyph has been moved to the */
/* unencoded area. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12,
p->glyph_enc, p->glyph_name ));
p->glyph_enc = -1;
font->modified = 1;
}
else
_bdf_set_glyph_modified( p->have, p->glyph_enc );
}
if ( p->glyph_enc >= 0 )
{
/* Make sure there are enough glyphs allocated in case the */
/* number of characters happen to be wrong. */
if ( font->glyphs_used == font->glyphs_size )
{
if ( FT_RENEW_ARRAY( font->glyphs,
font->glyphs_size,
font->glyphs_size + 64 ) )
goto Exit;
font->glyphs_size += 64;
}
glyph = font->glyphs + font->glyphs_used++;
glyph->name = p->glyph_name;
glyph->encoding = p->glyph_enc;
/* Reset the initial glyph info. */
p->glyph_name = 0;
}
else
{
/* Unencoded glyph. Check whether it should */
/* be added or not. */
if ( p->opts->keep_unencoded != 0 )
{
/* Allocate the next unencoded glyph. */
if ( font->unencoded_used == font->unencoded_size )
{
if ( FT_RENEW_ARRAY( font->unencoded ,
font->unencoded_size,
font->unencoded_size + 4 ) )
goto Exit;
font->unencoded_size += 4;
}
glyph = font->unencoded + font->unencoded_used;
glyph->name = p->glyph_name;
glyph->encoding = font->unencoded_used++;
}
else
/* Free up the glyph name if the unencoded shouldn't be */
/* kept. */
FT_FREE( p->glyph_name );
p->glyph_name = 0;
}
/* Clear the flags that might be added when width and height are */
/* checked for consistency. */
p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK );
p->flags |= _BDF_ENCODING;
goto Exit;
}
/* Point at the glyph being constructed. */
if ( p->glyph_enc == -1 )
glyph = font->unencoded + ( font->unencoded_used - 1 );
else
glyph = font->glyphs + ( font->glyphs_used - 1 );
/* Check whether a bitmap is being constructed. */
if ( p->flags & _BDF_BITMAP )
{
/* If there are more rows than are specified in the glyph metrics, */
/* ignore the remaining lines. */
if ( p->row >= (unsigned long)glyph->bbx.height )
{
if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding ));
p->flags |= _BDF_GLYPH_HEIGHT_CHECK;
font->modified = 1;
}
goto Exit;
}
/* Only collect the number of nibbles indicated by the glyph */
/* metrics. If there are more columns, they are simply ignored. */
nibbles = glyph->bpr << 1;
bp = glyph->bitmap + p->row * glyph->bpr;
for ( i = 0; i < nibbles; i++ )
{
c = line[i];
if ( !sbitset( hdigits, c ) )
break;
*bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] );
if ( i + 1 < nibbles && ( i & 1 ) )
*++bp = 0;
}
/* If any line has not enough columns, */
/* indicate they have been padded with zero bits. */
if ( i < nibbles &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
/* Remove possible garbage at the right. */
mask_index = ( glyph->bbx.width * p->font->bpp ) & 7;
if ( glyph->bbx.width )
*bp &= nibble_mask[mask_index];
/* If any line has extra columns, indicate they have been removed. */
if ( i == nibbles &&
sbitset( hdigits, line[nibbles] ) &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
p->row++;
goto Exit;
}
/* Expect the SWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
p->flags |= _BDF_SWIDTH;
goto Exit;
}
/* Expect the DWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
if ( !( p->flags & _BDF_SWIDTH ) )
{
/* Missing SWIDTH field. Emit an auto correction message and set */
/* the scalable width from the device width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno ));
glyph->swidth = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
}
p->flags |= _BDF_DWIDTH;
goto Exit;
}
/* Expect the BBX field next. */
if ( ft_memcmp( line, "BBX", 3 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 );
glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 );
glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 );
glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 );
/* Generate the ascent and descent of the character. */
glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset );
glyph->bbx.descent = (short)( -glyph->bbx.y_offset );
/* Determine the overall font bounding box as the characters are */
/* loaded so corrections can be done later if indicated. */
p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas );
p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds );
p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset );
p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb );
p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb );
p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb );
if ( !( p->flags & _BDF_DWIDTH ) )
{
/* Missing DWIDTH field. Emit an auto correction message and set */
/* the device width to the glyph width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno ));
glyph->dwidth = glyph->bbx.width;
}
/* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */
/* value if necessary. */
if ( p->opts->correct_metrics != 0 )
{
/* Determine the point size of the glyph. */
unsigned short sw = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
if ( sw != glyph->swidth )
{
glyph->swidth = sw;
if ( p->glyph_enc == -1 )
_bdf_set_glyph_modified( font->umod,
font->unencoded_used - 1 );
else
_bdf_set_glyph_modified( font->nmod, glyph->encoding );
p->flags |= _BDF_SWIDTH_ADJ;
font->modified = 1;
}
}
p->flags |= _BDF_BBX;
goto Exit;
}
/* And finally, gather up the bitmap. */
if ( ft_memcmp( line, "BITMAP", 6 ) == 0 )
{
unsigned long bitmap_size;
if ( !( p->flags & _BDF_BBX ) )
{
/* Missing BBX field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" ));
error = BDF_Err_Missing_Bbx_Field;
goto Exit;
}
/* Allocate enough space for the bitmap. */
glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3;
bitmap_size = glyph->bpr * glyph->bbx.height;
if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno ));
error = BDF_Err_Bbx_Too_Big;
goto Exit;
}
else
glyph->bytes = (unsigned short)bitmap_size;
if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) )
goto Exit;
p->row = 0;
p->flags |= _BDF_BITMAP;
goto Exit;
}
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
Missing_Encoding:
/* Missing ENCODING field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" ));
error = BDF_Err_Missing_Encoding_Field;
Exit:
if ( error && ( p->flags & _BDF_GLYPH ) )
FT_FREE( p->glyph_name );
return error;
}
|
CVE-2012-5670
|
The _bdf_parse_glyphs function in FreeType before 2.4.11 allows context-dependent attackers to cause a denial of service (out-of-bounds write and crash) via vectors related to BDF fonts and an ENCODING field with a negative value.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 169,
"text": " if ( p->glyph_enc < -1 )",
"char_start": null,
"char_end": null
},
{
"line_no": 170,
"text": " p->glyph_enc = -1;",
"char_start": null,
"char_end": null
},
{
"line_no": 171,
"text": "",
"char_start": null,
"char_end": null
}
] | 165
|
primevul
|
primevul_savannah_07bdb6e289c7954e2a533039dc93c1c136099d2d
|
07bdb6e289c7954e2a533039dc93c1c136099d2d
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
_bdf_parse_glyphs( char* line,
unsigned long linelen,
unsigned long lineno,
void* call_data,
void* client_data )
{
int c, mask_index;
char* s;
unsigned char* bp;
unsigned long i, slen, nibbles;
_bdf_parse_t* p;
bdf_glyph_t* glyph;
bdf_font_t* font;
FT_Memory memory;
FT_Error error = BDF_Err_Ok;
FT_UNUSED( call_data );
FT_UNUSED( lineno ); /* only used in debug mode */
p = (_bdf_parse_t *)client_data;
font = p->font;
memory = font->memory;
/* Check for a comment. */
if ( ft_memcmp( line, "COMMENT", 7 ) == 0 )
{
linelen -= 7;
s = line + 7;
if ( *s != 0 )
{
s++;
linelen--;
}
error = _bdf_add_comment( p->font, s, linelen );
goto Exit;
}
/* The very first thing expected is the number of glyphs. */
if ( !( p->flags & _BDF_GLYPHS ) )
{
if ( ft_memcmp( line, "CHARS", 5 ) != 0 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" ));
error = BDF_Err_Missing_Chars_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 );
/* Make sure the number of glyphs is non-zero. */
if ( p->cnt == 0 )
font->glyphs_size = 64;
/* Limit ourselves to 1,114,112 glyphs in the font (this is the */
/* number of code points available in Unicode). */
if ( p->cnt >= 0x110000UL )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" ));
error = BDF_Err_Invalid_Argument;
goto Exit;
}
if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) )
goto Exit;
p->flags |= _BDF_GLYPHS;
goto Exit;
}
/* Check for the ENDFONT field. */
if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 )
{
/* Sort the glyphs by encoding. */
ft_qsort( (char *)font->glyphs,
font->glyphs_used,
sizeof ( bdf_glyph_t ),
by_encoding );
p->flags &= ~_BDF_START;
goto Exit;
}
/* Check for the ENDCHAR field. */
if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 )
{
p->glyph_enc = 0;
p->flags &= ~_BDF_GLYPH_BITS;
goto Exit;
}
/* Check whether a glyph is being scanned but should be */
/* ignored because it is an unencoded glyph. */
if ( ( p->flags & _BDF_GLYPH ) &&
p->glyph_enc == -1 &&
p->opts->keep_unencoded == 0 )
goto Exit;
/* Check for the STARTCHAR field. */
if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 )
{
/* Set the character name in the parse info first until the */
/* encoding can be checked for an unencoded character. */
FT_FREE( p->glyph_name );
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
_bdf_list_shift( &p->list, 1 );
s = _bdf_list_join( &p->list, ' ', &slen );
if ( !s )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) )
goto Exit;
FT_MEM_COPY( p->glyph_name, s, slen + 1 );
p->flags |= _BDF_GLYPH;
FT_TRACE4(( DBGMSG1, lineno, s ));
goto Exit;
}
/* Check for the ENCODING field. */
if ( ft_memcmp( line, "ENCODING", 8 ) == 0 )
{
if ( !( p->flags & _BDF_GLYPH ) )
{
/* Missing STARTCHAR field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" ));
error = BDF_Err_Missing_Startchar_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 );
/* Normalize negative encoding values. The specification only */
/* allows -1, but we can be more generous here. */
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
/* Check for alternative encoding format. */
if ( p->glyph_enc == -1 && p->list.used > 2 )
p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 );
FT_TRACE4(( DBGMSG2, p->glyph_enc ));
/* Check that the encoding is in the Unicode range because */
/* otherwise p->have (a bitmap with static size) overflows. */
if ( p->glyph_enc > 0 &&
(size_t)p->glyph_enc >= sizeof ( p->have ) * 8 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" ));
error = BDF_Err_Invalid_File_Format;
}
/* Check whether this encoding has already been encountered. */
/* If it has then change it to unencoded so it gets added if */
/* indicated. */
if ( p->glyph_enc >= 0 )
{
if ( _bdf_glyph_modified( p->have, p->glyph_enc ) )
{
/* Emit a message saying a glyph has been moved to the */
/* unencoded area. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12,
p->glyph_enc, p->glyph_name ));
p->glyph_enc = -1;
font->modified = 1;
}
else
_bdf_set_glyph_modified( p->have, p->glyph_enc );
}
if ( p->glyph_enc >= 0 )
{
/* Make sure there are enough glyphs allocated in case the */
/* number of characters happen to be wrong. */
if ( font->glyphs_used == font->glyphs_size )
{
if ( FT_RENEW_ARRAY( font->glyphs,
font->glyphs_size,
font->glyphs_size + 64 ) )
goto Exit;
font->glyphs_size += 64;
}
glyph = font->glyphs + font->glyphs_used++;
glyph->name = p->glyph_name;
glyph->encoding = p->glyph_enc;
/* Reset the initial glyph info. */
p->glyph_name = 0;
}
else
{
/* Unencoded glyph. Check whether it should */
/* be added or not. */
if ( p->opts->keep_unencoded != 0 )
{
/* Allocate the next unencoded glyph. */
if ( font->unencoded_used == font->unencoded_size )
{
if ( FT_RENEW_ARRAY( font->unencoded ,
font->unencoded_size,
font->unencoded_size + 4 ) )
goto Exit;
font->unencoded_size += 4;
}
glyph = font->unencoded + font->unencoded_used;
glyph->name = p->glyph_name;
glyph->encoding = font->unencoded_used++;
}
else
/* Free up the glyph name if the unencoded shouldn't be */
/* kept. */
FT_FREE( p->glyph_name );
p->glyph_name = 0;
}
/* Clear the flags that might be added when width and height are */
/* checked for consistency. */
p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK );
p->flags |= _BDF_ENCODING;
goto Exit;
}
/* Point at the glyph being constructed. */
if ( p->glyph_enc == -1 )
glyph = font->unencoded + ( font->unencoded_used - 1 );
else
glyph = font->glyphs + ( font->glyphs_used - 1 );
/* Check whether a bitmap is being constructed. */
if ( p->flags & _BDF_BITMAP )
{
/* If there are more rows than are specified in the glyph metrics, */
/* ignore the remaining lines. */
if ( p->row >= (unsigned long)glyph->bbx.height )
{
if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding ));
p->flags |= _BDF_GLYPH_HEIGHT_CHECK;
font->modified = 1;
}
goto Exit;
}
/* Only collect the number of nibbles indicated by the glyph */
/* metrics. If there are more columns, they are simply ignored. */
nibbles = glyph->bpr << 1;
bp = glyph->bitmap + p->row * glyph->bpr;
for ( i = 0; i < nibbles; i++ )
{
c = line[i];
if ( !sbitset( hdigits, c ) )
break;
*bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] );
if ( i + 1 < nibbles && ( i & 1 ) )
*++bp = 0;
}
/* If any line has not enough columns, */
/* indicate they have been padded with zero bits. */
if ( i < nibbles &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
/* Remove possible garbage at the right. */
mask_index = ( glyph->bbx.width * p->font->bpp ) & 7;
if ( glyph->bbx.width )
*bp &= nibble_mask[mask_index];
/* If any line has extra columns, indicate they have been removed. */
if ( i == nibbles &&
sbitset( hdigits, line[nibbles] ) &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
p->row++;
goto Exit;
}
/* Expect the SWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
p->flags |= _BDF_SWIDTH;
goto Exit;
}
/* Expect the DWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
if ( !( p->flags & _BDF_SWIDTH ) )
{
/* Missing SWIDTH field. Emit an auto correction message and set */
/* the scalable width from the device width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno ));
glyph->swidth = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
}
p->flags |= _BDF_DWIDTH;
goto Exit;
}
/* Expect the BBX field next. */
if ( ft_memcmp( line, "BBX", 3 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 );
glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 );
glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 );
glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 );
/* Generate the ascent and descent of the character. */
glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset );
glyph->bbx.descent = (short)( -glyph->bbx.y_offset );
/* Determine the overall font bounding box as the characters are */
/* loaded so corrections can be done later if indicated. */
p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas );
p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds );
p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset );
p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb );
p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb );
p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb );
if ( !( p->flags & _BDF_DWIDTH ) )
{
/* Missing DWIDTH field. Emit an auto correction message and set */
/* the device width to the glyph width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno ));
glyph->dwidth = glyph->bbx.width;
}
/* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */
/* value if necessary. */
if ( p->opts->correct_metrics != 0 )
{
/* Determine the point size of the glyph. */
unsigned short sw = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
if ( sw != glyph->swidth )
{
glyph->swidth = sw;
if ( p->glyph_enc == -1 )
_bdf_set_glyph_modified( font->umod,
font->unencoded_used - 1 );
else
_bdf_set_glyph_modified( font->nmod, glyph->encoding );
p->flags |= _BDF_SWIDTH_ADJ;
font->modified = 1;
}
}
p->flags |= _BDF_BBX;
goto Exit;
}
/* And finally, gather up the bitmap. */
if ( ft_memcmp( line, "BITMAP", 6 ) == 0 )
{
unsigned long bitmap_size;
if ( !( p->flags & _BDF_BBX ) )
{
/* Missing BBX field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" ));
error = BDF_Err_Missing_Bbx_Field;
goto Exit;
}
/* Allocate enough space for the bitmap. */
glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3;
bitmap_size = glyph->bpr * glyph->bbx.height;
if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno ));
error = BDF_Err_Bbx_Too_Big;
goto Exit;
}
else
glyph->bytes = (unsigned short)bitmap_size;
if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) )
goto Exit;
p->row = 0;
p->flags |= _BDF_BITMAP;
goto Exit;
}
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
Missing_Encoding:
/* Missing ENCODING field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" ));
error = BDF_Err_Missing_Encoding_Field;
Exit:
if ( error && ( p->flags & _BDF_GLYPH ) )
FT_FREE( p->glyph_name );
return error;
}
|
_bdf_parse_glyphs( char* line,
unsigned long linelen,
unsigned long lineno,
void* call_data,
void* client_data )
{
int c, mask_index;
char* s;
unsigned char* bp;
unsigned long i, slen, nibbles;
_bdf_parse_t* p;
bdf_glyph_t* glyph;
bdf_font_t* font;
FT_Memory memory;
FT_Error error = BDF_Err_Ok;
FT_UNUSED( call_data );
FT_UNUSED( lineno ); /* only used in debug mode */
p = (_bdf_parse_t *)client_data;
font = p->font;
memory = font->memory;
/* Check for a comment. */
if ( ft_memcmp( line, "COMMENT", 7 ) == 0 )
{
linelen -= 7;
s = line + 7;
if ( *s != 0 )
{
s++;
linelen--;
}
error = _bdf_add_comment( p->font, s, linelen );
goto Exit;
}
/* The very first thing expected is the number of glyphs. */
if ( !( p->flags & _BDF_GLYPHS ) )
{
if ( ft_memcmp( line, "CHARS", 5 ) != 0 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" ));
error = BDF_Err_Missing_Chars_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 );
/* Make sure the number of glyphs is non-zero. */
if ( p->cnt == 0 )
font->glyphs_size = 64;
/* Limit ourselves to 1,114,112 glyphs in the font (this is the */
/* number of code points available in Unicode). */
if ( p->cnt >= 0x110000UL )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" ));
error = BDF_Err_Invalid_Argument;
goto Exit;
}
if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) )
goto Exit;
p->flags |= _BDF_GLYPHS;
goto Exit;
}
/* Check for the ENDFONT field. */
if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 )
{
/* Sort the glyphs by encoding. */
ft_qsort( (char *)font->glyphs,
font->glyphs_used,
sizeof ( bdf_glyph_t ),
by_encoding );
p->flags &= ~_BDF_START;
goto Exit;
}
/* Check for the ENDCHAR field. */
if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 )
{
p->glyph_enc = 0;
p->flags &= ~_BDF_GLYPH_BITS;
goto Exit;
}
/* Check whether a glyph is being scanned but should be */
/* ignored because it is an unencoded glyph. */
if ( ( p->flags & _BDF_GLYPH ) &&
p->glyph_enc == -1 &&
p->opts->keep_unencoded == 0 )
goto Exit;
/* Check for the STARTCHAR field. */
if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 )
{
/* Set the character name in the parse info first until the */
/* encoding can be checked for an unencoded character. */
FT_FREE( p->glyph_name );
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
_bdf_list_shift( &p->list, 1 );
s = _bdf_list_join( &p->list, ' ', &slen );
if ( !s )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) )
goto Exit;
FT_MEM_COPY( p->glyph_name, s, slen + 1 );
p->flags |= _BDF_GLYPH;
FT_TRACE4(( DBGMSG1, lineno, s ));
goto Exit;
}
/* Check for the ENCODING field. */
if ( ft_memcmp( line, "ENCODING", 8 ) == 0 )
{
if ( !( p->flags & _BDF_GLYPH ) )
{
/* Missing STARTCHAR field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" ));
error = BDF_Err_Missing_Startchar_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 );
/* Normalize negative encoding values. The specification only */
/* allows -1, but we can be more generous here. */
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
/* Check for alternative encoding format. */
if ( p->glyph_enc == -1 && p->list.used > 2 )
p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 );
FT_TRACE4(( DBGMSG2, p->glyph_enc ));
/* Check that the encoding is in the Unicode range because */
/* otherwise p->have (a bitmap with static size) overflows. */
if ( p->glyph_enc > 0 &&
(size_t)p->glyph_enc >= sizeof ( p->have ) /
sizeof ( unsigned long ) * 32 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" ));
error = BDF_Err_Invalid_File_Format;
}
/* Check whether this encoding has already been encountered. */
/* If it has then change it to unencoded so it gets added if */
/* indicated. */
if ( p->glyph_enc >= 0 )
{
if ( _bdf_glyph_modified( p->have, p->glyph_enc ) )
{
/* Emit a message saying a glyph has been moved to the */
/* unencoded area. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12,
p->glyph_enc, p->glyph_name ));
p->glyph_enc = -1;
font->modified = 1;
}
else
_bdf_set_glyph_modified( p->have, p->glyph_enc );
}
if ( p->glyph_enc >= 0 )
{
/* Make sure there are enough glyphs allocated in case the */
/* number of characters happen to be wrong. */
if ( font->glyphs_used == font->glyphs_size )
{
if ( FT_RENEW_ARRAY( font->glyphs,
font->glyphs_size,
font->glyphs_size + 64 ) )
goto Exit;
font->glyphs_size += 64;
}
glyph = font->glyphs + font->glyphs_used++;
glyph->name = p->glyph_name;
glyph->encoding = p->glyph_enc;
/* Reset the initial glyph info. */
p->glyph_name = 0;
}
else
{
/* Unencoded glyph. Check whether it should */
/* be added or not. */
if ( p->opts->keep_unencoded != 0 )
{
/* Allocate the next unencoded glyph. */
if ( font->unencoded_used == font->unencoded_size )
{
if ( FT_RENEW_ARRAY( font->unencoded ,
font->unencoded_size,
font->unencoded_size + 4 ) )
goto Exit;
font->unencoded_size += 4;
}
glyph = font->unencoded + font->unencoded_used;
glyph->name = p->glyph_name;
glyph->encoding = font->unencoded_used++;
}
else
/* Free up the glyph name if the unencoded shouldn't be */
/* kept. */
FT_FREE( p->glyph_name );
p->glyph_name = 0;
}
/* Clear the flags that might be added when width and height are */
/* checked for consistency. */
p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK );
p->flags |= _BDF_ENCODING;
goto Exit;
}
/* Point at the glyph being constructed. */
if ( p->glyph_enc == -1 )
glyph = font->unencoded + ( font->unencoded_used - 1 );
else
glyph = font->glyphs + ( font->glyphs_used - 1 );
/* Check whether a bitmap is being constructed. */
if ( p->flags & _BDF_BITMAP )
{
/* If there are more rows than are specified in the glyph metrics, */
/* ignore the remaining lines. */
if ( p->row >= (unsigned long)glyph->bbx.height )
{
if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding ));
p->flags |= _BDF_GLYPH_HEIGHT_CHECK;
font->modified = 1;
}
goto Exit;
}
/* Only collect the number of nibbles indicated by the glyph */
/* metrics. If there are more columns, they are simply ignored. */
nibbles = glyph->bpr << 1;
bp = glyph->bitmap + p->row * glyph->bpr;
for ( i = 0; i < nibbles; i++ )
{
c = line[i];
if ( !sbitset( hdigits, c ) )
break;
*bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] );
if ( i + 1 < nibbles && ( i & 1 ) )
*++bp = 0;
}
/* If any line has not enough columns, */
/* indicate they have been padded with zero bits. */
if ( i < nibbles &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
/* Remove possible garbage at the right. */
mask_index = ( glyph->bbx.width * p->font->bpp ) & 7;
if ( glyph->bbx.width )
*bp &= nibble_mask[mask_index];
/* If any line has extra columns, indicate they have been removed. */
if ( i == nibbles &&
sbitset( hdigits, line[nibbles] ) &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
p->row++;
goto Exit;
}
/* Expect the SWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
p->flags |= _BDF_SWIDTH;
goto Exit;
}
/* Expect the DWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
if ( !( p->flags & _BDF_SWIDTH ) )
{
/* Missing SWIDTH field. Emit an auto correction message and set */
/* the scalable width from the device width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno ));
glyph->swidth = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
}
p->flags |= _BDF_DWIDTH;
goto Exit;
}
/* Expect the BBX field next. */
if ( ft_memcmp( line, "BBX", 3 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 );
glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 );
glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 );
glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 );
/* Generate the ascent and descent of the character. */
glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset );
glyph->bbx.descent = (short)( -glyph->bbx.y_offset );
/* Determine the overall font bounding box as the characters are */
/* loaded so corrections can be done later if indicated. */
p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas );
p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds );
p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset );
p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb );
p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb );
p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb );
if ( !( p->flags & _BDF_DWIDTH ) )
{
/* Missing DWIDTH field. Emit an auto correction message and set */
/* the device width to the glyph width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno ));
glyph->dwidth = glyph->bbx.width;
}
/* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */
/* value if necessary. */
if ( p->opts->correct_metrics != 0 )
{
/* Determine the point size of the glyph. */
unsigned short sw = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
if ( sw != glyph->swidth )
{
glyph->swidth = sw;
if ( p->glyph_enc == -1 )
_bdf_set_glyph_modified( font->umod,
font->unencoded_used - 1 );
else
_bdf_set_glyph_modified( font->nmod, glyph->encoding );
p->flags |= _BDF_SWIDTH_ADJ;
font->modified = 1;
}
}
p->flags |= _BDF_BBX;
goto Exit;
}
/* And finally, gather up the bitmap. */
if ( ft_memcmp( line, "BITMAP", 6 ) == 0 )
{
unsigned long bitmap_size;
if ( !( p->flags & _BDF_BBX ) )
{
/* Missing BBX field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" ));
error = BDF_Err_Missing_Bbx_Field;
goto Exit;
}
/* Allocate enough space for the bitmap. */
glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3;
bitmap_size = glyph->bpr * glyph->bbx.height;
if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno ));
error = BDF_Err_Bbx_Too_Big;
goto Exit;
}
else
glyph->bytes = (unsigned short)bitmap_size;
if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) )
goto Exit;
p->row = 0;
p->flags |= _BDF_BITMAP;
goto Exit;
}
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
Missing_Encoding:
/* Missing ENCODING field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" ));
error = BDF_Err_Missing_Encoding_Field;
Exit:
if ( error && ( p->flags & _BDF_GLYPH ) )
FT_FREE( p->glyph_name );
return error;
}
|
CVE-2012-5669
|
The _bdf_parse_glyphs function in FreeType before 2.4.11 allows context-dependent attackers to cause a denial of service (crash) and possibly execute arbitrary code via vectors related to BDF fonts and an incorrect calculation that triggers an out-of-bounds read.
|
[
"CWE-119"
] |
[
{
"line_no": 173,
"text": " if ( p->glyph_enc > 0 &&",
"char_start": null,
"char_end": null
},
{
"line_no": 174,
"text": " (size_t)p->glyph_enc >= sizeof ( p->have ) * 8 )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 173,
"text": " if ( p->glyph_enc > 0 &&",
"char_start": null,
"char_end": null
},
{
"line_no": 174,
"text": " (size_t)p->glyph_enc >= sizeof ( p->have ) /",
"char_start": null,
"char_end": null
},
{
"line_no": 175,
"text": " sizeof ( unsigned long ) * 32 )",
"char_start": null,
"char_end": null
}
] | 166
|
primevul
|
primevul_savannah_8fcf61523644df42e1905c81bed26838e0b04f91
|
8fcf61523644df42e1905c81bed26838e0b04f91
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
context_length_arg (char const *str, int *out)
{
uintmax_t value;
if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK
&& 0 <= (*out = value)
&& *out == value))
{
error (EXIT_TROUBLE, 0, "%s: %s", str,
_("invalid context length argument"));
}
page size, unless a read yields a partial page. */
static char *buffer; /* Base of buffer. */
static size_t bufalloc; /* Allocated buffer size, counting slop. */
#define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */
static int bufdesc; /* File descriptor. */
static char *bufbeg; /* Beginning of user-visible stuff. */
static char *buflim; /* Limit of user-visible stuff. */
static size_t pagesize; /* alignment of memory pages */
static off_t bufoffset; /* Read offset; defined on regular files. */
static off_t after_last_match; /* Pointer after last matching line that
would have been output if we were
outputting characters. */
/* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be
an integer or a pointer. Both args must be free of side effects. */
#define ALIGN_TO(val, alignment) \
((size_t) (val) % (alignment) == 0 \
? (val) \
: (val) + ((alignment) - (size_t) (val) % (alignment)))
/* Reset the buffer for a new file, returning zero if we should skip it.
Initialize on the first time through. */
static int
reset (int fd, char const *file, struct stats *stats)
{
if (! pagesize)
{
pagesize = getpagesize ();
if (pagesize == 0 || 2 * pagesize + 1 <= pagesize)
abort ();
bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1;
buffer = xmalloc (bufalloc);
}
bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize);
bufbeg[-1] = eolbyte;
bufdesc = fd;
if (S_ISREG (stats->stat.st_mode))
{
if (file)
bufoffset = 0;
else
{
bufoffset = lseek (fd, 0, SEEK_CUR);
if (bufoffset < 0)
{
suppressible_error (_("lseek failed"), errno);
return 0;
}
}
}
return 1;
}
/* Read new stuff into the buffer, saving the specified
amount of old stuff. When we're done, 'bufbeg' points
to the beginning of the buffer contents, and 'buflim'
points just after the end. Return zero if there's an error. */
static int
fillbuf (size_t save, struct stats const *stats)
{
size_t fillsize = 0;
int cc = 1;
char *readbuf;
size_t readsize;
/* Offset from start of buffer to start of old stuff
that we want to save. */
size_t saved_offset = buflim - save - buffer;
if (pagesize <= buffer + bufalloc - buflim)
{
readbuf = buflim;
bufbeg = buflim - save;
}
else
{
size_t minsize = save + pagesize;
size_t newsize;
size_t newalloc;
char *newbuf;
/* Grow newsize until it is at least as great as minsize. */
for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2)
if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2)
xalloc_die ();
/* Try not to allocate more memory than the file size indicates,
as that might cause unnecessary memory exhaustion if the file
is large. However, do not use the original file size as a
heuristic if we've already read past the file end, as most
likely the file is growing. */
if (S_ISREG (stats->stat.st_mode))
{
off_t to_be_read = stats->stat.st_size - bufoffset;
off_t maxsize_off = save + to_be_read;
if (0 <= to_be_read && to_be_read <= maxsize_off
&& maxsize_off == (size_t) maxsize_off
&& minsize <= (size_t) maxsize_off
&& (size_t) maxsize_off < newsize)
newsize = maxsize_off;
}
/* Add enough room so that the buffer is aligned and has room
for byte sentinels fore and aft. */
newalloc = newsize + pagesize + 1;
newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer;
readbuf = ALIGN_TO (newbuf + 1 + save, pagesize);
bufbeg = readbuf - save;
memmove (bufbeg, buffer + saved_offset, save);
bufbeg[-1] = eolbyte;
if (newbuf != buffer)
{
free (buffer);
buffer = newbuf;
}
}
readsize = buffer + bufalloc - readbuf;
readsize -= readsize % pagesize;
if (! fillsize)
{
ssize_t bytesread;
while ((bytesread = read (bufdesc, readbuf, readsize)) < 0
&& errno == EINTR)
continue;
if (bytesread < 0)
cc = 0;
else
fillsize = bytesread;
}
bufoffset += fillsize;
#if defined HAVE_DOS_FILE_CONTENTS
if (fillsize)
fillsize = undossify_input (readbuf, fillsize);
#endif
buflim = readbuf + fillsize;
return cc;
}
/* Flags controlling the style of output. */
static enum
{
BINARY_BINARY_FILES,
TEXT_BINARY_FILES,
WITHOUT_MATCH_BINARY_FILES
} binary_files; /* How to handle binary files. */
static int filename_mask; /* If zero, output nulls after filenames. */
static int out_quiet; /* Suppress all normal output. */
static int out_invert; /* Print nonmatching stuff. */
static int out_file; /* Print filenames. */
static int out_line; /* Print line numbers. */
static int out_byte; /* Print byte offsets. */
static int out_before; /* Lines of leading context. */
static int out_after; /* Lines of trailing context. */
static int out_file; /* Print filenames. */
static int out_line; /* Print line numbers. */
static int out_byte; /* Print byte offsets. */
static int out_before; /* Lines of leading context. */
static int out_after; /* Lines of trailing context. */
static int count_matches; /* Count matching lines. */
static int list_files; /* List matching files. */
static int no_filenames; /* Suppress file names. */
static off_t max_count; /* Stop after outputting this many
lines from an input file. */
static int line_buffered; /* If nonzero, use line buffering, i.e.
fflush everyline out. */
static char const *lastnl; /* Pointer after last newline counted. */
static char const *lastout; /* Pointer after last character output;
NULL if no character has been output
or if it's conceptually before bufbeg. */
static uintmax_t totalnl; /* Total newline count before lastnl. */
static off_t outleft; /* Maximum number of lines to be output. */
static int pending; /* Pending lines of output.
NULL if no character has been output
or if it's conceptually before bufbeg. */
static uintmax_t totalnl; /* Total newline count before lastnl. */
static off_t outleft; /* Maximum number of lines to be output. */
static int pending; /* Pending lines of output.
Always kept 0 if out_quiet is true. */
static int done_on_match; /* Stop scanning file on first match. */
static int exit_on_match; /* Exit on first match. */
/* Add two numbers that count input bytes or lines, and report an
error if the addition overflows. */
static uintmax_t
add_count (uintmax_t a, uintmax_t b)
{
uintmax_t sum = a + b;
if (sum < a)
error (EXIT_TROUBLE, 0, _("input is too large to count"));
return sum;
}
static void
nlscan (char const *lim)
{
size_t newlines = 0;
char const *beg;
for (beg = lastnl; beg < lim; beg++)
{
beg = memchr (beg, eolbyte, lim - beg);
if (!beg)
break;
newlines++;
}
totalnl = add_count (totalnl, newlines);
lastnl = lim;
}
/* Print the current filename. */
static void
print_filename (void)
{
pr_sgr_start_if (filename_color);
fputs (filename, stdout);
pr_sgr_end_if (filename_color);
}
/* Print a character separator. */
static void
print_sep (char sep)
{
pr_sgr_start_if (sep_color);
fputc (sep, stdout);
pr_sgr_end_if (sep_color);
}
/* Print a line number or a byte offset. */
static void
print_offset (uintmax_t pos, int min_width, const char *color)
{
/* Do not rely on printf to print pos, since uintmax_t may be longer
than long, and long long is not portable. */
char buf[sizeof pos * CHAR_BIT];
char *p = buf + sizeof buf;
do
{
*--p = '0' + pos % 10;
--min_width;
}
while ((pos /= 10) != 0);
/* Do this to maximize the probability of alignment across lines. */
if (align_tabs)
while (--min_width >= 0)
*--p = ' ';
pr_sgr_start_if (color);
fwrite (p, 1, buf + sizeof buf - p, stdout);
pr_sgr_end_if (color);
}
/* Print a whole line head (filename, line, byte). */
static void
print_line_head (char const *beg, char const *lim, int sep)
{
int pending_sep = 0;
if (out_file)
{
print_filename ();
if (filename_mask)
pending_sep = 1;
else
fputc (0, stdout);
}
if (out_line)
{
if (lastnl < lim)
{
nlscan (beg);
totalnl = add_count (totalnl, 1);
lastnl = lim;
}
if (pending_sep)
print_sep (sep);
print_offset (totalnl, 4, line_num_color);
pending_sep = 1;
}
if (out_byte)
{
uintmax_t pos = add_count (totalcc, beg - bufbeg);
#if defined HAVE_DOS_FILE_CONTENTS
pos = dossified_pos (pos);
#endif
if (pending_sep)
print_sep (sep);
print_offset (pos, 6, byte_num_color);
pending_sep = 1;
}
if (pending_sep)
{
/* This assumes sep is one column wide.
Try doing this any other way with Unicode
(and its combining and wide characters)
filenames and you're wasting your efforts. */
if (align_tabs)
fputs ("\t\b", stdout);
print_sep (sep);
}
}
static const char *
print_line_middle (const char *beg, const char *lim,
const char *line_color, const char *match_color)
{
size_t match_size;
size_t match_offset;
const char *cur = beg;
const char *mid = NULL;
while (cur < lim
&& ((match_offset = execute (beg, lim - beg, &match_size,
beg + (cur - beg))) != (size_t) -1))
{
char const *b = beg + match_offset;
/* Avoid matching the empty line at the end of the buffer. */
if (b == lim)
break;
/* Avoid hanging on grep --color "" foo */
if (match_size == 0)
{
/* Make minimal progress; there may be further non-empty matches. */
/* XXX - Could really advance by one whole multi-octet character. */
match_size = 1;
if (!mid)
mid = cur;
}
else
{
/* This function is called on a matching line only,
but is it selected or rejected/context? */
if (only_matching)
print_line_head (b, lim, (out_invert ? SEP_CHAR_REJECTED
: SEP_CHAR_SELECTED));
else
{
pr_sgr_start (line_color);
if (mid)
{
cur = mid;
mid = NULL;
}
fwrite (cur, sizeof (char), b - cur, stdout);
}
pr_sgr_start_if (match_color);
fwrite (b, sizeof (char), match_size, stdout);
pr_sgr_end_if (match_color);
if (only_matching)
fputs ("\n", stdout);
}
cur = b + match_size;
}
if (only_matching)
cur = lim;
else if (mid)
cur = mid;
return cur;
}
static const char *
print_line_tail (const char *beg, const char *lim, const char *line_color)
{
size_t eol_size;
size_t tail_size;
eol_size = (lim > beg && lim[-1] == eolbyte);
eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r');
tail_size = lim - eol_size - beg;
if (tail_size > 0)
{
pr_sgr_start (line_color);
fwrite (beg, 1, tail_size, stdout);
beg += tail_size;
pr_sgr_end (line_color);
}
return beg;
}
static void
prline (char const *beg, char const *lim, int sep)
{
int matching;
const char *line_color;
const char *match_color;
if (!only_matching)
print_line_head (beg, lim, sep);
matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert;
if (color_option)
{
line_color = (((sep == SEP_CHAR_SELECTED)
^ (out_invert && (color_option < 0)))
? selected_line_color : context_line_color);
match_color = (sep == SEP_CHAR_SELECTED
? selected_match_color : context_match_color);
}
else
line_color = match_color = NULL; /* Shouldn't be used. */
if ((only_matching && matching)
|| (color_option && (*line_color || *match_color)))
{
/* We already know that non-matching lines have no match (to colorize). */
if (matching && (only_matching || *match_color))
beg = print_line_middle (beg, lim, line_color, match_color);
/* FIXME: this test may be removable. */
if (!only_matching && *line_color)
beg = print_line_tail (beg, lim, line_color);
}
if (!only_matching && lim > beg)
fwrite (beg, 1, lim - beg, stdout);
if (ferror (stdout))
{
write_error_seen = 1;
error (EXIT_TROUBLE, 0, _("write error"));
}
lastout = lim;
if (line_buffered)
fflush (stdout);
}
/* Print pending lines of trailing context prior to LIM. Trailing context ends
at the next matching line when OUTLEFT is 0. */
static void
prpending (char const *lim)
{
if (!lastout)
lastout = bufbeg;
while (pending > 0 && lastout < lim)
{
char const *nl = memchr (lastout, eolbyte, lim - lastout);
size_t match_size;
--pending;
if (outleft
|| ((execute (lastout, nl + 1 - lastout,
&match_size, NULL) == (size_t) -1)
== !out_invert))
prline (lastout, nl + 1, SEP_CHAR_REJECTED);
else
pending = 0;
}
}
/* Print the lines between BEG and LIM. Deal with context crap.
If NLINESP is non-null, store a count of lines between BEG and LIM. */
static void
prtext (char const *beg, char const *lim, int *nlinesp)
{
/* Print the lines between BEG and LIM. Deal with context crap.
If NLINESP is non-null, store a count of lines between BEG and LIM. */
static void
prtext (char const *beg, char const *lim, int *nlinesp)
{
static int used; /* avoid printing SEP_STR_GROUP before any output */
char const *bp, *p;
char eol = eolbyte;
int i, n;
if (!out_quiet && pending > 0)
prpending (beg);
/* Deal with leading context crap. */
bp = lastout ? lastout : bufbeg;
for (i = 0; i < out_before; ++i)
if (p > bp)
do
--p;
while (p[-1] != eol);
/* We print the SEP_STR_GROUP separator only if our output is
discontiguous from the last output in the file. */
if ((out_before || out_after) && used && p != lastout && group_separator)
{
pr_sgr_start_if (sep_color);
fputs (group_separator, stdout);
pr_sgr_end_if (sep_color);
fputc ('\n', stdout);
}
while (p < beg)
{
char const *nl = memchr (p, eol, beg - p);
nl++;
prline (p, nl, SEP_CHAR_REJECTED);
p = nl;
}
}
if (nlinesp)
{
/* Caller wants a line count. */
for (n = 0; p < lim && n < outleft; n++)
{
char const *nl = memchr (p, eol, lim - p);
nl++;
if (!out_quiet)
prline (p, nl, SEP_CHAR_SELECTED);
p = nl;
}
*nlinesp = n;
/* relying on it that this function is never called when outleft = 0. */
after_last_match = bufoffset - (buflim - p);
}
else if (!out_quiet)
prline (beg, lim, SEP_CHAR_SELECTED);
pending = out_quiet ? 0 : out_after;
used = 1;
}
static size_t
do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr)
{
size_t result;
const char *line_next;
/* With the current implementation, using --ignore-case with a multi-byte
character set is very inefficient when applied to a large buffer
containing many matches. We can avoid much of the wasted effort
by matching line-by-line.
FIXME: this is just an ugly workaround, and it doesn't really
belong here. Also, PCRE is always using this same per-line
matching algorithm. Either we fix -i, or we should refactor
this code---for example, we could add another function pointer
to struct matcher to split the buffer passed to execute. It would
perform the memchr if line-by-line matching is necessary, or just
return buf + size otherwise. */
if (MB_CUR_MAX == 1 || !match_icase)
return execute (buf, size, match_size, start_ptr);
for (line_next = buf; line_next < buf + size; )
{
const char *line_buf = line_next;
const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf);
if (line_end == NULL)
line_next = line_end = buf + size;
else
line_next = line_end + 1;
if (start_ptr && start_ptr >= line_end)
continue;
result = execute (line_buf, line_next - line_buf, match_size, start_ptr);
if (result != (size_t) -1)
return (line_buf - buf) + result;
}
return (size_t) -1;
}
/* Scan the specified portion of the buffer, matching lines (or
between matching lines if OUT_INVERT is true). Return a count of
lines printed. */
static int
grepbuf (char const *beg, char const *lim)
/* Scan the specified portion of the buffer, matching lines (or
between matching lines if OUT_INVERT is true). Return a count of
lines printed. */
static int
grepbuf (char const *beg, char const *lim)
{
int nlines, n;
char const *p;
size_t match_offset;
size_t match_size;
{
char const *b = p + match_offset;
char const *endp = b + match_size;
/* Avoid matching the empty line at the end of the buffer. */
if (b == lim)
break;
if (!out_invert)
{
prtext (b, endp, (int *) 0);
nlines++;
break;
if (!out_invert)
{
prtext (b, endp, (int *) 0);
nlines++;
outleft--;
if (!outleft || done_on_match)
}
}
else if (p < b)
{
prtext (p, b, &n);
nlines += n;
outleft -= n;
if (!outleft)
return nlines;
}
p = endp;
}
if (out_invert && p < lim)
{
prtext (p, lim, &n);
nlines += n;
outleft -= n;
}
return nlines;
}
/* Search a given file. Normally, return a count of lines printed;
but if the file is a directory and we search it recursively, then
return -2 if there was a match, and -1 otherwise. */
static int
grep (int fd, char const *file, struct stats *stats)
/* Search a given file. Normally, return a count of lines printed;
but if the file is a directory and we search it recursively, then
return -2 if there was a match, and -1 otherwise. */
static int
grep (int fd, char const *file, struct stats *stats)
{
int nlines, i;
int not_text;
size_t residue, save;
char oldc;
return 0;
if (file && directories == RECURSE_DIRECTORIES
&& S_ISDIR (stats->stat.st_mode))
{
/* Close fd now, so that we don't open a lot of file descriptors
when we recurse deeply. */
if (close (fd) != 0)
suppressible_error (file, errno);
return grepdir (file, stats) - 2;
}
totalcc = 0;
lastout = 0;
totalnl = 0;
outleft = max_count;
after_last_match = 0;
pending = 0;
nlines = 0;
residue = 0;
save = 0;
if (! fillbuf (save, stats))
{
suppressible_error (filename, errno);
return 0;
}
not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
|| binary_files == WITHOUT_MATCH_BINARY_FILES)
&& memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
return 0;
done_on_match += not_text;
out_quiet += not_text;
for (;;)
{
lastnl = bufbeg;
if (lastout)
lastout = bufbeg;
beg = bufbeg + save;
/* no more data to scan (eof) except for maybe a residue -> break */
if (beg == buflim)
break;
/* Determine new residue (the length of an incomplete line at the end of
the buffer, 0 means there is no incomplete last line). */
oldc = beg[-1];
beg[-1] = eol;
for (lim = buflim; lim[-1] != eol; lim--)
continue;
beg[-1] = oldc;
if (lim == beg)
lim = beg - residue;
beg -= residue;
residue = buflim - lim;
if (beg < lim)
{
if (outleft)
nlines += grepbuf (beg, lim);
if (pending)
prpending (lim);
if ((!outleft && !pending) || (nlines && done_on_match && !out_invert))
goto finish_grep;
}
/* The last OUT_BEFORE lines at the end of the buffer will be needed as
leading context if there is a matching line at the begin of the
next data. Make beg point to their begin. */
i = 0;
beg = lim;
while (i < out_before && beg > bufbeg && beg != lastout)
{
++i;
do
--beg;
while (beg[-1] != eol);
}
/* detect if leading context is discontinuous from last printed line. */
if (beg != lastout)
lastout = 0;
/* Handle some details and read more data to scan. */
save = residue + lim - beg;
if (out_byte)
totalcc = add_count (totalcc, buflim - bufbeg - save);
if (out_line)
nlscan (beg);
if (! fillbuf (save, stats))
{
suppressible_error (filename, errno);
goto finish_grep;
}
}
if (residue)
{
*buflim++ = eol;
if (outleft)
nlines += grepbuf (bufbeg + save - residue, buflim);
if (pending)
prpending (buflim);
}
finish_grep:
done_on_match -= not_text;
out_quiet -= not_text;
if ((not_text & ~out_quiet) && nlines != 0)
printf (_("Binary file %s matches\n"), filename);
return nlines;
}
static int
grepfile (char const *file, struct stats *stats)
{
int desc;
int count;
int status;
grepfile (char const *file, struct stats *stats)
{
int desc;
int count;
int status;
filename = (file ? file : label ? label : _("(standard input)"));
/* Don't open yet, since that might have side effects on a device. */
desc = -1;
}
else
{
/* When skipping directories, don't worry about directories
that can't be opened. */
desc = open (file, O_RDONLY);
if (desc < 0 && directories != SKIP_DIRECTORIES)
{
suppressible_error (file, errno);
return 1;
}
}
if (desc < 0
? stat (file, &stats->stat) != 0
: fstat (desc, &stats->stat) != 0)
{
suppressible_error (filename, errno);
if (file)
close (desc);
return 1;
}
if ((directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
|| (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
|| S_ISBLK (stats->stat.st_mode)
|| S_ISSOCK (stats->stat.st_mode)
|| S_ISFIFO (stats->stat.st_mode))))
{
if (file)
close (desc);
return 1;
}
/* If there is a regular file on stdout and the current file refers
to the same i-node, we have to report the problem and skip it.
Otherwise when matching lines from some other input reach the
disk before we open this file, we can end up reading and matching
those lines and appending them to the file from which we're reading.
Then we'd have what appears to be an infinite loop that'd terminate
only upon filling the output file system or reaching a quota.
However, there is no risk of an infinite loop if grep is generating
no output, i.e., with --silent, --quiet, -q.
Similarly, with any of these:
--max-count=N (-m) (for N >= 2)
--files-with-matches (-l)
--files-without-match (-L)
there is no risk of trouble.
For --max-count=1, grep stops after printing the first match,
so there is no risk of malfunction. But even --max-count=2, with
input==output, while there is no risk of infloop, there is a race
condition that could result in "alternate" output. */
if (!out_quiet && list_files == 0 && 1 < max_count
&& S_ISREG (out_stat.st_mode) && out_stat.st_ino
&& SAME_INODE (stats->stat, out_stat))
{
if (! suppress_errors)
error (0, 0, _("input file %s is also the output"), quote (filename));
errseen = 1;
if (file)
close (desc);
return 1;
}
if (desc < 0)
{
desc = open (file, O_RDONLY);
if (desc < 0)
{
suppressible_error (file, errno);
return 1;
}
}
#if defined SET_BINARY
/* Set input to binary mode. Pipes are simulated with files
on DOS, so this includes the case of "foo | grep bar". */
if (!isatty (desc))
SET_BINARY (desc);
#endif
count = grep (desc, file, stats);
if (count < 0)
status = count + 2;
else
{
if (count_matches)
{
if (out_file)
{
print_filename ();
if (filename_mask)
print_sep (SEP_CHAR_SELECTED);
else
fputc (0, stdout);
}
printf ("%d\n", count);
}
else
fputc (0, stdout);
}
printf ("%d\n", count);
}
status = !count;
if (! file)
{
off_t required_offset = outleft ? bufoffset : after_last_match;
if (required_offset != bufoffset
&& lseek (desc, required_offset, SEEK_SET) < 0
&& S_ISREG (stats->stat.st_mode))
suppressible_error (filename, errno);
}
else
while (close (desc) != 0)
if (errno != EINTR)
{
suppressible_error (file, errno);
break;
}
}
|
context_length_arg (char const *str, int *out)
context_length_arg (char const *str, intmax_t *out)
{
switch (xstrtoimax (str, 0, 10, out, ""))
{
case LONGINT_OK:
case LONGINT_OVERFLOW:
if (0 <= *out)
break;
/* Fall through. */
default:
error (EXIT_TROUBLE, 0, "%s: %s", str,
_("invalid context length argument"));
}
page size, unless a read yields a partial page. */
static char *buffer; /* Base of buffer. */
static size_t bufalloc; /* Allocated buffer size, counting slop. */
#define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */
static int bufdesc; /* File descriptor. */
static char *bufbeg; /* Beginning of user-visible stuff. */
static char *buflim; /* Limit of user-visible stuff. */
static size_t pagesize; /* alignment of memory pages */
static off_t bufoffset; /* Read offset; defined on regular files. */
static off_t after_last_match; /* Pointer after last matching line that
would have been output if we were
outputting characters. */
/* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be
an integer or a pointer. Both args must be free of side effects. */
#define ALIGN_TO(val, alignment) \
((size_t) (val) % (alignment) == 0 \
? (val) \
: (val) + ((alignment) - (size_t) (val) % (alignment)))
/* Reset the buffer for a new file, returning zero if we should skip it.
Initialize on the first time through. */
static int
reset (int fd, char const *file, struct stats *stats)
{
if (! pagesize)
{
pagesize = getpagesize ();
if (pagesize == 0 || 2 * pagesize + 1 <= pagesize)
abort ();
bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1;
buffer = xmalloc (bufalloc);
}
bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize);
bufbeg[-1] = eolbyte;
bufdesc = fd;
if (S_ISREG (stats->stat.st_mode))
{
if (file)
bufoffset = 0;
else
{
bufoffset = lseek (fd, 0, SEEK_CUR);
if (bufoffset < 0)
{
suppressible_error (_("lseek failed"), errno);
return 0;
}
}
}
return 1;
}
/* Read new stuff into the buffer, saving the specified
amount of old stuff. When we're done, 'bufbeg' points
to the beginning of the buffer contents, and 'buflim'
points just after the end. Return zero if there's an error. */
static int
fillbuf (size_t save, struct stats const *stats)
{
size_t fillsize = 0;
int cc = 1;
char *readbuf;
size_t readsize;
/* Offset from start of buffer to start of old stuff
that we want to save. */
size_t saved_offset = buflim - save - buffer;
if (pagesize <= buffer + bufalloc - buflim)
{
readbuf = buflim;
bufbeg = buflim - save;
}
else
{
size_t minsize = save + pagesize;
size_t newsize;
size_t newalloc;
char *newbuf;
/* Grow newsize until it is at least as great as minsize. */
for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2)
if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2)
xalloc_die ();
/* Try not to allocate more memory than the file size indicates,
as that might cause unnecessary memory exhaustion if the file
is large. However, do not use the original file size as a
heuristic if we've already read past the file end, as most
likely the file is growing. */
if (S_ISREG (stats->stat.st_mode))
{
off_t to_be_read = stats->stat.st_size - bufoffset;
off_t maxsize_off = save + to_be_read;
if (0 <= to_be_read && to_be_read <= maxsize_off
&& maxsize_off == (size_t) maxsize_off
&& minsize <= (size_t) maxsize_off
&& (size_t) maxsize_off < newsize)
newsize = maxsize_off;
}
/* Add enough room so that the buffer is aligned and has room
for byte sentinels fore and aft. */
newalloc = newsize + pagesize + 1;
newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer;
readbuf = ALIGN_TO (newbuf + 1 + save, pagesize);
bufbeg = readbuf - save;
memmove (bufbeg, buffer + saved_offset, save);
bufbeg[-1] = eolbyte;
if (newbuf != buffer)
{
free (buffer);
buffer = newbuf;
}
}
readsize = buffer + bufalloc - readbuf;
readsize -= readsize % pagesize;
if (! fillsize)
{
ssize_t bytesread;
while ((bytesread = read (bufdesc, readbuf, readsize)) < 0
&& errno == EINTR)
continue;
if (bytesread < 0)
cc = 0;
else
fillsize = bytesread;
}
bufoffset += fillsize;
#if defined HAVE_DOS_FILE_CONTENTS
if (fillsize)
fillsize = undossify_input (readbuf, fillsize);
#endif
buflim = readbuf + fillsize;
return cc;
}
/* Flags controlling the style of output. */
static enum
{
BINARY_BINARY_FILES,
TEXT_BINARY_FILES,
WITHOUT_MATCH_BINARY_FILES
} binary_files; /* How to handle binary files. */
static int filename_mask; /* If zero, output nulls after filenames. */
static int out_quiet; /* Suppress all normal output. */
static int out_invert; /* Print nonmatching stuff. */
static int out_file; /* Print filenames. */
static int out_line; /* Print line numbers. */
static int out_byte; /* Print byte offsets. */
static int out_before; /* Lines of leading context. */
static int out_after; /* Lines of trailing context. */
static int out_file; /* Print filenames. */
static int out_line; /* Print line numbers. */
static int out_byte; /* Print byte offsets. */
static intmax_t out_before; /* Lines of leading context. */
static intmax_t out_after; /* Lines of trailing context. */
static int count_matches; /* Count matching lines. */
static int list_files; /* List matching files. */
static int no_filenames; /* Suppress file names. */
static intmax_t max_count; /* Stop after outputting this many
lines from an input file. */
static int line_buffered; /* If nonzero, use line buffering, i.e.
fflush everyline out. */
static char const *lastnl; /* Pointer after last newline counted. */
static char const *lastout; /* Pointer after last character output;
NULL if no character has been output
or if it's conceptually before bufbeg. */
static uintmax_t totalnl; /* Total newline count before lastnl. */
static off_t outleft; /* Maximum number of lines to be output. */
static int pending; /* Pending lines of output.
NULL if no character has been output
or if it's conceptually before bufbeg. */
static uintmax_t totalnl; /* Total newline count before lastnl. */
static intmax_t outleft; /* Maximum number of lines to be output. */
static intmax_t pending; /* Pending lines of output.
Always kept 0 if out_quiet is true. */
static int done_on_match; /* Stop scanning file on first match. */
static int exit_on_match; /* Exit on first match. */
/* Add two numbers that count input bytes or lines, and report an
error if the addition overflows. */
static uintmax_t
add_count (uintmax_t a, uintmax_t b)
{
uintmax_t sum = a + b;
if (sum < a)
error (EXIT_TROUBLE, 0, _("input is too large to count"));
return sum;
}
static void
nlscan (char const *lim)
{
size_t newlines = 0;
char const *beg;
for (beg = lastnl; beg < lim; beg++)
{
beg = memchr (beg, eolbyte, lim - beg);
if (!beg)
break;
newlines++;
}
totalnl = add_count (totalnl, newlines);
lastnl = lim;
}
/* Print the current filename. */
static void
print_filename (void)
{
pr_sgr_start_if (filename_color);
fputs (filename, stdout);
pr_sgr_end_if (filename_color);
}
/* Print a character separator. */
static void
print_sep (char sep)
{
pr_sgr_start_if (sep_color);
fputc (sep, stdout);
pr_sgr_end_if (sep_color);
}
/* Print a line number or a byte offset. */
static void
print_offset (uintmax_t pos, int min_width, const char *color)
{
/* Do not rely on printf to print pos, since uintmax_t may be longer
than long, and long long is not portable. */
char buf[sizeof pos * CHAR_BIT];
char *p = buf + sizeof buf;
do
{
*--p = '0' + pos % 10;
--min_width;
}
while ((pos /= 10) != 0);
/* Do this to maximize the probability of alignment across lines. */
if (align_tabs)
while (--min_width >= 0)
*--p = ' ';
pr_sgr_start_if (color);
fwrite (p, 1, buf + sizeof buf - p, stdout);
pr_sgr_end_if (color);
}
/* Print a whole line head (filename, line, byte). */
static void
print_line_head (char const *beg, char const *lim, int sep)
{
int pending_sep = 0;
if (out_file)
{
print_filename ();
if (filename_mask)
pending_sep = 1;
else
fputc (0, stdout);
}
if (out_line)
{
if (lastnl < lim)
{
nlscan (beg);
totalnl = add_count (totalnl, 1);
lastnl = lim;
}
if (pending_sep)
print_sep (sep);
print_offset (totalnl, 4, line_num_color);
pending_sep = 1;
}
if (out_byte)
{
uintmax_t pos = add_count (totalcc, beg - bufbeg);
#if defined HAVE_DOS_FILE_CONTENTS
pos = dossified_pos (pos);
#endif
if (pending_sep)
print_sep (sep);
print_offset (pos, 6, byte_num_color);
pending_sep = 1;
}
if (pending_sep)
{
/* This assumes sep is one column wide.
Try doing this any other way with Unicode
(and its combining and wide characters)
filenames and you're wasting your efforts. */
if (align_tabs)
fputs ("\t\b", stdout);
print_sep (sep);
}
}
static const char *
print_line_middle (const char *beg, const char *lim,
const char *line_color, const char *match_color)
{
size_t match_size;
size_t match_offset;
const char *cur = beg;
const char *mid = NULL;
while (cur < lim
&& ((match_offset = execute (beg, lim - beg, &match_size,
beg + (cur - beg))) != (size_t) -1))
{
char const *b = beg + match_offset;
/* Avoid matching the empty line at the end of the buffer. */
if (b == lim)
break;
/* Avoid hanging on grep --color "" foo */
if (match_size == 0)
{
/* Make minimal progress; there may be further non-empty matches. */
/* XXX - Could really advance by one whole multi-octet character. */
match_size = 1;
if (!mid)
mid = cur;
}
else
{
/* This function is called on a matching line only,
but is it selected or rejected/context? */
if (only_matching)
print_line_head (b, lim, (out_invert ? SEP_CHAR_REJECTED
: SEP_CHAR_SELECTED));
else
{
pr_sgr_start (line_color);
if (mid)
{
cur = mid;
mid = NULL;
}
fwrite (cur, sizeof (char), b - cur, stdout);
}
pr_sgr_start_if (match_color);
fwrite (b, sizeof (char), match_size, stdout);
pr_sgr_end_if (match_color);
if (only_matching)
fputs ("\n", stdout);
}
cur = b + match_size;
}
if (only_matching)
cur = lim;
else if (mid)
cur = mid;
return cur;
}
static const char *
print_line_tail (const char *beg, const char *lim, const char *line_color)
{
size_t eol_size;
size_t tail_size;
eol_size = (lim > beg && lim[-1] == eolbyte);
eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r');
tail_size = lim - eol_size - beg;
if (tail_size > 0)
{
pr_sgr_start (line_color);
fwrite (beg, 1, tail_size, stdout);
beg += tail_size;
pr_sgr_end (line_color);
}
return beg;
}
static void
prline (char const *beg, char const *lim, int sep)
{
int matching;
const char *line_color;
const char *match_color;
if (!only_matching)
print_line_head (beg, lim, sep);
matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert;
if (color_option)
{
line_color = (((sep == SEP_CHAR_SELECTED)
^ (out_invert && (color_option < 0)))
? selected_line_color : context_line_color);
match_color = (sep == SEP_CHAR_SELECTED
? selected_match_color : context_match_color);
}
else
line_color = match_color = NULL; /* Shouldn't be used. */
if ((only_matching && matching)
|| (color_option && (*line_color || *match_color)))
{
/* We already know that non-matching lines have no match (to colorize). */
if (matching && (only_matching || *match_color))
beg = print_line_middle (beg, lim, line_color, match_color);
/* FIXME: this test may be removable. */
if (!only_matching && *line_color)
beg = print_line_tail (beg, lim, line_color);
}
if (!only_matching && lim > beg)
fwrite (beg, 1, lim - beg, stdout);
if (ferror (stdout))
{
write_error_seen = 1;
error (EXIT_TROUBLE, 0, _("write error"));
}
lastout = lim;
if (line_buffered)
fflush (stdout);
}
/* Print pending lines of trailing context prior to LIM. Trailing context ends
at the next matching line when OUTLEFT is 0. */
static void
prpending (char const *lim)
{
if (!lastout)
lastout = bufbeg;
while (pending > 0 && lastout < lim)
{
char const *nl = memchr (lastout, eolbyte, lim - lastout);
size_t match_size;
--pending;
if (outleft
|| ((execute (lastout, nl + 1 - lastout,
&match_size, NULL) == (size_t) -1)
== !out_invert))
prline (lastout, nl + 1, SEP_CHAR_REJECTED);
else
pending = 0;
}
}
/* Print the lines between BEG and LIM. Deal with context crap.
If NLINESP is non-null, store a count of lines between BEG and LIM. */
static void
prtext (char const *beg, char const *lim, int *nlinesp)
{
/* Print the lines between BEG and LIM. Deal with context crap.
If NLINESP is non-null, store a count of lines between BEG and LIM. */
static void
prtext (char const *beg, char const *lim, intmax_t *nlinesp)
{
static int used; /* avoid printing SEP_STR_GROUP before any output */
char const *bp, *p;
char eol = eolbyte;
intmax_t i, n;
if (!out_quiet && pending > 0)
prpending (beg);
/* Deal with leading context crap. */
bp = lastout ? lastout : bufbeg;
for (i = 0; i < out_before; ++i)
if (p > bp)
do
--p;
while (p[-1] != eol);
/* We print the SEP_STR_GROUP separator only if our output is
discontiguous from the last output in the file. */
if ((out_before || out_after) && used && p != lastout && group_separator)
{
pr_sgr_start_if (sep_color);
fputs (group_separator, stdout);
pr_sgr_end_if (sep_color);
fputc ('\n', stdout);
}
while (p < beg)
{
char const *nl = memchr (p, eol, beg - p);
nl++;
prline (p, nl, SEP_CHAR_REJECTED);
p = nl;
}
}
if (nlinesp)
{
/* Caller wants a line count. */
for (n = 0; p < lim && n < outleft; n++)
{
char const *nl = memchr (p, eol, lim - p);
nl++;
if (!out_quiet)
prline (p, nl, SEP_CHAR_SELECTED);
p = nl;
}
*nlinesp = n;
/* relying on it that this function is never called when outleft = 0. */
after_last_match = bufoffset - (buflim - p);
}
else if (!out_quiet)
prline (beg, lim, SEP_CHAR_SELECTED);
pending = out_quiet ? 0 : out_after;
used = 1;
}
static size_t
do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr)
{
size_t result;
const char *line_next;
/* With the current implementation, using --ignore-case with a multi-byte
character set is very inefficient when applied to a large buffer
containing many matches. We can avoid much of the wasted effort
by matching line-by-line.
FIXME: this is just an ugly workaround, and it doesn't really
belong here. Also, PCRE is always using this same per-line
matching algorithm. Either we fix -i, or we should refactor
this code---for example, we could add another function pointer
to struct matcher to split the buffer passed to execute. It would
perform the memchr if line-by-line matching is necessary, or just
return buf + size otherwise. */
if (MB_CUR_MAX == 1 || !match_icase)
return execute (buf, size, match_size, start_ptr);
for (line_next = buf; line_next < buf + size; )
{
const char *line_buf = line_next;
const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf);
if (line_end == NULL)
line_next = line_end = buf + size;
else
line_next = line_end + 1;
if (start_ptr && start_ptr >= line_end)
continue;
result = execute (line_buf, line_next - line_buf, match_size, start_ptr);
if (result != (size_t) -1)
return (line_buf - buf) + result;
}
return (size_t) -1;
}
/* Scan the specified portion of the buffer, matching lines (or
between matching lines if OUT_INVERT is true). Return a count of
lines printed. */
static int
grepbuf (char const *beg, char const *lim)
/* Scan the specified portion of the buffer, matching lines (or
between matching lines if OUT_INVERT is true). Return a count of
lines printed. */
static intmax_t
grepbuf (char const *beg, char const *lim)
{
intmax_t nlines, n;
char const *p;
size_t match_offset;
size_t match_size;
{
char const *b = p + match_offset;
char const *endp = b + match_size;
/* Avoid matching the empty line at the end of the buffer. */
if (b == lim)
break;
if (!out_invert)
{
prtext (b, endp, (int *) 0);
nlines++;
break;
if (!out_invert)
{
prtext (b, endp, NULL);
nlines++;
outleft--;
if (!outleft || done_on_match)
}
}
else if (p < b)
{
prtext (p, b, &n);
nlines += n;
outleft -= n;
if (!outleft)
return nlines;
}
p = endp;
}
if (out_invert && p < lim)
{
prtext (p, lim, &n);
nlines += n;
outleft -= n;
}
return nlines;
}
/* Search a given file. Normally, return a count of lines printed;
but if the file is a directory and we search it recursively, then
return -2 if there was a match, and -1 otherwise. */
static int
grep (int fd, char const *file, struct stats *stats)
/* Search a given file. Normally, return a count of lines printed;
but if the file is a directory and we search it recursively, then
return -2 if there was a match, and -1 otherwise. */
static intmax_t
grep (int fd, char const *file, struct stats *stats)
{
intmax_t nlines, i;
int not_text;
size_t residue, save;
char oldc;
return 0;
if (file && directories == RECURSE_DIRECTORIES
&& S_ISDIR (stats->stat.st_mode))
{
/* Close fd now, so that we don't open a lot of file descriptors
when we recurse deeply. */
if (close (fd) != 0)
suppressible_error (file, errno);
return grepdir (file, stats) - 2;
}
totalcc = 0;
lastout = 0;
totalnl = 0;
outleft = max_count;
after_last_match = 0;
pending = 0;
nlines = 0;
residue = 0;
save = 0;
if (! fillbuf (save, stats))
{
suppressible_error (filename, errno);
return 0;
}
not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
|| binary_files == WITHOUT_MATCH_BINARY_FILES)
&& memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
return 0;
done_on_match += not_text;
out_quiet += not_text;
for (;;)
{
lastnl = bufbeg;
if (lastout)
lastout = bufbeg;
beg = bufbeg + save;
/* no more data to scan (eof) except for maybe a residue -> break */
if (beg == buflim)
break;
/* Determine new residue (the length of an incomplete line at the end of
the buffer, 0 means there is no incomplete last line). */
oldc = beg[-1];
beg[-1] = eol;
for (lim = buflim; lim[-1] != eol; lim--)
continue;
beg[-1] = oldc;
if (lim == beg)
lim = beg - residue;
beg -= residue;
residue = buflim - lim;
if (beg < lim)
{
if (outleft)
nlines += grepbuf (beg, lim);
if (pending)
prpending (lim);
if ((!outleft && !pending) || (nlines && done_on_match && !out_invert))
goto finish_grep;
}
/* The last OUT_BEFORE lines at the end of the buffer will be needed as
leading context if there is a matching line at the begin of the
next data. Make beg point to their begin. */
i = 0;
beg = lim;
while (i < out_before && beg > bufbeg && beg != lastout)
{
++i;
do
--beg;
while (beg[-1] != eol);
}
/* detect if leading context is discontinuous from last printed line. */
if (beg != lastout)
lastout = 0;
/* Handle some details and read more data to scan. */
save = residue + lim - beg;
if (out_byte)
totalcc = add_count (totalcc, buflim - bufbeg - save);
if (out_line)
nlscan (beg);
if (! fillbuf (save, stats))
{
suppressible_error (filename, errno);
goto finish_grep;
}
}
if (residue)
{
*buflim++ = eol;
if (outleft)
nlines += grepbuf (bufbeg + save - residue, buflim);
if (pending)
prpending (buflim);
}
finish_grep:
done_on_match -= not_text;
out_quiet -= not_text;
if ((not_text & ~out_quiet) && nlines != 0)
printf (_("Binary file %s matches\n"), filename);
return nlines;
}
static int
grepfile (char const *file, struct stats *stats)
{
int desc;
int count;
int status;
grepfile (char const *file, struct stats *stats)
{
int desc;
intmax_t count;
int status;
filename = (file ? file : label ? label : _("(standard input)"));
/* Don't open yet, since that might have side effects on a device. */
desc = -1;
}
else
{
/* When skipping directories, don't worry about directories
that can't be opened. */
desc = open (file, O_RDONLY);
if (desc < 0 && directories != SKIP_DIRECTORIES)
{
suppressible_error (file, errno);
return 1;
}
}
if (desc < 0
? stat (file, &stats->stat) != 0
: fstat (desc, &stats->stat) != 0)
{
suppressible_error (filename, errno);
if (file)
close (desc);
return 1;
}
if ((directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
|| (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
|| S_ISBLK (stats->stat.st_mode)
|| S_ISSOCK (stats->stat.st_mode)
|| S_ISFIFO (stats->stat.st_mode))))
{
if (file)
close (desc);
return 1;
}
/* If there is a regular file on stdout and the current file refers
to the same i-node, we have to report the problem and skip it.
Otherwise when matching lines from some other input reach the
disk before we open this file, we can end up reading and matching
those lines and appending them to the file from which we're reading.
Then we'd have what appears to be an infinite loop that'd terminate
only upon filling the output file system or reaching a quota.
However, there is no risk of an infinite loop if grep is generating
no output, i.e., with --silent, --quiet, -q.
Similarly, with any of these:
--max-count=N (-m) (for N >= 2)
--files-with-matches (-l)
--files-without-match (-L)
there is no risk of trouble.
For --max-count=1, grep stops after printing the first match,
so there is no risk of malfunction. But even --max-count=2, with
input==output, while there is no risk of infloop, there is a race
condition that could result in "alternate" output. */
if (!out_quiet && list_files == 0 && 1 < max_count
&& S_ISREG (out_stat.st_mode) && out_stat.st_ino
&& SAME_INODE (stats->stat, out_stat))
{
if (! suppress_errors)
error (0, 0, _("input file %s is also the output"), quote (filename));
errseen = 1;
if (file)
close (desc);
return 1;
}
if (desc < 0)
{
desc = open (file, O_RDONLY);
if (desc < 0)
{
suppressible_error (file, errno);
return 1;
}
}
#if defined SET_BINARY
/* Set input to binary mode. Pipes are simulated with files
on DOS, so this includes the case of "foo | grep bar". */
if (!isatty (desc))
SET_BINARY (desc);
#endif
count = grep (desc, file, stats);
if (count < 0)
status = count + 2;
else
{
if (count_matches)
{
if (out_file)
{
print_filename ();
if (filename_mask)
print_sep (SEP_CHAR_SELECTED);
else
fputc (0, stdout);
}
printf ("%d\n", count);
}
else
fputc (0, stdout);
}
printf ("%" PRIdMAX "\n", count);
}
status = !count;
if (! file)
{
off_t required_offset = outleft ? bufoffset : after_last_match;
if (required_offset != bufoffset
&& lseek (desc, required_offset, SEEK_SET) < 0
&& S_ISREG (stats->stat.st_mode))
suppressible_error (filename, errno);
}
else
while (close (desc) != 0)
if (errno != EINTR)
{
suppressible_error (file, errno);
break;
}
}
|
CVE-2012-5667
|
Multiple integer overflows in GNU Grep before 2.11 might allow context-dependent attackers to execute arbitrary code via vectors involving a long input line that triggers a heap-based buffer overflow.
|
[
"CWE-189"
] |
[
{
"line_no": 3,
"text": " uintmax_t value;",
"char_start": null,
"char_end": null
},
{
"line_no": 4,
"text": " if (! (xstrtoumax (str, 0, 10, &value, \"\") == LONGINT_OK",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": " && 0 <= (*out = value)",
"char_start": null,
"char_end": null
},
{
"line_no": 6,
"text": " && *out == value))",
"char_start": null,
"char_end": null
},
{
"line_no": 175,
"text": "static int out_before;\t\t/* Lines of leading context. */",
"char_start": null,
"char_end": null
},
{
"line_no": 176,
"text": "static int out_after;\t\t/* Lines of trailing context. */",
"char_start": null,
"char_end": null
},
{
"line_no": 180,
"text": "static off_t max_count;\t\t/* Stop after outputting this many",
"char_start": null,
"char_end": null
},
{
"line_no": 194,
"text": "static off_t outleft;\t\t/* Maximum number of lines to be output. */",
"char_start": null,
"char_end": null
},
{
"line_no": 195,
"text": "static int pending;\t\t/* Pending lines of output.",
"char_start": null,
"char_end": null
},
{
"line_no": 489,
"text": "prtext (char const *beg, char const *lim, int *nlinesp)",
"char_start": null,
"char_end": null
},
{
"line_no": 494,
"text": " int i, n;",
"char_start": null,
"char_end": null
},
{
"line_no": 598,
"text": "static int",
"char_start": null,
"char_end": null
},
{
"line_no": 601,
"text": " int nlines, n;",
"char_start": null,
"char_end": null
},
{
"line_no": 618,
"text": " prtext (b, endp, (int *) 0);",
"char_start": null,
"char_end": null
},
{
"line_no": 651,
"text": "static int",
"char_start": null,
"char_end": null
},
{
"line_no": 654,
"text": " int nlines, i;",
"char_start": null,
"char_end": null
},
{
"line_no": 784,
"text": " int count;",
"char_start": null,
"char_end": null
},
{
"line_no": 891,
"text": " printf (\"%d\\n\", count);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 2,
"text": "context_length_arg (char const *str, intmax_t *out)",
"char_start": null,
"char_end": null
},
{
"line_no": 4,
"text": " switch (xstrtoimax (str, 0, 10, out, \"\"))",
"char_start": null,
"char_end": null
},
{
"line_no": 6,
"text": " case LONGINT_OK:",
"char_start": null,
"char_end": null
},
{
"line_no": 7,
"text": " case LONGINT_OVERFLOW:",
"char_start": null,
"char_end": null
},
{
"line_no": 8,
"text": " if (0 <= *out)",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " break;",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " /* Fall through. */",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " default:",
"char_start": null,
"char_end": null
},
{
"line_no": 179,
"text": "static intmax_t out_before;\t/* Lines of leading context. */",
"char_start": null,
"char_end": null
},
{
"line_no": 180,
"text": "static intmax_t out_after;\t/* Lines of trailing context. */",
"char_start": null,
"char_end": null
},
{
"line_no": 184,
"text": "static intmax_t max_count;\t/* Stop after outputting this many",
"char_start": null,
"char_end": null
},
{
"line_no": 198,
"text": "static intmax_t outleft;\t/* Maximum number of lines to be output. */",
"char_start": null,
"char_end": null
},
{
"line_no": 199,
"text": "static intmax_t pending;\t/* Pending lines of output.",
"char_start": null,
"char_end": null
},
{
"line_no": 493,
"text": "prtext (char const *beg, char const *lim, intmax_t *nlinesp)",
"char_start": null,
"char_end": null
},
{
"line_no": 498,
"text": " intmax_t i, n;",
"char_start": null,
"char_end": null
},
{
"line_no": 602,
"text": "static intmax_t",
"char_start": null,
"char_end": null
},
{
"line_no": 605,
"text": " intmax_t nlines, n;",
"char_start": null,
"char_end": null
},
{
"line_no": 622,
"text": " prtext (b, endp, NULL);",
"char_start": null,
"char_end": null
},
{
"line_no": 655,
"text": "static intmax_t",
"char_start": null,
"char_end": null
},
{
"line_no": 658,
"text": " intmax_t nlines, i;",
"char_start": null,
"char_end": null
},
{
"line_no": 788,
"text": " intmax_t count;",
"char_start": null,
"char_end": null
},
{
"line_no": 895,
"text": " printf (\"%\" PRIdMAX \"\\n\", count);",
"char_start": null,
"char_end": null
}
] | 167
|
primevul
|
primevul_kde_a90289b0962663bc1d247bbbd31b9e65b2ca000e
|
a90289b0962663bc1d247bbbd31b9e65b2ca000e
|
kde
|
https://cgit.kde.org/konversation
|
ActionReply Smb4KMountHelper::mount(const QVariantMap &args)
{
ActionReply reply;
QMapIterator<QString, QVariant> it(args);
proc.setOutputChannelMode(KProcess::SeparateChannels);
proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
#if defined(Q_OS_LINUX)
proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true);
#endif
QVariantMap entry = it.value().toMap();
KProcess proc(this);
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << entry["mh_command"].toString();
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
#else
#endif
proc.setProgram(command);
proc.start();
if (proc.waitForStarted(-1))
{
bool userKill = false;
QStringList command;
#if defined(Q_OS_LINUX)
command << entry["mh_command"].toString();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << entry["mh_command"].toString();
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
else
{
}
if (HelperSupport::isStopped())
{
proc.kill();
userKill = true;
break;
}
else
{
}
}
if (proc.exitStatus() == KProcess::CrashExit)
{
if (!userKill)
{
reply.setType(ActionReply::HelperErrorType);
reply.setErrorDescription(i18n("The mount process crashed."));
break;
}
else
{
}
}
else
{
QString stdErr = QString::fromUtf8(proc.readAllStandardError());
reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed());
}
}
|
ActionReply Smb4KMountHelper::mount(const QVariantMap &args)
{
//
// The action reply
//
ActionReply reply;
// Get the mount executable
//
const QString mount = findMountExecutable();
//
QMapIterator<QString, QVariant> it(args);
proc.setOutputChannelMode(KProcess::SeparateChannels);
proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
#if defined(Q_OS_LINUX)
proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true);
#endif
QVariantMap entry = it.value().toMap();
// Check the executable
//
if (mount != entry["mh_command"].toString())
{
// Something weird is going on, bail out.
reply.setType(ActionReply::HelperErrorType);
return reply;
}
else
{
// Do nothing
}
//
KProcess proc(this);
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << entry["mh_command"].toString();
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
#else
#endif
proc.setProgram(command);
proc.start();
if (proc.waitForStarted(-1))
{
bool userKill = false;
QStringList command;
#if defined(Q_OS_LINUX)
command << mount;
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << mount;
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
else
{
}
if (HelperSupport::isStopped())
{
proc.kill();
userKill = true;
break;
}
else
{
}
}
if (proc.exitStatus() == KProcess::CrashExit)
{
if (!userKill)
{
reply.setType(ActionReply::HelperErrorType);
reply.setErrorDescription(i18n("The mount process crashed."));
break;
}
else
{
}
}
else
{
QString stdErr = QString::fromUtf8(proc.readAllStandardError());
reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed());
}
}
|
CVE-2017-8849
|
smb4k before 2.0.1 allows local users to gain root privileges by leveraging failure to verify arguments to the mount helper DBUS service.
|
[
"CWE-20"
] |
[
{
"line_no": 32,
"text": " command << entry[\"mh_command\"].toString();",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": " command << entry[\"mh_command\"].toString();",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 3,
"text": " //",
"char_start": null,
"char_end": null
},
{
"line_no": 4,
"text": " // The action reply",
"char_start": null,
"char_end": null
},
{
"line_no": 5,
"text": " //",
"char_start": null,
"char_end": null
},
{
"line_no": 8,
"text": " // Get the mount executable",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " //",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " const QString mount = findMountExecutable();",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " ",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " //",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " // Check the executable",
"char_start": null,
"char_end": null
},
{
"line_no": 22,
"text": " //",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " if (mount != entry[\"mh_command\"].toString())",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " // Something weird is going on, bail out.",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " reply.setType(ActionReply::HelperErrorType);",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " return reply;",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " else",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": " // Do nothing",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " ",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " //",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " command << mount;",
"char_start": null,
"char_end": null
},
{
"line_no": 59,
"text": " command << mount;",
"char_start": null,
"char_end": null
}
] | 169
|
primevul
|
primevul_savannah_df14e6c0b9592cbb24d5381dfc6106b14f915e75
|
df14e6c0b9592cbb24d5381dfc6106b14f915e75
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
}
cur = parser->root.cursor;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
|
parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
/* protect against invalid charcode */
if ( cur == parser->root.cursor )
{
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
cur = parser->root.cursor;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
|
CVE-2014-9745
|
The parse_encoding function in type1/t1load.c in FreeType before 2.5.3 allows remote attackers to cause a denial of service (infinite loop) via a "broken number-with-base" in a Postscript stream, as demonstrated by 8#garbage.
|
[
"CWE-399"
] |
[] |
[
{
"line_no": 124,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 125,
"text": " /* protect against invalid charcode */",
"char_start": null,
"char_end": null
},
{
"line_no": 126,
"text": " if ( cur == parser->root.cursor )",
"char_start": null,
"char_end": null
},
{
"line_no": 127,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 128,
"text": " parser->root.error = FT_THROW( Unknown_File_Format );",
"char_start": null,
"char_end": null
},
{
"line_no": 129,
"text": " return;",
"char_start": null,
"char_end": null
},
{
"line_no": 130,
"text": " }",
"char_start": null,
"char_end": null
}
] | 177
|
primevul
|
primevul_haproxy_17514045e5d934dede62116216c1b016fe23dd06
|
17514045e5d934dede62116216c1b016fe23dd06
|
haproxy
|
https://github.com/haproxy/haproxy
|
void check_request_for_cacheability(struct stream *s, struct channel *chn)
{
struct http_txn *txn = s->txn;
char *p1, *p2;
char *cur_ptr, *cur_end, *cur_next;
int pragma_found;
int cc_found;
int cur_idx;
if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
return; /* nothing more to do here */
cur_idx = 0;
pragma_found = cc_found = 0;
cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
struct hdr_idx_elem *cur_hdr;
int val;
cur_hdr = &txn->hdr_idx.v[cur_idx];
cur_ptr = cur_next;
cur_end = cur_ptr + cur_hdr->len;
cur_next = cur_end + cur_hdr->cr + 1;
/* We have one full header between cur_ptr and cur_end, and the
* next header starts at cur_next.
*/
val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
if (val) {
if ((cur_end - (cur_ptr + val) >= 8) &&
strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
pragma_found = 1;
continue;
}
}
val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
if (!val)
continue;
p2 = p1;
while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
p2++;
/* we have a complete value between p1 and p2. We don't check the
* values after max-age, max-stale nor min-fresh, we simply don't
* use the cache when they're specified.
*/
if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) ||
((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) {
txn->flags |= TX_CACHE_IGNORE;
continue;
}
if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) {
txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
continue;
}
}
/* RFC7234#5.4:
* When the Cache-Control header field is also present and
* understood in a request, Pragma is ignored.
* When the Cache-Control header field is not present in a
* request, caches MUST consider the no-cache request
* pragma-directive as having the same effect as if
* "Cache-Control: no-cache" were present.
*/
if (!cc_found && pragma_found)
txn->flags |= TX_CACHE_IGNORE;
}
|
void check_request_for_cacheability(struct stream *s, struct channel *chn)
{
struct http_txn *txn = s->txn;
char *p1, *p2;
char *cur_ptr, *cur_end, *cur_next;
int pragma_found;
int cc_found;
int cur_idx;
if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
return; /* nothing more to do here */
cur_idx = 0;
pragma_found = cc_found = 0;
cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
struct hdr_idx_elem *cur_hdr;
int val;
cur_hdr = &txn->hdr_idx.v[cur_idx];
cur_ptr = cur_next;
cur_end = cur_ptr + cur_hdr->len;
cur_next = cur_end + cur_hdr->cr + 1;
/* We have one full header between cur_ptr and cur_end, and the
* next header starts at cur_next.
*/
val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
if (val) {
if ((cur_end - (cur_ptr + val) >= 8) &&
strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
pragma_found = 1;
continue;
}
}
/* Don't use the cache and don't try to store if we found the
* Authorization header */
val = http_header_match2(cur_ptr, cur_end, "Authorization", 13);
if (val) {
txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
txn->flags |= TX_CACHE_IGNORE;
continue;
}
val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
if (!val)
continue;
p2 = p1;
while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
p2++;
/* we have a complete value between p1 and p2. We don't check the
* values after max-age, max-stale nor min-fresh, we simply don't
* use the cache when they're specified.
*/
if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) ||
((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) {
txn->flags |= TX_CACHE_IGNORE;
continue;
}
if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) {
txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
continue;
}
}
/* RFC7234#5.4:
* When the Cache-Control header field is also present and
* understood in a request, Pragma is ignored.
* When the Cache-Control header field is not present in a
* request, caches MUST consider the no-cache request
* pragma-directive as having the same effect as if
* "Cache-Control: no-cache" were present.
*/
if (!cc_found && pragma_found)
txn->flags |= TX_CACHE_IGNORE;
}
|
CVE-2018-11469
|
Incorrect caching of responses to requests including an Authorization header in HAProxy 1.8.0 through 1.8.9 (if cache enabled) allows attackers to achieve information disclosure via an unauthenticated remote request, related to the proto_http.c check_request_for_cacheability function.
|
[
"CWE-200"
] |
[] |
[
{
"line_no": 39,
"text": " /* Don't use the cache and don't try to store if we found the",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": " * Authorization header */",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " val = http_header_match2(cur_ptr, cur_end, \"Authorization\", 13);",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": " if (val) {",
"char_start": null,
"char_end": null
},
{
"line_no": 43,
"text": " txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;",
"char_start": null,
"char_end": null
},
{
"line_no": 44,
"text": " txn->flags |= TX_CACHE_IGNORE;",
"char_start": null,
"char_end": null
},
{
"line_no": 45,
"text": " continue;",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": "",
"char_start": null,
"char_end": null
}
] | 178
|
primevul
|
primevul_savannah_18a8f0d9943369449bc4de92d411c78fb08d616c
|
18a8f0d9943369449bc4de92d411c78fb08d616c
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
p += sizeof ( short );
for ( i = 0; i < string_count && i < 64; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= FT_MIN( string_count, 64 ) )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
|
parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
string_count = FT_MIN( 64, string_count );
p += sizeof ( short );
for ( i = 0; i < string_count; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= string_count )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
|
CVE-2014-9672
|
Array index error in the parse_fond function in base/ftmac.c in FreeType before 2.5.4 allows remote attackers to cause a denial of service (out-of-bounds read) or obtain sensitive information from process memory via a crafted FOND resource in a Mac font file.
|
[
"CWE-119"
] |
[
{
"line_no": 59,
"text": " for ( i = 0; i < string_count && i < 64; i++ )",
"char_start": null,
"char_end": null
},
{
"line_no": 76,
"text": " style->indexes[face_index] <= FT_MIN( string_count, 64 ) )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 57,
"text": " string_count = FT_MIN( 64, string_count );",
"char_start": null,
"char_end": null
},
{
"line_no": 60,
"text": " for ( i = 0; i < string_count; i++ )",
"char_start": null,
"char_end": null
},
{
"line_no": 77,
"text": " style->indexes[face_index] <= string_count )",
"char_start": null,
"char_end": null
}
] | 179
|
primevul
|
primevul_savannah_ef1eba75187adfac750f326b563fe543dd5ff4e6
|
ef1eba75187adfac750f326b563fe543dd5ff4e6
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
pcf_get_encodings( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong format, size;
int firstCol, lastCol;
int firstRow, lastRow;
int nencoding, encodingOffset;
int i, j, k;
PCF_Encoding encoding = NULL;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_BDF_ENCODINGS,
&format,
&size );
if ( error )
return error;
error = FT_Stream_EnterFrame( stream, 14 );
if ( error )
return error;
format = FT_GET_ULONG_LE();
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
firstCol = FT_GET_SHORT();
lastCol = FT_GET_SHORT();
firstRow = FT_GET_SHORT();
lastRow = FT_GET_SHORT();
face->defaultChar = FT_GET_SHORT();
}
else
{
firstCol = FT_GET_SHORT_LE();
lastCol = FT_GET_SHORT_LE();
firstRow = FT_GET_SHORT_LE();
lastRow = FT_GET_SHORT_LE();
face->defaultChar = FT_GET_SHORT_LE();
}
FT_Stream_ExitFrame( stream );
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
return FT_THROW( Invalid_File_Format );
FT_TRACE4(( "pdf_get_encodings:\n" ));
FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n",
goto Bail;
k = 0;
for ( i = firstRow; i <= lastRow; i++ )
{
for ( j = firstCol; j <= lastCol; j++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
encodingOffset = FT_GET_SHORT();
else
encodingOffset = FT_GET_SHORT_LE();
if ( encodingOffset != -1 )
{
encoding[k].enc = i * 256 + j;
encoding[k].glyph = (FT_Short)encodingOffset;
FT_TRACE5(( " code %d (0x%04X): idx %d\n",
encoding[k].enc, encoding[k].enc, encoding[k].glyph ));
k++;
}
}
}
FT_Stream_ExitFrame( stream );
if ( FT_RENEW_ARRAY( encoding, nencoding, k ) )
goto Bail;
face->nencodings = k;
face->encodings = encoding;
return error;
Bail:
FT_FREE( encoding );
return error;
}
|
pcf_get_encodings( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong format, size;
int firstCol, lastCol;
int firstRow, lastRow;
int nencoding, encodingOffset;
int i, j, k;
PCF_Encoding encoding = NULL;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_BDF_ENCODINGS,
&format,
&size );
if ( error )
return error;
error = FT_Stream_EnterFrame( stream, 14 );
if ( error )
return error;
format = FT_GET_ULONG_LE();
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
firstCol = FT_GET_SHORT();
lastCol = FT_GET_SHORT();
firstRow = FT_GET_SHORT();
lastRow = FT_GET_SHORT();
face->defaultChar = FT_GET_SHORT();
}
else
{
firstCol = FT_GET_SHORT_LE();
lastCol = FT_GET_SHORT_LE();
firstRow = FT_GET_SHORT_LE();
lastRow = FT_GET_SHORT_LE();
face->defaultChar = FT_GET_SHORT_LE();
}
FT_Stream_ExitFrame( stream );
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
return FT_THROW( Invalid_File_Format );
/* sanity checks */
if ( firstCol < 0 ||
firstCol > lastCol ||
lastCol > 0xFF ||
firstRow < 0 ||
firstRow > lastRow ||
lastRow > 0xFF )
return FT_THROW( Invalid_Table );
FT_TRACE4(( "pdf_get_encodings:\n" ));
FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n",
goto Bail;
k = 0;
for ( i = firstRow; i <= lastRow; i++ )
{
for ( j = firstCol; j <= lastCol; j++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
encodingOffset = FT_GET_SHORT();
else
encodingOffset = FT_GET_SHORT_LE();
if ( encodingOffset != -1 )
{
encoding[k].enc = i * 256 + j;
encoding[k].glyph = (FT_Short)encodingOffset;
FT_TRACE5(( " code %d (0x%04X): idx %d\n",
encoding[k].enc, encoding[k].enc, encoding[k].glyph ));
k++;
}
}
}
FT_Stream_ExitFrame( stream );
if ( FT_RENEW_ARRAY( encoding, nencoding, k ) )
goto Bail;
face->nencodings = k;
face->encodings = encoding;
return error;
Bail:
FT_FREE( encoding );
return error;
}
|
CVE-2014-9670
|
Multiple integer signedness errors in the pcf_get_encodings function in pcf/pcfread.c in FreeType before 2.5.4 allow remote attackers to cause a denial of service (integer overflow, NULL pointer dereference, and application crash) via a crafted PCF file that specifies negative values for the first column and first row.
|
[
"CWE-189"
] |
[] |
[
{
"line_no": 51,
"text": " /* sanity checks */",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " if ( firstCol < 0 ||",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": " firstCol > lastCol ||",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " lastCol > 0xFF ||",
"char_start": null,
"char_end": null
},
{
"line_no": 55,
"text": " firstRow < 0 ||",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": " firstRow > lastRow ||",
"char_start": null,
"char_end": null
},
{
"line_no": 57,
"text": " lastRow > 0xFF )",
"char_start": null,
"char_end": null
},
{
"line_no": 58,
"text": " return FT_THROW( Invalid_Table );",
"char_start": null,
"char_end": null
},
{
"line_no": 59,
"text": "",
"char_start": null,
"char_end": null
}
] | 181
|
primevul
|
primevul_savannah_602040b1112c9f94d68e200be59ea7ac3d104565
|
602040b1112c9f94d68e200be59ea7ac3d104565
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
tt_cmap8_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_Byte* is32;
FT_UInt32 length;
FT_UInt32 num_groups;
if ( table + 16 + 8192 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 )
FT_INVALID_TOO_SHORT;
is32 = table + 12;
p = is32 + 8192; /* skip `is32' array */
num_groups = TT_NEXT_ULONG( p );
if ( p + num_groups * 12 > valid->limit )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
FT_UInt32 n, start, end, start_id, count, last = 0;
for ( n = 0; n < num_groups; n++ )
{
FT_UInt hi, lo;
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
count = (FT_UInt32)( end - start + 1 );
{
hi = (FT_UInt)( start >> 16 );
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 )
FT_INVALID_DATA;
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 )
FT_INVALID_DATA;
}
}
else
{
/* start_hi == 0; check that is32[i] is 0 for each i in */
/* the range [start..end] */
/* end_hi cannot be != 0! */
if ( end & ~0xFFFFU )
FT_INVALID_DATA;
for ( ; count > 0; count--, start++ )
{
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 )
FT_INVALID_DATA;
}
}
}
last = end;
}
|
tt_cmap8_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_Byte* is32;
FT_UInt32 length;
FT_UInt32 num_groups;
if ( table + 16 + 8192 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 )
FT_INVALID_TOO_SHORT;
is32 = table + 12;
p = is32 + 8192; /* skip `is32' array */
num_groups = TT_NEXT_ULONG( p );
/* p + num_groups * 12 > valid->limit ? */
if ( num_groups > (FT_UInt32)( valid->limit - p ) / 12 )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
FT_UInt32 n, start, end, start_id, count, last = 0;
for ( n = 0; n < num_groups; n++ )
{
FT_UInt hi, lo;
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
FT_UInt32 d = end - start;
/* start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ? */
if ( d > TT_VALID_GLYPH_COUNT( valid ) ||
start_id >= TT_VALID_GLYPH_COUNT( valid ) - d )
FT_INVALID_GLYPH_ID;
count = (FT_UInt32)( end - start + 1 );
{
hi = (FT_UInt)( start >> 16 );
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 )
FT_INVALID_DATA;
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 )
FT_INVALID_DATA;
}
}
else
{
/* start_hi == 0; check that is32[i] is 0 for each i in */
/* the range [start..end] */
/* end_hi cannot be != 0! */
if ( end & ~0xFFFFU )
FT_INVALID_DATA;
for ( ; count > 0; count--, start++ )
{
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 )
FT_INVALID_DATA;
}
}
}
last = end;
}
|
CVE-2014-9669
|
Multiple integer overflows in sfnt/ttcmap.c in FreeType before 2.5.4 allow remote attackers to cause a denial of service (out-of-bounds read or memory corruption) or possibly have unspecified other impact via a crafted cmap SFNT table.
|
[
"CWE-125"
] |
[
{
"line_no": 21,
"text": " if ( p + num_groups * 12 > valid->limit )",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 21,
"text": " /* p + num_groups * 12 > valid->limit ? */",
"char_start": null,
"char_end": null
},
{
"line_no": 22,
"text": " if ( num_groups > (FT_UInt32)( valid->limit - p ) / 12 )",
"char_start": null,
"char_end": null
},
{
"line_no": 47,
"text": " FT_UInt32 d = end - start;",
"char_start": null,
"char_end": null
},
{
"line_no": 48,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 49,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 50,
"text": " /* start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ? */",
"char_start": null,
"char_end": null
},
{
"line_no": 51,
"text": " if ( d > TT_VALID_GLYPH_COUNT( valid ) ||",
"char_start": null,
"char_end": null
},
{
"line_no": 52,
"text": " start_id >= TT_VALID_GLYPH_COUNT( valid ) - d )",
"char_start": null,
"char_end": null
}
] | 182
|
primevul
|
primevul_savannah_257c270bd25e15890190a28a1456e7623bba4439
|
257c270bd25e15890190a28a1456e7623bba4439
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
tt_sbit_decoder_init( TT_SBitDecoder decoder,
TT_Face face,
FT_ULong strike_index,
TT_SBit_MetricsRec* metrics )
{
FT_Error error;
FT_Stream stream = face->root.stream;
FT_ULong ebdt_size;
error = face->goto_table( face, TTAG_CBDT, stream, &ebdt_size );
if ( error )
error = face->goto_table( face, TTAG_EBDT, stream, &ebdt_size );
if ( error )
error = face->goto_table( face, TTAG_bdat, stream, &ebdt_size );
if ( error )
goto Exit;
decoder->face = face;
decoder->stream = stream;
decoder->bitmap = &face->root.glyph->bitmap;
decoder->metrics = metrics;
decoder->metrics_loaded = 0;
decoder->bitmap_allocated = 0;
decoder->ebdt_start = FT_STREAM_POS();
decoder->ebdt_size = ebdt_size;
decoder->eblc_base = face->sbit_table;
decoder->eblc_limit = face->sbit_table + face->sbit_table_size;
/* now find the strike corresponding to the index */
{
FT_Byte* p;
if ( 8 + 48 * strike_index + 3 * 4 + 34 + 1 > face->sbit_table_size )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
p = decoder->eblc_base + 8 + 48 * strike_index;
decoder->strike_index_array = FT_NEXT_ULONG( p );
p += 4;
decoder->strike_index_count = FT_NEXT_ULONG( p );
p += 34;
decoder->bit_depth = *p;
if ( decoder->strike_index_array > face->sbit_table_size ||
decoder->strike_index_array + 8 * decoder->strike_index_count >
face->sbit_table_size )
error = FT_THROW( Invalid_File_Format );
}
}
|
tt_sbit_decoder_init( TT_SBitDecoder decoder,
TT_Face face,
FT_ULong strike_index,
TT_SBit_MetricsRec* metrics )
{
FT_Error error;
FT_Stream stream = face->root.stream;
FT_ULong ebdt_size;
error = face->goto_table( face, TTAG_CBDT, stream, &ebdt_size );
if ( error )
error = face->goto_table( face, TTAG_EBDT, stream, &ebdt_size );
if ( error )
error = face->goto_table( face, TTAG_bdat, stream, &ebdt_size );
if ( error )
goto Exit;
decoder->face = face;
decoder->stream = stream;
decoder->bitmap = &face->root.glyph->bitmap;
decoder->metrics = metrics;
decoder->metrics_loaded = 0;
decoder->bitmap_allocated = 0;
decoder->ebdt_start = FT_STREAM_POS();
decoder->ebdt_size = ebdt_size;
decoder->eblc_base = face->sbit_table;
decoder->eblc_limit = face->sbit_table + face->sbit_table_size;
/* now find the strike corresponding to the index */
{
FT_Byte* p;
if ( 8 + 48 * strike_index + 3 * 4 + 34 + 1 > face->sbit_table_size )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
p = decoder->eblc_base + 8 + 48 * strike_index;
decoder->strike_index_array = FT_NEXT_ULONG( p );
p += 4;
decoder->strike_index_count = FT_NEXT_ULONG( p );
p += 34;
decoder->bit_depth = *p;
/* decoder->strike_index_array + */
/* 8 * decoder->strike_index_count > face->sbit_table_size ? */
if ( decoder->strike_index_array > face->sbit_table_size ||
decoder->strike_index_count >
( face->sbit_table_size - decoder->strike_index_array ) / 8 )
error = FT_THROW( Invalid_File_Format );
}
}
|
CVE-2014-9666
|
The tt_sbit_decoder_init function in sfnt/ttsbit.c in FreeType before 2.5.4 proceeds with a count-to-size association without restricting the count value, which allows remote attackers to cause a denial of service (integer overflow and out-of-bounds read) or possibly have unspecified other impact via a crafted embedded bitmap.
|
[
"CWE-189"
] |
[
{
"line_no": 52,
"text": " if ( decoder->strike_index_array > face->sbit_table_size ||",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": " decoder->strike_index_array + 8 * decoder->strike_index_count >",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " face->sbit_table_size )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 52,
"text": " /* decoder->strike_index_array + */",
"char_start": null,
"char_end": null
},
{
"line_no": 53,
"text": " /* 8 * decoder->strike_index_count > face->sbit_table_size ? */",
"char_start": null,
"char_end": null
},
{
"line_no": 54,
"text": " if ( decoder->strike_index_array > face->sbit_table_size ||",
"char_start": null,
"char_end": null
},
{
"line_no": 55,
"text": " decoder->strike_index_count >",
"char_start": null,
"char_end": null
},
{
"line_no": 56,
"text": " ( face->sbit_table_size - decoder->strike_index_array ) / 8 )",
"char_start": null,
"char_end": null
}
] | 183
|
primevul
|
primevul_savannah_f70d9342e65cd2cb44e9f26b6d7edeedf191fc6c
|
f70d9342e65cd2cb44e9f26b6d7edeedf191fc6c
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
tt_face_load_kern( TT_Face face,
FT_Stream stream )
{
FT_Error error;
FT_ULong table_size;
FT_Byte* p;
FT_Byte* p_limit;
FT_UInt nn, num_tables;
FT_UInt32 avail = 0, ordered = 0;
/* the kern table is optional; exit silently if it is missing */
error = face->goto_table( face, TTAG_kern, stream, &table_size );
if ( error )
goto Exit;
if ( table_size < 4 ) /* the case of a malformed table */
{
FT_ERROR(( "tt_face_load_kern:"
" kerning table is too small - ignored\n" ));
error = FT_THROW( Table_Missing );
goto Exit;
}
if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) )
{
FT_ERROR(( "tt_face_load_kern:"
" could not extract kerning table\n" ));
goto Exit;
}
face->kern_table_size = table_size;
p = face->kern_table;
p_limit = p + table_size;
p += 2; /* skip version */
num_tables = FT_NEXT_USHORT( p );
if ( num_tables > 32 ) /* we only support up to 32 sub-tables */
num_tables = 32;
for ( nn = 0; nn < num_tables; nn++ )
{
FT_UInt num_pairs, length, coverage;
FT_Byte* p_next;
FT_UInt32 mask = (FT_UInt32)1UL << nn;
if ( p + 6 > p_limit )
break;
p_next = p;
p += 2; /* skip version */
length = FT_NEXT_USHORT( p );
coverage = FT_NEXT_USHORT( p );
if ( length <= 6 )
break;
p_next += length;
if ( p_next > p_limit ) /* handle broken table */
p_next = p_limit;
/* only use horizontal kerning tables */
if ( ( coverage & ~8 ) != 0x0001 ||
p + 8 > p_limit )
goto NextTable;
num_pairs = FT_NEXT_USHORT( p );
p += 6;
if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */
num_pairs = (FT_UInt)( ( p_next - p ) / 6 );
avail |= mask;
/*
* Now check whether the pairs in this table are ordered.
* We then can use binary search.
*/
if ( num_pairs > 0 )
{
FT_ULong count;
FT_ULong old_pair;
old_pair = FT_NEXT_ULONG( p );
p += 2;
for ( count = num_pairs - 1; count > 0; count-- )
{
FT_UInt32 cur_pair;
cur_pair = FT_NEXT_ULONG( p );
if ( cur_pair <= old_pair )
break;
p += 2;
old_pair = cur_pair;
}
if ( count == 0 )
ordered |= mask;
}
NextTable:
p = p_next;
}
face->num_kern_tables = nn;
face->kern_avail_bits = avail;
face->kern_order_bits = ordered;
Exit:
return error;
}
|
tt_face_load_kern( TT_Face face,
FT_Stream stream )
{
FT_Error error;
FT_ULong table_size;
FT_Byte* p;
FT_Byte* p_limit;
FT_UInt nn, num_tables;
FT_UInt32 avail = 0, ordered = 0;
/* the kern table is optional; exit silently if it is missing */
error = face->goto_table( face, TTAG_kern, stream, &table_size );
if ( error )
goto Exit;
if ( table_size < 4 ) /* the case of a malformed table */
{
FT_ERROR(( "tt_face_load_kern:"
" kerning table is too small - ignored\n" ));
error = FT_THROW( Table_Missing );
goto Exit;
}
if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) )
{
FT_ERROR(( "tt_face_load_kern:"
" could not extract kerning table\n" ));
goto Exit;
}
face->kern_table_size = table_size;
p = face->kern_table;
p_limit = p + table_size;
p += 2; /* skip version */
num_tables = FT_NEXT_USHORT( p );
if ( num_tables > 32 ) /* we only support up to 32 sub-tables */
num_tables = 32;
for ( nn = 0; nn < num_tables; nn++ )
{
FT_UInt num_pairs, length, coverage;
FT_Byte* p_next;
FT_UInt32 mask = (FT_UInt32)1UL << nn;
if ( p + 6 > p_limit )
break;
p_next = p;
p += 2; /* skip version */
length = FT_NEXT_USHORT( p );
coverage = FT_NEXT_USHORT( p );
if ( length <= 6 + 8 )
break;
p_next += length;
if ( p_next > p_limit ) /* handle broken table */
p_next = p_limit;
/* only use horizontal kerning tables */
if ( ( coverage & ~8 ) != 0x0001 ||
p + 8 > p_limit )
goto NextTable;
num_pairs = FT_NEXT_USHORT( p );
p += 6;
if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */
num_pairs = (FT_UInt)( ( p_next - p ) / 6 );
avail |= mask;
/*
* Now check whether the pairs in this table are ordered.
* We then can use binary search.
*/
if ( num_pairs > 0 )
{
FT_ULong count;
FT_ULong old_pair;
old_pair = FT_NEXT_ULONG( p );
p += 2;
for ( count = num_pairs - 1; count > 0; count-- )
{
FT_UInt32 cur_pair;
cur_pair = FT_NEXT_ULONG( p );
if ( cur_pair <= old_pair )
break;
p += 2;
old_pair = cur_pair;
}
if ( count == 0 )
ordered |= mask;
}
NextTable:
p = p_next;
}
face->num_kern_tables = nn;
face->kern_avail_bits = avail;
face->kern_order_bits = ordered;
Exit:
return error;
}
|
CVE-2014-9658
|
The tt_face_load_kern function in sfnt/ttkern.c in FreeType before 2.5.4 enforces an incorrect minimum table length, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted TrueType font.
|
[
"CWE-125"
] |
[
{
"line_no": 59,
"text": " if ( length <= 6 )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 59,
"text": " if ( length <= 6 + 8 )",
"char_start": null,
"char_end": null
}
] | 199
|
primevul
|
primevul_savannah_f0292bb9920aa1dbfed5f53861e7c7a89b35833a
|
f0292bb9920aa1dbfed5f53861e7c7a89b35833a
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
|
tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( p + 4 > p_limit ||
num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
|
CVE-2014-9656
|
The tt_sbit_decoder_load_image function in sfnt/ttsbit.c in FreeType before 2.5.4 does not properly check for an integer overflow, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted OpenType font.
|
[
"CWE-119"
] |
[
{
"line_no": 102,
"text": " if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 102,
"text": " if ( p + 4 > p_limit ||",
"char_start": null,
"char_end": null
},
{
"line_no": 103,
"text": " num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )",
"char_start": null,
"char_end": null
}
] | 200
|
primevul
|
primevul_savannah_3774fc08b502c3e685afca098b6e8a195aded6a0
|
3774fc08b502c3e685afca098b6e8a195aded6a0
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
ps_parser_to_token( PS_Parser parser,
T1_Token token )
{
FT_Byte* cur;
FT_Byte* limit;
FT_Int embed;
token->type = T1_TOKEN_TYPE_NONE;
token->start = NULL;
token->limit = NULL;
/* first of all, skip leading whitespace */
ps_parser_skip_spaces( parser );
cur = parser->cursor;
limit = parser->limit;
if ( cur >= limit )
return;
switch ( *cur )
{
/************* check for literal string *****************/
case '(':
token->type = T1_TOKEN_TYPE_STRING;
token->start = cur;
if ( skip_literal_string( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for programs/array *****************/
case '{':
token->type = T1_TOKEN_TYPE_ARRAY;
token->start = cur;
if ( skip_procedure( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for table/array ********************/
/* XXX: in theory we should also look for "<<" */
/* since this is semantically equivalent to "["; */
/* in practice it doesn't matter (?) */
case '[':
token->type = T1_TOKEN_TYPE_ARRAY;
embed = 1;
token->start = cur++;
/* we need this to catch `[ ]' */
parser->cursor = cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
while ( cur < limit && !parser->error )
{
/* XXX: this is wrong because it does not */
/* skip comments, procedures, and strings */
if ( *cur == '[' )
embed++;
else if ( *cur == ']' )
{
embed--;
if ( embed <= 0 )
{
token->limit = ++cur;
break;
}
}
parser->cursor = cur;
ps_parser_skip_PS_token( parser );
/* we need this to catch `[XXX ]' */
ps_parser_skip_spaces ( parser );
cur = parser->cursor;
}
break;
/* ************ otherwise, it is any token **************/
default:
token->start = cur;
token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY;
ps_parser_skip_PS_token( parser );
cur = parser->cursor;
if ( !parser->error )
token->limit = cur;
}
if ( !token->limit )
{
token->start = NULL;
token->type = T1_TOKEN_TYPE_NONE;
}
parser->cursor = cur;
}
/* NB: `tokens' can be NULL if we only want to count */
/* the number of array elements */
FT_LOCAL_DEF( void )
ps_parser_to_token_array( PS_Parser parser,
T1_Token tokens,
FT_UInt max_tokens,
FT_Int* pnum_tokens )
{
T1_TokenRec master;
*pnum_tokens = -1;
/* this also handles leading whitespace */
ps_parser_to_token( parser, &master );
if ( master.type == T1_TOKEN_TYPE_ARRAY )
{
FT_Byte* old_cursor = parser->cursor;
FT_Byte* old_limit = parser->limit;
T1_Token cur = tokens;
T1_Token limit = cur + max_tokens;
/* don't include outermost delimiters */
parser->cursor = master.start + 1;
parser->limit = master.limit - 1;
while ( parser->cursor < parser->limit )
{
T1_TokenRec token;
ps_parser_to_token( parser, &token );
if ( !token.type )
break;
if ( tokens && cur < limit )
*cur = token;
cur++;
}
*pnum_tokens = (FT_Int)( cur - tokens );
parser->cursor = old_cursor;
parser->limit = old_limit;
}
}
/* first character must be a delimiter or a part of a number */
/* NB: `coords' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_coords' */
static FT_Int
ps_tocoordarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_coords,
FT_Short* coords )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* check for the beginning of an array; otherwise, only one number */
/* will be read */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the coordinates */
while ( cur < limit )
{
FT_Short dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( coords && count >= max_coords )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( coords ? &coords[count] : &dummy ) =
(FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
/* first character must be a delimiter or a part of a number */
/* NB: `values' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_values' */
/* */
/* return number of successfully parsed values */
static FT_Int
ps_tofixedarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* Check for the beginning of an array. Otherwise, only one number */
/* will be read. */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the values */
while ( cur < limit )
{
FT_Fixed dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( values && count >= max_values )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( values ? &values[count] : &dummy ) =
PS_Conv_ToFixed( &cur, limit, power_ten );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
#if 0
static FT_String*
ps_tostring( FT_Byte** cursor,
FT_Byte* limit,
FT_Memory memory )
{
FT_Byte* cur = *cursor;
FT_UInt len = 0;
FT_Int count;
FT_String* result;
FT_Error error;
/* XXX: some stupid fonts have a `Notice' or `Copyright' string */
/* that simply doesn't begin with an opening parenthesis, even */
/* though they have a closing one! E.g. "amuncial.pfb" */
/* */
/* We must deal with these ill-fated cases there. Note that */
/* these fonts didn't work with the old Type 1 driver as the */
/* notice/copyright was not recognized as a valid string token */
/* and made the old token parser commit errors. */
while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) )
cur++;
if ( cur + 1 >= limit )
return 0;
if ( *cur == '(' )
cur++; /* skip the opening parenthesis, if there is one */
*cursor = cur;
count = 0;
/* then, count its length */
for ( ; cur < limit; cur++ )
{
if ( *cur == '(' )
count++;
else if ( *cur == ')' )
{
count--;
if ( count < 0 )
break;
}
}
len = (FT_UInt)( cur - *cursor );
if ( cur >= limit || FT_ALLOC( result, len + 1 ) )
return 0;
/* now copy the string */
FT_MEM_COPY( result, *cursor, len );
result[len] = '\0';
*cursor = cur;
return result;
}
#endif /* 0 */
static int
ps_tobool( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
FT_Bool result = 0;
/* return 1 if we find `true', 0 otherwise */
if ( cur + 3 < limit &&
cur[0] == 't' &&
cur[1] == 'r' &&
cur[2] == 'u' &&
cur[3] == 'e' )
{
result = 1;
cur += 5;
}
else if ( cur + 4 < limit &&
cur[0] == 'f' &&
cur[1] == 'a' &&
cur[2] == 'l' &&
cur[3] == 's' &&
cur[4] == 'e' )
{
result = 0;
cur += 6;
}
*acur = cur;
return result;
}
/* load a simple field (i.e. non-table) into the current list of objects */
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec token;
FT_Byte* cur;
FT_Byte* limit;
FT_UInt count;
FT_UInt idx;
FT_Error error;
T1_FieldType type;
/* this also skips leading whitespace */
ps_parser_to_token( parser, &token );
if ( !token.type )
goto Fail;
count = 1;
idx = 0;
cur = token.start;
limit = token.limit;
type = field->type;
/* we must detect arrays in /FontBBox */
if ( type == T1_FIELD_TYPE_BBOX )
{
T1_TokenRec token2;
FT_Byte* old_cur = parser->cursor;
FT_Byte* old_limit = parser->limit;
/* don't include delimiters */
parser->cursor = token.start + 1;
parser->limit = token.limit - 1;
ps_parser_to_token( parser, &token2 );
parser->cursor = old_cur;
parser->limit = old_limit;
if ( token2.type == T1_TOKEN_TYPE_ARRAY )
{
type = T1_FIELD_TYPE_MM_BBOX;
goto FieldArray;
}
}
else if ( token.type == T1_TOKEN_TYPE_ARRAY )
{
count = max_objects;
FieldArray:
/* if this is an array and we have no blend, an error occurs */
if ( max_objects == 0 )
goto Fail;
idx = 1;
/* don't include delimiters */
cur++;
limit--;
}
for ( ; count > 0; count--, idx++ )
{
FT_Byte* q = (FT_Byte*)objects[idx] + field->offset;
FT_Long val;
FT_String* string = NULL;
skip_spaces( &cur, limit );
switch ( type )
{
case T1_FIELD_TYPE_BOOL:
val = ps_tobool( &cur, limit );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED:
val = PS_Conv_ToFixed( &cur, limit, 0 );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED_1000:
val = PS_Conv_ToFixed( &cur, limit, 3 );
goto Store_Integer;
case T1_FIELD_TYPE_INTEGER:
val = PS_Conv_ToInt( &cur, limit );
/* fall through */
Store_Integer:
switch ( field->size )
{
case (8 / FT_CHAR_BIT):
*(FT_Byte*)q = (FT_Byte)val;
break;
case (16 / FT_CHAR_BIT):
*(FT_UShort*)q = (FT_UShort)val;
break;
case (32 / FT_CHAR_BIT):
*(FT_UInt32*)q = (FT_UInt32)val;
break;
default: /* for 64-bit systems */
*(FT_Long*)q = val;
}
break;
case T1_FIELD_TYPE_STRING:
case T1_FIELD_TYPE_KEY:
{
FT_Memory memory = parser->memory;
FT_UInt len = (FT_UInt)( limit - cur );
if ( cur >= limit )
break;
/* we allow both a string or a name */
/* for cases like /FontName (foo) def */
if ( token.type == T1_TOKEN_TYPE_KEY )
{
/* don't include leading `/' */
len--;
cur++;
}
else if ( token.type == T1_TOKEN_TYPE_STRING )
{
/* don't include delimiting parentheses */
/* XXX we don't handle <<...>> here */
/* XXX should we convert octal escapes? */
/* if so, what encoding should we use? */
cur++;
len -= 2;
}
else
{
FT_ERROR(( "ps_parser_load_field:"
" expected a name or string\n"
" "
" but found token of type %d instead\n",
token.type ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* for this to work (FT_String**)q must have been */
/* initialized to NULL */
if ( *(FT_String**)q )
{
FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n",
field->ident ));
FT_FREE( *(FT_String**)q );
*(FT_String**)q = NULL;
}
if ( FT_ALLOC( string, len + 1 ) )
goto Exit;
FT_MEM_COPY( string, cur, len );
string[len] = 0;
*(FT_String**)q = string;
}
break;
case T1_FIELD_TYPE_BBOX:
{
FT_Fixed temp[4];
FT_BBox* bbox = (FT_BBox*)q;
FT_Int result;
result = ps_tofixedarray( &cur, limit, 4, temp, 0 );
if ( result < 4 )
{
FT_ERROR(( "ps_parser_load_field:"
" expected four integers in bounding box\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
bbox->xMin = FT_RoundFix( temp[0] );
bbox->yMin = FT_RoundFix( temp[1] );
bbox->xMax = FT_RoundFix( temp[2] );
bbox->yMax = FT_RoundFix( temp[3] );
}
break;
case T1_FIELD_TYPE_MM_BBOX:
{
FT_Memory memory = parser->memory;
FT_Fixed* temp = NULL;
FT_Int result;
FT_UInt i;
if ( FT_NEW_ARRAY( temp, max_objects * 4 ) )
goto Exit;
for ( i = 0; i < 4; i++ )
{
result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects,
temp + i * max_objects, 0 );
if ( result < 0 || (FT_UInt)result < max_objects )
{
FT_ERROR(( "ps_parser_load_field:"
" expected %d integer%s in the %s subarray\n"
" "
" of /FontBBox in the /Blend dictionary\n",
max_objects, max_objects > 1 ? "s" : "",
i == 0 ? "first"
: ( i == 1 ? "second"
: ( i == 2 ? "third"
: "fourth" ) ) ));
error = FT_THROW( Invalid_File_Format );
FT_FREE( temp );
goto Exit;
}
skip_spaces( &cur, limit );
}
for ( i = 0; i < max_objects; i++ )
{
FT_BBox* bbox = (FT_BBox*)objects[i];
bbox->xMin = FT_RoundFix( temp[i ] );
bbox->yMin = FT_RoundFix( temp[i + max_objects] );
bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] );
bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] );
}
FT_FREE( temp );
}
break;
default:
/* an error occurred */
goto Fail;
}
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
error = FT_Err_Ok;
Exit:
return error;
Fail:
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
#define T1_MAX_TABLE_ELEMENTS 32
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field_table( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS];
T1_Token token;
FT_Int num_elements;
FT_Error error = FT_Err_Ok;
FT_Byte* old_cursor;
FT_Byte* old_limit;
T1_FieldRec fieldrec = *(T1_Field)field;
fieldrec.type = T1_FIELD_TYPE_INTEGER;
if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY ||
field->type == T1_FIELD_TYPE_BBOX )
fieldrec.type = T1_FIELD_TYPE_FIXED;
ps_parser_to_token_array( parser, elements,
T1_MAX_TABLE_ELEMENTS, &num_elements );
if ( num_elements < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( (FT_UInt)num_elements > field->array_max )
num_elements = (FT_Int)field->array_max;
old_cursor = parser->cursor;
old_limit = parser->limit;
/* we store the elements count if necessary; */
/* we further assume that `count_offset' can't be zero */
if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 )
*(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) =
(FT_Byte)num_elements;
/* we now load each element, adjusting the field.offset on each one */
token = elements;
for ( ; num_elements > 0; num_elements--, token++ )
{
parser->cursor = token->start;
parser->limit = token->limit;
error = ps_parser_load_field( parser,
&fieldrec,
objects,
max_objects,
0 );
if ( error )
break;
fieldrec.offset += fieldrec.size;
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
parser->cursor = old_cursor;
parser->limit = old_limit;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Long )
ps_parser_to_int( PS_Parser parser )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToInt( &parser->cursor, parser->limit );
}
/* first character must be `<' if `delimiters' is non-zero */
FT_LOCAL_DEF( FT_Error )
ps_parser_to_bytes( PS_Parser parser,
FT_Byte* bytes,
FT_Offset max_bytes,
FT_ULong* pnum_bytes,
FT_Bool delimiters )
{
FT_Error error = FT_Err_Ok;
FT_Byte* cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
if ( cur >= parser->limit )
goto Exit;
if ( delimiters )
{
if ( *cur != '<' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
*pnum_bytes = PS_Conv_ASCIIHexDecode( &cur,
parser->limit,
bytes,
max_bytes );
if ( delimiters )
{
if ( cur < parser->limit && *cur != '>' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
parser->cursor = cur;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Fixed )
ps_parser_to_fixed( PS_Parser parser,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_coord_array( PS_Parser parser,
FT_Int max_coords,
FT_Short* coords )
{
ps_parser_skip_spaces( parser );
return ps_tocoordarray( &parser->cursor, parser->limit,
max_coords, coords );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_fixed_array( PS_Parser parser,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return ps_tofixedarray( &parser->cursor, parser->limit,
max_values, values, power_ten );
}
#if 0
FT_LOCAL_DEF( FT_String* )
T1_ToString( PS_Parser parser )
{
return ps_tostring( &parser->cursor, parser->limit, parser->memory );
}
FT_LOCAL_DEF( FT_Bool )
T1_ToBool( PS_Parser parser )
{
return ps_tobool( &parser->cursor, parser->limit );
}
#endif /* 0 */
FT_LOCAL_DEF( void )
ps_parser_init( PS_Parser parser,
FT_Byte* base,
FT_Byte* limit,
FT_Memory memory )
{
parser->error = FT_Err_Ok;
parser->base = base;
parser->limit = limit;
parser->cursor = base;
parser->memory = memory;
parser->funcs = ps_parser_funcs;
}
FT_LOCAL_DEF( void )
ps_parser_done( PS_Parser parser )
{
FT_UNUSED( parser );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* t1_builder_init */
/* */
/* <Description> */
/* Initializes a given glyph builder. */
/* */
/* <InOut> */
/* builder :: A pointer to the glyph builder to initialize. */
/* */
/* <Input> */
/* face :: The current face object. */
/* */
/* size :: The current size object. */
/* */
/* glyph :: The current glyph object. */
/* */
/* hinting :: Whether hinting should be applied. */
/* */
FT_LOCAL_DEF( void )
t1_builder_init( T1_Builder builder,
FT_Face face,
FT_Size size,
FT_GlyphSlot glyph,
FT_Bool hinting )
{
builder->parse_state = T1_Parse_Start;
builder->load_points = 1;
builder->face = face;
builder->glyph = glyph;
builder->memory = face->memory;
if ( glyph )
{
FT_GlyphLoader loader = glyph->internal->loader;
builder->loader = loader;
builder->base = &loader->base.outline;
builder->current = &loader->current.outline;
FT_GlyphLoader_Rewind( loader );
builder->hints_globals = size->internal;
builder->hints_funcs = NULL;
if ( hinting )
builder->hints_funcs = glyph->internal->glyph_hints;
}
builder->pos_x = 0;
builder->pos_y = 0;
builder->left_bearing.x = 0;
builder->left_bearing.y = 0;
builder->advance.x = 0;
builder->advance.y = 0;
builder->funcs = t1_builder_funcs;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1_builder_done */
/* */
/* <Description> */
/* Finalizes a given glyph builder. Its contents can still be used */
/* after the call, but the function saves important information */
/* within the corresponding glyph slot. */
/* */
/* <Input> */
/* builder :: A pointer to the glyph builder to finalize. */
/* */
FT_LOCAL_DEF( void )
t1_builder_done( T1_Builder builder )
{
FT_GlyphSlot glyph = builder->glyph;
if ( glyph )
glyph->outline = *builder->base;
}
/* check that there is enough space for `count' more points */
FT_LOCAL_DEF( FT_Error )
t1_builder_check_points( T1_Builder builder,
FT_Int count )
{
return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 );
}
/* add a new point, do not check space */
FT_LOCAL_DEF( void )
t1_builder_add_point( T1_Builder builder,
FT_Pos x,
FT_Pos y,
FT_Byte flag )
{
FT_Outline* outline = builder->current;
if ( builder->load_points )
{
FT_Vector* point = outline->points + outline->n_points;
FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points;
point->x = FIXED_TO_INT( x );
point->y = FIXED_TO_INT( y );
*control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC );
}
outline->n_points++;
}
/* check space for a new on-curve point, then add it */
FT_LOCAL_DEF( FT_Error )
t1_builder_add_point1( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error;
error = t1_builder_check_points( builder, 1 );
if ( !error )
t1_builder_add_point( builder, x, y, 1 );
return error;
}
/* check space for a new contour, then add it */
FT_LOCAL_DEF( FT_Error )
t1_builder_add_contour( T1_Builder builder )
{
FT_Outline* outline = builder->current;
FT_Error error;
/* this might happen in invalid fonts */
if ( !outline )
{
FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" ));
return FT_THROW( Invalid_File_Format );
}
if ( !builder->load_points )
{
outline->n_contours++;
return FT_Err_Ok;
}
error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 );
if ( !error )
{
if ( outline->n_contours > 0 )
outline->contours[outline->n_contours - 1] =
(short)( outline->n_points - 1 );
outline->n_contours++;
}
return error;
}
/* if a path was begun, add its first on-curve point */
FT_LOCAL_DEF( FT_Error )
t1_builder_start_point( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error = FT_ERR( Invalid_File_Format );
/* test whether we are building a new contour */
if ( builder->parse_state == T1_Parse_Have_Path )
error = FT_Err_Ok;
else
{
builder->parse_state = T1_Parse_Have_Path;
error = t1_builder_add_contour( builder );
if ( !error )
error = t1_builder_add_point1( builder, x, y );
}
return error;
}
/* close the current contour */
FT_LOCAL_DEF( void )
t1_builder_close_contour( T1_Builder builder )
{
FT_Outline* outline = builder->current;
FT_Int first;
if ( !outline )
return;
first = outline->n_contours <= 1
? 0 : outline->contours[outline->n_contours - 2] + 1;
/* We must not include the last point in the path if it */
/* is located on the first point. */
if ( outline->n_points > 1 )
if ( p1->x == p2->x && p1->y == p2->y )
if ( *control == FT_CURVE_TAG_ON )
outline->n_points--;
}
if ( outline->n_contours > 0 )
{
/* Don't add contours only consisting of one point, i.e., */
/* check whether the first and the last point is the same. */
if ( first == outline->n_points - 1 )
{
outline->n_contours--;
outline->n_points--;
}
else
outline->contours[outline->n_contours - 1] =
(short)( outline->n_points - 1 );
}
}
|
ps_parser_to_token( PS_Parser parser,
T1_Token token )
{
FT_Byte* cur;
FT_Byte* limit;
FT_Int embed;
token->type = T1_TOKEN_TYPE_NONE;
token->start = NULL;
token->limit = NULL;
/* first of all, skip leading whitespace */
ps_parser_skip_spaces( parser );
cur = parser->cursor;
limit = parser->limit;
if ( cur >= limit )
return;
switch ( *cur )
{
/************* check for literal string *****************/
case '(':
token->type = T1_TOKEN_TYPE_STRING;
token->start = cur;
if ( skip_literal_string( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for programs/array *****************/
case '{':
token->type = T1_TOKEN_TYPE_ARRAY;
token->start = cur;
if ( skip_procedure( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for table/array ********************/
/* XXX: in theory we should also look for "<<" */
/* since this is semantically equivalent to "["; */
/* in practice it doesn't matter (?) */
case '[':
token->type = T1_TOKEN_TYPE_ARRAY;
embed = 1;
token->start = cur++;
/* we need this to catch `[ ]' */
parser->cursor = cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
while ( cur < limit && !parser->error )
{
/* XXX: this is wrong because it does not */
/* skip comments, procedures, and strings */
if ( *cur == '[' )
embed++;
else if ( *cur == ']' )
{
embed--;
if ( embed <= 0 )
{
token->limit = ++cur;
break;
}
}
parser->cursor = cur;
ps_parser_skip_PS_token( parser );
/* we need this to catch `[XXX ]' */
ps_parser_skip_spaces ( parser );
cur = parser->cursor;
}
break;
/* ************ otherwise, it is any token **************/
default:
token->start = cur;
token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY;
ps_parser_skip_PS_token( parser );
cur = parser->cursor;
if ( !parser->error )
token->limit = cur;
}
if ( !token->limit )
{
token->start = NULL;
token->type = T1_TOKEN_TYPE_NONE;
}
parser->cursor = cur;
}
/* NB: `tokens' can be NULL if we only want to count */
/* the number of array elements */
FT_LOCAL_DEF( void )
ps_parser_to_token_array( PS_Parser parser,
T1_Token tokens,
FT_UInt max_tokens,
FT_Int* pnum_tokens )
{
T1_TokenRec master;
*pnum_tokens = -1;
/* this also handles leading whitespace */
ps_parser_to_token( parser, &master );
if ( master.type == T1_TOKEN_TYPE_ARRAY )
{
FT_Byte* old_cursor = parser->cursor;
FT_Byte* old_limit = parser->limit;
T1_Token cur = tokens;
T1_Token limit = cur + max_tokens;
/* don't include outermost delimiters */
parser->cursor = master.start + 1;
parser->limit = master.limit - 1;
while ( parser->cursor < parser->limit )
{
T1_TokenRec token;
ps_parser_to_token( parser, &token );
if ( !token.type )
break;
if ( tokens && cur < limit )
*cur = token;
cur++;
}
*pnum_tokens = (FT_Int)( cur - tokens );
parser->cursor = old_cursor;
parser->limit = old_limit;
}
}
/* first character must be a delimiter or a part of a number */
/* NB: `coords' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_coords' */
static FT_Int
ps_tocoordarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_coords,
FT_Short* coords )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* check for the beginning of an array; otherwise, only one number */
/* will be read */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the coordinates */
while ( cur < limit )
{
FT_Short dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( coords && count >= max_coords )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( coords ? &coords[count] : &dummy ) =
(FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
/* first character must be a delimiter or a part of a number */
/* NB: `values' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_values' */
/* */
/* return number of successfully parsed values */
static FT_Int
ps_tofixedarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* Check for the beginning of an array. Otherwise, only one number */
/* will be read. */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the values */
while ( cur < limit )
{
FT_Fixed dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( values && count >= max_values )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( values ? &values[count] : &dummy ) =
PS_Conv_ToFixed( &cur, limit, power_ten );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
#if 0
static FT_String*
ps_tostring( FT_Byte** cursor,
FT_Byte* limit,
FT_Memory memory )
{
FT_Byte* cur = *cursor;
FT_UInt len = 0;
FT_Int count;
FT_String* result;
FT_Error error;
/* XXX: some stupid fonts have a `Notice' or `Copyright' string */
/* that simply doesn't begin with an opening parenthesis, even */
/* though they have a closing one! E.g. "amuncial.pfb" */
/* */
/* We must deal with these ill-fated cases there. Note that */
/* these fonts didn't work with the old Type 1 driver as the */
/* notice/copyright was not recognized as a valid string token */
/* and made the old token parser commit errors. */
while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) )
cur++;
if ( cur + 1 >= limit )
return 0;
if ( *cur == '(' )
cur++; /* skip the opening parenthesis, if there is one */
*cursor = cur;
count = 0;
/* then, count its length */
for ( ; cur < limit; cur++ )
{
if ( *cur == '(' )
count++;
else if ( *cur == ')' )
{
count--;
if ( count < 0 )
break;
}
}
len = (FT_UInt)( cur - *cursor );
if ( cur >= limit || FT_ALLOC( result, len + 1 ) )
return 0;
/* now copy the string */
FT_MEM_COPY( result, *cursor, len );
result[len] = '\0';
*cursor = cur;
return result;
}
#endif /* 0 */
static int
ps_tobool( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
FT_Bool result = 0;
/* return 1 if we find `true', 0 otherwise */
if ( cur + 3 < limit &&
cur[0] == 't' &&
cur[1] == 'r' &&
cur[2] == 'u' &&
cur[3] == 'e' )
{
result = 1;
cur += 5;
}
else if ( cur + 4 < limit &&
cur[0] == 'f' &&
cur[1] == 'a' &&
cur[2] == 'l' &&
cur[3] == 's' &&
cur[4] == 'e' )
{
result = 0;
cur += 6;
}
*acur = cur;
return result;
}
/* load a simple field (i.e. non-table) into the current list of objects */
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec token;
FT_Byte* cur;
FT_Byte* limit;
FT_UInt count;
FT_UInt idx;
FT_Error error;
T1_FieldType type;
/* this also skips leading whitespace */
ps_parser_to_token( parser, &token );
if ( !token.type )
goto Fail;
count = 1;
idx = 0;
cur = token.start;
limit = token.limit;
type = field->type;
/* we must detect arrays in /FontBBox */
if ( type == T1_FIELD_TYPE_BBOX )
{
T1_TokenRec token2;
FT_Byte* old_cur = parser->cursor;
FT_Byte* old_limit = parser->limit;
/* don't include delimiters */
parser->cursor = token.start + 1;
parser->limit = token.limit - 1;
ps_parser_to_token( parser, &token2 );
parser->cursor = old_cur;
parser->limit = old_limit;
if ( token2.type == T1_TOKEN_TYPE_ARRAY )
{
type = T1_FIELD_TYPE_MM_BBOX;
goto FieldArray;
}
}
else if ( token.type == T1_TOKEN_TYPE_ARRAY )
{
count = max_objects;
FieldArray:
/* if this is an array and we have no blend, an error occurs */
if ( max_objects == 0 )
goto Fail;
idx = 1;
/* don't include delimiters */
cur++;
limit--;
}
for ( ; count > 0; count--, idx++ )
{
FT_Byte* q = (FT_Byte*)objects[idx] + field->offset;
FT_Long val;
FT_String* string = NULL;
skip_spaces( &cur, limit );
switch ( type )
{
case T1_FIELD_TYPE_BOOL:
val = ps_tobool( &cur, limit );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED:
val = PS_Conv_ToFixed( &cur, limit, 0 );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED_1000:
val = PS_Conv_ToFixed( &cur, limit, 3 );
goto Store_Integer;
case T1_FIELD_TYPE_INTEGER:
val = PS_Conv_ToInt( &cur, limit );
/* fall through */
Store_Integer:
switch ( field->size )
{
case (8 / FT_CHAR_BIT):
*(FT_Byte*)q = (FT_Byte)val;
break;
case (16 / FT_CHAR_BIT):
*(FT_UShort*)q = (FT_UShort)val;
break;
case (32 / FT_CHAR_BIT):
*(FT_UInt32*)q = (FT_UInt32)val;
break;
default: /* for 64-bit systems */
*(FT_Long*)q = val;
}
break;
case T1_FIELD_TYPE_STRING:
case T1_FIELD_TYPE_KEY:
{
FT_Memory memory = parser->memory;
FT_UInt len = (FT_UInt)( limit - cur );
if ( cur >= limit )
break;
/* we allow both a string or a name */
/* for cases like /FontName (foo) def */
if ( token.type == T1_TOKEN_TYPE_KEY )
{
/* don't include leading `/' */
len--;
cur++;
}
else if ( token.type == T1_TOKEN_TYPE_STRING )
{
/* don't include delimiting parentheses */
/* XXX we don't handle <<...>> here */
/* XXX should we convert octal escapes? */
/* if so, what encoding should we use? */
cur++;
len -= 2;
}
else
{
FT_ERROR(( "ps_parser_load_field:"
" expected a name or string\n"
" "
" but found token of type %d instead\n",
token.type ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* for this to work (FT_String**)q must have been */
/* initialized to NULL */
if ( *(FT_String**)q )
{
FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n",
field->ident ));
FT_FREE( *(FT_String**)q );
*(FT_String**)q = NULL;
}
if ( FT_ALLOC( string, len + 1 ) )
goto Exit;
FT_MEM_COPY( string, cur, len );
string[len] = 0;
*(FT_String**)q = string;
}
break;
case T1_FIELD_TYPE_BBOX:
{
FT_Fixed temp[4];
FT_BBox* bbox = (FT_BBox*)q;
FT_Int result;
result = ps_tofixedarray( &cur, limit, 4, temp, 0 );
if ( result < 4 )
{
FT_ERROR(( "ps_parser_load_field:"
" expected four integers in bounding box\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
bbox->xMin = FT_RoundFix( temp[0] );
bbox->yMin = FT_RoundFix( temp[1] );
bbox->xMax = FT_RoundFix( temp[2] );
bbox->yMax = FT_RoundFix( temp[3] );
}
break;
case T1_FIELD_TYPE_MM_BBOX:
{
FT_Memory memory = parser->memory;
FT_Fixed* temp = NULL;
FT_Int result;
FT_UInt i;
if ( FT_NEW_ARRAY( temp, max_objects * 4 ) )
goto Exit;
for ( i = 0; i < 4; i++ )
{
result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects,
temp + i * max_objects, 0 );
if ( result < 0 || (FT_UInt)result < max_objects )
{
FT_ERROR(( "ps_parser_load_field:"
" expected %d integer%s in the %s subarray\n"
" "
" of /FontBBox in the /Blend dictionary\n",
max_objects, max_objects > 1 ? "s" : "",
i == 0 ? "first"
: ( i == 1 ? "second"
: ( i == 2 ? "third"
: "fourth" ) ) ));
error = FT_THROW( Invalid_File_Format );
FT_FREE( temp );
goto Exit;
}
skip_spaces( &cur, limit );
}
for ( i = 0; i < max_objects; i++ )
{
FT_BBox* bbox = (FT_BBox*)objects[i];
bbox->xMin = FT_RoundFix( temp[i ] );
bbox->yMin = FT_RoundFix( temp[i + max_objects] );
bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] );
bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] );
}
FT_FREE( temp );
}
break;
default:
/* an error occurred */
goto Fail;
}
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
error = FT_Err_Ok;
Exit:
return error;
Fail:
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
#define T1_MAX_TABLE_ELEMENTS 32
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field_table( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS];
T1_Token token;
FT_Int num_elements;
FT_Error error = FT_Err_Ok;
FT_Byte* old_cursor;
FT_Byte* old_limit;
T1_FieldRec fieldrec = *(T1_Field)field;
fieldrec.type = T1_FIELD_TYPE_INTEGER;
if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY ||
field->type == T1_FIELD_TYPE_BBOX )
fieldrec.type = T1_FIELD_TYPE_FIXED;
ps_parser_to_token_array( parser, elements,
T1_MAX_TABLE_ELEMENTS, &num_elements );
if ( num_elements < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( (FT_UInt)num_elements > field->array_max )
num_elements = (FT_Int)field->array_max;
old_cursor = parser->cursor;
old_limit = parser->limit;
/* we store the elements count if necessary; */
/* we further assume that `count_offset' can't be zero */
if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 )
*(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) =
(FT_Byte)num_elements;
/* we now load each element, adjusting the field.offset on each one */
token = elements;
for ( ; num_elements > 0; num_elements--, token++ )
{
parser->cursor = token->start;
parser->limit = token->limit;
error = ps_parser_load_field( parser,
&fieldrec,
objects,
max_objects,
0 );
if ( error )
break;
fieldrec.offset += fieldrec.size;
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
parser->cursor = old_cursor;
parser->limit = old_limit;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Long )
ps_parser_to_int( PS_Parser parser )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToInt( &parser->cursor, parser->limit );
}
/* first character must be `<' if `delimiters' is non-zero */
FT_LOCAL_DEF( FT_Error )
ps_parser_to_bytes( PS_Parser parser,
FT_Byte* bytes,
FT_Offset max_bytes,
FT_ULong* pnum_bytes,
FT_Bool delimiters )
{
FT_Error error = FT_Err_Ok;
FT_Byte* cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
if ( cur >= parser->limit )
goto Exit;
if ( delimiters )
{
if ( *cur != '<' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
*pnum_bytes = PS_Conv_ASCIIHexDecode( &cur,
parser->limit,
bytes,
max_bytes );
if ( delimiters )
{
if ( cur < parser->limit && *cur != '>' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
parser->cursor = cur;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Fixed )
ps_parser_to_fixed( PS_Parser parser,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_coord_array( PS_Parser parser,
FT_Int max_coords,
FT_Short* coords )
{
ps_parser_skip_spaces( parser );
return ps_tocoordarray( &parser->cursor, parser->limit,
max_coords, coords );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_fixed_array( PS_Parser parser,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return ps_tofixedarray( &parser->cursor, parser->limit,
max_values, values, power_ten );
}
#if 0
FT_LOCAL_DEF( FT_String* )
T1_ToString( PS_Parser parser )
{
return ps_tostring( &parser->cursor, parser->limit, parser->memory );
}
FT_LOCAL_DEF( FT_Bool )
T1_ToBool( PS_Parser parser )
{
return ps_tobool( &parser->cursor, parser->limit );
}
#endif /* 0 */
FT_LOCAL_DEF( void )
ps_parser_init( PS_Parser parser,
FT_Byte* base,
FT_Byte* limit,
FT_Memory memory )
{
parser->error = FT_Err_Ok;
parser->base = base;
parser->limit = limit;
parser->cursor = base;
parser->memory = memory;
parser->funcs = ps_parser_funcs;
}
FT_LOCAL_DEF( void )
ps_parser_done( PS_Parser parser )
{
FT_UNUSED( parser );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* t1_builder_init */
/* */
/* <Description> */
/* Initializes a given glyph builder. */
/* */
/* <InOut> */
/* builder :: A pointer to the glyph builder to initialize. */
/* */
/* <Input> */
/* face :: The current face object. */
/* */
/* size :: The current size object. */
/* */
/* glyph :: The current glyph object. */
/* */
/* hinting :: Whether hinting should be applied. */
/* */
FT_LOCAL_DEF( void )
t1_builder_init( T1_Builder builder,
FT_Face face,
FT_Size size,
FT_GlyphSlot glyph,
FT_Bool hinting )
{
builder->parse_state = T1_Parse_Start;
builder->load_points = 1;
builder->face = face;
builder->glyph = glyph;
builder->memory = face->memory;
if ( glyph )
{
FT_GlyphLoader loader = glyph->internal->loader;
builder->loader = loader;
builder->base = &loader->base.outline;
builder->current = &loader->current.outline;
FT_GlyphLoader_Rewind( loader );
builder->hints_globals = size->internal;
builder->hints_funcs = NULL;
if ( hinting )
builder->hints_funcs = glyph->internal->glyph_hints;
}
builder->pos_x = 0;
builder->pos_y = 0;
builder->left_bearing.x = 0;
builder->left_bearing.y = 0;
builder->advance.x = 0;
builder->advance.y = 0;
builder->funcs = t1_builder_funcs;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1_builder_done */
/* */
/* <Description> */
/* Finalizes a given glyph builder. Its contents can still be used */
/* after the call, but the function saves important information */
/* within the corresponding glyph slot. */
/* */
/* <Input> */
/* builder :: A pointer to the glyph builder to finalize. */
/* */
FT_LOCAL_DEF( void )
t1_builder_done( T1_Builder builder )
{
FT_GlyphSlot glyph = builder->glyph;
if ( glyph )
glyph->outline = *builder->base;
}
/* check that there is enough space for `count' more points */
FT_LOCAL_DEF( FT_Error )
t1_builder_check_points( T1_Builder builder,
FT_Int count )
{
return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 );
}
/* add a new point, do not check space */
FT_LOCAL_DEF( void )
t1_builder_add_point( T1_Builder builder,
FT_Pos x,
FT_Pos y,
FT_Byte flag )
{
FT_Outline* outline = builder->current;
if ( builder->load_points )
{
FT_Vector* point = outline->points + outline->n_points;
FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points;
point->x = FIXED_TO_INT( x );
point->y = FIXED_TO_INT( y );
*control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC );
}
outline->n_points++;
}
/* check space for a new on-curve point, then add it */
FT_LOCAL_DEF( FT_Error )
t1_builder_add_point1( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error;
error = t1_builder_check_points( builder, 1 );
if ( !error )
t1_builder_add_point( builder, x, y, 1 );
return error;
}
/* check space for a new contour, then add it */
FT_LOCAL_DEF( FT_Error )
t1_builder_add_contour( T1_Builder builder )
{
FT_Outline* outline = builder->current;
FT_Error error;
/* this might happen in invalid fonts */
if ( !outline )
{
FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" ));
return FT_THROW( Invalid_File_Format );
}
if ( !builder->load_points )
{
outline->n_contours++;
return FT_Err_Ok;
}
error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 );
if ( !error )
{
if ( outline->n_contours > 0 )
outline->contours[outline->n_contours - 1] =
(short)( outline->n_points - 1 );
outline->n_contours++;
}
return error;
}
/* if a path was begun, add its first on-curve point */
FT_LOCAL_DEF( FT_Error )
t1_builder_start_point( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error = FT_ERR( Invalid_File_Format );
/* test whether we are building a new contour */
if ( builder->parse_state == T1_Parse_Have_Path )
error = FT_Err_Ok;
else
{
builder->parse_state = T1_Parse_Have_Path;
error = t1_builder_add_contour( builder );
if ( !error )
error = t1_builder_add_point1( builder, x, y );
}
return error;
}
/* close the current contour */
FT_LOCAL_DEF( void )
t1_builder_close_contour( T1_Builder builder )
{
FT_Outline* outline = builder->current;
FT_Int first;
if ( !outline )
return;
first = outline->n_contours <= 1
? 0 : outline->contours[outline->n_contours - 2] + 1;
/* in malformed fonts it can happen that a contour was started */
/* but no points were added */
if ( outline->n_contours && first == outline->n_points )
{
outline->n_contours--;
return;
}
/* We must not include the last point in the path if it */
/* is located on the first point. */
if ( outline->n_points > 1 )
if ( p1->x == p2->x && p1->y == p2->y )
if ( *control == FT_CURVE_TAG_ON )
outline->n_points--;
}
if ( outline->n_contours > 0 )
{
/* Don't add contours only consisting of one point, i.e., */
/* check whether the first and the last point is the same. */
if ( first == outline->n_points - 1 )
{
outline->n_contours--;
outline->n_points--;
}
else
outline->contours[outline->n_contours - 1] =
(short)( outline->n_points - 1 );
}
}
|
CVE-2017-8287
|
FreeType 2 before 2017-03-26 has an out-of-bounds write caused by a heap-based buffer overflow related to the t1_builder_close_contour function in psaux/psobjs.c.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 1106,
"text": " /* in malformed fonts it can happen that a contour was started */",
"char_start": null,
"char_end": null
},
{
"line_no": 1107,
"text": " /* but no points were added */",
"char_start": null,
"char_end": null
},
{
"line_no": 1108,
"text": " if ( outline->n_contours && first == outline->n_points )",
"char_start": null,
"char_end": null
},
{
"line_no": 1109,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 1110,
"text": " outline->n_contours--;",
"char_start": null,
"char_end": null
},
{
"line_no": 1111,
"text": " return;",
"char_start": null,
"char_end": null
},
{
"line_no": 1112,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 1113,
"text": "",
"char_start": null,
"char_end": null
}
] | 204
|
primevul
|
primevul_savannah_f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
|
f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* charstring_base,
FT_UInt charstring_len )
{
FT_Error error;
T1_Decoder_Zone zone;
FT_Byte* ip;
FT_Byte* limit;
T1_Builder builder = &decoder->builder;
FT_Pos x, y, orig_x, orig_y;
FT_Int known_othersubr_result_cnt = 0;
FT_Int unknown_othersubr_result_cnt = 0;
FT_Bool large_int;
FT_Fixed seed;
T1_Hints_Funcs hinter;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Bool bol = TRUE;
#endif
/* compute random seed from stack address of parameter */
seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^
(FT_Offset)(char*)&decoder ^
(FT_Offset)(char*)&charstring_base ) &
FT_ULONG_MAX );
seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL;
if ( seed == 0 )
seed = 0x7384;
/* First of all, initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
builder->parse_state = T1_Parse_Start;
hinter = (T1_Hints_Funcs)builder->hints_funcs;
/* a font that reads BuildCharArray without setting */
/* its values first is buggy, but ... */
FT_ASSERT( ( decoder->len_buildchar == 0 ) ==
( decoder->buildchar == NULL ) );
if ( decoder->buildchar && decoder->len_buildchar > 0 )
FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar );
FT_TRACE4(( "\n"
"Start charstring\n" ));
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = FT_Err_Ok;
x = orig_x = builder->pos_x;
y = orig_y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
large_int = FALSE;
/* now, execute loop */
while ( ip < limit )
{
FT_Long* top = decoder->top;
T1_Operator op = op_none;
FT_Int32 value = 0;
FT_ASSERT( known_othersubr_result_cnt == 0 ||
unknown_othersubr_result_cnt == 0 );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( bol )
{
FT_TRACE5(( " (%d)", decoder->top - decoder->stack ));
bol = FALSE;
}
#endif
/*********************************************************************/
/* */
/* Decode operator or operand */
/* */
/* */
/* first of all, decompress operator or value */
switch ( *ip++ )
{
case 1:
op = op_hstem;
break;
case 3:
op = op_vstem;
break;
case 4:
op = op_vmoveto;
break;
case 5:
op = op_rlineto;
break;
case 6:
op = op_hlineto;
break;
case 7:
op = op_vlineto;
break;
case 8:
op = op_rrcurveto;
break;
case 9:
op = op_closepath;
break;
case 10:
op = op_callsubr;
break;
case 11:
op = op_return;
break;
case 13:
op = op_hsbw;
break;
case 14:
op = op_endchar;
break;
case 15: /* undocumented, obsolete operator */
op = op_unknown15;
break;
case 21:
op = op_rmoveto;
break;
case 22:
op = op_hmoveto;
break;
case 30:
op = op_vhcurveto;
break;
case 31:
op = op_hvcurveto;
break;
case 12:
if ( ip >= limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+EOF)\n" ));
goto Syntax_Error;
}
switch ( *ip++ )
{
case 0:
op = op_dotsection;
break;
case 1:
op = op_vstem3;
break;
case 2:
op = op_hstem3;
break;
case 6:
op = op_seac;
break;
case 7:
op = op_sbw;
break;
case 12:
op = op_div;
break;
case 16:
op = op_callothersubr;
break;
case 17:
op = op_pop;
break;
case 33:
op = op_setcurrentpoint;
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+%d)\n",
ip[-1] ));
goto Syntax_Error;
}
break;
case 255: /* four bytes integer */
if ( ip + 4 > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) |
( (FT_UInt32)ip[1] << 16 ) |
( (FT_UInt32)ip[2] << 8 ) |
(FT_UInt32)ip[3] );
ip += 4;
/* According to the specification, values > 32000 or < -32000 must */
/* be followed by a `div' operator to make the result be in the */
/* range [-32000;32000]. We expect that the second argument of */
/* `div' is not a large number. Additionally, we don't handle */
/* stuff like `<large1> <large2> <num> div <num> div' or */
/* <large1> <large2> <num> div div'. This is probably not allowed */
/* anyway. */
if ( value > 32000 || value < -32000 )
{
if ( large_int )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
}
else
large_int = TRUE;
}
else
{
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
break;
default:
if ( ip[-1] >= 32 )
{
if ( ip[-1] < 247 )
value = (FT_Int32)ip[-1] - 139;
else
{
if ( ++ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
if ( ip[-2] < 251 )
value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108;
else
value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 );
}
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
else
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid byte (%d)\n", ip[-1] ));
goto Syntax_Error;
}
}
if ( unknown_othersubr_result_cnt > 0 )
{
switch ( op )
{
case op_callsubr:
case op_return:
case op_none:
case op_pop:
break;
default:
/* all operands have been transferred by previous pops */
unknown_othersubr_result_cnt = 0;
break;
}
}
if ( large_int && !( op == op_none || op == op_div ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
large_int = FALSE;
}
/*********************************************************************/
/* */
/* Push value on stack, or process operator */
/* */
/* */
if ( op == op_none )
{
if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS )
{
FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" ));
goto Syntax_Error;
}
#ifdef FT_DEBUG_LEVEL_TRACE
if ( large_int )
FT_TRACE4(( " %d", value ));
else
FT_TRACE4(( " %d", value / 65536 ));
#endif
*top++ = value;
decoder->top = top;
}
else if ( op == op_callothersubr ) /* callothersubr */
{
FT_Int subr_no;
FT_Int arg_cnt;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( " callothersubr\n" ));
bol = TRUE;
#endif
if ( top - decoder->stack < 2 )
goto Stack_Underflow;
top -= 2;
subr_no = Fix2Int( top[1] );
arg_cnt = Fix2Int( top[0] );
/***********************************************************/
/* */
/* remove all operands to callothersubr from the stack */
/* */
/* for handled othersubrs, where we know the number of */
/* arguments, we increase the stack by the value of */
/* known_othersubr_result_cnt */
/* */
/* for unhandled othersubrs the following pops adjust the */
/* stack pointer as necessary */
if ( arg_cnt > top - decoder->stack )
goto Stack_Underflow;
top -= arg_cnt;
known_othersubr_result_cnt = 0;
unknown_othersubr_result_cnt = 0;
/* XXX TODO: The checks to `arg_count == <whatever>' */
/* might not be correct; an othersubr expects a certain */
/* number of operands on the PostScript stack (as opposed */
/* to the T1 stack) but it doesn't have to put them there */
/* by itself; previous othersubrs might have left the */
/* operands there if they were not followed by an */
/* appropriate number of pops */
/* */
/* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */
/* accept a font that contains charstrings like */
/* */
/* 100 200 2 20 callothersubr */
/* 300 1 20 callothersubr pop */
/* */
/* Perhaps this is the reason why BuildCharArray exists. */
switch ( subr_no )
{
case 0: /* end flex feature */
if ( arg_cnt != 3 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state ||
decoder->num_flex_vectors != 7 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected flex end\n" ));
goto Syntax_Error;
}
/* the two `results' are popped by the following setcurrentpoint */
top[0] = x;
top[1] = y;
known_othersubr_result_cnt = 2;
break;
case 1: /* start flex feature */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) )
goto Fail;
decoder->flex_state = 1;
decoder->num_flex_vectors = 0;
break;
case 2: /* add flex vectors */
{
FT_Int idx;
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" missing flex start\n" ));
goto Syntax_Error;
}
/* note that we should not add a point for index 0; */
/* this will move our current position to the flex */
/* point without adding any point to the outline */
idx = decoder->num_flex_vectors++;
if ( idx > 0 && idx < 7 )
t1_builder_add_point( builder,
x,
y,
(FT_Byte)( idx == 3 || idx == 6 ) );
}
break;
break;
case 12:
case 13:
/* counter control hints, clear stack */
top = decoder->stack;
break;
case 14:
case 15:
case 16:
case 17:
case 18: /* multiple masters */
{
PS_Blend blend = decoder->blend;
FT_UInt num_points, nn, mm;
FT_Long* delta;
FT_Long* values;
if ( !blend )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected multiple masters operator\n" ));
goto Syntax_Error;
}
num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 );
if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" incorrect number of multiple masters arguments\n" ));
goto Syntax_Error;
}
/* We want to compute */
/* */
/* a0*w0 + a1*w1 + ... + ak*wk */
/* */
/* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */
/* */
/* However, given that w0 + w1 + ... + wk == 1, we can */
/* rewrite it easily as */
/* */
/* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */
/* */
/* where k == num_designs-1. */
/* */
/* I guess that's why it's written in this `compact' */
/* form. */
/* */
delta = top + num_points;
values = top;
for ( nn = 0; nn < num_points; nn++ )
{
FT_Long tmp = values[0];
for ( mm = 1; mm < blend->num_designs; mm++ )
tmp += FT_MulFix( *delta++, blend->weight_vector[mm] );
*values++ = tmp;
}
known_othersubr_result_cnt = (FT_Int)num_points;
break;
}
case 19:
/* <idx> 1 19 callothersubr */
/* => replace elements starting from index cvi( <idx> ) */
/* of BuildCharArray with WeightVector */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 ||
(FT_UInt)idx + blend->num_designs > decoder->len_buildchar )
goto Unexpected_OtherSubr;
ft_memcpy( &decoder->buildchar[idx],
blend->weight_vector,
blend->num_designs *
sizeof ( blend->weight_vector[0] ) );
}
break;
case 20:
/* <arg1> <arg2> 2 20 callothersubr pop */
/* ==> push <arg1> + <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] += top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 21:
/* <arg1> <arg2> 2 21 callothersubr pop */
/* ==> push <arg1> - <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] -= top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 22:
/* <arg1> <arg2> 2 22 callothersubr pop */
/* ==> push <arg1> * <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] = FT_MulFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 23:
/* <arg1> <arg2> 2 23 callothersubr pop */
/* ==> push <arg1> / <arg2> onto T1 stack */
if ( arg_cnt != 2 || top[1] == 0 )
goto Unexpected_OtherSubr;
top[0] = FT_DivFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 24:
/* <val> <idx> 2 24 callothersubr */
/* ==> set BuildCharArray[cvi( <idx> )] = <val> */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 2 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[1] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
decoder->buildchar[idx] = top[0];
}
break;
case 25:
/* <idx> 1 25 callothersubr pop */
/* ==> push BuildCharArray[cvi( idx )] */
/* onto T1 stack */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
top[0] = decoder->buildchar[idx];
}
known_othersubr_result_cnt = 1;
break;
#if 0
case 26:
/* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */
/* leave mark on T1 stack */
/* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */
XXX which routine has left its mark on the (PostScript) stack?;
break;
#endif
case 27:
/* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */
/* ==> push <res1> onto T1 stack if <val1> <= <val2>, */
/* otherwise push <res2> */
if ( arg_cnt != 4 )
goto Unexpected_OtherSubr;
if ( top[2] > top[3] )
top[0] = top[1];
known_othersubr_result_cnt = 1;
break;
case 28:
/* 0 28 callothersubr pop */
/* => push random value from interval [0, 1) onto stack */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
{
FT_Fixed Rand;
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
top[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
}
known_othersubr_result_cnt = 1;
break;
default:
if ( arg_cnt >= 0 && subr_no >= 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unknown othersubr [%d %d], wish me luck\n",
arg_cnt, subr_no ));
unknown_othersubr_result_cnt = arg_cnt;
break;
}
/* fall through */
Unexpected_OtherSubr:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid othersubr [%d %d]\n", arg_cnt, subr_no ));
goto Syntax_Error;
}
top += known_othersubr_result_cnt;
decoder->top = top;
}
else /* general operator */
{
FT_Int num_args = t1_args_count[op];
FT_ASSERT( num_args >= 0 );
if ( top - decoder->stack < num_args )
goto Stack_Underflow;
/* XXX Operators usually take their operands from the */
/* bottom of the stack, i.e., the operands are */
/* decoder->stack[0], ..., decoder->stack[num_args - 1]; */
/* only div, callsubr, and callothersubr are different. */
/* In practice it doesn't matter (?). */
#ifdef FT_DEBUG_LEVEL_TRACE
switch ( op )
{
case op_callsubr:
case op_div:
case op_callothersubr:
case op_pop:
case op_return:
break;
default:
if ( top - decoder->stack != num_args )
FT_TRACE0(( "t1_decoder_parse_charstrings:"
" too much operands on the stack"
" (seen %d, expected %d)\n",
top - decoder->stack, num_args ));
break;
}
#endif /* FT_DEBUG_LEVEL_TRACE */
top -= num_args;
switch ( op )
{
case op_endchar:
FT_TRACE4(( " endchar\n" ));
t1_builder_close_contour( builder );
/* close hints recording session */
if ( hinter )
{
if ( hinter->close( hinter->hints,
(FT_UInt)builder->current->n_points ) )
goto Syntax_Error;
/* apply hints to the loaded glyph outline now */
error = hinter->apply( hinter->hints,
builder->current,
(PSH_Globals)builder->hints_globals,
decoder->hint_mode );
if ( error )
goto Fail;
}
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
/* the compiler should optimize away this empty loop but ... */
#ifdef FT_DEBUG_LEVEL_TRACE
if ( decoder->len_buildchar > 0 )
{
FT_UInt i;
FT_TRACE4(( "BuildCharArray = [ " ));
for ( i = 0; i < decoder->len_buildchar; i++ )
FT_TRACE4(( "%d ", decoder->buildchar[i] ));
FT_TRACE4(( "]\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
FT_TRACE4(( "\n" ));
/* return now! */
return FT_Err_Ok;
case op_hsbw:
FT_TRACE4(( " hsbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->advance.x = top[1];
builder->advance.y = 0;
orig_x = x = builder->pos_x + top[0];
orig_y = y = builder->pos_y;
FT_UNUSED( orig_y );
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_seac:
return t1operator_seac( decoder,
top[0],
top[1],
top[2],
Fix2Int( top[3] ),
Fix2Int( top[4] ) );
case op_sbw:
FT_TRACE4(( " sbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->left_bearing.y += top[1];
builder->advance.x = top[2];
builder->advance.y = top[3];
x = builder->pos_x + top[0];
y = builder->pos_y + top[1];
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_closepath:
FT_TRACE4(( " closepath" ));
/* if there is no path, `closepath' is a no-op */
if ( builder->parse_state == T1_Parse_Have_Path ||
builder->parse_state == T1_Parse_Have_Moveto )
t1_builder_close_contour( builder );
builder->parse_state = T1_Parse_Have_Width;
break;
case op_hlineto:
FT_TRACE4(( " hlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
goto Add_Line;
case op_hmoveto:
FT_TRACE4(( " hmoveto" ));
x += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_hvcurveto:
FT_TRACE4(( " hvcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
y += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_rlineto:
FT_TRACE4(( " rlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
y += top[1];
Add_Line:
if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) )
goto Fail;
break;
case op_rmoveto:
FT_TRACE4(( " rmoveto" ));
x += top[0];
y += top[1];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_rrcurveto:
FT_TRACE4(( " rrcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
y += top[1];
t1_builder_add_point( builder, x, y, 0 );
x += top[2];
y += top[3];
t1_builder_add_point( builder, x, y, 0 );
x += top[4];
y += top[5];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vhcurveto:
FT_TRACE4(( " vhcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
y += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
x += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vlineto:
FT_TRACE4(( " vlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
y += top[0];
goto Add_Line;
case op_vmoveto:
FT_TRACE4(( " vmoveto" ));
y += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_div:
FT_TRACE4(( " div" ));
/* if `large_int' is set, we divide unscaled numbers; */
/* otherwise, we divide numbers in 16.16 format -- */
/* in both cases, it is the same operation */
*top = FT_DivFix( top[0], top[1] );
top++;
large_int = FALSE;
break;
case op_callsubr:
{
FT_Int idx;
FT_TRACE4(( " callsubr" ));
idx = Fix2Int( top[0] );
if ( decoder->subrs_hash )
{
size_t* val = ft_hash_num_lookup( idx,
decoder->subrs_hash );
if ( val )
idx = *val;
else
idx = -1;
}
if ( idx < 0 || idx >= decoder->num_subrs )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid subrs index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
/* The Type 1 driver stores subroutines without the seed bytes. */
/* The CID driver stores subroutines with seed bytes. This */
/* case is taken care of when decoder->subrs_len == 0. */
zone->base = decoder->subrs[idx];
if ( decoder->subrs_len )
zone->limit = zone->base + decoder->subrs_len[idx];
else
{
/* We are using subroutines from a CID font. We must adjust */
/* for the seed bytes. */
zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 );
zone->limit = decoder->subrs[idx + 1];
}
zone->cursor = zone->base;
if ( !zone->base )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
break;
}
case op_pop:
FT_TRACE4(( " pop" ));
if ( known_othersubr_result_cnt > 0 )
{
known_othersubr_result_cnt--;
/* ignore, we pushed the operands ourselves */
break;
}
if ( unknown_othersubr_result_cnt == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no more operands for othersubr\n" ));
goto Syntax_Error;
}
unknown_othersubr_result_cnt--;
top++; /* `push' the operand to callothersubr onto the stack */
break;
case op_return:
FT_TRACE4(( " return" ));
if ( zone <= decoder->zones )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
zone--;
ip = zone->cursor;
limit = zone->limit;
decoder->zone = zone;
break;
case op_dotsection:
FT_TRACE4(( " dotsection" ));
break;
case op_hstem:
FT_TRACE4(( " hstem" ));
/* record horizontal hint */
if ( hinter )
{
/* top[0] += builder->left_bearing.y; */
hinter->stem( hinter->hints, 1, top );
}
break;
case op_hstem3:
FT_TRACE4(( " hstem3" ));
/* record horizontal counter-controlled hints */
if ( hinter )
hinter->stem3( hinter->hints, 1, top );
break;
case op_vstem:
FT_TRACE4(( " vstem" ));
/* record vertical hint */
if ( hinter )
{
top[0] += orig_x;
hinter->stem( hinter->hints, 0, top );
}
break;
case op_vstem3:
FT_TRACE4(( " vstem3" ));
/* record vertical counter-controlled hints */
if ( hinter )
{
FT_Pos dx = orig_x;
top[0] += dx;
top[2] += dx;
top[4] += dx;
hinter->stem3( hinter->hints, 0, top );
}
break;
case op_setcurrentpoint:
FT_TRACE4(( " setcurrentpoint" ));
/* From the T1 specification, section 6.4: */
/* */
/* The setcurrentpoint command is used only in */
/* conjunction with results from OtherSubrs procedures. */
/* known_othersubr_result_cnt != 0 is already handled */
/* above. */
/* Note, however, that both Ghostscript and Adobe */
/* Distiller handle this situation by silently ignoring */
/* the inappropriate `setcurrentpoint' instruction. So */
/* we do the same. */
#if 0
if ( decoder->flex_state != 1 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected `setcurrentpoint'\n" ));
goto Syntax_Error;
}
else
...
#endif
x = top[0];
y = top[1];
decoder->flex_state = 0;
break;
case op_unknown15:
FT_TRACE4(( " opcode_15" ));
/* nothing to do except to pop the two arguments */
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unhandled opcode %d\n", op ));
goto Syntax_Error;
}
/* XXX Operators usually clear the operand stack; */
/* only div, callsubr, callothersubr, pop, and */
/* return are different. */
/* In practice it doesn't matter (?). */
decoder->top = top;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( "\n" ));
bol = TRUE;
#endif
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
return FT_THROW( Syntax_Error );
Stack_Underflow:
return FT_THROW( Stack_Underflow );
}
|
t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* charstring_base,
FT_UInt charstring_len )
{
FT_Error error;
T1_Decoder_Zone zone;
FT_Byte* ip;
FT_Byte* limit;
T1_Builder builder = &decoder->builder;
FT_Pos x, y, orig_x, orig_y;
FT_Int known_othersubr_result_cnt = 0;
FT_Int unknown_othersubr_result_cnt = 0;
FT_Bool large_int;
FT_Fixed seed;
T1_Hints_Funcs hinter;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Bool bol = TRUE;
#endif
/* compute random seed from stack address of parameter */
seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^
(FT_Offset)(char*)&decoder ^
(FT_Offset)(char*)&charstring_base ) &
FT_ULONG_MAX );
seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL;
if ( seed == 0 )
seed = 0x7384;
/* First of all, initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
builder->parse_state = T1_Parse_Start;
hinter = (T1_Hints_Funcs)builder->hints_funcs;
/* a font that reads BuildCharArray without setting */
/* its values first is buggy, but ... */
FT_ASSERT( ( decoder->len_buildchar == 0 ) ==
( decoder->buildchar == NULL ) );
if ( decoder->buildchar && decoder->len_buildchar > 0 )
FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar );
FT_TRACE4(( "\n"
"Start charstring\n" ));
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = FT_Err_Ok;
x = orig_x = builder->pos_x;
y = orig_y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
large_int = FALSE;
/* now, execute loop */
while ( ip < limit )
{
FT_Long* top = decoder->top;
T1_Operator op = op_none;
FT_Int32 value = 0;
FT_ASSERT( known_othersubr_result_cnt == 0 ||
unknown_othersubr_result_cnt == 0 );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( bol )
{
FT_TRACE5(( " (%d)", decoder->top - decoder->stack ));
bol = FALSE;
}
#endif
/*********************************************************************/
/* */
/* Decode operator or operand */
/* */
/* */
/* first of all, decompress operator or value */
switch ( *ip++ )
{
case 1:
op = op_hstem;
break;
case 3:
op = op_vstem;
break;
case 4:
op = op_vmoveto;
break;
case 5:
op = op_rlineto;
break;
case 6:
op = op_hlineto;
break;
case 7:
op = op_vlineto;
break;
case 8:
op = op_rrcurveto;
break;
case 9:
op = op_closepath;
break;
case 10:
op = op_callsubr;
break;
case 11:
op = op_return;
break;
case 13:
op = op_hsbw;
break;
case 14:
op = op_endchar;
break;
case 15: /* undocumented, obsolete operator */
op = op_unknown15;
break;
case 21:
op = op_rmoveto;
break;
case 22:
op = op_hmoveto;
break;
case 30:
op = op_vhcurveto;
break;
case 31:
op = op_hvcurveto;
break;
case 12:
if ( ip >= limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+EOF)\n" ));
goto Syntax_Error;
}
switch ( *ip++ )
{
case 0:
op = op_dotsection;
break;
case 1:
op = op_vstem3;
break;
case 2:
op = op_hstem3;
break;
case 6:
op = op_seac;
break;
case 7:
op = op_sbw;
break;
case 12:
op = op_div;
break;
case 16:
op = op_callothersubr;
break;
case 17:
op = op_pop;
break;
case 33:
op = op_setcurrentpoint;
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+%d)\n",
ip[-1] ));
goto Syntax_Error;
}
break;
case 255: /* four bytes integer */
if ( ip + 4 > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) |
( (FT_UInt32)ip[1] << 16 ) |
( (FT_UInt32)ip[2] << 8 ) |
(FT_UInt32)ip[3] );
ip += 4;
/* According to the specification, values > 32000 or < -32000 must */
/* be followed by a `div' operator to make the result be in the */
/* range [-32000;32000]. We expect that the second argument of */
/* `div' is not a large number. Additionally, we don't handle */
/* stuff like `<large1> <large2> <num> div <num> div' or */
/* <large1> <large2> <num> div div'. This is probably not allowed */
/* anyway. */
if ( value > 32000 || value < -32000 )
{
if ( large_int )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
}
else
large_int = TRUE;
}
else
{
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
break;
default:
if ( ip[-1] >= 32 )
{
if ( ip[-1] < 247 )
value = (FT_Int32)ip[-1] - 139;
else
{
if ( ++ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
if ( ip[-2] < 251 )
value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108;
else
value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 );
}
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
else
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid byte (%d)\n", ip[-1] ));
goto Syntax_Error;
}
}
if ( unknown_othersubr_result_cnt > 0 )
{
switch ( op )
{
case op_callsubr:
case op_return:
case op_none:
case op_pop:
break;
default:
/* all operands have been transferred by previous pops */
unknown_othersubr_result_cnt = 0;
break;
}
}
if ( large_int && !( op == op_none || op == op_div ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
large_int = FALSE;
}
/*********************************************************************/
/* */
/* Push value on stack, or process operator */
/* */
/* */
if ( op == op_none )
{
if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS )
{
FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" ));
goto Syntax_Error;
}
#ifdef FT_DEBUG_LEVEL_TRACE
if ( large_int )
FT_TRACE4(( " %d", value ));
else
FT_TRACE4(( " %d", value / 65536 ));
#endif
*top++ = value;
decoder->top = top;
}
else if ( op == op_callothersubr ) /* callothersubr */
{
FT_Int subr_no;
FT_Int arg_cnt;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( " callothersubr\n" ));
bol = TRUE;
#endif
if ( top - decoder->stack < 2 )
goto Stack_Underflow;
top -= 2;
subr_no = Fix2Int( top[1] );
arg_cnt = Fix2Int( top[0] );
/***********************************************************/
/* */
/* remove all operands to callothersubr from the stack */
/* */
/* for handled othersubrs, where we know the number of */
/* arguments, we increase the stack by the value of */
/* known_othersubr_result_cnt */
/* */
/* for unhandled othersubrs the following pops adjust the */
/* stack pointer as necessary */
if ( arg_cnt > top - decoder->stack )
goto Stack_Underflow;
top -= arg_cnt;
known_othersubr_result_cnt = 0;
unknown_othersubr_result_cnt = 0;
/* XXX TODO: The checks to `arg_count == <whatever>' */
/* might not be correct; an othersubr expects a certain */
/* number of operands on the PostScript stack (as opposed */
/* to the T1 stack) but it doesn't have to put them there */
/* by itself; previous othersubrs might have left the */
/* operands there if they were not followed by an */
/* appropriate number of pops */
/* */
/* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */
/* accept a font that contains charstrings like */
/* */
/* 100 200 2 20 callothersubr */
/* 300 1 20 callothersubr pop */
/* */
/* Perhaps this is the reason why BuildCharArray exists. */
switch ( subr_no )
{
case 0: /* end flex feature */
if ( arg_cnt != 3 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state ||
decoder->num_flex_vectors != 7 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected flex end\n" ));
goto Syntax_Error;
}
/* the two `results' are popped by the following setcurrentpoint */
top[0] = x;
top[1] = y;
known_othersubr_result_cnt = 2;
break;
case 1: /* start flex feature */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) )
goto Fail;
decoder->flex_state = 1;
decoder->num_flex_vectors = 0;
break;
case 2: /* add flex vectors */
{
FT_Int idx;
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" missing flex start\n" ));
goto Syntax_Error;
}
/* note that we should not add a point for index 0; */
/* this will move our current position to the flex */
/* point without adding any point to the outline */
idx = decoder->num_flex_vectors++;
if ( idx > 0 && idx < 7 )
{
/* in malformed fonts it is possible to have other */
/* opcodes in the middle of a flex (which don't */
/* increase `num_flex_vectors'); we thus have to */
/* check whether we can add a point */
if ( FT_SET_ERROR( t1_builder_check_points( builder, 1 ) ) )
goto Syntax_Error;
t1_builder_add_point( builder,
x,
y,
(FT_Byte)( idx == 3 || idx == 6 ) );
}
}
break;
break;
case 12:
case 13:
/* counter control hints, clear stack */
top = decoder->stack;
break;
case 14:
case 15:
case 16:
case 17:
case 18: /* multiple masters */
{
PS_Blend blend = decoder->blend;
FT_UInt num_points, nn, mm;
FT_Long* delta;
FT_Long* values;
if ( !blend )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected multiple masters operator\n" ));
goto Syntax_Error;
}
num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 );
if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" incorrect number of multiple masters arguments\n" ));
goto Syntax_Error;
}
/* We want to compute */
/* */
/* a0*w0 + a1*w1 + ... + ak*wk */
/* */
/* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */
/* */
/* However, given that w0 + w1 + ... + wk == 1, we can */
/* rewrite it easily as */
/* */
/* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */
/* */
/* where k == num_designs-1. */
/* */
/* I guess that's why it's written in this `compact' */
/* form. */
/* */
delta = top + num_points;
values = top;
for ( nn = 0; nn < num_points; nn++ )
{
FT_Long tmp = values[0];
for ( mm = 1; mm < blend->num_designs; mm++ )
tmp += FT_MulFix( *delta++, blend->weight_vector[mm] );
*values++ = tmp;
}
known_othersubr_result_cnt = (FT_Int)num_points;
break;
}
case 19:
/* <idx> 1 19 callothersubr */
/* => replace elements starting from index cvi( <idx> ) */
/* of BuildCharArray with WeightVector */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 ||
(FT_UInt)idx + blend->num_designs > decoder->len_buildchar )
goto Unexpected_OtherSubr;
ft_memcpy( &decoder->buildchar[idx],
blend->weight_vector,
blend->num_designs *
sizeof ( blend->weight_vector[0] ) );
}
break;
case 20:
/* <arg1> <arg2> 2 20 callothersubr pop */
/* ==> push <arg1> + <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] += top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 21:
/* <arg1> <arg2> 2 21 callothersubr pop */
/* ==> push <arg1> - <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] -= top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 22:
/* <arg1> <arg2> 2 22 callothersubr pop */
/* ==> push <arg1> * <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] = FT_MulFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 23:
/* <arg1> <arg2> 2 23 callothersubr pop */
/* ==> push <arg1> / <arg2> onto T1 stack */
if ( arg_cnt != 2 || top[1] == 0 )
goto Unexpected_OtherSubr;
top[0] = FT_DivFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 24:
/* <val> <idx> 2 24 callothersubr */
/* ==> set BuildCharArray[cvi( <idx> )] = <val> */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 2 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[1] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
decoder->buildchar[idx] = top[0];
}
break;
case 25:
/* <idx> 1 25 callothersubr pop */
/* ==> push BuildCharArray[cvi( idx )] */
/* onto T1 stack */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
top[0] = decoder->buildchar[idx];
}
known_othersubr_result_cnt = 1;
break;
#if 0
case 26:
/* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */
/* leave mark on T1 stack */
/* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */
XXX which routine has left its mark on the (PostScript) stack?;
break;
#endif
case 27:
/* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */
/* ==> push <res1> onto T1 stack if <val1> <= <val2>, */
/* otherwise push <res2> */
if ( arg_cnt != 4 )
goto Unexpected_OtherSubr;
if ( top[2] > top[3] )
top[0] = top[1];
known_othersubr_result_cnt = 1;
break;
case 28:
/* 0 28 callothersubr pop */
/* => push random value from interval [0, 1) onto stack */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
{
FT_Fixed Rand;
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
top[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
}
known_othersubr_result_cnt = 1;
break;
default:
if ( arg_cnt >= 0 && subr_no >= 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unknown othersubr [%d %d], wish me luck\n",
arg_cnt, subr_no ));
unknown_othersubr_result_cnt = arg_cnt;
break;
}
/* fall through */
Unexpected_OtherSubr:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid othersubr [%d %d]\n", arg_cnt, subr_no ));
goto Syntax_Error;
}
top += known_othersubr_result_cnt;
decoder->top = top;
}
else /* general operator */
{
FT_Int num_args = t1_args_count[op];
FT_ASSERT( num_args >= 0 );
if ( top - decoder->stack < num_args )
goto Stack_Underflow;
/* XXX Operators usually take their operands from the */
/* bottom of the stack, i.e., the operands are */
/* decoder->stack[0], ..., decoder->stack[num_args - 1]; */
/* only div, callsubr, and callothersubr are different. */
/* In practice it doesn't matter (?). */
#ifdef FT_DEBUG_LEVEL_TRACE
switch ( op )
{
case op_callsubr:
case op_div:
case op_callothersubr:
case op_pop:
case op_return:
break;
default:
if ( top - decoder->stack != num_args )
FT_TRACE0(( "t1_decoder_parse_charstrings:"
" too much operands on the stack"
" (seen %d, expected %d)\n",
top - decoder->stack, num_args ));
break;
}
#endif /* FT_DEBUG_LEVEL_TRACE */
top -= num_args;
switch ( op )
{
case op_endchar:
FT_TRACE4(( " endchar\n" ));
t1_builder_close_contour( builder );
/* close hints recording session */
if ( hinter )
{
if ( hinter->close( hinter->hints,
(FT_UInt)builder->current->n_points ) )
goto Syntax_Error;
/* apply hints to the loaded glyph outline now */
error = hinter->apply( hinter->hints,
builder->current,
(PSH_Globals)builder->hints_globals,
decoder->hint_mode );
if ( error )
goto Fail;
}
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
/* the compiler should optimize away this empty loop but ... */
#ifdef FT_DEBUG_LEVEL_TRACE
if ( decoder->len_buildchar > 0 )
{
FT_UInt i;
FT_TRACE4(( "BuildCharArray = [ " ));
for ( i = 0; i < decoder->len_buildchar; i++ )
FT_TRACE4(( "%d ", decoder->buildchar[i] ));
FT_TRACE4(( "]\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
FT_TRACE4(( "\n" ));
/* return now! */
return FT_Err_Ok;
case op_hsbw:
FT_TRACE4(( " hsbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->advance.x = top[1];
builder->advance.y = 0;
orig_x = x = builder->pos_x + top[0];
orig_y = y = builder->pos_y;
FT_UNUSED( orig_y );
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_seac:
return t1operator_seac( decoder,
top[0],
top[1],
top[2],
Fix2Int( top[3] ),
Fix2Int( top[4] ) );
case op_sbw:
FT_TRACE4(( " sbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->left_bearing.y += top[1];
builder->advance.x = top[2];
builder->advance.y = top[3];
x = builder->pos_x + top[0];
y = builder->pos_y + top[1];
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_closepath:
FT_TRACE4(( " closepath" ));
/* if there is no path, `closepath' is a no-op */
if ( builder->parse_state == T1_Parse_Have_Path ||
builder->parse_state == T1_Parse_Have_Moveto )
t1_builder_close_contour( builder );
builder->parse_state = T1_Parse_Have_Width;
break;
case op_hlineto:
FT_TRACE4(( " hlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
goto Add_Line;
case op_hmoveto:
FT_TRACE4(( " hmoveto" ));
x += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_hvcurveto:
FT_TRACE4(( " hvcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
y += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_rlineto:
FT_TRACE4(( " rlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
y += top[1];
Add_Line:
if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) )
goto Fail;
break;
case op_rmoveto:
FT_TRACE4(( " rmoveto" ));
x += top[0];
y += top[1];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_rrcurveto:
FT_TRACE4(( " rrcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
y += top[1];
t1_builder_add_point( builder, x, y, 0 );
x += top[2];
y += top[3];
t1_builder_add_point( builder, x, y, 0 );
x += top[4];
y += top[5];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vhcurveto:
FT_TRACE4(( " vhcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
y += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
x += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vlineto:
FT_TRACE4(( " vlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
y += top[0];
goto Add_Line;
case op_vmoveto:
FT_TRACE4(( " vmoveto" ));
y += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_div:
FT_TRACE4(( " div" ));
/* if `large_int' is set, we divide unscaled numbers; */
/* otherwise, we divide numbers in 16.16 format -- */
/* in both cases, it is the same operation */
*top = FT_DivFix( top[0], top[1] );
top++;
large_int = FALSE;
break;
case op_callsubr:
{
FT_Int idx;
FT_TRACE4(( " callsubr" ));
idx = Fix2Int( top[0] );
if ( decoder->subrs_hash )
{
size_t* val = ft_hash_num_lookup( idx,
decoder->subrs_hash );
if ( val )
idx = *val;
else
idx = -1;
}
if ( idx < 0 || idx >= decoder->num_subrs )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid subrs index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
/* The Type 1 driver stores subroutines without the seed bytes. */
/* The CID driver stores subroutines with seed bytes. This */
/* case is taken care of when decoder->subrs_len == 0. */
zone->base = decoder->subrs[idx];
if ( decoder->subrs_len )
zone->limit = zone->base + decoder->subrs_len[idx];
else
{
/* We are using subroutines from a CID font. We must adjust */
/* for the seed bytes. */
zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 );
zone->limit = decoder->subrs[idx + 1];
}
zone->cursor = zone->base;
if ( !zone->base )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
break;
}
case op_pop:
FT_TRACE4(( " pop" ));
if ( known_othersubr_result_cnt > 0 )
{
known_othersubr_result_cnt--;
/* ignore, we pushed the operands ourselves */
break;
}
if ( unknown_othersubr_result_cnt == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no more operands for othersubr\n" ));
goto Syntax_Error;
}
unknown_othersubr_result_cnt--;
top++; /* `push' the operand to callothersubr onto the stack */
break;
case op_return:
FT_TRACE4(( " return" ));
if ( zone <= decoder->zones )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
zone--;
ip = zone->cursor;
limit = zone->limit;
decoder->zone = zone;
break;
case op_dotsection:
FT_TRACE4(( " dotsection" ));
break;
case op_hstem:
FT_TRACE4(( " hstem" ));
/* record horizontal hint */
if ( hinter )
{
/* top[0] += builder->left_bearing.y; */
hinter->stem( hinter->hints, 1, top );
}
break;
case op_hstem3:
FT_TRACE4(( " hstem3" ));
/* record horizontal counter-controlled hints */
if ( hinter )
hinter->stem3( hinter->hints, 1, top );
break;
case op_vstem:
FT_TRACE4(( " vstem" ));
/* record vertical hint */
if ( hinter )
{
top[0] += orig_x;
hinter->stem( hinter->hints, 0, top );
}
break;
case op_vstem3:
FT_TRACE4(( " vstem3" ));
/* record vertical counter-controlled hints */
if ( hinter )
{
FT_Pos dx = orig_x;
top[0] += dx;
top[2] += dx;
top[4] += dx;
hinter->stem3( hinter->hints, 0, top );
}
break;
case op_setcurrentpoint:
FT_TRACE4(( " setcurrentpoint" ));
/* From the T1 specification, section 6.4: */
/* */
/* The setcurrentpoint command is used only in */
/* conjunction with results from OtherSubrs procedures. */
/* known_othersubr_result_cnt != 0 is already handled */
/* above. */
/* Note, however, that both Ghostscript and Adobe */
/* Distiller handle this situation by silently ignoring */
/* the inappropriate `setcurrentpoint' instruction. So */
/* we do the same. */
#if 0
if ( decoder->flex_state != 1 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected `setcurrentpoint'\n" ));
goto Syntax_Error;
}
else
...
#endif
x = top[0];
y = top[1];
decoder->flex_state = 0;
break;
case op_unknown15:
FT_TRACE4(( " opcode_15" ));
/* nothing to do except to pop the two arguments */
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unhandled opcode %d\n", op ));
goto Syntax_Error;
}
/* XXX Operators usually clear the operand stack; */
/* only div, callsubr, callothersubr, pop, and */
/* return are different. */
/* In practice it doesn't matter (?). */
decoder->top = top;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( "\n" ));
bol = TRUE;
#endif
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
return FT_THROW( Syntax_Error );
Stack_Underflow:
return FT_THROW( Stack_Underflow );
}
|
CVE-2017-8105
|
FreeType 2 before 2017-03-24 has an out-of-bounds write caused by a heap-based buffer overflow related to the t1_decoder_parse_charstrings function in psaux/t1decode.c.
|
[
"CWE-787"
] |
[] |
[
{
"line_no": 422,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 423,
"text": " /* in malformed fonts it is possible to have other */",
"char_start": null,
"char_end": null
},
{
"line_no": 424,
"text": " /* opcodes in the middle of a flex (which don't */",
"char_start": null,
"char_end": null
},
{
"line_no": 425,
"text": " /* increase `num_flex_vectors'); we thus have to */",
"char_start": null,
"char_end": null
},
{
"line_no": 426,
"text": " /* check whether we can add a point */",
"char_start": null,
"char_end": null
},
{
"line_no": 427,
"text": " if ( FT_SET_ERROR( t1_builder_check_points( builder, 1 ) ) )",
"char_start": null,
"char_end": null
},
{
"line_no": 428,
"text": " goto Syntax_Error;",
"char_start": null,
"char_end": null
},
{
"line_no": 429,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 434,
"text": " }",
"char_start": null,
"char_end": null
}
] | 211
|
primevul
|
primevul_dbus_7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
|
7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
|
dbus
|
http://gitweb.freedesktop.org/?p=dbus/dbus
|
validate_body_helper (DBusTypeReader *reader,
int byte_order,
dbus_bool_t walk_reader_to_end,
const unsigned char *p,
const unsigned char *end,
const unsigned char **new_p)
{
int current_type;
while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID)
{
const unsigned char *a;
case DBUS_TYPE_BYTE:
++p;
break;
case DBUS_TYPE_BOOLEAN:
case DBUS_TYPE_INT16:
case DBUS_TYPE_UINT16:
case DBUS_TYPE_INT32:
case DBUS_TYPE_UINT32:
case DBUS_TYPE_UNIX_FD:
case DBUS_TYPE_INT64:
case DBUS_TYPE_UINT64:
case DBUS_TYPE_DOUBLE:
alignment = _dbus_type_get_alignment (current_type);
a = _DBUS_ALIGN_ADDRESS (p, alignment);
if (a >= end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
if (current_type == DBUS_TYPE_BOOLEAN)
{
dbus_uint32_t v = _dbus_unpack_uint32 (byte_order,
p);
if (!(v == 0 || v == 1))
return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
}
p += alignment;
break;
case DBUS_TYPE_ARRAY:
case DBUS_TYPE_STRING:
case DBUS_TYPE_OBJECT_PATH:
{
dbus_uint32_t claimed_len;
a = _DBUS_ALIGN_ADDRESS (p, 4);
if (a + 4 > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
claimed_len = _dbus_unpack_uint32 (byte_order, p);
p += 4;
/* p may now be == end */
_dbus_assert (p <= end);
if (current_type == DBUS_TYPE_ARRAY)
{
int array_elem_type = _dbus_type_reader_get_element_type (reader);
if (!_dbus_type_is_valid (array_elem_type))
{
return DBUS_INVALID_UNKNOWN_TYPECODE;
}
alignment = _dbus_type_get_alignment (array_elem_type);
a = _DBUS_ALIGN_ADDRESS (p, alignment);
/* a may now be == end */
if (a > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
}
if (claimed_len > (unsigned long) (end - p))
return DBUS_INVALID_LENGTH_OUT_OF_BOUNDS;
if (current_type == DBUS_TYPE_OBJECT_PATH)
{
DBusString str;
_dbus_string_init_const_len (&str, p, claimed_len);
if (!_dbus_validate_path (&str, 0,
_dbus_string_get_length (&str)))
return DBUS_INVALID_BAD_PATH;
p += claimed_len;
}
else if (current_type == DBUS_TYPE_STRING)
{
DBusString str;
_dbus_string_init_const_len (&str, p, claimed_len);
if (!_dbus_string_validate_utf8 (&str, 0,
_dbus_string_get_length (&str)))
return DBUS_INVALID_BAD_UTF8_IN_STRING;
p += claimed_len;
}
else if (current_type == DBUS_TYPE_ARRAY && claimed_len > 0)
{
DBusTypeReader sub;
DBusValidity validity;
const unsigned char *array_end;
int array_elem_type;
if (claimed_len > DBUS_MAXIMUM_ARRAY_LENGTH)
return DBUS_INVALID_ARRAY_LENGTH_EXCEEDS_MAXIMUM;
/* Remember that the reader is types only, so we can't
* use it to iterate over elements. It stays the same
* for all elements.
*/
_dbus_type_reader_recurse (reader, &sub);
array_end = p + claimed_len;
array_elem_type = _dbus_type_reader_get_element_type (reader);
/* avoid recursive call to validate_body_helper if this is an array
* of fixed-size elements
*/
if (dbus_type_is_fixed (array_elem_type))
{
/* bools need to be handled differently, because they can
* have an invalid value
*/
if (array_elem_type == DBUS_TYPE_BOOLEAN)
{
dbus_uint32_t v;
alignment = _dbus_type_get_alignment (array_elem_type);
while (p < array_end)
{
v = _dbus_unpack_uint32 (byte_order, p);
if (!(v == 0 || v == 1))
return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
p += alignment;
}
}
else
{
p = array_end;
}
}
else
{
while (p < array_end)
{
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
}
if (p != array_end)
return DBUS_INVALID_ARRAY_LENGTH_INCORRECT;
}
/* check nul termination */
{
while (p < array_end)
{
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
}
break;
case DBUS_TYPE_SIGNATURE:
{
dbus_uint32_t claimed_len;
DBusString str;
DBusValidity validity;
claimed_len = *p;
++p;
/* 1 is for nul termination */
if (claimed_len + 1 > (unsigned long) (end - p))
return DBUS_INVALID_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
_dbus_string_init_const_len (&str, p, claimed_len);
validity =
_dbus_validate_signature_with_reason (&str, 0,
_dbus_string_get_length (&str));
if (validity != DBUS_VALID)
return validity;
p += claimed_len;
_dbus_assert (p < end);
if (*p != DBUS_TYPE_INVALID)
return DBUS_INVALID_SIGNATURE_MISSING_NUL;
++p;
_dbus_verbose ("p = %p end = %p claimed_len %u\n", p, end, claimed_len);
}
break;
case DBUS_TYPE_VARIANT:
{
/* 1 byte sig len, sig typecodes, align to
* contained-type-boundary, values.
*/
/* In addition to normal signature validation, we need to be sure
* the signature contains only a single (possibly container) type.
*/
dbus_uint32_t claimed_len;
DBusString sig;
DBusTypeReader sub;
DBusValidity validity;
int contained_alignment;
int contained_type;
DBusValidity reason;
claimed_len = *p;
++p;
/* + 1 for nul */
if (claimed_len + 1 > (unsigned long) (end - p))
return DBUS_INVALID_VARIANT_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
_dbus_string_init_const_len (&sig, p, claimed_len);
reason = _dbus_validate_signature_with_reason (&sig, 0,
_dbus_string_get_length (&sig));
if (!(reason == DBUS_VALID))
{
if (reason == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
return reason;
else
return DBUS_INVALID_VARIANT_SIGNATURE_BAD;
}
p += claimed_len;
if (*p != DBUS_TYPE_INVALID)
return DBUS_INVALID_VARIANT_SIGNATURE_MISSING_NUL;
++p;
contained_type = _dbus_first_type_in_signature (&sig, 0);
if (contained_type == DBUS_TYPE_INVALID)
return DBUS_INVALID_VARIANT_SIGNATURE_EMPTY;
contained_alignment = _dbus_type_get_alignment (contained_type);
a = _DBUS_ALIGN_ADDRESS (p, contained_alignment);
if (a > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
_dbus_type_reader_init_types_only (&sub, &sig, 0);
_dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID);
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
if (_dbus_type_reader_next (&sub))
return DBUS_INVALID_VARIANT_SIGNATURE_SPECIFIES_MULTIPLE_VALUES;
_dbus_assert (_dbus_type_reader_get_current_type (&sub) == DBUS_TYPE_INVALID);
}
break;
case DBUS_TYPE_DICT_ENTRY:
case DBUS_TYPE_STRUCT:
_dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID);
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
_dbus_type_reader_recurse (reader, &sub);
validity = validate_body_helper (&sub, byte_order, TRUE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
break;
default:
_dbus_assert_not_reached ("invalid typecode in supposedly-validated signature");
break;
}
|
validate_body_helper (DBusTypeReader *reader,
int byte_order,
dbus_bool_t walk_reader_to_end,
int total_depth,
const unsigned char *p,
const unsigned char *end,
const unsigned char **new_p)
{
int current_type;
/* The spec allows arrays and structs to each nest 32, for total
* nesting of 2*32. We want to impose the same limit on "dynamic"
* value nesting (not visible in the signature) which is introduced
* by DBUS_TYPE_VARIANT.
*/
if (total_depth > (DBUS_MAXIMUM_TYPE_RECURSION_DEPTH * 2))
{
return DBUS_INVALID_NESTED_TOO_DEEPLY;
}
while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID)
{
const unsigned char *a;
case DBUS_TYPE_BYTE:
++p;
break;
case DBUS_TYPE_BOOLEAN:
case DBUS_TYPE_INT16:
case DBUS_TYPE_UINT16:
case DBUS_TYPE_INT32:
case DBUS_TYPE_UINT32:
case DBUS_TYPE_UNIX_FD:
case DBUS_TYPE_INT64:
case DBUS_TYPE_UINT64:
case DBUS_TYPE_DOUBLE:
alignment = _dbus_type_get_alignment (current_type);
a = _DBUS_ALIGN_ADDRESS (p, alignment);
if (a >= end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
if (current_type == DBUS_TYPE_BOOLEAN)
{
dbus_uint32_t v = _dbus_unpack_uint32 (byte_order,
p);
if (!(v == 0 || v == 1))
return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
}
p += alignment;
break;
case DBUS_TYPE_ARRAY:
case DBUS_TYPE_STRING:
case DBUS_TYPE_OBJECT_PATH:
{
dbus_uint32_t claimed_len;
a = _DBUS_ALIGN_ADDRESS (p, 4);
if (a + 4 > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
claimed_len = _dbus_unpack_uint32 (byte_order, p);
p += 4;
/* p may now be == end */
_dbus_assert (p <= end);
if (current_type == DBUS_TYPE_ARRAY)
{
int array_elem_type = _dbus_type_reader_get_element_type (reader);
if (!_dbus_type_is_valid (array_elem_type))
{
return DBUS_INVALID_UNKNOWN_TYPECODE;
}
alignment = _dbus_type_get_alignment (array_elem_type);
a = _DBUS_ALIGN_ADDRESS (p, alignment);
/* a may now be == end */
if (a > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
}
if (claimed_len > (unsigned long) (end - p))
return DBUS_INVALID_LENGTH_OUT_OF_BOUNDS;
if (current_type == DBUS_TYPE_OBJECT_PATH)
{
DBusString str;
_dbus_string_init_const_len (&str, p, claimed_len);
if (!_dbus_validate_path (&str, 0,
_dbus_string_get_length (&str)))
return DBUS_INVALID_BAD_PATH;
p += claimed_len;
}
else if (current_type == DBUS_TYPE_STRING)
{
DBusString str;
_dbus_string_init_const_len (&str, p, claimed_len);
if (!_dbus_string_validate_utf8 (&str, 0,
_dbus_string_get_length (&str)))
return DBUS_INVALID_BAD_UTF8_IN_STRING;
p += claimed_len;
}
else if (current_type == DBUS_TYPE_ARRAY && claimed_len > 0)
{
DBusTypeReader sub;
DBusValidity validity;
const unsigned char *array_end;
int array_elem_type;
if (claimed_len > DBUS_MAXIMUM_ARRAY_LENGTH)
return DBUS_INVALID_ARRAY_LENGTH_EXCEEDS_MAXIMUM;
/* Remember that the reader is types only, so we can't
* use it to iterate over elements. It stays the same
* for all elements.
*/
_dbus_type_reader_recurse (reader, &sub);
array_end = p + claimed_len;
array_elem_type = _dbus_type_reader_get_element_type (reader);
/* avoid recursive call to validate_body_helper if this is an array
* of fixed-size elements
*/
if (dbus_type_is_fixed (array_elem_type))
{
/* bools need to be handled differently, because they can
* have an invalid value
*/
if (array_elem_type == DBUS_TYPE_BOOLEAN)
{
dbus_uint32_t v;
alignment = _dbus_type_get_alignment (array_elem_type);
while (p < array_end)
{
v = _dbus_unpack_uint32 (byte_order, p);
if (!(v == 0 || v == 1))
return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
p += alignment;
}
}
else
{
p = array_end;
}
}
else
{
while (p < array_end)
{
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
}
if (p != array_end)
return DBUS_INVALID_ARRAY_LENGTH_INCORRECT;
}
/* check nul termination */
{
while (p < array_end)
{
validity = validate_body_helper (&sub, byte_order, FALSE,
total_depth + 1,
p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
}
break;
case DBUS_TYPE_SIGNATURE:
{
dbus_uint32_t claimed_len;
DBusString str;
DBusValidity validity;
claimed_len = *p;
++p;
/* 1 is for nul termination */
if (claimed_len + 1 > (unsigned long) (end - p))
return DBUS_INVALID_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
_dbus_string_init_const_len (&str, p, claimed_len);
validity =
_dbus_validate_signature_with_reason (&str, 0,
_dbus_string_get_length (&str));
if (validity != DBUS_VALID)
return validity;
p += claimed_len;
_dbus_assert (p < end);
if (*p != DBUS_TYPE_INVALID)
return DBUS_INVALID_SIGNATURE_MISSING_NUL;
++p;
_dbus_verbose ("p = %p end = %p claimed_len %u\n", p, end, claimed_len);
}
break;
case DBUS_TYPE_VARIANT:
{
/* 1 byte sig len, sig typecodes, align to
* contained-type-boundary, values.
*/
/* In addition to normal signature validation, we need to be sure
* the signature contains only a single (possibly container) type.
*/
dbus_uint32_t claimed_len;
DBusString sig;
DBusTypeReader sub;
DBusValidity validity;
int contained_alignment;
int contained_type;
DBusValidity reason;
claimed_len = *p;
++p;
/* + 1 for nul */
if (claimed_len + 1 > (unsigned long) (end - p))
return DBUS_INVALID_VARIANT_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
_dbus_string_init_const_len (&sig, p, claimed_len);
reason = _dbus_validate_signature_with_reason (&sig, 0,
_dbus_string_get_length (&sig));
if (!(reason == DBUS_VALID))
{
if (reason == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
return reason;
else
return DBUS_INVALID_VARIANT_SIGNATURE_BAD;
}
p += claimed_len;
if (*p != DBUS_TYPE_INVALID)
return DBUS_INVALID_VARIANT_SIGNATURE_MISSING_NUL;
++p;
contained_type = _dbus_first_type_in_signature (&sig, 0);
if (contained_type == DBUS_TYPE_INVALID)
return DBUS_INVALID_VARIANT_SIGNATURE_EMPTY;
contained_alignment = _dbus_type_get_alignment (contained_type);
a = _DBUS_ALIGN_ADDRESS (p, contained_alignment);
if (a > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
_dbus_type_reader_init_types_only (&sub, &sig, 0);
_dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID);
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
if (_dbus_type_reader_next (&sub))
return DBUS_INVALID_VARIANT_SIGNATURE_SPECIFIES_MULTIPLE_VALUES;
_dbus_assert (_dbus_type_reader_get_current_type (&sub) == DBUS_TYPE_INVALID);
}
break;
case DBUS_TYPE_DICT_ENTRY:
case DBUS_TYPE_STRUCT:
_dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID);
validity = validate_body_helper (&sub, byte_order, FALSE,
total_depth + 1,
p, end, &p);
if (validity != DBUS_VALID)
return validity;
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
_dbus_type_reader_recurse (reader, &sub);
validity = validate_body_helper (&sub, byte_order, TRUE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
break;
default:
_dbus_assert_not_reached ("invalid typecode in supposedly-validated signature");
break;
}
|
CVE-2010-4352
|
Stack consumption vulnerability in D-Bus (aka DBus) before 1.4.1 allows local users to cause a denial of service (daemon crash) via a message containing many nested variants.
|
[
"CWE-399"
] |
[
{
"line_no": 186,
"text": " validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);",
"char_start": null,
"char_end": null
},
{
"line_no": 303,
"text": " validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 4,
"text": " int total_depth,",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " /* The spec allows arrays and structs to each nest 32, for total",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " * nesting of 2*32. We want to impose the same limit on \"dynamic\"",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": " * value nesting (not visible in the signature) which is introduced",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " * by DBUS_TYPE_VARIANT.",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " if (total_depth > (DBUS_MAXIMUM_TYPE_RECURSION_DEPTH * 2))",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " return DBUS_INVALID_NESTED_TOO_DEEPLY;",
"char_start": null,
"char_end": null
},
{
"line_no": 19,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 20,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 197,
"text": " validity = validate_body_helper (&sub, byte_order, FALSE,",
"char_start": null,
"char_end": null
},
{
"line_no": 198,
"text": " total_depth + 1,",
"char_start": null,
"char_end": null
},
{
"line_no": 199,
"text": " p, end, &p);",
"char_start": null,
"char_end": null
},
{
"line_no": 316,
"text": " validity = validate_body_helper (&sub, byte_order, FALSE,",
"char_start": null,
"char_end": null
},
{
"line_no": 317,
"text": " total_depth + 1,",
"char_start": null,
"char_end": null
},
{
"line_no": 318,
"text": " p, end, &p);",
"char_start": null,
"char_end": null
}
] | 212
|
primevul
|
primevul_savannah_e6699596af5c5d6f0ae0ea06e19df87dce088df8
|
e6699596af5c5d6f0ae0ea06e19df87dce088df8
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
tt_size_reset( TT_Size size,
FT_Bool only_height )
{
TT_Face face;
FT_Size_Metrics* metrics;
size->ttmetrics.valid = FALSE;
face = (TT_Face)size->root.face;
metrics = &size->metrics;
/* copy the result from base layer */
/* This bit flag, if set, indicates that the ppems must be */
/* rounded to integers. Nearly all TrueType fonts have this bit */
/* set, as hinting won't work really well otherwise. */
/* */
if ( face->header.Flags & 8 )
{
metrics->ascender =
FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) );
metrics->descender =
FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) );
metrics->height =
FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) );
}
size->ttmetrics.valid = TRUE;
if ( only_height )
return FT_Err_Ok;
if ( face->header.Flags & 8 )
{
metrics->x_scale = FT_DivFix( metrics->x_ppem << 6,
face->root.units_per_EM );
metrics->y_scale = FT_DivFix( metrics->y_ppem << 6,
face->root.units_per_EM );
metrics->max_advance =
FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width,
metrics->x_scale ) );
}
/* compute new transformation */
if ( metrics->x_ppem >= metrics->y_ppem )
{
size->ttmetrics.scale = metrics->x_scale;
size->ttmetrics.ppem = metrics->x_ppem;
size->ttmetrics.x_ratio = 0x10000L;
size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem,
metrics->x_ppem );
}
else
{
size->ttmetrics.scale = metrics->y_scale;
size->ttmetrics.ppem = metrics->y_ppem;
size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem,
metrics->y_ppem );
size->ttmetrics.y_ratio = 0x10000L;
}
#ifdef TT_USE_BYTECODE_INTERPRETER
size->cvt_ready = -1;
#endif /* TT_USE_BYTECODE_INTERPRETER */
return FT_Err_Ok;
}
|
tt_size_reset( TT_Size size,
FT_Bool only_height )
{
TT_Face face;
FT_Size_Metrics* metrics;
face = (TT_Face)size->root.face;
/* nothing to do for CFF2 */
if ( face->isCFF2 )
return FT_Err_Ok;
size->ttmetrics.valid = FALSE;
metrics = &size->metrics;
/* copy the result from base layer */
/* This bit flag, if set, indicates that the ppems must be */
/* rounded to integers. Nearly all TrueType fonts have this bit */
/* set, as hinting won't work really well otherwise. */
/* */
if ( face->header.Flags & 8 )
{
metrics->ascender =
FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) );
metrics->descender =
FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) );
metrics->height =
FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) );
}
size->ttmetrics.valid = TRUE;
if ( only_height )
return FT_Err_Ok;
if ( face->header.Flags & 8 )
{
metrics->x_scale = FT_DivFix( metrics->x_ppem << 6,
face->root.units_per_EM );
metrics->y_scale = FT_DivFix( metrics->y_ppem << 6,
face->root.units_per_EM );
metrics->max_advance =
FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width,
metrics->x_scale ) );
}
/* compute new transformation */
if ( metrics->x_ppem >= metrics->y_ppem )
{
size->ttmetrics.scale = metrics->x_scale;
size->ttmetrics.ppem = metrics->x_ppem;
size->ttmetrics.x_ratio = 0x10000L;
size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem,
metrics->x_ppem );
}
else
{
size->ttmetrics.scale = metrics->y_scale;
size->ttmetrics.ppem = metrics->y_ppem;
size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem,
metrics->y_ppem );
size->ttmetrics.y_ratio = 0x10000L;
}
#ifdef TT_USE_BYTECODE_INTERPRETER
size->cvt_ready = -1;
#endif /* TT_USE_BYTECODE_INTERPRETER */
return FT_Err_Ok;
}
|
CVE-2017-7864
|
FreeType 2 before 2017-02-02 has an out-of-bounds write caused by a heap-based buffer overflow related to the tt_size_reset function in truetype/ttobjs.c.
|
[
"CWE-787"
] |
[
{
"line_no": 8,
"text": " size->ttmetrics.valid = FALSE;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 10,
"text": " /* nothing to do for CFF2 */",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " if ( face->isCFF2 )",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " return FT_Err_Ok;",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 14,
"text": " size->ttmetrics.valid = FALSE;",
"char_start": null,
"char_end": null
},
{
"line_no": 15,
"text": "",
"char_start": null,
"char_end": null
}
] | 213
|
primevul
|
primevul_savannah_7bbb91fbf47fc0775cc9705673caf0c47a81f94b
|
7bbb91fbf47fc0775cc9705673caf0c47a81f94b
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
sfnt_init_face( FT_Stream stream,
TT_Face face,
FT_Int face_instance_index,
FT_Int num_params,
FT_Parameter* params )
{
FT_Error error;
FT_Memory memory = face->root.memory;
FT_Library library = face->root.driver->root.library;
SFNT_Service sfnt;
FT_Int face_index;
/* for now, parameters are unused */
FT_UNUSED( num_params );
FT_UNUSED( params );
sfnt = (SFNT_Service)face->sfnt;
if ( !sfnt )
{
sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" );
if ( !sfnt )
{
FT_ERROR(( "sfnt_init_face: cannot access `sfnt' module\n" ));
return FT_THROW( Missing_Module );
}
face->sfnt = sfnt;
face->goto_table = sfnt->goto_table;
}
FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS );
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
if ( !face->mm )
{
/* we want the MM interface from the `truetype' module only */
FT_Module tt_module = FT_Get_Module( library, "truetype" );
face->mm = ft_module_get_service( tt_module,
FT_SERVICE_ID_MULTI_MASTERS,
0 );
}
if ( !face->var )
{
/* we want the metrics variations interface */
/* from the `truetype' module only */
FT_Module tt_module = FT_Get_Module( library, "truetype" );
face->var = ft_module_get_service( tt_module,
FT_SERVICE_ID_METRICS_VARIATIONS,
0 );
}
#endif
FT_TRACE2(( "SFNT driver\n" ));
error = sfnt_open_font( stream, face );
if ( error )
return error;
/* Stream may have changed in sfnt_open_font. */
stream = face->root.stream;
FT_TRACE2(( "sfnt_init_face: %08p, %d\n", face, face_instance_index ));
face_index = FT_ABS( face_instance_index ) & 0xFFFF;
/* value -(N+1) requests information on index N */
if ( face_instance_index < 0 )
face_index--;
if ( face_index >= face->ttc_header.count )
{
if ( face_instance_index >= 0 )
return FT_THROW( Invalid_Argument );
else
face_index = 0;
}
if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) )
return error;
/* check whether we have a valid TrueType file */
error = sfnt->load_font_dir( face, stream );
if ( error )
return error;
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
{
FT_ULong fvar_len;
FT_ULong version;
FT_ULong offset;
FT_UShort num_axes;
FT_UShort axis_size;
FT_UShort num_instances;
FT_UShort instance_size;
FT_Int instance_index;
FT_Byte* default_values = NULL;
FT_Byte* instance_values = NULL;
face->is_default_instance = 1;
instance_index = FT_ABS( face_instance_index ) >> 16;
/* test whether current face is a GX font with named instances */
if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) ||
fvar_len < 20 ||
FT_READ_ULONG( version ) ||
FT_READ_USHORT( offset ) ||
FT_STREAM_SKIP( 2 ) /* reserved */ ||
FT_READ_USHORT( num_axes ) ||
FT_READ_USHORT( axis_size ) ||
FT_READ_USHORT( num_instances ) ||
FT_READ_USHORT( instance_size ) )
{
version = 0;
offset = 0;
num_axes = 0;
axis_size = 0;
num_instances = 0;
instance_size = 0;
}
/* check that the data is bound by the table length */
if ( version != 0x00010000UL ||
axis_size != 20 ||
num_axes == 0 ||
/* `num_axes' limit implied by 16-bit `instance_size' */
num_axes > 0x3FFE ||
!( instance_size == 4 + 4 * num_axes ||
instance_size == 6 + 4 * num_axes ) ||
/* `num_instances' limit implied by limited range of name IDs */
num_instances > 0x7EFF ||
offset +
axis_size * num_axes +
instance_size * num_instances > fvar_len )
num_instances = 0;
else
face->variation_support |= TT_FACE_FLAG_VAR_FVAR;
/*
* As documented in the OpenType specification, an entry for the
* default instance may be omitted in the named instance table. In
* particular this means that even if there is no named instance
* table in the font we actually do have a named instance, namely the
* default instance.
*
* For consistency, we always want the default instance in our list
* of named instances. If it is missing, we try to synthesize it
* later on. Here, we have to adjust `num_instances' accordingly.
*/
if ( !( FT_ALLOC( default_values, num_axes * 2 ) ||
FT_ALLOC( instance_values, num_axes * 2 ) ) )
{
/* the current stream position is 16 bytes after the table start */
FT_ULong array_start = FT_STREAM_POS() - 16 + offset;
FT_ULong default_value_offset, instance_offset;
FT_Byte* p;
FT_UInt i;
default_value_offset = array_start + 8;
p = default_values;
for ( i = 0; i < num_axes; i++ )
{
(void)FT_STREAM_READ_AT( default_value_offset, p, 2 );
default_value_offset += axis_size;
p += 2;
}
instance_offset = array_start + axis_size * num_axes + 4;
for ( i = 0; i < num_instances; i++ )
{
(void)FT_STREAM_READ_AT( instance_offset,
instance_values,
num_axes * 2 );
if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) )
break;
instance_offset += instance_size;
}
if ( i == num_instances )
{
/* no default instance in named instance table; */
/* we thus have to synthesize it */
num_instances++;
}
}
FT_FREE( default_values );
FT_FREE( instance_values );
/* we don't support Multiple Master CFFs yet */
if ( face->goto_table( face, TTAG_glyf, stream, 0 ) &&
!face->goto_table( face, TTAG_CFF, stream, 0 ) )
num_instances = 0;
if ( instance_index > num_instances )
{
if ( face_instance_index >= 0 )
return FT_THROW( Invalid_Argument );
else
num_instances = 0;
}
face->root.style_flags = (FT_Long)num_instances << 16;
}
#endif
face->root.num_faces = face->ttc_header.count;
face->root.face_index = face_instance_index;
return error;
}
|
sfnt_init_face( FT_Stream stream,
TT_Face face,
FT_Int face_instance_index,
FT_Int num_params,
FT_Parameter* params )
{
FT_Error error;
FT_Memory memory = face->root.memory;
FT_Library library = face->root.driver->root.library;
SFNT_Service sfnt;
FT_Int face_index;
/* for now, parameters are unused */
FT_UNUSED( num_params );
FT_UNUSED( params );
sfnt = (SFNT_Service)face->sfnt;
if ( !sfnt )
{
sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" );
if ( !sfnt )
{
FT_ERROR(( "sfnt_init_face: cannot access `sfnt' module\n" ));
return FT_THROW( Missing_Module );
}
face->sfnt = sfnt;
face->goto_table = sfnt->goto_table;
}
FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS );
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
if ( !face->mm )
{
/* we want the MM interface from the `truetype' module only */
FT_Module tt_module = FT_Get_Module( library, "truetype" );
face->mm = ft_module_get_service( tt_module,
FT_SERVICE_ID_MULTI_MASTERS,
0 );
}
if ( !face->var )
{
/* we want the metrics variations interface */
/* from the `truetype' module only */
FT_Module tt_module = FT_Get_Module( library, "truetype" );
face->var = ft_module_get_service( tt_module,
FT_SERVICE_ID_METRICS_VARIATIONS,
0 );
}
#endif
FT_TRACE2(( "SFNT driver\n" ));
error = sfnt_open_font( stream, face );
if ( error )
return error;
/* Stream may have changed in sfnt_open_font. */
stream = face->root.stream;
FT_TRACE2(( "sfnt_init_face: %08p, %d\n", face, face_instance_index ));
face_index = FT_ABS( face_instance_index ) & 0xFFFF;
/* value -(N+1) requests information on index N */
if ( face_instance_index < 0 )
face_index--;
if ( face_index >= face->ttc_header.count )
{
if ( face_instance_index >= 0 )
return FT_THROW( Invalid_Argument );
else
face_index = 0;
}
if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) )
return error;
/* check whether we have a valid TrueType file */
error = sfnt->load_font_dir( face, stream );
if ( error )
return error;
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
{
FT_ULong fvar_len;
FT_ULong version;
FT_ULong offset;
FT_UShort num_axes;
FT_UShort axis_size;
FT_UShort num_instances;
FT_UShort instance_size;
FT_Int instance_index;
FT_Byte* default_values = NULL;
FT_Byte* instance_values = NULL;
face->is_default_instance = 1;
instance_index = FT_ABS( face_instance_index ) >> 16;
/* test whether current face is a GX font with named instances */
if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) ||
fvar_len < 20 ||
FT_READ_ULONG( version ) ||
FT_READ_USHORT( offset ) ||
FT_STREAM_SKIP( 2 ) /* reserved */ ||
FT_READ_USHORT( num_axes ) ||
FT_READ_USHORT( axis_size ) ||
FT_READ_USHORT( num_instances ) ||
FT_READ_USHORT( instance_size ) )
{
version = 0;
offset = 0;
num_axes = 0;
axis_size = 0;
num_instances = 0;
instance_size = 0;
}
/* check that the data is bound by the table length */
if ( version != 0x00010000UL ||
axis_size != 20 ||
num_axes == 0 ||
/* `num_axes' limit implied by 16-bit `instance_size' */
num_axes > 0x3FFE ||
!( instance_size == 4 + 4 * num_axes ||
instance_size == 6 + 4 * num_axes ) ||
/* `num_instances' limit implied by limited range of name IDs */
num_instances > 0x7EFF ||
offset +
axis_size * num_axes +
instance_size * num_instances > fvar_len )
num_instances = 0;
else
face->variation_support |= TT_FACE_FLAG_VAR_FVAR;
/*
* As documented in the OpenType specification, an entry for the
* default instance may be omitted in the named instance table. In
* particular this means that even if there is no named instance
* table in the font we actually do have a named instance, namely the
* default instance.
*
* For consistency, we always want the default instance in our list
* of named instances. If it is missing, we try to synthesize it
* later on. Here, we have to adjust `num_instances' accordingly.
*/
if ( !( FT_ALLOC( default_values, num_axes * 2 ) ||
FT_ALLOC( instance_values, num_axes * 2 ) ) )
{
/* the current stream position is 16 bytes after the table start */
FT_ULong array_start = FT_STREAM_POS() - 16 + offset;
FT_ULong default_value_offset, instance_offset;
FT_Byte* p;
FT_UInt i;
default_value_offset = array_start + 8;
p = default_values;
for ( i = 0; i < num_axes; i++ )
{
(void)FT_STREAM_READ_AT( default_value_offset, p, 2 );
default_value_offset += axis_size;
p += 2;
}
instance_offset = array_start + axis_size * num_axes + 4;
for ( i = 0; i < num_instances; i++ )
{
(void)FT_STREAM_READ_AT( instance_offset,
instance_values,
num_axes * 2 );
if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) )
break;
instance_offset += instance_size;
}
if ( i == num_instances )
{
/* no default instance in named instance table; */
/* we thus have to synthesize it */
num_instances++;
}
}
FT_FREE( default_values );
FT_FREE( instance_values );
/* we don't support Multiple Master CFFs yet; */
/* note that `glyf' or `CFF2' have precedence */
if ( face->goto_table( face, TTAG_glyf, stream, 0 ) &&
face->goto_table( face, TTAG_CFF2, stream, 0 ) &&
!face->goto_table( face, TTAG_CFF, stream, 0 ) )
num_instances = 0;
if ( instance_index > num_instances )
{
if ( face_instance_index >= 0 )
return FT_THROW( Invalid_Argument );
else
num_instances = 0;
}
face->root.style_flags = (FT_Long)num_instances << 16;
}
#endif
face->root.num_faces = face->ttc_header.count;
face->root.face_index = face_instance_index;
return error;
}
|
CVE-2017-7857
|
FreeType 2 before 2017-03-08 has an out-of-bounds write caused by a heap-based buffer overflow related to the TT_Get_MM_Var function in truetype/ttgxvar.c and the sfnt_init_face function in sfnt/sfobjs.c.
|
[
"CWE-787"
] |
[
{
"line_no": 210,
"text": " /* we don't support Multiple Master CFFs yet */",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 210,
"text": " /* we don't support Multiple Master CFFs yet; */",
"char_start": null,
"char_end": null
},
{
"line_no": 211,
"text": " /* note that `glyf' or `CFF2' have precedence */",
"char_start": null,
"char_end": null
},
{
"line_no": 213,
"text": " face->goto_table( face, TTAG_CFF2, stream, 0 ) &&",
"char_start": null,
"char_end": null
}
] | 214
|
primevul
|
primevul_poppler_5c9b08a875b07853be6c44e43ff5f7f059df666a
|
5c9b08a875b07853be6c44e43ff5f7f059df666a
|
poppler
|
https://github.com/freedesktop/poppler
|
int main (int argc, char *argv[])
{
int objectsCount = 0;
Guint numOffset = 0;
std::vector<Object> pages;
std::vector<Guint> offsets;
XRef *yRef, *countRef;
FILE *f;
OutStream *outStr;
int i;
int j, rootNum;
std::vector<PDFDoc *>docs;
int majorVersion = 0;
int minorVersion = 0;
char *fileName = argv[argc - 1];
int exitCode;
exitCode = 99;
const GBool ok = parseArgs (argDesc, &argc, argv);
if (!ok || argc < 3 || printVersion || printHelp) {
fprintf(stderr, "pdfunite version %s\n", PACKAGE_VERSION);
fprintf(stderr, "%s\n", popplerCopyright);
fprintf(stderr, "%s\n", xpdfCopyright);
if (!printVersion) {
printUsage("pdfunite", "<PDF-sourcefile-1>..<PDF-sourcefile-n> <PDF-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
return exitCode;
}
exitCode = 0;
globalParams = new GlobalParams();
for (i = 1; i < argc - 1; i++) {
GooString *gfileName = new GooString(argv[i]);
PDFDoc *doc = new PDFDoc(gfileName, NULL, NULL, NULL);
if (doc->isOk() && !doc->isEncrypted()) {
docs.push_back(doc);
if (doc->getPDFMajorVersion() > majorVersion) {
majorVersion = doc->getPDFMajorVersion();
minorVersion = doc->getPDFMinorVersion();
} else if (doc->getPDFMajorVersion() == majorVersion) {
if (doc->getPDFMinorVersion() > minorVersion) {
minorVersion = doc->getPDFMinorVersion();
}
}
} else if (doc->isOk()) {
error(errUnimplemented, -1, "Could not merge encrypted files ('{0:s}')", argv[i]);
return -1;
} else {
error(errSyntaxError, -1, "Could not merge damaged documents ('{0:s}')", argv[i]);
return -1;
}
}
if (!(f = fopen(fileName, "wb"))) {
error(errIO, -1, "Could not open file '{0:s}'", fileName);
return -1;
}
outStr = new FileOutStream(f, 0);
yRef = new XRef();
countRef = new XRef();
yRef->add(0, 65535, 0, gFalse);
PDFDoc::writeHeader(outStr, majorVersion, minorVersion);
Object intents;
Object afObj;
Object ocObj;
Object names;
if (docs.size() >= 1) {
Object catObj;
docs[0]->getXRef()->getCatalog(&catObj);
Dict *catDict = catObj.getDict();
catDict->lookup("OutputIntents", &intents);
catDict->lookupNF("AcroForm", &afObj);
Ref *refPage = docs[0]->getCatalog()->getPageRef(1);
if (!afObj.isNull()) {
docs[0]->markAcroForm(&afObj, yRef, countRef, 0, refPage->num, refPage->num);
}
catDict->lookupNF("OCProperties", &ocObj);
if (!ocObj.isNull() && ocObj.isDict()) {
docs[0]->markPageObjects(ocObj.getDict(), yRef, countRef, 0, refPage->num, refPage->num);
}
catDict->lookup("Names", &names);
if (!names.isNull() && names.isDict()) {
docs[0]->markPageObjects(names.getDict(), yRef, countRef, 0, refPage->num, refPage->num);
}
if (intents.isArray() && intents.arrayGetLength() > 0) {
for (i = 1; i < (int) docs.size(); i++) {
Object pagecatObj, pageintents;
docs[i]->getXRef()->getCatalog(&pagecatObj);
Dict *pagecatDict = pagecatObj.getDict();
pagecatDict->lookup("OutputIntents", &pageintents);
if (pageintents.isArray() && pageintents.arrayGetLength() > 0) {
for (j = intents.arrayGetLength() - 1; j >= 0; j--) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
Object idf;
intent.dictLookup("OutputConditionIdentifier", &idf);
if (idf.isString()) {
GooString *gidf = idf.getString();
GBool removeIntent = gTrue;
for (int k = 0; k < pageintents.arrayGetLength(); k++) {
Object pgintent;
pageintents.arrayGet(k, &pgintent, 0);
if (pgintent.isDict()) {
Object pgidf;
pgintent.dictLookup("OutputConditionIdentifier", &pgidf);
if (pgidf.isString()) {
GooString *gpgidf = pgidf.getString();
if (gpgidf->cmp(gidf) == 0) {
pgidf.free();
removeIntent = gFalse;
break;
}
}
pgidf.free();
}
}
if (removeIntent) {
intents.arrayRemove(j);
error(errSyntaxWarning, -1, "Output intent {0:s} missing in pdf {1:s}, removed",
gidf->getCString(), docs[i]->getFileName()->getCString());
}
} else {
intents.arrayRemove(j);
error(errSyntaxWarning, -1, "Invalid output intent dict, missing required OutputConditionIdentifier");
}
idf.free();
} else {
intents.arrayRemove(j);
}
intent.free();
}
} else {
error(errSyntaxWarning, -1, "Output intents differs, remove them all");
intents.free();
break;
}
pagecatObj.free();
pageintents.free();
}
}
if (intents.isArray() && intents.arrayGetLength() > 0) {
for (j = intents.arrayGetLength() - 1; j >= 0; j--) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
docs[0]->markPageObjects(intent.getDict(), yRef, countRef, numOffset, 0, 0);
} else {
intents.arrayRemove(j);
}
intent.free();
}
}
catObj.free();
}
for (i = 0; i < (int) docs.size(); i++) {
for (j = 1; j <= docs[i]->getNumPages(); j++) {
PDFRectangle *cropBox = NULL;
if (docs[i]->getCatalog()->getPage(j)->isCropped())
cropBox = docs[i]->getCatalog()->getPage(j)->getCropBox();
Object page;
docs[i]->getXRef()->fetch(refPage->num, refPage->gen, &page);
Dict *pageDict = page.getDict();
Dict *resDict = docs[i]->getCatalog()->getPage(j)->getResourceDict();
if (resDict) {
Object *newResource = new Object();
newResource->initDict(resDict);
pageDict->set("Resources", newResource);
delete newResource;
}
pages.push_back(page);
offsets.push_back(numOffset);
docs[i]->markPageObjects(pageDict, yRef, countRef, numOffset, refPage->num, refPage->num);
Object annotsObj;
pageDict->lookupNF("Annots", &annotsObj);
if (!annotsObj.isNull()) {
docs[i]->markAnnotations(&annotsObj, yRef, countRef, numOffset, refPage->num, refPage->num);
annotsObj.free();
}
}
Object pageCatObj, pageNames, pageForm;
docs[i]->getXRef()->getCatalog(&pageCatObj);
Dict *pageCatDict = pageCatObj.getDict();
pageCatDict->lookup("Names", &pageNames);
if (!pageNames.isNull() && pageNames.isDict()) {
if (!names.isDict()) {
names.free();
names.initDict(yRef);
}
doMergeNameDict(docs[i], yRef, countRef, 0, 0, names.getDict(), pageNames.getDict(), numOffset);
}
pageCatDict->lookup("AcroForm", &pageForm);
if (i > 0 && !pageForm.isNull() && pageForm.isDict()) {
if (afObj.isNull()) {
pageCatDict->lookupNF("AcroForm", &afObj);
} else if (afObj.isDict()) {
doMergeFormDict(afObj.getDict(), pageForm.getDict(), numOffset);
}
}
pageForm.free();
pageNames.free();
pageCatObj.free();
objectsCount += docs[i]->writePageObjects(outStr, yRef, numOffset, gTrue);
numOffset = yRef->getNumObjects() + 1;
}
rootNum = yRef->getNumObjects() + 1;
yRef->add(rootNum, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum);
outStr->printf("<< /Type /Catalog /Pages %d 0 R", rootNum + 1);
if (intents.isArray() && intents.arrayGetLength() > 0) {
outStr->printf(" /OutputIntents [");
for (j = 0; j < intents.arrayGetLength(); j++) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
PDFDoc::writeObject(&intent, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
}
intent.free();
}
outStr->printf("]");
}
intents.free();
if (!afObj.isNull()) {
outStr->printf(" /AcroForm ");
PDFDoc::writeObject(&afObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
afObj.free();
}
if (!ocObj.isNull() && ocObj.isDict()) {
outStr->printf(" /OCProperties ");
PDFDoc::writeObject(&ocObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
ocObj.free();
}
if (!names.isNull() && names.isDict()) {
outStr->printf(" /Names ");
PDFDoc::writeObject(&names, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
names.free();
}
outStr->printf(">>\nendobj\n");
objectsCount++;
yRef->add(rootNum + 1, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum + 1);
outStr->printf("<< /Type /Pages /Kids [");
for (j = 0; j < (int) pages.size(); j++)
outStr->printf(" %d 0 R", rootNum + j + 2);
outStr->printf(" ] /Count %zd >>\nendobj\n", pages.size());
objectsCount++;
for (i = 0; i < (int) pages.size(); i++) {
yRef->add(rootNum + i + 2, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum + i + 2);
outStr->printf("<< ");
Dict *pageDict = pages[i].getDict();
for (j = 0; j < pageDict->getLength(); j++) {
if (j > 0)
outStr->printf(" ");
const char *key = pageDict->getKey(j);
Object value;
pageDict->getValNF(j, &value);
if (strcmp(key, "Parent") == 0) {
outStr->printf("/Parent %d 0 R", rootNum + 1);
} else {
outStr->printf("/%s ", key);
PDFDoc::writeObject(&value, outStr, yRef, offsets[i], NULL, cryptRC4, 0, 0, 0);
}
value.free();
}
outStr->printf(" >>\nendobj\n");
objectsCount++;
}
Goffset uxrefOffset = outStr->getPos();
Ref ref;
ref.num = rootNum;
ref.gen = 0;
Dict *trailerDict = PDFDoc::createTrailerDict(objectsCount, gFalse, 0, &ref, yRef,
fileName, outStr->getPos());
PDFDoc::writeXRefTableTrailer(trailerDict, yRef, gTrue, // write all entries according to ISO 32000-1, 7.5.4 Cross-Reference Table: "For a file that has never been incrementally updated, the cross-reference section shall contain only one subsection, whose object numbering begins at 0."
uxrefOffset, outStr, yRef);
delete trailerDict;
outStr->close();
delete outStr;
fclose(f);
delete yRef;
delete countRef;
for (j = 0; j < (int) pages.size (); j++) pages[j].free();
for (i = 0; i < (int) docs.size (); i++) delete docs[i];
delete globalParams;
return exitCode;
}
|
int main (int argc, char *argv[])
{
int objectsCount = 0;
Guint numOffset = 0;
std::vector<Object> pages;
std::vector<Guint> offsets;
XRef *yRef, *countRef;
FILE *f;
OutStream *outStr;
int i;
int j, rootNum;
std::vector<PDFDoc *>docs;
int majorVersion = 0;
int minorVersion = 0;
char *fileName = argv[argc - 1];
int exitCode;
exitCode = 99;
const GBool ok = parseArgs (argDesc, &argc, argv);
if (!ok || argc < 3 || printVersion || printHelp) {
fprintf(stderr, "pdfunite version %s\n", PACKAGE_VERSION);
fprintf(stderr, "%s\n", popplerCopyright);
fprintf(stderr, "%s\n", xpdfCopyright);
if (!printVersion) {
printUsage("pdfunite", "<PDF-sourcefile-1>..<PDF-sourcefile-n> <PDF-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
return exitCode;
}
exitCode = 0;
globalParams = new GlobalParams();
for (i = 1; i < argc - 1; i++) {
GooString *gfileName = new GooString(argv[i]);
PDFDoc *doc = new PDFDoc(gfileName, NULL, NULL, NULL);
if (doc->isOk() && !doc->isEncrypted()) {
docs.push_back(doc);
if (doc->getPDFMajorVersion() > majorVersion) {
majorVersion = doc->getPDFMajorVersion();
minorVersion = doc->getPDFMinorVersion();
} else if (doc->getPDFMajorVersion() == majorVersion) {
if (doc->getPDFMinorVersion() > minorVersion) {
minorVersion = doc->getPDFMinorVersion();
}
}
} else if (doc->isOk()) {
error(errUnimplemented, -1, "Could not merge encrypted files ('{0:s}')", argv[i]);
return -1;
} else {
error(errSyntaxError, -1, "Could not merge damaged documents ('{0:s}')", argv[i]);
return -1;
}
}
if (!(f = fopen(fileName, "wb"))) {
error(errIO, -1, "Could not open file '{0:s}'", fileName);
return -1;
}
outStr = new FileOutStream(f, 0);
yRef = new XRef();
countRef = new XRef();
yRef->add(0, 65535, 0, gFalse);
PDFDoc::writeHeader(outStr, majorVersion, minorVersion);
Object intents;
Object afObj;
Object ocObj;
Object names;
if (docs.size() >= 1) {
Object catObj;
docs[0]->getXRef()->getCatalog(&catObj);
Dict *catDict = catObj.getDict();
catDict->lookup("OutputIntents", &intents);
catDict->lookupNF("AcroForm", &afObj);
Ref *refPage = docs[0]->getCatalog()->getPageRef(1);
if (!afObj.isNull() && refPage) {
docs[0]->markAcroForm(&afObj, yRef, countRef, 0, refPage->num, refPage->num);
}
catDict->lookupNF("OCProperties", &ocObj);
if (!ocObj.isNull() && ocObj.isDict() && refPage) {
docs[0]->markPageObjects(ocObj.getDict(), yRef, countRef, 0, refPage->num, refPage->num);
}
catDict->lookup("Names", &names);
if (!names.isNull() && names.isDict() && refPage) {
docs[0]->markPageObjects(names.getDict(), yRef, countRef, 0, refPage->num, refPage->num);
}
if (intents.isArray() && intents.arrayGetLength() > 0) {
for (i = 1; i < (int) docs.size(); i++) {
Object pagecatObj, pageintents;
docs[i]->getXRef()->getCatalog(&pagecatObj);
Dict *pagecatDict = pagecatObj.getDict();
pagecatDict->lookup("OutputIntents", &pageintents);
if (pageintents.isArray() && pageintents.arrayGetLength() > 0) {
for (j = intents.arrayGetLength() - 1; j >= 0; j--) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
Object idf;
intent.dictLookup("OutputConditionIdentifier", &idf);
if (idf.isString()) {
GooString *gidf = idf.getString();
GBool removeIntent = gTrue;
for (int k = 0; k < pageintents.arrayGetLength(); k++) {
Object pgintent;
pageintents.arrayGet(k, &pgintent, 0);
if (pgintent.isDict()) {
Object pgidf;
pgintent.dictLookup("OutputConditionIdentifier", &pgidf);
if (pgidf.isString()) {
GooString *gpgidf = pgidf.getString();
if (gpgidf->cmp(gidf) == 0) {
pgidf.free();
removeIntent = gFalse;
break;
}
}
pgidf.free();
}
}
if (removeIntent) {
intents.arrayRemove(j);
error(errSyntaxWarning, -1, "Output intent {0:s} missing in pdf {1:s}, removed",
gidf->getCString(), docs[i]->getFileName()->getCString());
}
} else {
intents.arrayRemove(j);
error(errSyntaxWarning, -1, "Invalid output intent dict, missing required OutputConditionIdentifier");
}
idf.free();
} else {
intents.arrayRemove(j);
}
intent.free();
}
} else {
error(errSyntaxWarning, -1, "Output intents differs, remove them all");
intents.free();
break;
}
pagecatObj.free();
pageintents.free();
}
}
if (intents.isArray() && intents.arrayGetLength() > 0) {
for (j = intents.arrayGetLength() - 1; j >= 0; j--) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
docs[0]->markPageObjects(intent.getDict(), yRef, countRef, numOffset, 0, 0);
} else {
intents.arrayRemove(j);
}
intent.free();
}
}
catObj.free();
}
for (i = 0; i < (int) docs.size(); i++) {
for (j = 1; j <= docs[i]->getNumPages(); j++) {
if (!docs[i]->getCatalog()->getPage(j)) {
continue;
}
PDFRectangle *cropBox = NULL;
if (docs[i]->getCatalog()->getPage(j)->isCropped())
cropBox = docs[i]->getCatalog()->getPage(j)->getCropBox();
Object page;
docs[i]->getXRef()->fetch(refPage->num, refPage->gen, &page);
Dict *pageDict = page.getDict();
Dict *resDict = docs[i]->getCatalog()->getPage(j)->getResourceDict();
if (resDict) {
Object *newResource = new Object();
newResource->initDict(resDict);
pageDict->set("Resources", newResource);
delete newResource;
}
pages.push_back(page);
offsets.push_back(numOffset);
docs[i]->markPageObjects(pageDict, yRef, countRef, numOffset, refPage->num, refPage->num);
Object annotsObj;
pageDict->lookupNF("Annots", &annotsObj);
if (!annotsObj.isNull()) {
docs[i]->markAnnotations(&annotsObj, yRef, countRef, numOffset, refPage->num, refPage->num);
annotsObj.free();
}
}
Object pageCatObj, pageNames, pageForm;
docs[i]->getXRef()->getCatalog(&pageCatObj);
Dict *pageCatDict = pageCatObj.getDict();
pageCatDict->lookup("Names", &pageNames);
if (!pageNames.isNull() && pageNames.isDict()) {
if (!names.isDict()) {
names.free();
names.initDict(yRef);
}
doMergeNameDict(docs[i], yRef, countRef, 0, 0, names.getDict(), pageNames.getDict(), numOffset);
}
pageCatDict->lookup("AcroForm", &pageForm);
if (i > 0 && !pageForm.isNull() && pageForm.isDict()) {
if (afObj.isNull()) {
pageCatDict->lookupNF("AcroForm", &afObj);
} else if (afObj.isDict()) {
doMergeFormDict(afObj.getDict(), pageForm.getDict(), numOffset);
}
}
pageForm.free();
pageNames.free();
pageCatObj.free();
objectsCount += docs[i]->writePageObjects(outStr, yRef, numOffset, gTrue);
numOffset = yRef->getNumObjects() + 1;
}
rootNum = yRef->getNumObjects() + 1;
yRef->add(rootNum, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum);
outStr->printf("<< /Type /Catalog /Pages %d 0 R", rootNum + 1);
if (intents.isArray() && intents.arrayGetLength() > 0) {
outStr->printf(" /OutputIntents [");
for (j = 0; j < intents.arrayGetLength(); j++) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
PDFDoc::writeObject(&intent, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
}
intent.free();
}
outStr->printf("]");
}
intents.free();
if (!afObj.isNull()) {
outStr->printf(" /AcroForm ");
PDFDoc::writeObject(&afObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
afObj.free();
}
if (!ocObj.isNull() && ocObj.isDict()) {
outStr->printf(" /OCProperties ");
PDFDoc::writeObject(&ocObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
ocObj.free();
}
if (!names.isNull() && names.isDict()) {
outStr->printf(" /Names ");
PDFDoc::writeObject(&names, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
names.free();
}
outStr->printf(">>\nendobj\n");
objectsCount++;
yRef->add(rootNum + 1, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum + 1);
outStr->printf("<< /Type /Pages /Kids [");
for (j = 0; j < (int) pages.size(); j++)
outStr->printf(" %d 0 R", rootNum + j + 2);
outStr->printf(" ] /Count %zd >>\nendobj\n", pages.size());
objectsCount++;
for (i = 0; i < (int) pages.size(); i++) {
yRef->add(rootNum + i + 2, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum + i + 2);
outStr->printf("<< ");
Dict *pageDict = pages[i].getDict();
for (j = 0; j < pageDict->getLength(); j++) {
if (j > 0)
outStr->printf(" ");
const char *key = pageDict->getKey(j);
Object value;
pageDict->getValNF(j, &value);
if (strcmp(key, "Parent") == 0) {
outStr->printf("/Parent %d 0 R", rootNum + 1);
} else {
outStr->printf("/%s ", key);
PDFDoc::writeObject(&value, outStr, yRef, offsets[i], NULL, cryptRC4, 0, 0, 0);
}
value.free();
}
outStr->printf(" >>\nendobj\n");
objectsCount++;
}
Goffset uxrefOffset = outStr->getPos();
Ref ref;
ref.num = rootNum;
ref.gen = 0;
Dict *trailerDict = PDFDoc::createTrailerDict(objectsCount, gFalse, 0, &ref, yRef,
fileName, outStr->getPos());
PDFDoc::writeXRefTableTrailer(trailerDict, yRef, gTrue, // write all entries according to ISO 32000-1, 7.5.4 Cross-Reference Table: "For a file that has never been incrementally updated, the cross-reference section shall contain only one subsection, whose object numbering begins at 0."
uxrefOffset, outStr, yRef);
delete trailerDict;
outStr->close();
delete outStr;
fclose(f);
delete yRef;
delete countRef;
for (j = 0; j < (int) pages.size (); j++) pages[j].free();
for (i = 0; i < (int) docs.size (); i++) delete docs[i];
delete globalParams;
return exitCode;
}
|
CVE-2017-7511
|
poppler since version 0.17.3 has been vulnerable to NULL pointer dereference in pdfunite triggered by specially crafted documents.
|
[
"CWE-476"
] |
[
{
"line_no": 79,
"text": " if (!afObj.isNull()) {",
"char_start": null,
"char_end": null
},
{
"line_no": 83,
"text": " if (!ocObj.isNull() && ocObj.isDict()) {",
"char_start": null,
"char_end": null
},
{
"line_no": 87,
"text": " if (!names.isNull() && names.isDict()) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 79,
"text": " if (!afObj.isNull() && refPage) {",
"char_start": null,
"char_end": null
},
{
"line_no": 83,
"text": " if (!ocObj.isNull() && ocObj.isDict() && refPage) {",
"char_start": null,
"char_end": null
},
{
"line_no": 87,
"text": " if (!names.isNull() && names.isDict() && refPage) {",
"char_start": null,
"char_end": null
},
{
"line_no": 164,
"text": " if (!docs[i]->getCatalog()->getPage(j)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 165,
"text": " continue;",
"char_start": null,
"char_end": null
},
{
"line_no": 166,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 167,
"text": "",
"char_start": null,
"char_end": null
}
] | 215
|
primevul
|
primevul_savannah_94e01571507835ff59dd8ce2a0b56a4b566965a4
|
94e01571507835ff59dd8ce2a0b56a4b566965a4
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
main (int argc _GL_UNUSED, char **argv)
{
struct timespec result;
struct timespec result2;
struct timespec expected;
struct timespec now;
const char *p;
int i;
long gmtoff;
time_t ref_time = 1304250918;
/* Set the time zone to US Eastern time with the 2012 rules. This
should disable any leap second support. Otherwise, there will be
a problem with glibc on sites that default to leap seconds; see
<http://bugs.gnu.org/12206>. */
setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1);
gmtoff = gmt_offset (ref_time);
/* ISO 8601 extended date and time of day representation,
'T' separator, local time zone */
p = "2011-05-01T11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, local time zone */
p = "2011-05-01 11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
'T' separator, UTC */
p = "2011-05-01T11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
' ' separator, UTC */
p = "2011-05-01 11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/UTC offset */
p = "2011-05-01T11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/UTC offset */
p = "2011-05-01 11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/hour only UTC offset */
p = "2011-05-01T11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/hour only UTC offset */
p = "2011-05-01 11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "4 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
/* test if timezone is not being ignored for day offset */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 +24 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* test if several time zones formats are handled same way */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC-1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+0:15";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+0015";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-1:30";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-130";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* TZ out of range should cause parse_datetime failure */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+25:00";
ASSERT (!parse_datetime (&result, p, &now));
/* Check for several invalid countable dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+4:00 +40 yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 next yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow hence";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 40 now ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 last tomorrow";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 -4 today";
ASSERT (!parse_datetime (&result, p, &now));
/* And check correct usage of dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+400 1 day hence";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 1 day ago";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* Check that some "next Monday", "last Wednesday", etc. are correct. */
setenv ("TZ", "UTC0", 1);
for (i = 0; day_table[i]; i++)
{
unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */
char tmp[32];
sprintf (tmp, "NEXT %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600);
sprintf (tmp, "LAST %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600);
}
p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == now.tv_sec
&& result.tv_nsec == now.tv_nsec);
p = "FRIDAY UTC+00";
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == 24 * 3600
&& result.tv_nsec == now.tv_nsec);
/* Exercise a sign-extension bug. Before July 2012, an input
starting with a high-bit-set byte would be treated like "0". */
ASSERT ( ! parse_datetime (&result, "\xb0", &now));
/* Exercise TZ="" parsing code. */
/* These two would infloop or segfault before Feb 2014. */
ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now));
/* Exercise invalid patterns. */
ASSERT ( ! parse_datetime (&result, "TZ=\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now));
/* Exercise valid patterns. */
ASSERT ( parse_datetime (&result, "TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now));
ASSERT ( parse_datetime (&result, " TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now));
return 0;
}
|
main (int argc _GL_UNUSED, char **argv)
{
struct timespec result;
struct timespec result2;
struct timespec expected;
struct timespec now;
const char *p;
int i;
long gmtoff;
time_t ref_time = 1304250918;
/* Set the time zone to US Eastern time with the 2012 rules. This
should disable any leap second support. Otherwise, there will be
a problem with glibc on sites that default to leap seconds; see
<http://bugs.gnu.org/12206>. */
setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1);
gmtoff = gmt_offset (ref_time);
/* ISO 8601 extended date and time of day representation,
'T' separator, local time zone */
p = "2011-05-01T11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, local time zone */
p = "2011-05-01 11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
'T' separator, UTC */
p = "2011-05-01T11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
' ' separator, UTC */
p = "2011-05-01 11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/UTC offset */
p = "2011-05-01T11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/UTC offset */
p = "2011-05-01 11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/hour only UTC offset */
p = "2011-05-01T11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/hour only UTC offset */
p = "2011-05-01 11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "4 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
/* test if timezone is not being ignored for day offset */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 +24 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* test if several time zones formats are handled same way */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC-1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+0:15";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+0015";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-1:30";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-130";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* TZ out of range should cause parse_datetime failure */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+25:00";
ASSERT (!parse_datetime (&result, p, &now));
/* Check for several invalid countable dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+4:00 +40 yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 next yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow hence";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 40 now ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 last tomorrow";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 -4 today";
ASSERT (!parse_datetime (&result, p, &now));
/* And check correct usage of dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+400 1 day hence";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 1 day ago";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* Check that some "next Monday", "last Wednesday", etc. are correct. */
setenv ("TZ", "UTC0", 1);
for (i = 0; day_table[i]; i++)
{
unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */
char tmp[32];
sprintf (tmp, "NEXT %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600);
sprintf (tmp, "LAST %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600);
}
p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == now.tv_sec
&& result.tv_nsec == now.tv_nsec);
p = "FRIDAY UTC+00";
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == 24 * 3600
&& result.tv_nsec == now.tv_nsec);
/* Exercise a sign-extension bug. Before July 2012, an input
starting with a high-bit-set byte would be treated like "0". */
ASSERT ( ! parse_datetime (&result, "\xb0", &now));
/* Exercise TZ="" parsing code. */
/* These two would infloop or segfault before Feb 2014. */
ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now));
/* Exercise invalid patterns. */
ASSERT ( ! parse_datetime (&result, "TZ=\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now));
/* Exercise valid patterns. */
ASSERT ( parse_datetime (&result, "TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now));
ASSERT ( parse_datetime (&result, " TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now));
/* Outlandishly-long time zone abbreviations should not cause problems. */
{
static char const bufprefix[] = "TZ=\"";
enum { tzname_len = 2000 };
static char const bufsuffix[] = "0\" 1970-01-01 01:02:03.123456789";
enum { bufsize = sizeof bufprefix - 1 + tzname_len + sizeof bufsuffix };
char buf[bufsize];
memcpy (buf, bufprefix, sizeof bufprefix - 1);
memset (buf + sizeof bufprefix - 1, 'X', tzname_len);
strcpy (buf + bufsize - sizeof bufsuffix, bufsuffix);
ASSERT (parse_datetime (&result, buf, &now));
LOG (buf, now, result);
ASSERT (result.tv_sec == 1 * 60 * 60 + 2 * 60 + 3
&& result.tv_nsec == 123456789);
}
return 0;
}
|
CVE-2017-7476
|
Gnulib before 2017-04-26 has a heap-based buffer overflow with the TZ environment variable. The error is in the save_abbr function in time_rz.c.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 324,
"text": " /* Outlandishly-long time zone abbreviations should not cause problems. */",
"char_start": null,
"char_end": null
},
{
"line_no": 325,
"text": " {",
"char_start": null,
"char_end": null
},
{
"line_no": 326,
"text": " static char const bufprefix[] = \"TZ=\\\"\";",
"char_start": null,
"char_end": null
},
{
"line_no": 327,
"text": " enum { tzname_len = 2000 };",
"char_start": null,
"char_end": null
},
{
"line_no": 328,
"text": " static char const bufsuffix[] = \"0\\\" 1970-01-01 01:02:03.123456789\";",
"char_start": null,
"char_end": null
},
{
"line_no": 329,
"text": " enum { bufsize = sizeof bufprefix - 1 + tzname_len + sizeof bufsuffix };",
"char_start": null,
"char_end": null
},
{
"line_no": 330,
"text": " char buf[bufsize];",
"char_start": null,
"char_end": null
},
{
"line_no": 331,
"text": " memcpy (buf, bufprefix, sizeof bufprefix - 1);",
"char_start": null,
"char_end": null
},
{
"line_no": 332,
"text": " memset (buf + sizeof bufprefix - 1, 'X', tzname_len);",
"char_start": null,
"char_end": null
},
{
"line_no": 333,
"text": " strcpy (buf + bufsize - sizeof bufsuffix, bufsuffix);",
"char_start": null,
"char_end": null
},
{
"line_no": 334,
"text": " ASSERT (parse_datetime (&result, buf, &now));",
"char_start": null,
"char_end": null
},
{
"line_no": 335,
"text": " LOG (buf, now, result);",
"char_start": null,
"char_end": null
},
{
"line_no": 336,
"text": " ASSERT (result.tv_sec == 1 * 60 * 60 + 2 * 60 + 3",
"char_start": null,
"char_end": null
},
{
"line_no": 337,
"text": " && result.tv_nsec == 123456789);",
"char_start": null,
"char_end": null
},
{
"line_no": 338,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 339,
"text": "",
"char_start": null,
"char_end": null
}
] | 216
|
primevul
|
primevul_savannah_59eb9f8cfe7d1df379a2318316d1f04f80fba54a
|
59eb9f8cfe7d1df379a2318316d1f04f80fba54a
|
savannah
|
https://git.savannah.gnu.org/gitweb/?p=gnutls
|
ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
|
ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
|
CVE-2010-3855
|
Buffer overflow in the ft_var_readpackedpoints function in truetype/ttgxvar.c in FreeType 2.4.3 and earlier allows remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted TrueType GX font.
|
[
"CWE-119"
] |
[
{
"line_no": 11,
"text": " FT_Error error = TT_Err_Ok;",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " if ( runcnt < 1 )",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " if ( runcnt < 1 )",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 11,
"text": " FT_Error error = TT_Err_Ok;",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": " if ( runcnt < 1 || i + runcnt >= n )",
"char_start": null,
"char_end": null
},
{
"line_no": 46,
"text": " if ( runcnt < 1 || i + runcnt >= n )",
"char_start": null,
"char_end": null
}
] | 217
|
primevul
|
primevul_haproxy_3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
|
3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
|
haproxy
|
https://github.com/haproxy/haproxy
|
static void h2_process_demux(struct h2c *h2c)
{
struct h2s *h2s;
if (h2c->st0 >= H2_CS_ERROR)
return;
if (unlikely(h2c->st0 < H2_CS_FRAME_H)) {
if (h2c->st0 == H2_CS_PREFACE) {
if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
if (h2c->st0 == H2_CS_ERROR)
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
h2c->max_id = 0;
h2c->st0 = H2_CS_SETTINGS1;
}
if (h2c->st0 == H2_CS_SETTINGS1) {
struct h2_fh hdr;
/* ensure that what is pending is a valid SETTINGS frame
* without an ACK.
*/
if (!h2_get_frame_hdr(h2c->dbuf, &hdr)) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
if (h2c->st0 == H2_CS_ERROR)
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
if (hdr.sid || hdr.ft != H2_FT_SETTINGS || hdr.ff & H2_F_SETTINGS_ACK) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
/* that's OK, switch to FRAME_P to process it */
h2c->dfl = hdr.len;
h2c->dsi = hdr.sid;
h2c->dft = hdr.ft;
h2c->dff = hdr.ff;
h2c->dpl = 0;
h2c->st0 = H2_CS_FRAME_P;
}
}
/* process as many incoming frames as possible below */
while (h2c->dbuf->i) {
int ret = 0;
if (h2c->st0 >= H2_CS_ERROR)
break;
if (h2c->st0 == H2_CS_FRAME_H) {
struct h2_fh hdr;
if (!h2_peek_frame_hdr(h2c->dbuf, &hdr))
break;
if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) {
h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);
h2c->st0 = H2_CS_ERROR;
break;
}
h2c->dfl = hdr.len;
h2c->dsi = hdr.sid;
h2c->dft = hdr.ft;
h2c->dff = hdr.ff;
h2c->dpl = 0;
h2c->st0 = H2_CS_FRAME_P;
h2_skip_frame_hdr(h2c->dbuf);
}
/* Only H2_CS_FRAME_P and H2_CS_FRAME_A here */
h2s = h2c_st_by_id(h2c, h2c->dsi);
if (h2c->st0 == H2_CS_FRAME_E)
goto strm_err;
if (h2s->st == H2_SS_IDLE &&
h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than HEADERS or PRIORITY in
* this state MUST be treated as a connection error
*/
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
h2c->st0 = H2_CS_ERROR;
break;
}
if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE &&
h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than WU/PRIO/RST in
* this state MUST be treated as a stream error
*/
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
goto strm_err;
}
/* Below the management of frames received in closed state is a
* bit hackish because the spec makes strong differences between
* streams closed by receiving RST, sending RST, and seeing ES
* in both directions. In addition to this, the creation of a
* new stream reusing the identifier of a closed one will be
* detected here. Given that we cannot keep track of all closed
* streams forever, we consider that unknown closed streams were
* closed on RST received, which allows us to respond with an
* RST without breaking the connection (eg: to abort a transfer).
* Some frames have to be silently ignored as well.
*/
if (h2s->st == H2_SS_CLOSED && h2c->dsi) {
if (h2c->dft == H2_FT_HEADERS || h2c->dft == H2_FT_PUSH_PROMISE) {
/* #5.1.1: The identifier of a newly
* established stream MUST be numerically
* greater than all streams that the initiating
* endpoint has opened or reserved. This
* governs streams that are opened using a
* HEADERS frame and streams that are reserved
* using PUSH_PROMISE. An endpoint that
* receives an unexpected stream identifier
* MUST respond with a connection error.
*/
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
goto strm_err;
}
if (h2s->flags & H2_SF_RST_RCVD) {
/* RFC7540#5.1:closed: an endpoint that
* receives any frame other than PRIORITY after
* receiving a RST_STREAM MUST treat that as a
* stream error of type STREAM_CLOSED.
*
* Note that old streams fall into this category
* and will lead to an RST being sent.
*/
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
goto strm_err;
}
/* RFC7540#5.1:closed: if this state is reached as a
* result of sending a RST_STREAM frame, the peer that
* receives the RST_STREAM might have already sent
* frames on the stream that cannot be withdrawn. An
* endpoint MUST ignore frames that it receives on
* closed streams after it has sent a RST_STREAM
* frame. An endpoint MAY choose to limit the period
* over which it ignores frames and treat frames that
* arrive after this time as being in error.
*/
if (!(h2s->flags & H2_SF_RST_SENT)) {
/* RFC7540#5.1:closed: any frame other than
* PRIO/WU/RST in this state MUST be treated as
* a connection error
*/
if (h2c->dft != H2_FT_RST_STREAM &&
h2c->dft != H2_FT_PRIORITY &&
h2c->dft != H2_FT_WINDOW_UPDATE) {
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
goto strm_err;
}
}
}
#if 0
/* graceful shutdown, ignore streams whose ID is higher than
* the one advertised in GOAWAY. RFC7540#6.8.
*/
if (unlikely(h2c->last_sid >= 0) && h2c->dsi > h2c->last_sid) {
ret = MIN(h2c->dbuf->i, h2c->dfl);
bi_del(h2c->dbuf, ret);
h2c->dfl -= ret;
ret = h2c->dfl == 0;
goto strm_err;
}
#endif
switch (h2c->dft) {
case H2_FT_SETTINGS:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_settings(h2c);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_ack_settings(h2c);
break;
case H2_FT_PING:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_ping(h2c);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_ack_ping(h2c);
break;
case H2_FT_WINDOW_UPDATE:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_window_update(h2c, h2s);
break;
case H2_FT_CONTINUATION:
/* we currently don't support CONTINUATION frames since
* we have nowhere to store the partial HEADERS frame.
* Let's abort the stream on an INTERNAL_ERROR here.
*/
if (h2c->st0 == H2_CS_FRAME_P) {
h2s_error(h2s, H2_ERR_INTERNAL_ERROR);
h2c->st0 = H2_CS_FRAME_E;
}
break;
case H2_FT_HEADERS:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_frt_handle_headers(h2c, h2s);
break;
case H2_FT_DATA:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_frt_handle_data(h2c, h2s);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_send_strm_wu(h2c);
break;
case H2_FT_PRIORITY:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_priority(h2c);
break;
case H2_FT_RST_STREAM:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_rst_stream(h2c, h2s);
break;
case H2_FT_GOAWAY:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_goaway(h2c);
break;
case H2_FT_PUSH_PROMISE:
/* not permitted here, RFC7540#5.1 */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
break;
/* implement all extra frame types here */
default:
/* drop frames that we ignore. They may be larger than
* the buffer so we drain all of their contents until
* we reach the end.
*/
ret = MIN(h2c->dbuf->i, h2c->dfl);
bi_del(h2c->dbuf, ret);
h2c->dfl -= ret;
ret = h2c->dfl == 0;
}
strm_err:
/* We may have to send an RST if not done yet */
if (h2s->st == H2_SS_ERROR)
h2c->st0 = H2_CS_FRAME_E;
if (h2c->st0 == H2_CS_FRAME_E)
ret = h2c_send_rst_stream(h2c, h2s);
/* error or missing data condition met above ? */
if (ret <= 0)
break;
if (h2c->st0 != H2_CS_FRAME_H) {
bi_del(h2c->dbuf, h2c->dfl);
h2c->st0 = H2_CS_FRAME_H;
}
}
if (h2c->rcvd_c > 0 &&
!(h2c->flags & (H2_CF_MUX_MFULL | H2_CF_DEM_MBUSY | H2_CF_DEM_MROOM)))
h2c_send_conn_wu(h2c);
fail:
/* we can go here on missing data, blocked response or error */
return;
}
|
static void h2_process_demux(struct h2c *h2c)
{
struct h2s *h2s;
if (h2c->st0 >= H2_CS_ERROR)
return;
if (unlikely(h2c->st0 < H2_CS_FRAME_H)) {
if (h2c->st0 == H2_CS_PREFACE) {
if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
if (h2c->st0 == H2_CS_ERROR)
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
h2c->max_id = 0;
h2c->st0 = H2_CS_SETTINGS1;
}
if (h2c->st0 == H2_CS_SETTINGS1) {
struct h2_fh hdr;
/* ensure that what is pending is a valid SETTINGS frame
* without an ACK.
*/
if (!h2_get_frame_hdr(h2c->dbuf, &hdr)) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
if (h2c->st0 == H2_CS_ERROR)
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
if (hdr.sid || hdr.ft != H2_FT_SETTINGS || hdr.ff & H2_F_SETTINGS_ACK) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
/* that's OK, switch to FRAME_P to process it */
h2c->dfl = hdr.len;
h2c->dsi = hdr.sid;
h2c->dft = hdr.ft;
h2c->dff = hdr.ff;
h2c->dpl = 0;
h2c->st0 = H2_CS_FRAME_P;
}
}
/* process as many incoming frames as possible below */
while (h2c->dbuf->i) {
int ret = 0;
if (h2c->st0 >= H2_CS_ERROR)
break;
if (h2c->st0 == H2_CS_FRAME_H) {
struct h2_fh hdr;
if (!h2_peek_frame_hdr(h2c->dbuf, &hdr))
break;
if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) {
h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);
h2c->st0 = H2_CS_ERROR;
break;
}
h2c->dfl = hdr.len;
h2c->dsi = hdr.sid;
h2c->dft = hdr.ft;
h2c->dff = hdr.ff;
h2c->dpl = 0;
h2c->st0 = H2_CS_FRAME_P;
h2_skip_frame_hdr(h2c->dbuf);
}
/* Only H2_CS_FRAME_P and H2_CS_FRAME_A here */
h2s = h2c_st_by_id(h2c, h2c->dsi);
if (h2c->st0 == H2_CS_FRAME_E)
goto strm_err;
if (h2s->st == H2_SS_IDLE &&
h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than HEADERS or PRIORITY in
* this state MUST be treated as a connection error
*/
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
h2c->st0 = H2_CS_ERROR;
break;
}
if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE &&
h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than WU/PRIO/RST in
* this state MUST be treated as a stream error
*/
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
goto strm_err;
}
/* Below the management of frames received in closed state is a
* bit hackish because the spec makes strong differences between
* streams closed by receiving RST, sending RST, and seeing ES
* in both directions. In addition to this, the creation of a
* new stream reusing the identifier of a closed one will be
* detected here. Given that we cannot keep track of all closed
* streams forever, we consider that unknown closed streams were
* closed on RST received, which allows us to respond with an
* RST without breaking the connection (eg: to abort a transfer).
* Some frames have to be silently ignored as well.
*/
if (h2s->st == H2_SS_CLOSED && h2c->dsi) {
if (h2c->dft == H2_FT_HEADERS || h2c->dft == H2_FT_PUSH_PROMISE) {
/* #5.1.1: The identifier of a newly
* established stream MUST be numerically
* greater than all streams that the initiating
* endpoint has opened or reserved. This
* governs streams that are opened using a
* HEADERS frame and streams that are reserved
* using PUSH_PROMISE. An endpoint that
* receives an unexpected stream identifier
* MUST respond with a connection error.
*/
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
goto strm_err;
}
if (h2s->flags & H2_SF_RST_RCVD) {
/* RFC7540#5.1:closed: an endpoint that
* receives any frame other than PRIORITY after
* receiving a RST_STREAM MUST treat that as a
* stream error of type STREAM_CLOSED.
*
* Note that old streams fall into this category
* and will lead to an RST being sent.
*/
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
goto strm_err;
}
/* RFC7540#5.1:closed: if this state is reached as a
* result of sending a RST_STREAM frame, the peer that
* receives the RST_STREAM might have already sent
* frames on the stream that cannot be withdrawn. An
* endpoint MUST ignore frames that it receives on
* closed streams after it has sent a RST_STREAM
* frame. An endpoint MAY choose to limit the period
* over which it ignores frames and treat frames that
* arrive after this time as being in error.
*/
if (!(h2s->flags & H2_SF_RST_SENT)) {
/* RFC7540#5.1:closed: any frame other than
* PRIO/WU/RST in this state MUST be treated as
* a connection error
*/
if (h2c->dft != H2_FT_RST_STREAM &&
h2c->dft != H2_FT_PRIORITY &&
h2c->dft != H2_FT_WINDOW_UPDATE) {
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
goto strm_err;
}
}
}
#if 0
/* graceful shutdown, ignore streams whose ID is higher than
* the one advertised in GOAWAY. RFC7540#6.8.
*/
if (unlikely(h2c->last_sid >= 0) && h2c->dsi > h2c->last_sid) {
ret = MIN(h2c->dbuf->i, h2c->dfl);
bi_del(h2c->dbuf, ret);
h2c->dfl -= ret;
ret = h2c->dfl == 0;
goto strm_err;
}
#endif
switch (h2c->dft) {
case H2_FT_SETTINGS:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_settings(h2c);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_ack_settings(h2c);
break;
case H2_FT_PING:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_ping(h2c);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_ack_ping(h2c);
break;
case H2_FT_WINDOW_UPDATE:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_window_update(h2c, h2s);
break;
case H2_FT_CONTINUATION:
/* we currently don't support CONTINUATION frames since
* we have nowhere to store the partial HEADERS frame.
* Let's abort the stream on an INTERNAL_ERROR here.
*/
if (h2c->st0 == H2_CS_FRAME_P) {
h2s_error(h2s, H2_ERR_INTERNAL_ERROR);
h2c->st0 = H2_CS_FRAME_E;
}
break;
case H2_FT_HEADERS:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_frt_handle_headers(h2c, h2s);
break;
case H2_FT_DATA:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_frt_handle_data(h2c, h2s);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_send_strm_wu(h2c);
break;
case H2_FT_PRIORITY:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_priority(h2c);
break;
case H2_FT_RST_STREAM:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_rst_stream(h2c, h2s);
break;
case H2_FT_GOAWAY:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_goaway(h2c);
break;
case H2_FT_PUSH_PROMISE:
/* not permitted here, RFC7540#5.1 */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
break;
/* implement all extra frame types here */
default:
/* drop frames that we ignore. They may be larger than
* the buffer so we drain all of their contents until
* we reach the end.
*/
ret = MIN(h2c->dbuf->i, h2c->dfl);
bi_del(h2c->dbuf, ret);
h2c->dfl -= ret;
ret = h2c->dfl == 0;
}
strm_err:
/* We may have to send an RST if not done yet */
if (h2s->st == H2_SS_ERROR)
h2c->st0 = H2_CS_FRAME_E;
if (h2c->st0 == H2_CS_FRAME_E)
ret = h2c_send_rst_stream(h2c, h2s);
/* error or missing data condition met above ? */
if (ret <= 0)
break;
if (h2c->st0 != H2_CS_FRAME_H) {
bi_del(h2c->dbuf, h2c->dfl);
h2c->st0 = H2_CS_FRAME_H;
}
}
if (h2c->rcvd_c > 0 &&
!(h2c->flags & (H2_CF_MUX_MFULL | H2_CF_DEM_MBUSY | H2_CF_DEM_MROOM)))
h2c_send_conn_wu(h2c);
fail:
/* we can go here on missing data, blocked response or error */
return;
}
|
CVE-2018-10184
|
An issue was discovered in HAProxy before 1.8.8. The incoming H2 frame length was checked against the max_frame_size setting instead of being checked against the bufsize. The max_frame_size only applies to outgoing traffic and not to incoming, so if a large enough frame size is advertised in the SETTINGS frame, a wrapped frame will be defragmented into a temporary allocated buffer where the second fragment may overflow the heap by up to 16 kB. It is very unlikely that this can be exploited for code execution given that buffers are very short lived and their addresses not realistically predictable in production, but the likelihood of an immediate crash is absolutely certain.
|
[
"CWE-119"
] |
[
{
"line_no": 41,
"text": " if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) {",
"char_start": null,
"char_end": null
},
{
"line_no": 71,
"text": " if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 41,
"text": " if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) {",
"char_start": null,
"char_end": null
},
{
"line_no": 71,
"text": " if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) {",
"char_start": null,
"char_end": null
}
] | 219
|
primevul
|
primevul_libXvMC_2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
|
2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
|
libXvMC
|
https://cgit.freedesktop.org/xorg/lib/libXvMC/commit/?id=2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
|
Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
|
Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen == 0 ? 0 : rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen == 0 ? 0 : rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
|
CVE-2016-7953
|
Buffer underflow in X.org libXvMC before 1.0.10 allows remote X servers to have unspecified impact via an empty string.
|
[
"CWE-119"
] |
[
{
"line_no": 98,
"text": "\t (*name)[rep.nameLen - 1] = '\\0';",
"char_start": null,
"char_end": null
},
{
"line_no": 100,
"text": "\t (*busID)[rep.busIDLen - 1] = '\\0';",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 98,
"text": "\t (*name)[rep.nameLen == 0 ? 0 : rep.nameLen - 1] = '\\0';",
"char_start": null,
"char_end": null
},
{
"line_no": 100,
"text": "\t (*busID)[rep.busIDLen == 0 ? 0 : rep.busIDLen - 1] = '\\0';",
"char_start": null,
"char_end": null
}
] | 223
|
primevul
|
primevul_libXfixes_61c1039ee23a2d1de712843bed3480654d7ef42e
|
61c1039ee23a2d1de712843bed3480654d7ef42e
|
libXfixes
|
https://cgit.freedesktop.org/xorg/lib/libXfixes/commit/?id=61c1039ee23a2d1de712843bed3480654d7ef42e
|
XFixesFetchRegionAndBounds (Display *dpy,
XserverRegion region,
int *nrectanglesRet,
XRectangle *bounds)
{
XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy);
xXFixesFetchRegionReq *req;
xXFixesFetchRegionReply rep;
XRectangle *rects;
int nrects;
long nbytes;
long nread;
XFixesCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (XFixesFetchRegion, req);
req->reqType = info->codes->major_opcode;
req->xfixesReqType = X_XFixesFetchRegion;
req->region = region;
*nrectanglesRet = 0;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
bounds->x = rep.x;
bounds->y = rep.y;
bounds->y = rep.y;
bounds->width = rep.width;
bounds->height = rep.height;
nbytes = (long) rep.length << 2;
nrects = rep.length >> 1;
rects = Xmalloc (nrects * sizeof (XRectangle));
if (!rects)
{
_XEatDataWords(dpy, rep.length);
_XEatData (dpy, (unsigned long) (nbytes - nread));
}
UnlockDisplay (dpy);
SyncHandle();
*nrectanglesRet = nrects;
return rects;
}
|
XFixesFetchRegionAndBounds (Display *dpy,
XserverRegion region,
int *nrectanglesRet,
XRectangle *bounds)
{
XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy);
xXFixesFetchRegionReq *req;
xXFixesFetchRegionReply rep;
XRectangle *rects;
int nrects;
long nbytes;
long nread;
XFixesCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (XFixesFetchRegion, req);
req->reqType = info->codes->major_opcode;
req->xfixesReqType = X_XFixesFetchRegion;
req->region = region;
*nrectanglesRet = 0;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
bounds->x = rep.x;
bounds->y = rep.y;
bounds->y = rep.y;
bounds->width = rep.width;
bounds->height = rep.height;
if (rep.length < (INT_MAX >> 2)) {
nbytes = (long) rep.length << 2;
nrects = rep.length >> 1;
rects = Xmalloc (nrects * sizeof (XRectangle));
} else {
nbytes = 0;
nrects = 0;
rects = NULL;
}
if (!rects)
{
_XEatDataWords(dpy, rep.length);
_XEatData (dpy, (unsigned long) (nbytes - nread));
}
UnlockDisplay (dpy);
SyncHandle();
*nrectanglesRet = nrects;
return rects;
}
|
CVE-2016-7944
|
Integer overflow in X.org libXfixes before 5.0.3 on 32-bit platforms might allow remote X servers to gain privileges via a length value of INT_MAX, which triggers the client to stop reading data and get out of sync.
|
[
"CWE-190"
] |
[
{
"line_no": 32,
"text": " nbytes = (long) rep.length << 2;",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " nrects = rep.length >> 1;",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": " rects = Xmalloc (nrects * sizeof (XRectangle));",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 32,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 33,
"text": " if (rep.length < (INT_MAX >> 2)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 34,
"text": "\tnbytes = (long) rep.length << 2;",
"char_start": null,
"char_end": null
},
{
"line_no": 35,
"text": "\tnrects = rep.length >> 1;",
"char_start": null,
"char_end": null
},
{
"line_no": 36,
"text": "\trects = Xmalloc (nrects * sizeof (XRectangle));",
"char_start": null,
"char_end": null
},
{
"line_no": 37,
"text": " } else {",
"char_start": null,
"char_end": null
},
{
"line_no": 38,
"text": "\tnbytes = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 39,
"text": "\tnrects = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 40,
"text": "\trects = NULL;",
"char_start": null,
"char_end": null
},
{
"line_no": 41,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 42,
"text": "",
"char_start": null,
"char_end": null
}
] | 231
|
primevul
|
primevul_libav_136f55207521f0b03194ef5b55ba70f1635d6aee
|
136f55207521f0b03194ef5b55ba70f1635d6aee
|
libav
|
https://github.com/libav/libav
|
static inline int hpel_motion(MpegEncContext *s,
uint8_t *dest, uint8_t *src,
int src_x, int src_y,
op_pixels_func *pix_op,
int motion_x, int motion_y)
{
int dxy = 0;
int emu = 0;
src_x += motion_x >> 1;
src_y += motion_y >> 1;
/* WARNING: do no forget half pels */
src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu?
if (src_x != s->width)
dxy |= motion_x & 1;
src_y = av_clip(src_y, -16, s->height);
if (src_y != s->height)
dxy |= (motion_y & 1) << 1;
src += src_y * s->linesize + src_x;
if (s->unrestricted_mv) {
if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||
(unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {
s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,
s->linesize, s->linesize,
9, 9,
src_x, src_y, s->h_edge_pos,
s->v_edge_pos);
src = s->sc.edge_emu_buffer;
emu = 1;
}
}
pix_op[dxy](dest, src, s->linesize, 8);
return emu;
}
|
static inline int hpel_motion(MpegEncContext *s,
uint8_t *dest, uint8_t *src,
int src_x, int src_y,
op_pixels_func *pix_op,
int motion_x, int motion_y)
{
int dxy = 0;
int emu = 0;
src_x += motion_x >> 1;
src_y += motion_y >> 1;
/* WARNING: do no forget half pels */
src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu?
if (src_x != s->width)
dxy |= motion_x & 1;
src_y = av_clip(src_y, -16, s->height);
if (src_y != s->height)
dxy |= (motion_y & 1) << 1;
src += src_y * s->linesize + src_x;
if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||
(unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {
s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,
s->linesize, s->linesize,
9, 9, src_x, src_y,
s->h_edge_pos, s->v_edge_pos);
src = s->sc.edge_emu_buffer;
emu = 1;
}
pix_op[dxy](dest, src, s->linesize, 8);
return emu;
}
|
CVE-2016-7424
|
The put_no_rnd_pixels8_xy2_mmx function in x86/rnd_template.c in libav 11.7 and earlier allows remote attackers to cause a denial of service (NULL pointer dereference and crash) via a crafted MP3 file.
|
[
"CWE-476"
] |
[
{
"line_no": 22,
"text": " if (s->unrestricted_mv) {",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " s->linesize, s->linesize,",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " 9, 9,",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " src_x, src_y, s->h_edge_pos,",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " s->v_edge_pos);",
"char_start": null,
"char_end": null
},
{
"line_no": 30,
"text": " src = s->sc.edge_emu_buffer;",
"char_start": null,
"char_end": null
},
{
"line_no": 31,
"text": " emu = 1;",
"char_start": null,
"char_end": null
},
{
"line_no": 32,
"text": " }",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 22,
"text": " if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " s->linesize, s->linesize,",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " 9, 9, src_x, src_y,",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " s->h_edge_pos, s->v_edge_pos);",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " src = s->sc.edge_emu_buffer;",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": " emu = 1;",
"char_start": null,
"char_end": null
}
] | 232
|
primevul
|
primevul_tartarus_4ff22863d895cb7ebfced4cf923a012a614adaa8
|
4ff22863d895cb7ebfced4cf923a012a614adaa8
|
tartarus
|
https://git.tartarus.org/?p=simon/putty
|
static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
{
int i;
struct ssh_channel *c;
if (enable == ssh->throttled_all)
return;
ssh->throttled_all = enable;
ssh->overall_bufsize = bufsize;
if (!ssh->channels)
return;
for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
switch (c->type) {
case CHAN_MAINSESSION:
/*
* This is treated separately, outside the switch.
*/
break;
x11_override_throttle(c->u.x11.xconn, enable);
break;
case CHAN_AGENT:
/* Agent channels require no buffer management. */
break;
case CHAN_SOCKDATA:
pfd_override_throttle(c->u.pfd.pf, enable);
static void ssh_agent_callback(void *sshv, void *reply, int replylen)
{
Ssh ssh = (Ssh) sshv;
ssh->auth_agent_query = NULL;
ssh->agent_response = reply;
ssh->agent_response_len = replylen;
if (ssh->version == 1)
do_ssh1_login(ssh, NULL, -1, NULL);
else
do_ssh2_authconn(ssh, NULL, -1, NULL);
}
static void ssh_dialog_callback(void *sshv, int ret)
{
Ssh ssh = (Ssh) sshv;
ssh->user_response = ret;
if (ssh->version == 1)
do_ssh1_login(ssh, NULL, -1, NULL);
else
do_ssh2_transport(ssh, NULL, -1, NULL);
/*
* This may have unfrozen the SSH connection, so do a
* queued-data run.
*/
ssh_process_queued_incoming_data(ssh);
}
static void ssh_agentf_callback(void *cv, void *reply, int replylen)
ssh_process_queued_incoming_data(ssh);
}
static void ssh_agentf_callback(void *cv, void *reply, int replylen)
{
struct ssh_channel *c = (struct ssh_channel *)cv;
const void *sentreply = reply;
c->u.a.pending = NULL;
c->u.a.outstanding_requests--;
if (!sentreply) {
/* Fake SSH_AGENT_FAILURE. */
sentreply = "\0\0\0\1\5";
replylen = 5;
}
ssh_send_channel_data(c, sentreply, replylen);
if (reply)
sfree(reply);
/*
* If we've already seen an incoming EOF but haven't sent an
* outgoing one, this may be the moment to send it.
*/
if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
sshfwd_write_eof(c);
}
/*
* Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
* non-NULL, otherwise just close the connection. `client_reason' == NULL
struct Packet *pktin)
{
int i, j, ret;
unsigned char cookie[8], *ptr;
struct MD5Context md5c;
struct do_ssh1_login_state {
int crLine;
int len;
unsigned char *rsabuf;
const unsigned char *keystr1, *keystr2;
unsigned long supported_ciphers_mask, supported_auths_mask;
int tried_publickey, tried_agent;
int tis_auth_refused, ccard_auth_refused;
unsigned char session_id[16];
int cipher_type;
void *publickey_blob;
int publickey_bloblen;
char *publickey_comment;
int privatekey_available, privatekey_encrypted;
prompts_t *cur_prompt;
char c;
int pwpkt_type;
unsigned char request[5], *response, *p;
int responselen;
int keyi, nkeys;
int authed;
struct RSAKey key;
Bignum challenge;
char *commentp;
int commentlen;
int dlgret;
Filename *keyfile;
struct RSAKey servkey, hostkey;
};
crState(do_ssh1_login_state);
crBeginState;
if (!pktin)
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
bombout(("Public key packet not received"));
crStop(0);
}
logevent("Received public keys");
ptr = ssh_pkt_getdata(pktin, 8);
if (!ptr) {
bombout(("SSH-1 public key packet stopped before random cookie"));
crStop(0);
}
memcpy(cookie, ptr, 8);
if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
!ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
bombout(("Failed to read SSH-1 public keys from public key packet"));
crStop(0);
}
/*
* Log the host key fingerprint.
*/
{
char logmsg[80];
logevent("Host key fingerprint is:");
strcpy(logmsg, " ");
s->hostkey.comment = NULL;
rsa_fingerprint(logmsg + strlen(logmsg),
sizeof(logmsg) - strlen(logmsg), &s->hostkey);
logevent(logmsg);
}
ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
s->supported_auths_mask = ssh_pkt_getuint32(pktin);
if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
ssh->v1_local_protoflags =
ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
MD5Init(&md5c);
MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
MD5Update(&md5c, s->keystr1, s->servkey.bytes);
MD5Update(&md5c, cookie, 8);
MD5Final(s->session_id, &md5c);
for (i = 0; i < 32; i++)
ssh->session_key[i] = random_byte();
/*
* Verify that the `bits' and `bytes' parameters match.
*/
if (s->hostkey.bits > s->hostkey.bytes * 8 ||
s->servkey.bits > s->servkey.bytes * 8) {
bombout(("SSH-1 public keys were badly formatted"));
crStop(0);
}
s->len = (s->hostkey.bytes > s->servkey.bytes ?
s->hostkey.bytes : s->servkey.bytes);
s->rsabuf = snewn(s->len, unsigned char);
/*
* Verify the host key.
*/
{
/*
* First format the key into a string.
*/
int len = rsastr_len(&s->hostkey);
char fingerprint[100];
char *keystr = snewn(len, char);
rsastr_fmt(keystr, &s->hostkey);
rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
/* First check against manually configured host keys. */
s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
if (s->dlgret == 0) { /* did not match */
bombout(("Host key did not appear in manually configured list"));
sfree(keystr);
crStop(0);
} else if (s->dlgret < 0) { /* none configured; use standard handling */
ssh_set_frozen(ssh, 1);
s->dlgret = verify_ssh_host_key(ssh->frontend,
ssh->savedhost, ssh->savedport,
"rsa", keystr, fingerprint,
ssh_dialog_callback, ssh);
sfree(keystr);
#ifdef FUZZING
s->dlgret = 1;
#endif
if (s->dlgret < 0) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for user host key response"));
crStop(0);
}
} while (pktin || inlen > 0);
s->dlgret = ssh->user_response;
}
ssh_set_frozen(ssh, 0);
if (s->dlgret == 0) {
ssh_disconnect(ssh, "User aborted at host key verification",
NULL, 0, TRUE);
crStop(0);
}
} else {
sfree(keystr);
}
}
for (i = 0; i < 32; i++) {
s->rsabuf[i] = ssh->session_key[i];
if (i < 16)
s->rsabuf[i] ^= s->session_id[i];
}
if (s->hostkey.bytes > s->servkey.bytes) {
ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
if (ret)
ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
} else {
ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
if (ret)
ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
}
if (!ret) {
bombout(("SSH-1 public key encryptions failed due to bad formatting"));
crStop(0);
}
logevent("Encrypted session key");
{
int cipher_chosen = 0, warn = 0;
const char *cipher_string = NULL;
int i;
for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
int next_cipher = conf_get_int_int(ssh->conf,
CONF_ssh_cipherlist, i);
if (next_cipher == CIPHER_WARN) {
/* If/when we choose a cipher, warn about it */
warn = 1;
} else if (next_cipher == CIPHER_AES) {
/* XXX Probably don't need to mention this. */
logevent("AES not supported in SSH-1, skipping");
} else {
switch (next_cipher) {
case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
cipher_string = "3DES"; break;
case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
cipher_string = "Blowfish"; break;
case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
cipher_string = "single-DES"; break;
}
if (s->supported_ciphers_mask & (1 << s->cipher_type))
cipher_chosen = 1;
}
}
if (!cipher_chosen) {
if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
bombout(("Server violates SSH-1 protocol by not "
"supporting 3DES encryption"));
else
/* shouldn't happen */
bombout(("No supported ciphers found"));
crStop(0);
}
/* Warn about chosen cipher if necessary. */
if (warn) {
ssh_set_frozen(ssh, 1);
s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
ssh_dialog_callback, ssh);
if (s->dlgret < 0) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for user response"));
crStop(0);
}
} while (pktin || inlen > 0);
s->dlgret = ssh->user_response;
}
ssh_set_frozen(ssh, 0);
if (s->dlgret == 0) {
ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
0, TRUE);
crStop(0);
}
}
}
switch (s->cipher_type) {
case SSH_CIPHER_3DES:
logevent("Using 3DES encryption");
break;
case SSH_CIPHER_DES:
logevent("Using single-DES encryption");
break;
case SSH_CIPHER_BLOWFISH:
logevent("Using Blowfish encryption");
break;
}
send_packet(ssh, SSH1_CMSG_SESSION_KEY,
PKT_CHAR, s->cipher_type,
PKT_DATA, cookie, 8,
PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
PKT_DATA, s->rsabuf, s->len,
PKT_INT, ssh->v1_local_protoflags, PKT_END);
logevent("Trying to enable encryption...");
sfree(s->rsabuf);
ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
&ssh_3des);
ssh->v1_cipher_ctx = ssh->cipher->make_context();
ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
ssh->crcda_ctx = crcda_make_context();
logevent("Installing CRC compensation attack detector");
if (s->servkey.modulus) {
sfree(s->servkey.modulus);
s->servkey.modulus = NULL;
}
if (s->servkey.exponent) {
sfree(s->servkey.exponent);
s->servkey.exponent = NULL;
}
if (s->hostkey.modulus) {
sfree(s->hostkey.modulus);
s->hostkey.modulus = NULL;
}
if (s->hostkey.exponent) {
sfree(s->hostkey.exponent);
s->hostkey.exponent = NULL;
}
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Encryption not successfully enabled"));
crStop(0);
}
logevent("Successfully started encryption");
fflush(stdout); /* FIXME eh? */
{
if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
int ret; /* need not be kept over crReturn */
s->cur_prompt = new_prompts(ssh->frontend);
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH login name");
add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/*
* Failed to get a username. Terminate.
*/
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
crStop(0);
}
ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
free_prompts(s->cur_prompt);
}
send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
{
char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
logevent(userlog);
if (flags & FLAG_INTERACTIVE &&
(!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
c_write_str(ssh, userlog);
c_write_str(ssh, "\r\n");
}
sfree(userlog);
}
}
crWaitUntil(pktin);
if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
/* We must not attempt PK auth. Pretend we've already tried it. */
s->tried_publickey = s->tried_agent = 1;
} else {
s->tried_publickey = s->tried_agent = 0;
}
s->tis_auth_refused = s->ccard_auth_refused = 0;
/*
* Load the public half of any configured keyfile for later use.
*/
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
if (!filename_is_null(s->keyfile)) {
int keytype;
logeventf(ssh, "Reading key file \"%.150s\"",
filename_to_str(s->keyfile));
keytype = key_type(s->keyfile);
if (keytype == SSH_KEYTYPE_SSH1 ||
keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
const char *error;
if (rsakey_pubblob(s->keyfile,
&s->publickey_blob, &s->publickey_bloblen,
&s->publickey_comment, &error)) {
s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
if (!s->privatekey_available)
logeventf(ssh, "Key file contains public key only");
s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
NULL);
} else {
char *msgbuf;
logeventf(ssh, "Unable to load key (%s)", error);
msgbuf = dupprintf("Unable to load key file "
"\"%.150s\" (%s)\r\n",
filename_to_str(s->keyfile),
error);
c_write_str(ssh, msgbuf);
sfree(msgbuf);
s->publickey_blob = NULL;
}
} else {
char *msgbuf;
logeventf(ssh, "Unable to use this key file (%s)",
key_type_to_str(keytype));
msgbuf = dupprintf("Unable to use key file \"%.150s\""
" (%s)\r\n",
filename_to_str(s->keyfile),
key_type_to_str(keytype));
c_write_str(ssh, msgbuf);
sfree(msgbuf);
s->publickey_blob = NULL;
}
} else
s->publickey_blob = NULL;
while (pktin->type == SSH1_SMSG_FAILURE) {
s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
/*
* Attempt RSA authentication using Pageant.
*/
void *r;
s->authed = FALSE;
s->tried_agent = 1;
logevent("Pageant is running. Requesting keys.");
/* Request the keys held by the agent. */
PUT_32BIT(s->request, 1);
s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
ssh->auth_agent_query = agent_query(
s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
if (ssh->auth_agent_query) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for agent response"));
crStop(0);
}
} while (pktin || inlen > 0);
r = ssh->agent_response;
s->responselen = ssh->agent_response_len;
}
s->response = (unsigned char *) r;
if (s->response && s->responselen >= 5 &&
s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
s->p = s->response + 5;
s->nkeys = toint(GET_32BIT(s->p));
if (s->nkeys < 0) {
logeventf(ssh, "Pageant reported negative key count %d",
s->nkeys);
s->nkeys = 0;
}
s->p += 4;
logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
unsigned char *pkblob = s->p;
s->p += 4;
{
int n, ok = FALSE;
do { /* do while (0) to make breaking easy */
n = ssh1_read_bignum
(s->p, toint(s->responselen-(s->p-s->response)),
&s->key.exponent);
if (n < 0)
break;
s->p += n;
n = ssh1_read_bignum
(s->p, toint(s->responselen-(s->p-s->response)),
&s->key.modulus);
if (n < 0)
break;
s->p += n;
if (s->responselen - (s->p-s->response) < 4)
break;
s->commentlen = toint(GET_32BIT(s->p));
s->p += 4;
if (s->commentlen < 0 ||
toint(s->responselen - (s->p-s->response)) <
s->commentlen)
break;
s->commentp = (char *)s->p;
s->p += s->commentlen;
ok = TRUE;
} while (0);
if (!ok) {
logevent("Pageant key list packet was truncated");
break;
}
}
if (s->publickey_blob) {
if (!memcmp(pkblob, s->publickey_blob,
s->publickey_bloblen)) {
logeventf(ssh, "Pageant key #%d matches "
"configured key file", s->keyi);
s->tried_publickey = 1;
} else
/* Skip non-configured key */
continue;
}
logeventf(ssh, "Trying Pageant key #%d", s->keyi);
send_packet(ssh, SSH1_CMSG_AUTH_RSA,
PKT_BIGNUM, s->key.modulus, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
logevent("Key refused");
continue;
}
logevent("Received RSA challenge");
if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
bombout(("Server's RSA challenge was badly formatted"));
crStop(0);
}
{
char *agentreq, *q, *ret;
void *vret;
int len, retlen;
len = 1 + 4; /* message type, bit count */
len += ssh1_bignum_length(s->key.exponent);
len += ssh1_bignum_length(s->key.modulus);
len += ssh1_bignum_length(s->challenge);
len += 16; /* session id */
len += 4; /* response format */
agentreq = snewn(4 + len, char);
PUT_32BIT(agentreq, len);
q = agentreq + 4;
*q++ = SSH1_AGENTC_RSA_CHALLENGE;
PUT_32BIT(q, bignum_bitcount(s->key.modulus));
q += 4;
q += ssh1_write_bignum(q, s->key.exponent);
q += ssh1_write_bignum(q, s->key.modulus);
q += ssh1_write_bignum(q, s->challenge);
memcpy(q, s->session_id, 16);
q += 16;
PUT_32BIT(q, 1); /* response format */
ssh->auth_agent_query = agent_query(
agentreq, len + 4, &vret, &retlen,
ssh_agent_callback, ssh);
if (ssh->auth_agent_query) {
sfree(agentreq);
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server"
" while waiting for agent"
" response"));
crStop(0);
}
} while (pktin || inlen > 0);
vret = ssh->agent_response;
retlen = ssh->agent_response_len;
} else
sfree(agentreq);
ret = vret;
if (ret) {
if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
logevent("Sending Pageant's response");
send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
PKT_DATA, ret + 5, 16,
PKT_END);
sfree(ret);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_SUCCESS) {
logevent
("Pageant's response accepted");
if (flags & FLAG_VERBOSE) {
c_write_str(ssh, "Authenticated using"
" RSA key \"");
c_write(ssh, s->commentp,
s->commentlen);
c_write_str(ssh, "\" from agent\r\n");
}
s->authed = TRUE;
} else
logevent
("Pageant's response not accepted");
} else {
logevent
("Pageant failed to answer challenge");
sfree(ret);
}
} else {
logevent("No reply received from Pageant");
}
}
freebn(s->key.exponent);
freebn(s->key.modulus);
freebn(s->challenge);
if (s->authed)
break;
}
sfree(s->response);
if (s->publickey_blob && !s->tried_publickey)
logevent("Configured key file not in Pageant");
} else {
logevent("Failed to get reply from Pageant");
}
if (s->authed)
break;
}
if (s->publickey_blob && s->privatekey_available &&
!s->tried_publickey) {
/*
* Try public key authentication with the specified
* key file.
*/
int got_passphrase; /* need not be kept over crReturn */
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Trying public key authentication.\r\n");
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
logeventf(ssh, "Trying public key \"%s\"",
filename_to_str(s->keyfile));
s->tried_publickey = 1;
got_passphrase = FALSE;
while (!got_passphrase) {
/*
* Get a passphrase, if necessary.
*/
char *passphrase = NULL; /* only written after crReturn */
const char *error;
if (!s->privatekey_encrypted) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "No passphrase required.\r\n");
passphrase = NULL;
} else {
int ret; /* need not be kept over crReturn */
s->cur_prompt = new_prompts(ssh->frontend);
s->cur_prompt->to_server = FALSE;
s->cur_prompt->name = dupstr("SSH key passphrase");
add_prompt(s->cur_prompt,
dupprintf("Passphrase for key \"%.100s\": ",
s->publickey_comment), FALSE);
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/* Failed to get a passphrase. Terminate. */
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, NULL, "Unable to authenticate",
0, TRUE);
crStop(0);
}
passphrase = dupstr(s->cur_prompt->prompts[0]->result);
free_prompts(s->cur_prompt);
}
/*
* Try decrypting key with passphrase.
*/
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
ret = loadrsakey(s->keyfile, &s->key, passphrase,
&error);
if (passphrase) {
smemclr(passphrase, strlen(passphrase));
sfree(passphrase);
}
if (ret == 1) {
/* Correct passphrase. */
got_passphrase = TRUE;
} else if (ret == 0) {
c_write_str(ssh, "Couldn't load private key from ");
c_write_str(ssh, filename_to_str(s->keyfile));
c_write_str(ssh, " (");
c_write_str(ssh, error);
c_write_str(ssh, ").\r\n");
got_passphrase = FALSE;
break; /* go and try something else */
} else if (ret == -1) {
c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
got_passphrase = FALSE;
/* and try again */
} else {
assert(0 && "unexpected return from loadrsakey()");
got_passphrase = FALSE; /* placate optimisers */
}
}
if (got_passphrase) {
/*
* Send a public key attempt.
*/
send_packet(ssh, SSH1_CMSG_AUTH_RSA,
PKT_BIGNUM, s->key.modulus, PKT_END);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
c_write_str(ssh, "Server refused our public key.\r\n");
continue; /* go and try something else */
}
if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
bombout(("Bizarre response to offer of public key"));
crStop(0);
}
{
int i;
unsigned char buffer[32];
Bignum challenge, response;
if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
bombout(("Server's RSA challenge was badly formatted"));
crStop(0);
}
response = rsadecrypt(challenge, &s->key);
freebn(s->key.private_exponent);/* burn the evidence */
for (i = 0; i < 32; i++) {
buffer[i] = bignum_byte(response, 31 - i);
}
MD5Init(&md5c);
MD5Update(&md5c, buffer, 32);
MD5Update(&md5c, s->session_id, 16);
MD5Final(buffer, &md5c);
send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
PKT_DATA, buffer, 16, PKT_END);
freebn(challenge);
freebn(response);
}
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Failed to authenticate with"
" our public key.\r\n");
continue; /* go and try something else */
} else if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Bizarre response to RSA authentication response"));
crStop(0);
}
break; /* we're through! */
}
}
/*
* Otherwise, try various forms of password-like authentication.
*/
s->cur_prompt = new_prompts(ssh->frontend);
if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
(s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
!s->tis_auth_refused) {
s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
logevent("Requested TIS authentication");
send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
logevent("TIS authentication declined");
if (flags & FLAG_INTERACTIVE)
c_write_str(ssh, "TIS authentication refused.\r\n");
s->tis_auth_refused = 1;
continue;
} else {
char *challenge;
int challengelen;
char *instr_suf, *prompt;
ssh_pkt_getstring(pktin, &challenge, &challengelen);
if (!challenge) {
bombout(("TIS challenge packet was badly formed"));
crStop(0);
}
logevent("Received TIS challenge");
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH TIS authentication");
/* Prompt heuristic comes from OpenSSH */
if (memchr(challenge, '\n', challengelen)) {
instr_suf = dupstr("");
prompt = dupprintf("%.*s", challengelen, challenge);
} else {
instr_suf = dupprintf("%.*s", challengelen, challenge);
prompt = dupstr("Response: ");
}
s->cur_prompt->instruction =
dupprintf("Using TIS authentication.%s%s",
(*instr_suf) ? "\n" : "",
instr_suf);
s->cur_prompt->instr_reqd = TRUE;
add_prompt(s->cur_prompt, prompt, FALSE);
sfree(instr_suf);
}
}
if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
(s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
!s->ccard_auth_refused) {
s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
logevent("Requested CryptoCard authentication");
send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
logevent("CryptoCard authentication declined");
c_write_str(ssh, "CryptoCard authentication refused.\r\n");
s->ccard_auth_refused = 1;
continue;
} else {
char *challenge;
int challengelen;
char *instr_suf, *prompt;
ssh_pkt_getstring(pktin, &challenge, &challengelen);
if (!challenge) {
bombout(("CryptoCard challenge packet was badly formed"));
crStop(0);
}
logevent("Received CryptoCard challenge");
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
s->cur_prompt->name_reqd = FALSE;
/* Prompt heuristic comes from OpenSSH */
if (memchr(challenge, '\n', challengelen)) {
instr_suf = dupstr("");
prompt = dupprintf("%.*s", challengelen, challenge);
} else {
instr_suf = dupprintf("%.*s", challengelen, challenge);
prompt = dupstr("Response: ");
}
s->cur_prompt->instruction =
dupprintf("Using CryptoCard authentication.%s%s",
(*instr_suf) ? "\n" : "",
instr_suf);
s->cur_prompt->instr_reqd = TRUE;
add_prompt(s->cur_prompt, prompt, FALSE);
sfree(instr_suf);
}
}
if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
bombout(("No supported authentication methods available"));
crStop(0);
}
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH password");
add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
ssh->username, ssh->savedhost),
FALSE);
}
/*
* Show password prompt, having first obtained it via a TIS
* or CryptoCard exchange if we're doing TIS or CryptoCard
* authentication.
*/
{
int ret; /* need not be kept over crReturn */
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/*
* Failed to get a password (for example
* because one was supplied on the command line
* which has already failed to work). Terminate.
*/
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
crStop(0);
}
}
if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
/*
* Defence against traffic analysis: we send a
* whole bunch of packets containing strings of
* different lengths. One of these strings is the
* password, in a SSH1_CMSG_AUTH_PASSWORD packet.
* The others are all random data in
* SSH1_MSG_IGNORE packets. This way a passive
* listener can't tell which is the password, and
* hence can't deduce the password length.
*
* Anybody with a password length greater than 16
* bytes is going to have enough entropy in their
* password that a listener won't find it _that_
* much help to know how long it is. So what we'll
* do is:
*
* - if password length < 16, we send 15 packets
* containing string lengths 1 through 15
*
* - otherwise, we let N be the nearest multiple
* of 8 below the password length, and send 8
* packets containing string lengths N through
* N+7. This won't obscure the order of
* magnitude of the password length, but it will
* introduce a bit of extra uncertainty.
*
* A few servers can't deal with SSH1_MSG_IGNORE, at
* least in this context. For these servers, we need
* an alternative defence. We make use of the fact
* that the password is interpreted as a C string:
* so we can append a NUL, then some random data.
*
* A few servers can deal with neither SSH1_MSG_IGNORE
* here _nor_ a padded password string.
* For these servers we are left with no defences
* against password length sniffing.
*/
if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
/*
* The server can deal with SSH1_MSG_IGNORE, so
* we can use the primary defence.
*/
int bottom, top, pwlen, i;
char *randomstr;
pwlen = strlen(s->cur_prompt->prompts[0]->result);
if (pwlen < 16) {
bottom = 0; /* zero length passwords are OK! :-) */
top = 15;
} else {
bottom = pwlen & ~7;
top = bottom + 7;
}
assert(pwlen >= bottom && pwlen <= top);
randomstr = snewn(top + 1, char);
for (i = bottom; i <= top; i++) {
if (i == pwlen) {
defer_packet(ssh, s->pwpkt_type,
PKT_STR,s->cur_prompt->prompts[0]->result,
PKT_END);
} else {
for (j = 0; j < i; j++) {
do {
randomstr[j] = random_byte();
} while (randomstr[j] == '\0');
}
randomstr[i] = '\0';
defer_packet(ssh, SSH1_MSG_IGNORE,
PKT_STR, randomstr, PKT_END);
}
}
logevent("Sending password with camouflage packets");
ssh_pkt_defersend(ssh);
sfree(randomstr);
}
else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
/*
* The server can't deal with SSH1_MSG_IGNORE
* but can deal with padded passwords, so we
* can use the secondary defence.
*/
char string[64];
char *ss;
int len;
len = strlen(s->cur_prompt->prompts[0]->result);
if (len < sizeof(string)) {
ss = string;
strcpy(string, s->cur_prompt->prompts[0]->result);
len++; /* cover the zero byte */
while (len < sizeof(string)) {
string[len++] = (char) random_byte();
}
} else {
ss = s->cur_prompt->prompts[0]->result;
}
logevent("Sending length-padded password");
send_packet(ssh, s->pwpkt_type,
PKT_INT, len, PKT_DATA, ss, len,
PKT_END);
} else {
/*
* The server is believed unable to cope with
* any of our password camouflage methods.
*/
int len;
len = strlen(s->cur_prompt->prompts[0]->result);
logevent("Sending unpadded password");
send_packet(ssh, s->pwpkt_type,
PKT_INT, len,
PKT_DATA, s->cur_prompt->prompts[0]->result, len,
PKT_END);
}
} else {
send_packet(ssh, s->pwpkt_type,
PKT_STR, s->cur_prompt->prompts[0]->result,
PKT_END);
}
logevent("Sent password");
free_prompts(s->cur_prompt);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Access denied\r\n");
logevent("Authentication refused");
} else if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Strange packet received, type %d", pktin->type));
crStop(0);
}
}
/* Clear up */
if (s->publickey_blob) {
sfree(s->publickey_blob);
sfree(s->publickey_comment);
}
logevent("Authentication successful");
crFinish(1);
}
static void ssh_channel_try_eof(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
assert(c->pending_eof); /* precondition for calling us */
if (c->halfopen)
return; /* can't close: not even opened yet */
if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
return; /* can't send EOF: pending outgoing data */
c->pending_eof = FALSE; /* we're about to send it */
if (ssh->version == 1) {
send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
PKT_END);
c->closes |= CLOSES_SENT_EOF;
} else {
struct Packet *pktout;
pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
ssh2_pkt_adduint32(pktout, c->remoteid);
ssh2_pkt_send(ssh, pktout);
c->closes |= CLOSES_SENT_EOF;
ssh2_channel_check_close(c);
}
}
Conf *sshfwd_get_conf(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
return ssh->conf;
}
void sshfwd_write_eof(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return;
if (c->closes & CLOSES_SENT_EOF)
return;
c->pending_eof = TRUE;
ssh_channel_try_eof(c);
}
void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
{
Ssh ssh = c->ssh;
char *reason;
if (ssh->state == SSH_STATE_CLOSED)
return;
reason = dupprintf("due to local error: %s", err);
ssh_channel_close_local(c, reason);
sfree(reason);
c->pending_eof = FALSE; /* this will confuse a zombie channel */
ssh2_channel_check_close(c);
}
int sshfwd_write(struct ssh_channel *c, char *buf, int len)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return 0;
return ssh_send_channel_data(c, buf, len);
}
void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return;
ssh_channel_unthrottle(c, bufsize);
}
static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
{
struct queued_handler *qh = ssh->qhead;
assert(qh != NULL);
assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
if (qh->msg1 > 0) {
assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
}
if (qh->msg2 > 0) {
assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
}
if (qh->next) {
ssh->qhead = qh->next;
if (ssh->qhead->msg1 > 0) {
ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
}
if (ssh->qhead->msg2 > 0) {
ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
}
} else {
ssh->qhead = ssh->qtail = NULL;
}
qh->handler(ssh, pktin, qh->ctx);
sfree(qh);
}
static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
chandler_fn_t handler, void *ctx)
{
struct queued_handler *qh;
qh = snew(struct queued_handler);
qh->msg1 = msg1;
qh->msg2 = msg2;
qh->handler = handler;
qh->ctx = ctx;
qh->next = NULL;
if (ssh->qtail == NULL) {
ssh->qhead = qh;
if (qh->msg1 > 0) {
ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
}
if (qh->msg2 > 0) {
ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
}
} else {
ssh->qtail->next = qh;
}
ssh->qtail = qh;
}
static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
{
struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
SSH2_MSG_REQUEST_SUCCESS)) {
logeventf(ssh, "Remote port forwarding from %s enabled",
pf->sportdesc);
} else {
logeventf(ssh, "Remote port forwarding from %s refused",
pf->sportdesc);
rpf = del234(ssh->rportfwds, pf);
assert(rpf == pf);
pf->pfrec->remote = NULL;
free_rportfwd(pf);
}
}
int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
void *share_ctx)
{
struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
pf->dhost = NULL;
pf->dport = 0;
pf->share_ctx = share_ctx;
pf->shost = dupstr(shost);
pf->sport = sport;
pf->sportdesc = NULL;
if (!ssh->rportfwds) {
assert(ssh->version == 2);
ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
}
if (add234(ssh->rportfwds, pf) != pf) {
sfree(pf->shost);
sfree(pf);
return FALSE;
}
return TRUE;
}
static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
void *ctx)
{
share_got_pkt_from_server(ctx, pktin->type,
pktin->body, pktin->length);
}
void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
{
ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
ssh_sharing_global_request_response, share_ctx);
}
static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
{
struct ssh_portfwd *epf;
int i;
char *key, *val;
if (!ssh->portfwds) {
ssh->portfwds = newtree234(ssh_portcmp);
} else {
/*
* Go through the existing port forwardings and tag them
* with status==DESTROY. Any that we want to keep will be
* re-enabled (status==KEEP) as we go through the
* configuration and find out which bits are the same as
* they were before.
*/
struct ssh_portfwd *epf;
int i;
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
epf->status = DESTROY;
}
for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
val != NULL;
val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
char *kp, *kp2, *vp, *vp2;
char address_family, type;
int sport,dport,sserv,dserv;
char *sports, *dports, *saddr, *host;
kp = key;
address_family = 'A';
type = 'L';
if (*kp == 'A' || *kp == '4' || *kp == '6')
address_family = *kp++;
if (*kp == 'L' || *kp == 'R')
type = *kp++;
if ((kp2 = host_strchr(kp, ':')) != NULL) {
/*
* There's a colon in the middle of the source port
* string, which means that the part before it is
* actually a source address.
*/
char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
saddr = host_strduptrim(saddr_tmp);
sfree(saddr_tmp);
sports = kp2+1;
} else {
saddr = NULL;
sports = kp;
}
sport = atoi(sports);
sserv = 0;
if (sport == 0) {
sserv = 1;
sport = net_service_lookup(sports);
if (!sport) {
logeventf(ssh, "Service lookup failed for source"
" port \"%s\"", sports);
}
}
if (type == 'L' && !strcmp(val, "D")) {
/* dynamic forwarding */
host = NULL;
dports = NULL;
dport = -1;
dserv = 0;
type = 'D';
} else {
/* ordinary forwarding */
vp = val;
vp2 = vp + host_strcspn(vp, ":");
host = dupprintf("%.*s", (int)(vp2 - vp), vp);
if (*vp2)
vp2++;
dports = vp2;
dport = atoi(dports);
dserv = 0;
if (dport == 0) {
dserv = 1;
dport = net_service_lookup(dports);
if (!dport) {
logeventf(ssh, "Service lookup failed for destination"
" port \"%s\"", dports);
}
}
}
if (sport && dport) {
/* Set up a description of the source port. */
struct ssh_portfwd *pfrec, *epfrec;
pfrec = snew(struct ssh_portfwd);
pfrec->type = type;
pfrec->saddr = saddr;
pfrec->sserv = sserv ? dupstr(sports) : NULL;
pfrec->sport = sport;
pfrec->daddr = host;
pfrec->dserv = dserv ? dupstr(dports) : NULL;
pfrec->dport = dport;
pfrec->local = NULL;
pfrec->remote = NULL;
pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
address_family == '6' ? ADDRTYPE_IPV6 :
ADDRTYPE_UNSPEC);
epfrec = add234(ssh->portfwds, pfrec);
if (epfrec != pfrec) {
if (epfrec->status == DESTROY) {
/*
* We already have a port forwarding up and running
* with precisely these parameters. Hence, no need
* to do anything; simply re-tag the existing one
* as KEEP.
*/
epfrec->status = KEEP;
}
/*
* Anything else indicates that there was a duplicate
* in our input, which we'll silently ignore.
*/
free_portfwd(pfrec);
} else {
pfrec->status = CREATE;
}
} else {
sfree(saddr);
sfree(host);
}
}
/*
* Now go through and destroy any port forwardings which were
* not re-enabled.
*/
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
if (epf->status == DESTROY) {
char *message;
message = dupprintf("%s port forwarding from %s%s%d",
epf->type == 'L' ? "local" :
epf->type == 'R' ? "remote" : "dynamic",
epf->saddr ? epf->saddr : "",
epf->saddr ? ":" : "",
epf->sport);
if (epf->type != 'D') {
char *msg2 = dupprintf("%s to %s:%d", message,
epf->daddr, epf->dport);
sfree(message);
message = msg2;
}
logeventf(ssh, "Cancelling %s", message);
sfree(message);
/* epf->remote or epf->local may be NULL if setting up a
* forwarding failed. */
if (epf->remote) {
struct ssh_rportfwd *rpf = epf->remote;
struct Packet *pktout;
/*
* Cancel the port forwarding at the server
* end.
*/
if (ssh->version == 1) {
/*
* We cannot cancel listening ports on the
* server side in SSH-1! There's no message
* to support it. Instead, we simply remove
* the rportfwd record from the local end
* so that any connections the server tries
* to make on it are rejected.
*/
} else {
pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
if (epf->saddr) {
ssh2_pkt_addstring(pktout, epf->saddr);
} else if (conf_get_int(conf, CONF_rport_acceptall)) {
/* XXX: rport_acceptall may not represent
* what was used to open the original connection,
* since it's reconfigurable. */
ssh2_pkt_addstring(pktout, "");
} else {
ssh2_pkt_addstring(pktout, "localhost");
}
ssh2_pkt_adduint32(pktout, epf->sport);
ssh2_pkt_send(ssh, pktout);
}
del234(ssh->rportfwds, rpf);
free_rportfwd(rpf);
} else if (epf->local) {
pfl_terminate(epf->local);
}
delpos234(ssh->portfwds, i);
free_portfwd(epf);
i--; /* so we don't skip one in the list */
}
/*
* And finally, set up any new port forwardings (status==CREATE).
*/
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
if (epf->status == CREATE) {
char *sportdesc, *dportdesc;
sportdesc = dupprintf("%s%s%s%s%d%s",
epf->saddr ? epf->saddr : "",
epf->saddr ? ":" : "",
epf->sserv ? epf->sserv : "",
epf->sserv ? "(" : "",
epf->sport,
epf->sserv ? ")" : "");
if (epf->type == 'D') {
dportdesc = NULL;
} else {
dportdesc = dupprintf("%s:%s%s%d%s",
epf->daddr,
epf->dserv ? epf->dserv : "",
epf->dserv ? "(" : "",
epf->dport,
epf->dserv ? ")" : "");
}
if (epf->type == 'L') {
char *err = pfl_listen(epf->daddr, epf->dport,
epf->saddr, epf->sport,
ssh, conf, &epf->local,
epf->addressfamily);
logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
sportdesc, dportdesc,
err ? " failed: " : "", err ? err : "");
if (err)
sfree(err);
} else if (epf->type == 'D') {
char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
ssh, conf, &epf->local,
epf->addressfamily);
logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
sportdesc,
err ? " failed: " : "", err ? err : "");
if (err)
sfree(err);
} else {
struct ssh_rportfwd *pf;
/*
* Ensure the remote port forwardings tree exists.
*/
if (!ssh->rportfwds) {
if (ssh->version == 1)
ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
else
ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
}
pf = snew(struct ssh_rportfwd);
pf->share_ctx = NULL;
pf->dhost = dupstr(epf->daddr);
pf->dport = epf->dport;
if (epf->saddr) {
pf->shost = dupstr(epf->saddr);
} else if (conf_get_int(conf, CONF_rport_acceptall)) {
pf->shost = dupstr("");
} else {
pf->shost = dupstr("localhost");
}
pf->sport = epf->sport;
if (add234(ssh->rportfwds, pf) != pf) {
logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
epf->daddr, epf->dport);
sfree(pf);
} else {
logeventf(ssh, "Requesting remote port %s"
" forward to %s", sportdesc, dportdesc);
pf->sportdesc = sportdesc;
sportdesc = NULL;
epf->remote = pf;
pf->pfrec = epf;
if (ssh->version == 1) {
send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
PKT_INT, epf->sport,
PKT_STR, epf->daddr,
PKT_INT, epf->dport,
PKT_END);
ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
SSH1_SMSG_FAILURE,
ssh_rportfwd_succfail, pf);
} else {
struct Packet *pktout;
pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
ssh2_pkt_addstring(pktout, "tcpip-forward");
ssh2_pkt_addbool(pktout, 1);/* want reply */
ssh2_pkt_addstring(pktout, pf->shost);
ssh2_pkt_adduint32(pktout, pf->sport);
ssh2_pkt_send(ssh, pktout);
ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
SSH2_MSG_REQUEST_FAILURE,
ssh_rportfwd_succfail, pf);
}
}
}
sfree(sportdesc);
sfree(dportdesc);
}
}
static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
{
char *string;
int stringlen, bufsize;
ssh_pkt_getstring(pktin, &string, &stringlen);
if (string == NULL) {
bombout(("Incoming terminal data packet was badly formed"));
return;
}
bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
string, stringlen);
if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
ssh->v1_stdout_throttling = 1;
ssh_throttle_conn(ssh, +1);
}
}
static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to our
* X-Server. Give them back a local channel number. */
struct ssh_channel *c;
int remoteid = ssh_pkt_getuint32(pktin);
logevent("Received X11 connect request");
/* Refuse if X11 forwarding is disabled. */
if (!ssh->X11_fwd_enabled) {
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
logevent("Rejected X11 connect request");
} else {
c = snew(struct ssh_channel);
c->ssh = ssh;
ssh_channel_init(c);
c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_X11; /* identify channel type */
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT,
c->localid, PKT_END);
logevent("Opened X11 forward channel");
}
}
static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to our
* agent. Give them back a local channel number. */
struct ssh_channel *c;
int remoteid = ssh_pkt_getuint32(pktin);
/* Refuse if agent forwarding is disabled. */
if (!ssh->agentfwd_enabled) {
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
c = snew(struct ssh_channel);
c->ssh = ssh;
ssh_channel_init(c);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_AGENT; /* identify channel type */
c->u.a.lensofar = 0;
c->u.a.message = NULL;
c->u.a.pending = NULL;
c->u.a.outstanding_requests = 0;
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT, c->localid,
PKT_END);
}
}
static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to a
* forwarded port. Give them back a local channel number. */
struct ssh_rportfwd pf, *pfp;
int remoteid;
int hostsize, port;
char *host;
char *err;
remoteid = ssh_pkt_getuint32(pktin);
ssh_pkt_getstring(pktin, &host, &hostsize);
port = ssh_pkt_getuint32(pktin);
pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
pf.dport = port;
pfp = find234(ssh->rportfwds, &pf, NULL);
if (pfp == NULL) {
logeventf(ssh, "Rejected remote port open request for %s:%d",
pf.dhost, port);
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
struct ssh_channel *c = snew(struct ssh_channel);
c->ssh = ssh;
logeventf(ssh, "Received remote port open request for %s:%d",
pf.dhost, port);
err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
c, ssh->conf, pfp->pfrec->addressfamily);
if (err != NULL) {
logeventf(ssh, "Port open failed: %s", err);
sfree(err);
sfree(c);
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
ssh_channel_init(c);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_SOCKDATA; /* identify channel type */
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT,
c->localid, PKT_END);
logevent("Forwarded port opened successfully");
}
}
sfree(pf.dhost);
}
static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
{
struct ssh_channel *c;
c = ssh_channel_msg(ssh, pktin);
if (c && c->type == CHAN_SOCKDATA) {
c->remoteid = ssh_pkt_getuint32(pktin);
c->halfopen = FALSE;
c->throttling_conn = 0;
pfd_confirm(c->u.pfd.pf);
}
if (c && c->pending_eof) {
/*
* We have a pending close on this channel,
* which we decided on before the server acked
* the channel open. So now we know the
* remoteid, we can close it again.
*/
ssh_channel_try_eof(c);
}
}
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_AGENT; /* identify channel type */
c->u.a.lensofar = 0;
c->u.a.message = NULL;
c->u.a.pending = NULL;
c->u.a.outstanding_requests = 0;
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT, c->localid,
PKT_END);
del234(ssh->channels, c);
sfree(c);
}
}
|
static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
{
int i;
struct ssh_channel *c;
if (enable == ssh->throttled_all)
return;
ssh->throttled_all = enable;
ssh->overall_bufsize = bufsize;
if (!ssh->channels)
return;
for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
switch (c->type) {
case CHAN_MAINSESSION:
/*
* This is treated separately, outside the switch.
*/
break;
x11_override_throttle(c->u.x11.xconn, enable);
break;
case CHAN_AGENT:
/* Agent forwarding channels are buffer-managed by
* checking ssh->throttled_all in ssh_agentf_try_forward.
* So at the moment we _un_throttle again, we must make an
* attempt to do something. */
if (!enable)
ssh_agentf_try_forward(c);
break;
case CHAN_SOCKDATA:
pfd_override_throttle(c->u.pfd.pf, enable);
static void ssh_agent_callback(void *sshv, void *reply, int replylen)
{
Ssh ssh = (Ssh) sshv;
ssh->auth_agent_query = NULL;
ssh->agent_response = reply;
ssh->agent_response_len = replylen;
if (ssh->version == 1)
do_ssh1_login(ssh, NULL, -1, NULL);
else
do_ssh2_authconn(ssh, NULL, -1, NULL);
}
static void ssh_dialog_callback(void *sshv, int ret)
{
Ssh ssh = (Ssh) sshv;
ssh->user_response = ret;
if (ssh->version == 1)
do_ssh1_login(ssh, NULL, -1, NULL);
else
do_ssh2_transport(ssh, NULL, -1, NULL);
/*
* This may have unfrozen the SSH connection, so do a
* queued-data run.
*/
ssh_process_queued_incoming_data(ssh);
}
static void ssh_agentf_callback(void *cv, void *reply, int replylen)
ssh_process_queued_incoming_data(ssh);
}
static void ssh_agentf_got_response(struct ssh_channel *c,
void *reply, int replylen)
{
c->u.a.pending = NULL;
if (!reply) {
/* The real agent didn't send any kind of reply at all for
* some reason, so fake an SSH_AGENT_FAILURE. */
reply = "\0\0\0\1\5";
replylen = 5;
}
ssh_send_channel_data(c, reply, replylen);
}
static void ssh_agentf_callback(void *cv, void *reply, int replylen);
static void ssh_agentf_try_forward(struct ssh_channel *c)
{
unsigned datalen, lengthfield, messagelen;
unsigned char *message;
unsigned char msglen[4];
void *reply;
int replylen;
/*
* Don't try to parallelise agent requests. Wait for each one to
* return before attempting the next.
*/
if (c->u.a.pending)
return;
/*
* If the outgoing side of the channel connection is currently
* throttled (for any reason, either that channel's window size or
* the entire SSH connection being throttled), don't submit any
* new forwarded requests to the real agent. This causes the input
* side of the agent forwarding not to be emptied, exerting the
* required back-pressure on the remote client, and encouraging it
* to read our responses before sending too many more requests.
*/
if (c->ssh->throttled_all ||
(c->ssh->version == 2 && c->v.v2.remwindow == 0))
return;
while (1) {
/*
* Try to extract a complete message from the input buffer.
*/
datalen = bufchain_size(&c->u.a.inbuffer);
if (datalen < 4)
break; /* not even a length field available yet */
bufchain_fetch(&c->u.a.inbuffer, msglen, 4);
lengthfield = GET_32BIT(msglen);
if (lengthfield > datalen - 4)
break; /* a whole message is not yet available */
messagelen = lengthfield + 4;
message = snewn(messagelen, unsigned char);
bufchain_fetch(&c->u.a.inbuffer, message, messagelen);
bufchain_consume(&c->u.a.inbuffer, messagelen);
c->u.a.pending = agent_query(
message, messagelen, &reply, &replylen, ssh_agentf_callback, c);
sfree(message);
if (c->u.a.pending)
return; /* agent_query promised to reply in due course */
/*
* If the agent gave us an answer immediately, pass it
* straight on and go round this loop again.
*/
ssh_agentf_got_response(c, reply, replylen);
}
/*
* If we get here (i.e. we left the above while loop via 'break'
* rather than 'return'), that means we've determined that the
* input buffer for the agent forwarding connection doesn't
* contain a complete request.
*
* So if there's potentially more data to come, we can return now,
* and wait for the remote client to send it. But if the remote
* has sent EOF, it would be a mistake to do that, because we'd be
* waiting a long time. So this is the moment to check for EOF,
* and respond appropriately.
*/
if (c->closes & CLOSES_RCVD_EOF)
sshfwd_write_eof(c);
}
static void ssh_agentf_callback(void *cv, void *reply, int replylen)
{
struct ssh_channel *c = (struct ssh_channel *)cv;
ssh_agentf_got_response(c, reply, replylen);
sfree(reply);
/*
* Now try to extract and send further messages from the channel's
* input-side buffer.
*/
ssh_agentf_try_forward(c);
}
/*
* Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
* non-NULL, otherwise just close the connection. `client_reason' == NULL
struct Packet *pktin)
{
int i, j, ret;
unsigned char cookie[8], *ptr;
struct MD5Context md5c;
struct do_ssh1_login_state {
int crLine;
int len;
unsigned char *rsabuf;
const unsigned char *keystr1, *keystr2;
unsigned long supported_ciphers_mask, supported_auths_mask;
int tried_publickey, tried_agent;
int tis_auth_refused, ccard_auth_refused;
unsigned char session_id[16];
int cipher_type;
void *publickey_blob;
int publickey_bloblen;
char *publickey_comment;
int privatekey_available, privatekey_encrypted;
prompts_t *cur_prompt;
char c;
int pwpkt_type;
unsigned char request[5], *response, *p;
int responselen;
int keyi, nkeys;
int authed;
struct RSAKey key;
Bignum challenge;
char *commentp;
int commentlen;
int dlgret;
Filename *keyfile;
struct RSAKey servkey, hostkey;
};
crState(do_ssh1_login_state);
crBeginState;
if (!pktin)
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
bombout(("Public key packet not received"));
crStop(0);
}
logevent("Received public keys");
ptr = ssh_pkt_getdata(pktin, 8);
if (!ptr) {
bombout(("SSH-1 public key packet stopped before random cookie"));
crStop(0);
}
memcpy(cookie, ptr, 8);
if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
!ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
bombout(("Failed to read SSH-1 public keys from public key packet"));
crStop(0);
}
/*
* Log the host key fingerprint.
*/
{
char logmsg[80];
logevent("Host key fingerprint is:");
strcpy(logmsg, " ");
s->hostkey.comment = NULL;
rsa_fingerprint(logmsg + strlen(logmsg),
sizeof(logmsg) - strlen(logmsg), &s->hostkey);
logevent(logmsg);
}
ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
s->supported_auths_mask = ssh_pkt_getuint32(pktin);
if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
ssh->v1_local_protoflags =
ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
MD5Init(&md5c);
MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
MD5Update(&md5c, s->keystr1, s->servkey.bytes);
MD5Update(&md5c, cookie, 8);
MD5Final(s->session_id, &md5c);
for (i = 0; i < 32; i++)
ssh->session_key[i] = random_byte();
/*
* Verify that the `bits' and `bytes' parameters match.
*/
if (s->hostkey.bits > s->hostkey.bytes * 8 ||
s->servkey.bits > s->servkey.bytes * 8) {
bombout(("SSH-1 public keys were badly formatted"));
crStop(0);
}
s->len = (s->hostkey.bytes > s->servkey.bytes ?
s->hostkey.bytes : s->servkey.bytes);
s->rsabuf = snewn(s->len, unsigned char);
/*
* Verify the host key.
*/
{
/*
* First format the key into a string.
*/
int len = rsastr_len(&s->hostkey);
char fingerprint[100];
char *keystr = snewn(len, char);
rsastr_fmt(keystr, &s->hostkey);
rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
/* First check against manually configured host keys. */
s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
if (s->dlgret == 0) { /* did not match */
bombout(("Host key did not appear in manually configured list"));
sfree(keystr);
crStop(0);
} else if (s->dlgret < 0) { /* none configured; use standard handling */
ssh_set_frozen(ssh, 1);
s->dlgret = verify_ssh_host_key(ssh->frontend,
ssh->savedhost, ssh->savedport,
"rsa", keystr, fingerprint,
ssh_dialog_callback, ssh);
sfree(keystr);
#ifdef FUZZING
s->dlgret = 1;
#endif
if (s->dlgret < 0) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for user host key response"));
crStop(0);
}
} while (pktin || inlen > 0);
s->dlgret = ssh->user_response;
}
ssh_set_frozen(ssh, 0);
if (s->dlgret == 0) {
ssh_disconnect(ssh, "User aborted at host key verification",
NULL, 0, TRUE);
crStop(0);
}
} else {
sfree(keystr);
}
}
for (i = 0; i < 32; i++) {
s->rsabuf[i] = ssh->session_key[i];
if (i < 16)
s->rsabuf[i] ^= s->session_id[i];
}
if (s->hostkey.bytes > s->servkey.bytes) {
ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
if (ret)
ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
} else {
ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
if (ret)
ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
}
if (!ret) {
bombout(("SSH-1 public key encryptions failed due to bad formatting"));
crStop(0);
}
logevent("Encrypted session key");
{
int cipher_chosen = 0, warn = 0;
const char *cipher_string = NULL;
int i;
for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
int next_cipher = conf_get_int_int(ssh->conf,
CONF_ssh_cipherlist, i);
if (next_cipher == CIPHER_WARN) {
/* If/when we choose a cipher, warn about it */
warn = 1;
} else if (next_cipher == CIPHER_AES) {
/* XXX Probably don't need to mention this. */
logevent("AES not supported in SSH-1, skipping");
} else {
switch (next_cipher) {
case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
cipher_string = "3DES"; break;
case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
cipher_string = "Blowfish"; break;
case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
cipher_string = "single-DES"; break;
}
if (s->supported_ciphers_mask & (1 << s->cipher_type))
cipher_chosen = 1;
}
}
if (!cipher_chosen) {
if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
bombout(("Server violates SSH-1 protocol by not "
"supporting 3DES encryption"));
else
/* shouldn't happen */
bombout(("No supported ciphers found"));
crStop(0);
}
/* Warn about chosen cipher if necessary. */
if (warn) {
ssh_set_frozen(ssh, 1);
s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
ssh_dialog_callback, ssh);
if (s->dlgret < 0) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for user response"));
crStop(0);
}
} while (pktin || inlen > 0);
s->dlgret = ssh->user_response;
}
ssh_set_frozen(ssh, 0);
if (s->dlgret == 0) {
ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
0, TRUE);
crStop(0);
}
}
}
switch (s->cipher_type) {
case SSH_CIPHER_3DES:
logevent("Using 3DES encryption");
break;
case SSH_CIPHER_DES:
logevent("Using single-DES encryption");
break;
case SSH_CIPHER_BLOWFISH:
logevent("Using Blowfish encryption");
break;
}
send_packet(ssh, SSH1_CMSG_SESSION_KEY,
PKT_CHAR, s->cipher_type,
PKT_DATA, cookie, 8,
PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
PKT_DATA, s->rsabuf, s->len,
PKT_INT, ssh->v1_local_protoflags, PKT_END);
logevent("Trying to enable encryption...");
sfree(s->rsabuf);
ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
&ssh_3des);
ssh->v1_cipher_ctx = ssh->cipher->make_context();
ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
ssh->crcda_ctx = crcda_make_context();
logevent("Installing CRC compensation attack detector");
if (s->servkey.modulus) {
sfree(s->servkey.modulus);
s->servkey.modulus = NULL;
}
if (s->servkey.exponent) {
sfree(s->servkey.exponent);
s->servkey.exponent = NULL;
}
if (s->hostkey.modulus) {
sfree(s->hostkey.modulus);
s->hostkey.modulus = NULL;
}
if (s->hostkey.exponent) {
sfree(s->hostkey.exponent);
s->hostkey.exponent = NULL;
}
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Encryption not successfully enabled"));
crStop(0);
}
logevent("Successfully started encryption");
fflush(stdout); /* FIXME eh? */
{
if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
int ret; /* need not be kept over crReturn */
s->cur_prompt = new_prompts(ssh->frontend);
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH login name");
add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/*
* Failed to get a username. Terminate.
*/
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
crStop(0);
}
ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
free_prompts(s->cur_prompt);
}
send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
{
char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
logevent(userlog);
if (flags & FLAG_INTERACTIVE &&
(!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
c_write_str(ssh, userlog);
c_write_str(ssh, "\r\n");
}
sfree(userlog);
}
}
crWaitUntil(pktin);
if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
/* We must not attempt PK auth. Pretend we've already tried it. */
s->tried_publickey = s->tried_agent = 1;
} else {
s->tried_publickey = s->tried_agent = 0;
}
s->tis_auth_refused = s->ccard_auth_refused = 0;
/*
* Load the public half of any configured keyfile for later use.
*/
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
if (!filename_is_null(s->keyfile)) {
int keytype;
logeventf(ssh, "Reading key file \"%.150s\"",
filename_to_str(s->keyfile));
keytype = key_type(s->keyfile);
if (keytype == SSH_KEYTYPE_SSH1 ||
keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
const char *error;
if (rsakey_pubblob(s->keyfile,
&s->publickey_blob, &s->publickey_bloblen,
&s->publickey_comment, &error)) {
s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
if (!s->privatekey_available)
logeventf(ssh, "Key file contains public key only");
s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
NULL);
} else {
char *msgbuf;
logeventf(ssh, "Unable to load key (%s)", error);
msgbuf = dupprintf("Unable to load key file "
"\"%.150s\" (%s)\r\n",
filename_to_str(s->keyfile),
error);
c_write_str(ssh, msgbuf);
sfree(msgbuf);
s->publickey_blob = NULL;
}
} else {
char *msgbuf;
logeventf(ssh, "Unable to use this key file (%s)",
key_type_to_str(keytype));
msgbuf = dupprintf("Unable to use key file \"%.150s\""
" (%s)\r\n",
filename_to_str(s->keyfile),
key_type_to_str(keytype));
c_write_str(ssh, msgbuf);
sfree(msgbuf);
s->publickey_blob = NULL;
}
} else
s->publickey_blob = NULL;
while (pktin->type == SSH1_SMSG_FAILURE) {
s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
/*
* Attempt RSA authentication using Pageant.
*/
void *r;
s->authed = FALSE;
s->tried_agent = 1;
logevent("Pageant is running. Requesting keys.");
/* Request the keys held by the agent. */
PUT_32BIT(s->request, 1);
s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
ssh->auth_agent_query = agent_query(
s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
if (ssh->auth_agent_query) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for agent response"));
crStop(0);
}
} while (pktin || inlen > 0);
r = ssh->agent_response;
s->responselen = ssh->agent_response_len;
}
s->response = (unsigned char *) r;
if (s->response && s->responselen >= 5 &&
s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
s->p = s->response + 5;
s->nkeys = toint(GET_32BIT(s->p));
if (s->nkeys < 0) {
logeventf(ssh, "Pageant reported negative key count %d",
s->nkeys);
s->nkeys = 0;
}
s->p += 4;
logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
unsigned char *pkblob = s->p;
s->p += 4;
{
int n, ok = FALSE;
do { /* do while (0) to make breaking easy */
n = ssh1_read_bignum
(s->p, toint(s->responselen-(s->p-s->response)),
&s->key.exponent);
if (n < 0)
break;
s->p += n;
n = ssh1_read_bignum
(s->p, toint(s->responselen-(s->p-s->response)),
&s->key.modulus);
if (n < 0)
break;
s->p += n;
if (s->responselen - (s->p-s->response) < 4)
break;
s->commentlen = toint(GET_32BIT(s->p));
s->p += 4;
if (s->commentlen < 0 ||
toint(s->responselen - (s->p-s->response)) <
s->commentlen)
break;
s->commentp = (char *)s->p;
s->p += s->commentlen;
ok = TRUE;
} while (0);
if (!ok) {
logevent("Pageant key list packet was truncated");
break;
}
}
if (s->publickey_blob) {
if (!memcmp(pkblob, s->publickey_blob,
s->publickey_bloblen)) {
logeventf(ssh, "Pageant key #%d matches "
"configured key file", s->keyi);
s->tried_publickey = 1;
} else
/* Skip non-configured key */
continue;
}
logeventf(ssh, "Trying Pageant key #%d", s->keyi);
send_packet(ssh, SSH1_CMSG_AUTH_RSA,
PKT_BIGNUM, s->key.modulus, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
logevent("Key refused");
continue;
}
logevent("Received RSA challenge");
if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
bombout(("Server's RSA challenge was badly formatted"));
crStop(0);
}
{
char *agentreq, *q, *ret;
void *vret;
int len, retlen;
len = 1 + 4; /* message type, bit count */
len += ssh1_bignum_length(s->key.exponent);
len += ssh1_bignum_length(s->key.modulus);
len += ssh1_bignum_length(s->challenge);
len += 16; /* session id */
len += 4; /* response format */
agentreq = snewn(4 + len, char);
PUT_32BIT(agentreq, len);
q = agentreq + 4;
*q++ = SSH1_AGENTC_RSA_CHALLENGE;
PUT_32BIT(q, bignum_bitcount(s->key.modulus));
q += 4;
q += ssh1_write_bignum(q, s->key.exponent);
q += ssh1_write_bignum(q, s->key.modulus);
q += ssh1_write_bignum(q, s->challenge);
memcpy(q, s->session_id, 16);
q += 16;
PUT_32BIT(q, 1); /* response format */
ssh->auth_agent_query = agent_query(
agentreq, len + 4, &vret, &retlen,
ssh_agent_callback, ssh);
if (ssh->auth_agent_query) {
sfree(agentreq);
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server"
" while waiting for agent"
" response"));
crStop(0);
}
} while (pktin || inlen > 0);
vret = ssh->agent_response;
retlen = ssh->agent_response_len;
} else
sfree(agentreq);
ret = vret;
if (ret) {
if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
logevent("Sending Pageant's response");
send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
PKT_DATA, ret + 5, 16,
PKT_END);
sfree(ret);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_SUCCESS) {
logevent
("Pageant's response accepted");
if (flags & FLAG_VERBOSE) {
c_write_str(ssh, "Authenticated using"
" RSA key \"");
c_write(ssh, s->commentp,
s->commentlen);
c_write_str(ssh, "\" from agent\r\n");
}
s->authed = TRUE;
} else
logevent
("Pageant's response not accepted");
} else {
logevent
("Pageant failed to answer challenge");
sfree(ret);
}
} else {
logevent("No reply received from Pageant");
}
}
freebn(s->key.exponent);
freebn(s->key.modulus);
freebn(s->challenge);
if (s->authed)
break;
}
sfree(s->response);
if (s->publickey_blob && !s->tried_publickey)
logevent("Configured key file not in Pageant");
} else {
logevent("Failed to get reply from Pageant");
}
if (s->authed)
break;
}
if (s->publickey_blob && s->privatekey_available &&
!s->tried_publickey) {
/*
* Try public key authentication with the specified
* key file.
*/
int got_passphrase; /* need not be kept over crReturn */
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Trying public key authentication.\r\n");
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
logeventf(ssh, "Trying public key \"%s\"",
filename_to_str(s->keyfile));
s->tried_publickey = 1;
got_passphrase = FALSE;
while (!got_passphrase) {
/*
* Get a passphrase, if necessary.
*/
char *passphrase = NULL; /* only written after crReturn */
const char *error;
if (!s->privatekey_encrypted) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "No passphrase required.\r\n");
passphrase = NULL;
} else {
int ret; /* need not be kept over crReturn */
s->cur_prompt = new_prompts(ssh->frontend);
s->cur_prompt->to_server = FALSE;
s->cur_prompt->name = dupstr("SSH key passphrase");
add_prompt(s->cur_prompt,
dupprintf("Passphrase for key \"%.100s\": ",
s->publickey_comment), FALSE);
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/* Failed to get a passphrase. Terminate. */
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, NULL, "Unable to authenticate",
0, TRUE);
crStop(0);
}
passphrase = dupstr(s->cur_prompt->prompts[0]->result);
free_prompts(s->cur_prompt);
}
/*
* Try decrypting key with passphrase.
*/
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
ret = loadrsakey(s->keyfile, &s->key, passphrase,
&error);
if (passphrase) {
smemclr(passphrase, strlen(passphrase));
sfree(passphrase);
}
if (ret == 1) {
/* Correct passphrase. */
got_passphrase = TRUE;
} else if (ret == 0) {
c_write_str(ssh, "Couldn't load private key from ");
c_write_str(ssh, filename_to_str(s->keyfile));
c_write_str(ssh, " (");
c_write_str(ssh, error);
c_write_str(ssh, ").\r\n");
got_passphrase = FALSE;
break; /* go and try something else */
} else if (ret == -1) {
c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
got_passphrase = FALSE;
/* and try again */
} else {
assert(0 && "unexpected return from loadrsakey()");
got_passphrase = FALSE; /* placate optimisers */
}
}
if (got_passphrase) {
/*
* Send a public key attempt.
*/
send_packet(ssh, SSH1_CMSG_AUTH_RSA,
PKT_BIGNUM, s->key.modulus, PKT_END);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
c_write_str(ssh, "Server refused our public key.\r\n");
continue; /* go and try something else */
}
if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
bombout(("Bizarre response to offer of public key"));
crStop(0);
}
{
int i;
unsigned char buffer[32];
Bignum challenge, response;
if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
bombout(("Server's RSA challenge was badly formatted"));
crStop(0);
}
response = rsadecrypt(challenge, &s->key);
freebn(s->key.private_exponent);/* burn the evidence */
for (i = 0; i < 32; i++) {
buffer[i] = bignum_byte(response, 31 - i);
}
MD5Init(&md5c);
MD5Update(&md5c, buffer, 32);
MD5Update(&md5c, s->session_id, 16);
MD5Final(buffer, &md5c);
send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
PKT_DATA, buffer, 16, PKT_END);
freebn(challenge);
freebn(response);
}
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Failed to authenticate with"
" our public key.\r\n");
continue; /* go and try something else */
} else if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Bizarre response to RSA authentication response"));
crStop(0);
}
break; /* we're through! */
}
}
/*
* Otherwise, try various forms of password-like authentication.
*/
s->cur_prompt = new_prompts(ssh->frontend);
if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
(s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
!s->tis_auth_refused) {
s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
logevent("Requested TIS authentication");
send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
logevent("TIS authentication declined");
if (flags & FLAG_INTERACTIVE)
c_write_str(ssh, "TIS authentication refused.\r\n");
s->tis_auth_refused = 1;
continue;
} else {
char *challenge;
int challengelen;
char *instr_suf, *prompt;
ssh_pkt_getstring(pktin, &challenge, &challengelen);
if (!challenge) {
bombout(("TIS challenge packet was badly formed"));
crStop(0);
}
logevent("Received TIS challenge");
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH TIS authentication");
/* Prompt heuristic comes from OpenSSH */
if (memchr(challenge, '\n', challengelen)) {
instr_suf = dupstr("");
prompt = dupprintf("%.*s", challengelen, challenge);
} else {
instr_suf = dupprintf("%.*s", challengelen, challenge);
prompt = dupstr("Response: ");
}
s->cur_prompt->instruction =
dupprintf("Using TIS authentication.%s%s",
(*instr_suf) ? "\n" : "",
instr_suf);
s->cur_prompt->instr_reqd = TRUE;
add_prompt(s->cur_prompt, prompt, FALSE);
sfree(instr_suf);
}
}
if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
(s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
!s->ccard_auth_refused) {
s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
logevent("Requested CryptoCard authentication");
send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
logevent("CryptoCard authentication declined");
c_write_str(ssh, "CryptoCard authentication refused.\r\n");
s->ccard_auth_refused = 1;
continue;
} else {
char *challenge;
int challengelen;
char *instr_suf, *prompt;
ssh_pkt_getstring(pktin, &challenge, &challengelen);
if (!challenge) {
bombout(("CryptoCard challenge packet was badly formed"));
crStop(0);
}
logevent("Received CryptoCard challenge");
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
s->cur_prompt->name_reqd = FALSE;
/* Prompt heuristic comes from OpenSSH */
if (memchr(challenge, '\n', challengelen)) {
instr_suf = dupstr("");
prompt = dupprintf("%.*s", challengelen, challenge);
} else {
instr_suf = dupprintf("%.*s", challengelen, challenge);
prompt = dupstr("Response: ");
}
s->cur_prompt->instruction =
dupprintf("Using CryptoCard authentication.%s%s",
(*instr_suf) ? "\n" : "",
instr_suf);
s->cur_prompt->instr_reqd = TRUE;
add_prompt(s->cur_prompt, prompt, FALSE);
sfree(instr_suf);
}
}
if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
bombout(("No supported authentication methods available"));
crStop(0);
}
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH password");
add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
ssh->username, ssh->savedhost),
FALSE);
}
/*
* Show password prompt, having first obtained it via a TIS
* or CryptoCard exchange if we're doing TIS or CryptoCard
* authentication.
*/
{
int ret; /* need not be kept over crReturn */
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/*
* Failed to get a password (for example
* because one was supplied on the command line
* which has already failed to work). Terminate.
*/
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
crStop(0);
}
}
if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
/*
* Defence against traffic analysis: we send a
* whole bunch of packets containing strings of
* different lengths. One of these strings is the
* password, in a SSH1_CMSG_AUTH_PASSWORD packet.
* The others are all random data in
* SSH1_MSG_IGNORE packets. This way a passive
* listener can't tell which is the password, and
* hence can't deduce the password length.
*
* Anybody with a password length greater than 16
* bytes is going to have enough entropy in their
* password that a listener won't find it _that_
* much help to know how long it is. So what we'll
* do is:
*
* - if password length < 16, we send 15 packets
* containing string lengths 1 through 15
*
* - otherwise, we let N be the nearest multiple
* of 8 below the password length, and send 8
* packets containing string lengths N through
* N+7. This won't obscure the order of
* magnitude of the password length, but it will
* introduce a bit of extra uncertainty.
*
* A few servers can't deal with SSH1_MSG_IGNORE, at
* least in this context. For these servers, we need
* an alternative defence. We make use of the fact
* that the password is interpreted as a C string:
* so we can append a NUL, then some random data.
*
* A few servers can deal with neither SSH1_MSG_IGNORE
* here _nor_ a padded password string.
* For these servers we are left with no defences
* against password length sniffing.
*/
if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
/*
* The server can deal with SSH1_MSG_IGNORE, so
* we can use the primary defence.
*/
int bottom, top, pwlen, i;
char *randomstr;
pwlen = strlen(s->cur_prompt->prompts[0]->result);
if (pwlen < 16) {
bottom = 0; /* zero length passwords are OK! :-) */
top = 15;
} else {
bottom = pwlen & ~7;
top = bottom + 7;
}
assert(pwlen >= bottom && pwlen <= top);
randomstr = snewn(top + 1, char);
for (i = bottom; i <= top; i++) {
if (i == pwlen) {
defer_packet(ssh, s->pwpkt_type,
PKT_STR,s->cur_prompt->prompts[0]->result,
PKT_END);
} else {
for (j = 0; j < i; j++) {
do {
randomstr[j] = random_byte();
} while (randomstr[j] == '\0');
}
randomstr[i] = '\0';
defer_packet(ssh, SSH1_MSG_IGNORE,
PKT_STR, randomstr, PKT_END);
}
}
logevent("Sending password with camouflage packets");
ssh_pkt_defersend(ssh);
sfree(randomstr);
}
else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
/*
* The server can't deal with SSH1_MSG_IGNORE
* but can deal with padded passwords, so we
* can use the secondary defence.
*/
char string[64];
char *ss;
int len;
len = strlen(s->cur_prompt->prompts[0]->result);
if (len < sizeof(string)) {
ss = string;
strcpy(string, s->cur_prompt->prompts[0]->result);
len++; /* cover the zero byte */
while (len < sizeof(string)) {
string[len++] = (char) random_byte();
}
} else {
ss = s->cur_prompt->prompts[0]->result;
}
logevent("Sending length-padded password");
send_packet(ssh, s->pwpkt_type,
PKT_INT, len, PKT_DATA, ss, len,
PKT_END);
} else {
/*
* The server is believed unable to cope with
* any of our password camouflage methods.
*/
int len;
len = strlen(s->cur_prompt->prompts[0]->result);
logevent("Sending unpadded password");
send_packet(ssh, s->pwpkt_type,
PKT_INT, len,
PKT_DATA, s->cur_prompt->prompts[0]->result, len,
PKT_END);
}
} else {
send_packet(ssh, s->pwpkt_type,
PKT_STR, s->cur_prompt->prompts[0]->result,
PKT_END);
}
logevent("Sent password");
free_prompts(s->cur_prompt);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Access denied\r\n");
logevent("Authentication refused");
} else if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Strange packet received, type %d", pktin->type));
crStop(0);
}
}
/* Clear up */
if (s->publickey_blob) {
sfree(s->publickey_blob);
sfree(s->publickey_comment);
}
logevent("Authentication successful");
crFinish(1);
}
static void ssh_channel_try_eof(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
assert(c->pending_eof); /* precondition for calling us */
if (c->halfopen)
return; /* can't close: not even opened yet */
if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
return; /* can't send EOF: pending outgoing data */
c->pending_eof = FALSE; /* we're about to send it */
if (ssh->version == 1) {
send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
PKT_END);
c->closes |= CLOSES_SENT_EOF;
} else {
struct Packet *pktout;
pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
ssh2_pkt_adduint32(pktout, c->remoteid);
ssh2_pkt_send(ssh, pktout);
c->closes |= CLOSES_SENT_EOF;
ssh2_channel_check_close(c);
}
}
Conf *sshfwd_get_conf(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
return ssh->conf;
}
void sshfwd_write_eof(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return;
if (c->closes & CLOSES_SENT_EOF)
return;
c->pending_eof = TRUE;
ssh_channel_try_eof(c);
}
void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
{
Ssh ssh = c->ssh;
char *reason;
if (ssh->state == SSH_STATE_CLOSED)
return;
reason = dupprintf("due to local error: %s", err);
ssh_channel_close_local(c, reason);
sfree(reason);
c->pending_eof = FALSE; /* this will confuse a zombie channel */
ssh2_channel_check_close(c);
}
int sshfwd_write(struct ssh_channel *c, char *buf, int len)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return 0;
return ssh_send_channel_data(c, buf, len);
}
void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return;
ssh_channel_unthrottle(c, bufsize);
}
static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
{
struct queued_handler *qh = ssh->qhead;
assert(qh != NULL);
assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
if (qh->msg1 > 0) {
assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
}
if (qh->msg2 > 0) {
assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
}
if (qh->next) {
ssh->qhead = qh->next;
if (ssh->qhead->msg1 > 0) {
ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
}
if (ssh->qhead->msg2 > 0) {
ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
}
} else {
ssh->qhead = ssh->qtail = NULL;
}
qh->handler(ssh, pktin, qh->ctx);
sfree(qh);
}
static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
chandler_fn_t handler, void *ctx)
{
struct queued_handler *qh;
qh = snew(struct queued_handler);
qh->msg1 = msg1;
qh->msg2 = msg2;
qh->handler = handler;
qh->ctx = ctx;
qh->next = NULL;
if (ssh->qtail == NULL) {
ssh->qhead = qh;
if (qh->msg1 > 0) {
ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
}
if (qh->msg2 > 0) {
ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
}
} else {
ssh->qtail->next = qh;
}
ssh->qtail = qh;
}
static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
{
struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
SSH2_MSG_REQUEST_SUCCESS)) {
logeventf(ssh, "Remote port forwarding from %s enabled",
pf->sportdesc);
} else {
logeventf(ssh, "Remote port forwarding from %s refused",
pf->sportdesc);
rpf = del234(ssh->rportfwds, pf);
assert(rpf == pf);
pf->pfrec->remote = NULL;
free_rportfwd(pf);
}
}
int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
void *share_ctx)
{
struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
pf->dhost = NULL;
pf->dport = 0;
pf->share_ctx = share_ctx;
pf->shost = dupstr(shost);
pf->sport = sport;
pf->sportdesc = NULL;
if (!ssh->rportfwds) {
assert(ssh->version == 2);
ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
}
if (add234(ssh->rportfwds, pf) != pf) {
sfree(pf->shost);
sfree(pf);
return FALSE;
}
return TRUE;
}
static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
void *ctx)
{
share_got_pkt_from_server(ctx, pktin->type,
pktin->body, pktin->length);
}
void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
{
ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
ssh_sharing_global_request_response, share_ctx);
}
static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
{
struct ssh_portfwd *epf;
int i;
char *key, *val;
if (!ssh->portfwds) {
ssh->portfwds = newtree234(ssh_portcmp);
} else {
/*
* Go through the existing port forwardings and tag them
* with status==DESTROY. Any that we want to keep will be
* re-enabled (status==KEEP) as we go through the
* configuration and find out which bits are the same as
* they were before.
*/
struct ssh_portfwd *epf;
int i;
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
epf->status = DESTROY;
}
for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
val != NULL;
val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
char *kp, *kp2, *vp, *vp2;
char address_family, type;
int sport,dport,sserv,dserv;
char *sports, *dports, *saddr, *host;
kp = key;
address_family = 'A';
type = 'L';
if (*kp == 'A' || *kp == '4' || *kp == '6')
address_family = *kp++;
if (*kp == 'L' || *kp == 'R')
type = *kp++;
if ((kp2 = host_strchr(kp, ':')) != NULL) {
/*
* There's a colon in the middle of the source port
* string, which means that the part before it is
* actually a source address.
*/
char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
saddr = host_strduptrim(saddr_tmp);
sfree(saddr_tmp);
sports = kp2+1;
} else {
saddr = NULL;
sports = kp;
}
sport = atoi(sports);
sserv = 0;
if (sport == 0) {
sserv = 1;
sport = net_service_lookup(sports);
if (!sport) {
logeventf(ssh, "Service lookup failed for source"
" port \"%s\"", sports);
}
}
if (type == 'L' && !strcmp(val, "D")) {
/* dynamic forwarding */
host = NULL;
dports = NULL;
dport = -1;
dserv = 0;
type = 'D';
} else {
/* ordinary forwarding */
vp = val;
vp2 = vp + host_strcspn(vp, ":");
host = dupprintf("%.*s", (int)(vp2 - vp), vp);
if (*vp2)
vp2++;
dports = vp2;
dport = atoi(dports);
dserv = 0;
if (dport == 0) {
dserv = 1;
dport = net_service_lookup(dports);
if (!dport) {
logeventf(ssh, "Service lookup failed for destination"
" port \"%s\"", dports);
}
}
}
if (sport && dport) {
/* Set up a description of the source port. */
struct ssh_portfwd *pfrec, *epfrec;
pfrec = snew(struct ssh_portfwd);
pfrec->type = type;
pfrec->saddr = saddr;
pfrec->sserv = sserv ? dupstr(sports) : NULL;
pfrec->sport = sport;
pfrec->daddr = host;
pfrec->dserv = dserv ? dupstr(dports) : NULL;
pfrec->dport = dport;
pfrec->local = NULL;
pfrec->remote = NULL;
pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
address_family == '6' ? ADDRTYPE_IPV6 :
ADDRTYPE_UNSPEC);
epfrec = add234(ssh->portfwds, pfrec);
if (epfrec != pfrec) {
if (epfrec->status == DESTROY) {
/*
* We already have a port forwarding up and running
* with precisely these parameters. Hence, no need
* to do anything; simply re-tag the existing one
* as KEEP.
*/
epfrec->status = KEEP;
}
/*
* Anything else indicates that there was a duplicate
* in our input, which we'll silently ignore.
*/
free_portfwd(pfrec);
} else {
pfrec->status = CREATE;
}
} else {
sfree(saddr);
sfree(host);
}
}
/*
* Now go through and destroy any port forwardings which were
* not re-enabled.
*/
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
if (epf->status == DESTROY) {
char *message;
message = dupprintf("%s port forwarding from %s%s%d",
epf->type == 'L' ? "local" :
epf->type == 'R' ? "remote" : "dynamic",
epf->saddr ? epf->saddr : "",
epf->saddr ? ":" : "",
epf->sport);
if (epf->type != 'D') {
char *msg2 = dupprintf("%s to %s:%d", message,
epf->daddr, epf->dport);
sfree(message);
message = msg2;
}
logeventf(ssh, "Cancelling %s", message);
sfree(message);
/* epf->remote or epf->local may be NULL if setting up a
* forwarding failed. */
if (epf->remote) {
struct ssh_rportfwd *rpf = epf->remote;
struct Packet *pktout;
/*
* Cancel the port forwarding at the server
* end.
*/
if (ssh->version == 1) {
/*
* We cannot cancel listening ports on the
* server side in SSH-1! There's no message
* to support it. Instead, we simply remove
* the rportfwd record from the local end
* so that any connections the server tries
* to make on it are rejected.
*/
} else {
pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
if (epf->saddr) {
ssh2_pkt_addstring(pktout, epf->saddr);
} else if (conf_get_int(conf, CONF_rport_acceptall)) {
/* XXX: rport_acceptall may not represent
* what was used to open the original connection,
* since it's reconfigurable. */
ssh2_pkt_addstring(pktout, "");
} else {
ssh2_pkt_addstring(pktout, "localhost");
}
ssh2_pkt_adduint32(pktout, epf->sport);
ssh2_pkt_send(ssh, pktout);
}
del234(ssh->rportfwds, rpf);
free_rportfwd(rpf);
} else if (epf->local) {
pfl_terminate(epf->local);
}
delpos234(ssh->portfwds, i);
free_portfwd(epf);
i--; /* so we don't skip one in the list */
}
/*
* And finally, set up any new port forwardings (status==CREATE).
*/
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
if (epf->status == CREATE) {
char *sportdesc, *dportdesc;
sportdesc = dupprintf("%s%s%s%s%d%s",
epf->saddr ? epf->saddr : "",
epf->saddr ? ":" : "",
epf->sserv ? epf->sserv : "",
epf->sserv ? "(" : "",
epf->sport,
epf->sserv ? ")" : "");
if (epf->type == 'D') {
dportdesc = NULL;
} else {
dportdesc = dupprintf("%s:%s%s%d%s",
epf->daddr,
epf->dserv ? epf->dserv : "",
epf->dserv ? "(" : "",
epf->dport,
epf->dserv ? ")" : "");
}
if (epf->type == 'L') {
char *err = pfl_listen(epf->daddr, epf->dport,
epf->saddr, epf->sport,
ssh, conf, &epf->local,
epf->addressfamily);
logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
sportdesc, dportdesc,
err ? " failed: " : "", err ? err : "");
if (err)
sfree(err);
} else if (epf->type == 'D') {
char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
ssh, conf, &epf->local,
epf->addressfamily);
logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
sportdesc,
err ? " failed: " : "", err ? err : "");
if (err)
sfree(err);
} else {
struct ssh_rportfwd *pf;
/*
* Ensure the remote port forwardings tree exists.
*/
if (!ssh->rportfwds) {
if (ssh->version == 1)
ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
else
ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
}
pf = snew(struct ssh_rportfwd);
pf->share_ctx = NULL;
pf->dhost = dupstr(epf->daddr);
pf->dport = epf->dport;
if (epf->saddr) {
pf->shost = dupstr(epf->saddr);
} else if (conf_get_int(conf, CONF_rport_acceptall)) {
pf->shost = dupstr("");
} else {
pf->shost = dupstr("localhost");
}
pf->sport = epf->sport;
if (add234(ssh->rportfwds, pf) != pf) {
logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
epf->daddr, epf->dport);
sfree(pf);
} else {
logeventf(ssh, "Requesting remote port %s"
" forward to %s", sportdesc, dportdesc);
pf->sportdesc = sportdesc;
sportdesc = NULL;
epf->remote = pf;
pf->pfrec = epf;
if (ssh->version == 1) {
send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
PKT_INT, epf->sport,
PKT_STR, epf->daddr,
PKT_INT, epf->dport,
PKT_END);
ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
SSH1_SMSG_FAILURE,
ssh_rportfwd_succfail, pf);
} else {
struct Packet *pktout;
pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
ssh2_pkt_addstring(pktout, "tcpip-forward");
ssh2_pkt_addbool(pktout, 1);/* want reply */
ssh2_pkt_addstring(pktout, pf->shost);
ssh2_pkt_adduint32(pktout, pf->sport);
ssh2_pkt_send(ssh, pktout);
ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
SSH2_MSG_REQUEST_FAILURE,
ssh_rportfwd_succfail, pf);
}
}
}
sfree(sportdesc);
sfree(dportdesc);
}
}
static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
{
char *string;
int stringlen, bufsize;
ssh_pkt_getstring(pktin, &string, &stringlen);
if (string == NULL) {
bombout(("Incoming terminal data packet was badly formed"));
return;
}
bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
string, stringlen);
if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
ssh->v1_stdout_throttling = 1;
ssh_throttle_conn(ssh, +1);
}
}
static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to our
* X-Server. Give them back a local channel number. */
struct ssh_channel *c;
int remoteid = ssh_pkt_getuint32(pktin);
logevent("Received X11 connect request");
/* Refuse if X11 forwarding is disabled. */
if (!ssh->X11_fwd_enabled) {
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
logevent("Rejected X11 connect request");
} else {
c = snew(struct ssh_channel);
c->ssh = ssh;
ssh_channel_init(c);
c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_X11; /* identify channel type */
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT,
c->localid, PKT_END);
logevent("Opened X11 forward channel");
}
}
static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to our
* agent. Give them back a local channel number. */
struct ssh_channel *c;
int remoteid = ssh_pkt_getuint32(pktin);
/* Refuse if agent forwarding is disabled. */
if (!ssh->agentfwd_enabled) {
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
c = snew(struct ssh_channel);
c->ssh = ssh;
ssh_channel_init(c);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_AGENT; /* identify channel type */
c->u.a.lensofar = 0;
c->u.a.message = NULL;
c->u.a.pending = NULL;
c->u.a.outstanding_requests = 0;
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT, c->localid,
PKT_END);
}
}
static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to a
* forwarded port. Give them back a local channel number. */
struct ssh_rportfwd pf, *pfp;
int remoteid;
int hostsize, port;
char *host;
char *err;
remoteid = ssh_pkt_getuint32(pktin);
ssh_pkt_getstring(pktin, &host, &hostsize);
port = ssh_pkt_getuint32(pktin);
pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
pf.dport = port;
pfp = find234(ssh->rportfwds, &pf, NULL);
if (pfp == NULL) {
logeventf(ssh, "Rejected remote port open request for %s:%d",
pf.dhost, port);
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
struct ssh_channel *c = snew(struct ssh_channel);
c->ssh = ssh;
logeventf(ssh, "Received remote port open request for %s:%d",
pf.dhost, port);
err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
c, ssh->conf, pfp->pfrec->addressfamily);
if (err != NULL) {
logeventf(ssh, "Port open failed: %s", err);
sfree(err);
sfree(c);
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
ssh_channel_init(c);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_SOCKDATA; /* identify channel type */
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT,
c->localid, PKT_END);
logevent("Forwarded port opened successfully");
}
}
sfree(pf.dhost);
}
static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
{
struct ssh_channel *c;
c = ssh_channel_msg(ssh, pktin);
if (c && c->type == CHAN_SOCKDATA) {
c->remoteid = ssh_pkt_getuint32(pktin);
c->halfopen = FALSE;
c->throttling_conn = 0;
pfd_confirm(c->u.pfd.pf);
}
if (c && c->pending_eof) {
/*
* We have a pending close on this channel,
* which we decided on before the server acked
* the channel open. So now we know the
* remoteid, we can close it again.
*/
ssh_channel_try_eof(c);
}
}
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_AGENT; /* identify channel type */
c->u.a.pending = NULL;
bufchain_init(&c->u.a.inbuffer);
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT, c->localid,
PKT_END);
del234(ssh->channels, c);
sfree(c);
}
}
|
CVE-2017-6542
|
The ssh_agent_channel_data function in PuTTY before 0.68 allows remote attackers to have unspecified impact via a large length value in an agent protocol message and leveraging the ability to connect to the Unix-domain socket representing the forwarded agent connection, which trigger a buffer overflow.
|
[
"CWE-119"
] |
[
{
"line_no": 22,
"text": " /* Agent channels require no buffer management. */",
"char_start": null,
"char_end": null
},
{
"line_no": 64,
"text": "static void ssh_agentf_callback(void *cv, void *reply, int replylen)",
"char_start": null,
"char_end": null
},
{
"line_no": 66,
"text": " struct ssh_channel *c = (struct ssh_channel *)cv;",
"char_start": null,
"char_end": null
},
{
"line_no": 67,
"text": " const void *sentreply = reply;",
"char_start": null,
"char_end": null
},
{
"line_no": 69,
"text": " c->u.a.outstanding_requests--;",
"char_start": null,
"char_end": null
},
{
"line_no": 70,
"text": " if (!sentreply) {",
"char_start": null,
"char_end": null
},
{
"line_no": 71,
"text": " /* Fake SSH_AGENT_FAILURE. */",
"char_start": null,
"char_end": null
},
{
"line_no": 72,
"text": " sentreply = \"\\0\\0\\0\\1\\5\";",
"char_start": null,
"char_end": null
},
{
"line_no": 75,
"text": " ssh_send_channel_data(c, sentreply, replylen);",
"char_start": null,
"char_end": null
},
{
"line_no": 76,
"text": " if (reply)",
"char_start": null,
"char_end": null
},
{
"line_no": 77,
"text": " sfree(reply);",
"char_start": null,
"char_end": null
},
{
"line_no": 79,
"text": " * If we've already seen an incoming EOF but haven't sent an",
"char_start": null,
"char_end": null
},
{
"line_no": 80,
"text": " * outgoing one, this may be the moment to send it.",
"char_start": null,
"char_end": null
},
{
"line_no": 82,
"text": " if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))",
"char_start": null,
"char_end": null
},
{
"line_no": 1768,
"text": " c->u.a.lensofar = 0;",
"char_start": null,
"char_end": null
},
{
"line_no": 1769,
"text": " c->u.a.message = NULL;",
"char_start": null,
"char_end": null
},
{
"line_no": 1771,
"text": " c->u.a.outstanding_requests = 0;",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 22,
"text": " /* Agent forwarding channels are buffer-managed by",
"char_start": null,
"char_end": null
},
{
"line_no": 23,
"text": " * checking ssh->throttled_all in ssh_agentf_try_forward.",
"char_start": null,
"char_end": null
},
{
"line_no": 24,
"text": " * So at the moment we _un_throttle again, we must make an",
"char_start": null,
"char_end": null
},
{
"line_no": 25,
"text": " * attempt to do something. */",
"char_start": null,
"char_end": null
},
{
"line_no": 26,
"text": " if (!enable)",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " ssh_agentf_try_forward(c);",
"char_start": null,
"char_end": null
},
{
"line_no": 69,
"text": "static void ssh_agentf_got_response(struct ssh_channel *c,",
"char_start": null,
"char_end": null
},
{
"line_no": 70,
"text": " void *reply, int replylen)",
"char_start": null,
"char_end": null
},
{
"line_no": 73,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 74,
"text": " if (!reply) {",
"char_start": null,
"char_end": null
},
{
"line_no": 75,
"text": " /* The real agent didn't send any kind of reply at all for",
"char_start": null,
"char_end": null
},
{
"line_no": 76,
"text": " * some reason, so fake an SSH_AGENT_FAILURE. */",
"char_start": null,
"char_end": null
},
{
"line_no": 77,
"text": " reply = \"\\0\\0\\0\\1\\5\";",
"char_start": null,
"char_end": null
},
{
"line_no": 80,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 81,
"text": " ssh_send_channel_data(c, reply, replylen);",
"char_start": null,
"char_end": null
},
{
"line_no": 82,
"text": "}",
"char_start": null,
"char_end": null
},
{
"line_no": 83,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 84,
"text": "static void ssh_agentf_callback(void *cv, void *reply, int replylen);",
"char_start": null,
"char_end": null
},
{
"line_no": 85,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 86,
"text": "static void ssh_agentf_try_forward(struct ssh_channel *c)",
"char_start": null,
"char_end": null
},
{
"line_no": 87,
"text": "{",
"char_start": null,
"char_end": null
},
{
"line_no": 88,
"text": " unsigned datalen, lengthfield, messagelen;",
"char_start": null,
"char_end": null
},
{
"line_no": 89,
"text": " unsigned char *message;",
"char_start": null,
"char_end": null
},
{
"line_no": 90,
"text": " unsigned char msglen[4];",
"char_start": null,
"char_end": null
},
{
"line_no": 91,
"text": " void *reply;",
"char_start": null,
"char_end": null
},
{
"line_no": 92,
"text": " int replylen;",
"char_start": null,
"char_end": null
},
{
"line_no": 93,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 95,
"text": " * Don't try to parallelise agent requests. Wait for each one to",
"char_start": null,
"char_end": null
},
{
"line_no": 96,
"text": " * return before attempting the next.",
"char_start": null,
"char_end": null
},
{
"line_no": 98,
"text": " if (c->u.a.pending)",
"char_start": null,
"char_end": null
},
{
"line_no": 99,
"text": " return;",
"char_start": null,
"char_end": null
},
{
"line_no": 100,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 101,
"text": " /*",
"char_start": null,
"char_end": null
},
{
"line_no": 102,
"text": " * If the outgoing side of the channel connection is currently",
"char_start": null,
"char_end": null
},
{
"line_no": 103,
"text": " * throttled (for any reason, either that channel's window size or",
"char_start": null,
"char_end": null
},
{
"line_no": 104,
"text": " * the entire SSH connection being throttled), don't submit any",
"char_start": null,
"char_end": null
},
{
"line_no": 105,
"text": " * new forwarded requests to the real agent. This causes the input",
"char_start": null,
"char_end": null
},
{
"line_no": 106,
"text": " * side of the agent forwarding not to be emptied, exerting the",
"char_start": null,
"char_end": null
},
{
"line_no": 107,
"text": " * required back-pressure on the remote client, and encouraging it",
"char_start": null,
"char_end": null
},
{
"line_no": 108,
"text": " * to read our responses before sending too many more requests.",
"char_start": null,
"char_end": null
},
{
"line_no": 109,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 110,
"text": " if (c->ssh->throttled_all ||",
"char_start": null,
"char_end": null
},
{
"line_no": 111,
"text": " (c->ssh->version == 2 && c->v.v2.remwindow == 0))",
"char_start": null,
"char_end": null
},
{
"line_no": 112,
"text": " return;",
"char_start": null,
"char_end": null
},
{
"line_no": 113,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 114,
"text": " while (1) {",
"char_start": null,
"char_end": null
},
{
"line_no": 115,
"text": " /*",
"char_start": null,
"char_end": null
},
{
"line_no": 116,
"text": " * Try to extract a complete message from the input buffer.",
"char_start": null,
"char_end": null
},
{
"line_no": 117,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 118,
"text": " datalen = bufchain_size(&c->u.a.inbuffer);",
"char_start": null,
"char_end": null
},
{
"line_no": 119,
"text": " if (datalen < 4)",
"char_start": null,
"char_end": null
},
{
"line_no": 120,
"text": " break; /* not even a length field available yet */",
"char_start": null,
"char_end": null
},
{
"line_no": 121,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 122,
"text": " bufchain_fetch(&c->u.a.inbuffer, msglen, 4);",
"char_start": null,
"char_end": null
},
{
"line_no": 123,
"text": " lengthfield = GET_32BIT(msglen);",
"char_start": null,
"char_end": null
},
{
"line_no": 124,
"text": " if (lengthfield > datalen - 4)",
"char_start": null,
"char_end": null
},
{
"line_no": 125,
"text": " break; /* a whole message is not yet available */",
"char_start": null,
"char_end": null
},
{
"line_no": 126,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 127,
"text": " messagelen = lengthfield + 4;",
"char_start": null,
"char_end": null
},
{
"line_no": 128,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 129,
"text": " message = snewn(messagelen, unsigned char);",
"char_start": null,
"char_end": null
},
{
"line_no": 130,
"text": " bufchain_fetch(&c->u.a.inbuffer, message, messagelen);",
"char_start": null,
"char_end": null
},
{
"line_no": 131,
"text": " bufchain_consume(&c->u.a.inbuffer, messagelen);",
"char_start": null,
"char_end": null
},
{
"line_no": 132,
"text": " c->u.a.pending = agent_query(",
"char_start": null,
"char_end": null
},
{
"line_no": 133,
"text": " message, messagelen, &reply, &replylen, ssh_agentf_callback, c);",
"char_start": null,
"char_end": null
},
{
"line_no": 134,
"text": " sfree(message);",
"char_start": null,
"char_end": null
},
{
"line_no": 135,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 136,
"text": " if (c->u.a.pending)",
"char_start": null,
"char_end": null
},
{
"line_no": 137,
"text": " return; /* agent_query promised to reply in due course */",
"char_start": null,
"char_end": null
},
{
"line_no": 138,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 139,
"text": " /*",
"char_start": null,
"char_end": null
},
{
"line_no": 140,
"text": " * If the agent gave us an answer immediately, pass it",
"char_start": null,
"char_end": null
},
{
"line_no": 141,
"text": " * straight on and go round this loop again.",
"char_start": null,
"char_end": null
},
{
"line_no": 142,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 143,
"text": " ssh_agentf_got_response(c, reply, replylen);",
"char_start": null,
"char_end": null
},
{
"line_no": 144,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 145,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 146,
"text": " /*",
"char_start": null,
"char_end": null
},
{
"line_no": 147,
"text": " * If we get here (i.e. we left the above while loop via 'break'",
"char_start": null,
"char_end": null
},
{
"line_no": 148,
"text": " * rather than 'return'), that means we've determined that the",
"char_start": null,
"char_end": null
},
{
"line_no": 149,
"text": " * input buffer for the agent forwarding connection doesn't",
"char_start": null,
"char_end": null
},
{
"line_no": 150,
"text": " * contain a complete request.",
"char_start": null,
"char_end": null
},
{
"line_no": 151,
"text": " *",
"char_start": null,
"char_end": null
},
{
"line_no": 152,
"text": " * So if there's potentially more data to come, we can return now,",
"char_start": null,
"char_end": null
},
{
"line_no": 153,
"text": " * and wait for the remote client to send it. But if the remote",
"char_start": null,
"char_end": null
},
{
"line_no": 154,
"text": " * has sent EOF, it would be a mistake to do that, because we'd be",
"char_start": null,
"char_end": null
},
{
"line_no": 155,
"text": " * waiting a long time. So this is the moment to check for EOF,",
"char_start": null,
"char_end": null
},
{
"line_no": 156,
"text": " * and respond appropriately.",
"char_start": null,
"char_end": null
},
{
"line_no": 157,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 158,
"text": " if (c->closes & CLOSES_RCVD_EOF)",
"char_start": null,
"char_end": null
},
{
"line_no": 162,
"text": "static void ssh_agentf_callback(void *cv, void *reply, int replylen)",
"char_start": null,
"char_end": null
},
{
"line_no": 163,
"text": "{",
"char_start": null,
"char_end": null
},
{
"line_no": 164,
"text": " struct ssh_channel *c = (struct ssh_channel *)cv;",
"char_start": null,
"char_end": null
},
{
"line_no": 165,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 166,
"text": " ssh_agentf_got_response(c, reply, replylen);",
"char_start": null,
"char_end": null
},
{
"line_no": 167,
"text": " sfree(reply);",
"char_start": null,
"char_end": null
},
{
"line_no": 168,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 169,
"text": " /*",
"char_start": null,
"char_end": null
},
{
"line_no": 170,
"text": " * Now try to extract and send further messages from the channel's",
"char_start": null,
"char_end": null
},
{
"line_no": 171,
"text": " * input-side buffer.",
"char_start": null,
"char_end": null
},
{
"line_no": 172,
"text": " */",
"char_start": null,
"char_end": null
},
{
"line_no": 173,
"text": " ssh_agentf_try_forward(c);",
"char_start": null,
"char_end": null
},
{
"line_no": 174,
"text": "}",
"char_start": null,
"char_end": null
},
{
"line_no": 175,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 1859,
"text": " bufchain_init(&c->u.a.inbuffer);",
"char_start": null,
"char_end": null
}
] | 233
|
primevul
|
primevul_openssl_6e629b5be45face20b4ca71c4fcbfed78b864a2e
|
6e629b5be45face20b4ca71c4fcbfed78b864a2e
|
openssl
|
https://github.com/openssl/openssl
|
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
X509 **pissuer, int *pscore, unsigned int *preasons,
STACK_OF(X509_CRL) *crls)
{
int i, crl_score, best_score = *pscore;
unsigned int reasons, best_reasons = 0;
X509 *x = ctx->current_cert;
X509_CRL *crl, *best_crl = NULL;
X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
reasons = *preasons;
crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
if (crl_score < best_score)
continue;
/* If current CRL is equivalent use it if it is newer */
if (crl_score == best_score) {
int day, sec;
if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl),
X509_CRL_get_lastUpdate(crl)) == 0)
continue;
/*
* ASN1_TIME_diff never returns inconsistent signs for |day|
* and |sec|.
*/
if (day <= 0 && sec <= 0)
continue;
}
best_crl = crl;
best_crl_issuer = crl_issuer;
best_score = crl_score;
best_reasons = reasons;
}
if (best_crl) {
if (*pcrl)
X509_CRL_free(*pcrl);
*pcrl = best_crl;
*pissuer = best_crl_issuer;
*pscore = best_score;
*preasons = best_reasons;
CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
if (*pdcrl) {
X509_CRL_free(*pdcrl);
*pdcrl = NULL;
}
get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
}
if (best_score >= CRL_SCORE_VALID)
return 1;
return 0;
}
|
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
X509 **pissuer, int *pscore, unsigned int *preasons,
STACK_OF(X509_CRL) *crls)
{
int i, crl_score, best_score = *pscore;
unsigned int reasons, best_reasons = 0;
X509 *x = ctx->current_cert;
X509_CRL *crl, *best_crl = NULL;
X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
reasons = *preasons;
crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
if (crl_score < best_score || crl_score == 0)
continue;
/* If current CRL is equivalent use it if it is newer */
if (crl_score == best_score && best_crl != NULL) {
int day, sec;
if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl),
X509_CRL_get_lastUpdate(crl)) == 0)
continue;
/*
* ASN1_TIME_diff never returns inconsistent signs for |day|
* and |sec|.
*/
if (day <= 0 && sec <= 0)
continue;
}
best_crl = crl;
best_crl_issuer = crl_issuer;
best_score = crl_score;
best_reasons = reasons;
}
if (best_crl) {
if (*pcrl)
X509_CRL_free(*pcrl);
*pcrl = best_crl;
*pissuer = best_crl_issuer;
*pscore = best_score;
*preasons = best_reasons;
CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
if (*pdcrl) {
X509_CRL_free(*pdcrl);
*pdcrl = NULL;
}
get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
}
if (best_score >= CRL_SCORE_VALID)
return 1;
return 0;
}
|
CVE-2016-7052
|
crypto/x509/x509_vfy.c in OpenSSL 1.0.2i allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) by triggering a CRL operation.
|
[
"CWE-476"
] |
[
{
"line_no": 15,
"text": " if (crl_score < best_score)",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " if (crl_score == best_score) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 15,
"text": " if (crl_score < best_score || crl_score == 0)",
"char_start": null,
"char_end": null
},
{
"line_no": 18,
"text": " if (crl_score == best_score && best_crl != NULL) {",
"char_start": null,
"char_end": null
}
] | 234
|
primevul
|
primevul_spice_9113dc6a303604a2d9812ac70c17d076ef11886c
|
9113dc6a303604a2d9812ac70c17d076ef11886c
|
spice
|
https://gitlab.freedesktop.org/spice/spice
|
vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
|
vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
vcard_apdu_delete(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
|
CVE-2017-6414
|
Memory leak in the vcard_apdu_new function in card_7816.c in libcacard before 2.5.3 allows local guest OS users to cause a denial of service (host memory consumption) via vectors related to allocating a new APDU object.
|
[
"CWE-772"
] |
[
{
"line_no": 16,
"text": " g_free(new_apdu);",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " g_free(new_apdu);",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 16,
"text": " vcard_apdu_delete(new_apdu);",
"char_start": null,
"char_end": null
},
{
"line_no": 21,
"text": " vcard_apdu_delete(new_apdu);",
"char_start": null,
"char_end": null
}
] | 235
|
primevul
|
primevul_virglrenderer_93761787b29f37fa627dea9082cdfc1a1ec608d6
|
93761787b29f37fa627dea9082cdfc1a1ec608d6
|
virglrenderer
|
https://gitlab.freedesktop.org/virgl/virglrenderer
|
int vrend_create_shader(struct vrend_context *ctx,
uint32_t handle,
const struct pipe_stream_output_info *so_info,
const char *shd_text, uint32_t offlen, uint32_t num_tokens,
uint32_t type, uint32_t pkt_length)
{
struct vrend_shader_selector *sel = NULL;
int ret_handle;
bool new_shader = true, long_shader = false;
bool finished = false;
int ret;
if (type > PIPE_SHADER_GEOMETRY)
return EINVAL;
if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT)
new_shader = false;
else if (((offlen + 3) / 4) > pkt_length)
long_shader = true;
/* if we have an in progress one - don't allow a new shader
of that type or a different handle. */
if (ctx->sub->long_shader_in_progress_handle[type]) {
if (new_shader == true)
return EINVAL;
if (handle != ctx->sub->long_shader_in_progress_handle[type])
return EINVAL;
}
if (new_shader) {
sel = vrend_create_shader_state(ctx, so_info, type);
if (sel == NULL)
return ENOMEM;
if (long_shader) {
sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */
sel->tmp_buf = malloc(sel->buf_len);
if (!sel->tmp_buf) {
ret = ENOMEM;
goto error;
}
memcpy(sel->tmp_buf, shd_text, pkt_length * 4);
sel->buf_offset = pkt_length * 4;
ctx->sub->long_shader_in_progress_handle[type] = handle;
} else
finished = true;
} else {
sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER);
if (!sel) {
fprintf(stderr, "got continuation without original shader %d\n", handle);
ret = EINVAL;
goto error;
}
offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT;
if (offlen != sel->buf_offset) {
fprintf(stderr, "Got mismatched shader continuation %d vs %d\n",
offlen, sel->buf_offset);
ret = EINVAL;
goto error;
}
if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) {
fprintf(stderr, "Got too large shader continuation %d vs %d\n",
pkt_length * 4 + sel->buf_offset, sel->buf_len);
shd_text = sel->tmp_buf;
}
}
if (finished) {
struct tgsi_token *tokens;
tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token));
if (!tokens) {
ret = ENOMEM;
goto error;
}
if (vrend_dump_shaders)
fprintf(stderr,"shader\n%s\n", shd_text);
if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) {
free(tokens);
ret = EINVAL;
goto error;
}
if (vrend_finish_shader(ctx, sel, tokens)) {
free(tokens);
ret = EINVAL;
goto error;
} else {
free(sel->tmp_buf);
sel->tmp_buf = NULL;
}
free(tokens);
ctx->sub->long_shader_in_progress_handle[type] = 0;
}
if (new_shader) {
ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER);
if (ret_handle == 0) {
ret = ENOMEM;
goto error;
}
}
return 0;
error:
if (new_shader)
vrend_destroy_shader_selector(sel);
else
vrend_renderer_object_destroy(ctx, handle);
return ret;
}
|
int vrend_create_shader(struct vrend_context *ctx,
uint32_t handle,
const struct pipe_stream_output_info *so_info,
const char *shd_text, uint32_t offlen, uint32_t num_tokens,
uint32_t type, uint32_t pkt_length)
{
struct vrend_shader_selector *sel = NULL;
int ret_handle;
bool new_shader = true, long_shader = false;
bool finished = false;
int ret;
if (type > PIPE_SHADER_GEOMETRY)
return EINVAL;
if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT)
new_shader = false;
else if (((offlen + 3) / 4) > pkt_length)
long_shader = true;
/* if we have an in progress one - don't allow a new shader
of that type or a different handle. */
if (ctx->sub->long_shader_in_progress_handle[type]) {
if (new_shader == true)
return EINVAL;
if (handle != ctx->sub->long_shader_in_progress_handle[type])
return EINVAL;
}
if (new_shader) {
sel = vrend_create_shader_state(ctx, so_info, type);
if (sel == NULL)
return ENOMEM;
if (long_shader) {
sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */
sel->tmp_buf = malloc(sel->buf_len);
if (!sel->tmp_buf) {
ret = ENOMEM;
goto error;
}
memcpy(sel->tmp_buf, shd_text, pkt_length * 4);
sel->buf_offset = pkt_length * 4;
ctx->sub->long_shader_in_progress_handle[type] = handle;
} else
finished = true;
} else {
sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER);
if (!sel) {
fprintf(stderr, "got continuation without original shader %d\n", handle);
ret = EINVAL;
goto error;
}
offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT;
if (offlen != sel->buf_offset) {
fprintf(stderr, "Got mismatched shader continuation %d vs %d\n",
offlen, sel->buf_offset);
ret = EINVAL;
goto error;
}
/*make sure no overflow */
if (pkt_length * 4 < pkt_length ||
pkt_length * 4 + sel->buf_offset < pkt_length * 4 ||
pkt_length * 4 + sel->buf_offset < sel->buf_offset) {
ret = EINVAL;
goto error;
}
if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) {
fprintf(stderr, "Got too large shader continuation %d vs %d\n",
pkt_length * 4 + sel->buf_offset, sel->buf_len);
shd_text = sel->tmp_buf;
}
}
if (finished) {
struct tgsi_token *tokens;
tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token));
if (!tokens) {
ret = ENOMEM;
goto error;
}
if (vrend_dump_shaders)
fprintf(stderr,"shader\n%s\n", shd_text);
if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) {
free(tokens);
ret = EINVAL;
goto error;
}
if (vrend_finish_shader(ctx, sel, tokens)) {
free(tokens);
ret = EINVAL;
goto error;
} else {
free(sel->tmp_buf);
sel->tmp_buf = NULL;
}
free(tokens);
ctx->sub->long_shader_in_progress_handle[type] = 0;
}
if (new_shader) {
ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER);
if (ret_handle == 0) {
ret = ENOMEM;
goto error;
}
}
return 0;
error:
if (new_shader)
vrend_destroy_shader_selector(sel);
else
vrend_renderer_object_destroy(ctx, handle);
return ret;
}
|
CVE-2017-6355
|
Integer overflow in the vrend_create_shader function in vrend_renderer.c in virglrenderer before 0.6.0 allows local guest OS users to cause a denial of service (process crash) via crafted pkt_length and offlen values, which trigger an out-of-bounds access.
|
[
"CWE-190"
] |
[] |
[
{
"line_no": 62,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 63,
"text": " /*make sure no overflow */",
"char_start": null,
"char_end": null
},
{
"line_no": 64,
"text": " if (pkt_length * 4 < pkt_length ||",
"char_start": null,
"char_end": null
},
{
"line_no": 65,
"text": " pkt_length * 4 + sel->buf_offset < pkt_length * 4 ||",
"char_start": null,
"char_end": null
},
{
"line_no": 66,
"text": " pkt_length * 4 + sel->buf_offset < sel->buf_offset) {",
"char_start": null,
"char_end": null
},
{
"line_no": 67,
"text": " ret = EINVAL;",
"char_start": null,
"char_end": null
},
{
"line_no": 68,
"text": " goto error;",
"char_start": null,
"char_end": null
},
{
"line_no": 69,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 70,
"text": "",
"char_start": null,
"char_end": null
}
] | 238
|
primevul
|
primevul_virglrenderer_a2f12a1b0f95b13b6f8dc3d05d7b74b4386394e4
|
a2f12a1b0f95b13b6f8dc3d05d7b74b4386394e4
|
virglrenderer
|
https://gitlab.freedesktop.org/virgl/virglrenderer
|
static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx,
struct vrend_shader *vs,
struct vrend_shader *fs,
struct vrend_shader *gs)
{
struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program);
char name[16];
int i;
GLuint prog_id;
GLint lret;
int id;
int last_shader;
if (!sprog)
return NULL;
/* need to rewrite VS code to add interpolation params */
if ((gs && gs->compiled_fs_id != fs->id) ||
(!gs && vs->compiled_fs_id != fs->id)) {
bool ret;
if (gs)
vrend_patch_vertex_shader_interpolants(gs->glsl_prog,
&gs->sel->sinfo,
&fs->sel->sinfo, true, fs->key.flatshade);
else
vrend_patch_vertex_shader_interpolants(vs->glsl_prog,
&vs->sel->sinfo,
&fs->sel->sinfo, false, fs->key.flatshade);
ret = vrend_compile_shader(ctx, gs ? gs : vs);
if (ret == false) {
glDeleteShader(gs ? gs->id : vs->id);
free(sprog);
return NULL;
}
if (gs)
gs->compiled_fs_id = fs->id;
else
vs->compiled_fs_id = fs->id;
}
prog_id = glCreateProgram();
glAttachShader(prog_id, vs->id);
if (gs) {
if (gs->id > 0)
glAttachShader(prog_id, gs->id);
set_stream_out_varyings(prog_id, &gs->sel->sinfo);
}
else
set_stream_out_varyings(prog_id, &vs->sel->sinfo);
glAttachShader(prog_id, fs->id);
if (fs->sel->sinfo.num_outputs > 1) {
if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1");
sprog->dual_src_linked = true;
} else {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1");
sprog->dual_src_linked = false;
}
} else
sprog->dual_src_linked = false;
if (vrend_state.have_vertex_attrib_binding) {
uint32_t mask = vs->sel->sinfo.attrib_input_mask;
while (mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "in_%d", i);
glBindAttribLocation(prog_id, i, name);
}
}
glLinkProgram(prog_id);
glGetProgramiv(prog_id, GL_LINK_STATUS, &lret);
if (lret == GL_FALSE) {
char infolog[65536];
int len;
glGetProgramInfoLog(prog_id, 65536, &len, infolog);
fprintf(stderr,"got error linking\n%s\n", infolog);
/* dump shaders */
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0);
fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog);
if (gs)
fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog);
fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog);
glDeleteProgram(prog_id);
return NULL;
}
sprog->ss[PIPE_SHADER_FRAGMENT] = fs;
sprog->ss[PIPE_SHADER_GEOMETRY] = gs;
list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs);
list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs);
if (gs)
list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs);
last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT;
sprog->id = prog_id;
list_addtail(&sprog->head, &ctx->sub->programs);
if (fs->key.pstipple_tex)
sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler");
else
sprog->fs_stipple_loc = -1;
sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust");
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.samplers_used_mask) {
uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask;
int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask);
int index;
sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask;
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) {
sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t));
sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t));
} else {
sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL;
}
sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t));
if (sprog->samp_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
index = 0;
while(mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "%ssamp%d", prefix, i);
sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name);
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) {
snprintf(name, 14, "%sshadmask%d", prefix, i);
sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name);
snprintf(name, 14, "%sshadadd%d", prefix, i);
sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name);
}
index++;
}
}
} else {
sprog->samp_locs[id] = NULL;
sprog->shadow_samp_mask_locs[id] = NULL;
sprog->shadow_samp_add_locs[id] = NULL;
sprog->shadow_samp_mask[id] = 0;
}
sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_consts) {
sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t));
if (sprog->const_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) {
snprintf(name, 16, "%sconst0[%d]", prefix, i);
sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name);
}
}
} else
sprog->const_locs[id] = NULL;
}
if (!vrend_state.have_vertex_attrib_binding) {
if (vs->sel->sinfo.num_inputs) {
sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t));
if (sprog->attrib_locs) {
for (i = 0; i < vs->sel->sinfo.num_inputs; i++) {
snprintf(name, 10, "in_%d", i);
sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name);
}
}
} else
sprog->attrib_locs = NULL;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_ubos) {
const char *prefix = pipe_shader_to_prefix(id);
sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t));
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) {
snprintf(name, 16, "%subo%d", prefix, i + 1);
sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name);
}
} else
sprog->ubo_locs[id] = NULL;
}
if (vs->sel->sinfo.num_ucp) {
for (i = 0; i < vs->sel->sinfo.num_ucp; i++) {
snprintf(name, 10, "clipp[%d]", i);
sprog->clip_locs[i] = glGetUniformLocation(prog_id, name);
}
}
return sprog;
}
|
static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx,
struct vrend_shader *vs,
struct vrend_shader *fs,
struct vrend_shader *gs)
{
struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program);
char name[16];
int i;
GLuint prog_id;
GLint lret;
int id;
int last_shader;
if (!sprog)
return NULL;
/* need to rewrite VS code to add interpolation params */
if ((gs && gs->compiled_fs_id != fs->id) ||
(!gs && vs->compiled_fs_id != fs->id)) {
bool ret;
if (gs)
vrend_patch_vertex_shader_interpolants(gs->glsl_prog,
&gs->sel->sinfo,
&fs->sel->sinfo, true, fs->key.flatshade);
else
vrend_patch_vertex_shader_interpolants(vs->glsl_prog,
&vs->sel->sinfo,
&fs->sel->sinfo, false, fs->key.flatshade);
ret = vrend_compile_shader(ctx, gs ? gs : vs);
if (ret == false) {
glDeleteShader(gs ? gs->id : vs->id);
free(sprog);
return NULL;
}
if (gs)
gs->compiled_fs_id = fs->id;
else
vs->compiled_fs_id = fs->id;
}
prog_id = glCreateProgram();
glAttachShader(prog_id, vs->id);
if (gs) {
if (gs->id > 0)
glAttachShader(prog_id, gs->id);
set_stream_out_varyings(prog_id, &gs->sel->sinfo);
}
else
set_stream_out_varyings(prog_id, &vs->sel->sinfo);
glAttachShader(prog_id, fs->id);
if (fs->sel->sinfo.num_outputs > 1) {
if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1");
sprog->dual_src_linked = true;
} else {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1");
sprog->dual_src_linked = false;
}
} else
sprog->dual_src_linked = false;
if (vrend_state.have_vertex_attrib_binding) {
uint32_t mask = vs->sel->sinfo.attrib_input_mask;
while (mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "in_%d", i);
glBindAttribLocation(prog_id, i, name);
}
}
glLinkProgram(prog_id);
glGetProgramiv(prog_id, GL_LINK_STATUS, &lret);
if (lret == GL_FALSE) {
char infolog[65536];
int len;
glGetProgramInfoLog(prog_id, 65536, &len, infolog);
fprintf(stderr,"got error linking\n%s\n", infolog);
/* dump shaders */
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0);
fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog);
if (gs)
fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog);
fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog);
glDeleteProgram(prog_id);
free(sprog);
return NULL;
}
sprog->ss[PIPE_SHADER_FRAGMENT] = fs;
sprog->ss[PIPE_SHADER_GEOMETRY] = gs;
list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs);
list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs);
if (gs)
list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs);
last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT;
sprog->id = prog_id;
list_addtail(&sprog->head, &ctx->sub->programs);
if (fs->key.pstipple_tex)
sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler");
else
sprog->fs_stipple_loc = -1;
sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust");
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.samplers_used_mask) {
uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask;
int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask);
int index;
sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask;
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) {
sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t));
sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t));
} else {
sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL;
}
sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t));
if (sprog->samp_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
index = 0;
while(mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "%ssamp%d", prefix, i);
sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name);
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) {
snprintf(name, 14, "%sshadmask%d", prefix, i);
sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name);
snprintf(name, 14, "%sshadadd%d", prefix, i);
sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name);
}
index++;
}
}
} else {
sprog->samp_locs[id] = NULL;
sprog->shadow_samp_mask_locs[id] = NULL;
sprog->shadow_samp_add_locs[id] = NULL;
sprog->shadow_samp_mask[id] = 0;
}
sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_consts) {
sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t));
if (sprog->const_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) {
snprintf(name, 16, "%sconst0[%d]", prefix, i);
sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name);
}
}
} else
sprog->const_locs[id] = NULL;
}
if (!vrend_state.have_vertex_attrib_binding) {
if (vs->sel->sinfo.num_inputs) {
sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t));
if (sprog->attrib_locs) {
for (i = 0; i < vs->sel->sinfo.num_inputs; i++) {
snprintf(name, 10, "in_%d", i);
sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name);
}
}
} else
sprog->attrib_locs = NULL;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_ubos) {
const char *prefix = pipe_shader_to_prefix(id);
sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t));
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) {
snprintf(name, 16, "%subo%d", prefix, i + 1);
sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name);
}
} else
sprog->ubo_locs[id] = NULL;
}
if (vs->sel->sinfo.num_ucp) {
for (i = 0; i < vs->sel->sinfo.num_ucp; i++) {
snprintf(name, 10, "clipp[%d]", i);
sprog->clip_locs[i] = glGetUniformLocation(prog_id, name);
}
}
return sprog;
}
|
CVE-2017-6317
|
Memory leak in the add_shader_program function in vrend_renderer.c in virglrenderer before 0.6.0 allows local guest OS users to cause a denial of service (host memory consumption) via vectors involving the sprog variable.
|
[
"CWE-772"
] |
[] |
[
{
"line_no": 89,
"text": " free(sprog);",
"char_start": null,
"char_end": null
}
] | 239
|
primevul
|
primevul_virglrenderer_0a5dff15912207b83018485f83e067474e818bab
|
0a5dff15912207b83018485f83e067474e818bab
|
virglrenderer
|
https://gitlab.freedesktop.org/virgl/virglrenderer
|
void vrend_renderer_context_destroy(uint32_t handle)
{
struct vrend_decode_ctx *ctx;
bool ret;
if (handle >= VREND_MAX_CTX)
return;
ctx = dec_ctx[handle];
if (!ctx)
return;
vrend_hw_switch_context(dec_ctx[0]->grctx, true);
}
|
void vrend_renderer_context_destroy(uint32_t handle)
{
struct vrend_decode_ctx *ctx;
bool ret;
if (handle >= VREND_MAX_CTX)
return;
/* never destroy context 0 here, it will be destroyed in vrend_decode_reset()*/
if (handle == 0) {
return;
}
ctx = dec_ctx[handle];
if (!ctx)
return;
vrend_hw_switch_context(dec_ctx[0]->grctx, true);
}
|
CVE-2017-6210
|
The vrend_decode_reset function in vrend_decode.c in virglrenderer before 0.6.0 allows local guest OS users to cause a denial of service (NULL pointer dereference and QEMU process crash) by destroying context 0 (zero).
|
[
"CWE-476"
] |
[] |
[
{
"line_no": 9,
"text": " /* never destroy context 0 here, it will be destroyed in vrend_decode_reset()*/",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " if (handle == 0) {",
"char_start": null,
"char_end": null
},
{
"line_no": 11,
"text": " return;",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 13,
"text": "",
"char_start": null,
"char_end": null
}
] | 240
|
primevul
|
primevul_virglrenderer_e534b51ca3c3cd25f3990589932a9ed711c59b27
|
e534b51ca3c3cd25f3990589932a9ed711c59b27
|
virglrenderer
|
https://gitlab.freedesktop.org/virgl/virglrenderer
|
static boolean parse_identifier( const char **pcur, char *ret )
{
const char *cur = *pcur;
int i = 0;
if (is_alpha_underscore( cur )) {
ret[i++] = *cur++;
while (is_alpha_underscore( cur ) || is_digit( cur ))
ret[i++] = *cur++;
ret[i++] = '\0';
*pcur = cur;
return TRUE;
/* Parse floating point.
*/
static boolean parse_float( const char **pcur, float *val )
{
const char *cur = *pcur;
boolean integral_part = FALSE;
boolean fractional_part = FALSE;
if (*cur == '0' && *(cur + 1) == 'x') {
union fi fi;
fi.ui = strtoul(cur, NULL, 16);
*val = fi.f;
cur += 10;
goto out;
}
*val = (float) atof( cur );
if (*cur == '-' || *cur == '+')
cur++;
if (is_digit( cur )) {
cur++;
integral_part = TRUE;
while (is_digit( cur ))
cur++;
}
if (*cur == '.') {
cur++;
if (is_digit( cur )) {
cur++;
fractional_part = TRUE;
while (is_digit( cur ))
cur++;
}
}
if (!integral_part && !fractional_part)
return FALSE;
if (uprcase( *cur ) == 'E') {
cur++;
if (*cur == '-' || *cur == '+')
cur++;
if (is_digit( cur )) {
cur++;
while (is_digit( cur ))
cur++;
}
else
return FALSE;
}
out:
*pcur = cur;
return TRUE;
}
static boolean parse_double( const char **pcur, uint32_t *val0, uint32_t *val1)
{
const char *cur = *pcur;
union {
double dval;
uint32_t uval[2];
} v;
v.dval = strtod(cur, (char**)pcur);
if (*pcur == cur)
return FALSE;
*val0 = v.uval[0];
*val1 = v.uval[1];
return TRUE;
}
struct translate_ctx
{
const char *text;
const char *cur;
struct tgsi_token *tokens;
struct tgsi_token *tokens_cur;
struct tgsi_token *tokens_end;
struct tgsi_header *header;
unsigned processor : 4;
unsigned implied_array_size : 6;
unsigned num_immediates;
};
static void report_error(struct translate_ctx *ctx, const char *format, ...)
{
va_list args;
int line = 1;
int column = 1;
const char *itr = ctx->text;
debug_printf("\nTGSI asm error: ");
va_start(args, format);
_debug_vprintf(format, args);
va_end(args);
while (itr != ctx->cur) {
if (*itr == '\n') {
column = 1;
++line;
}
++column;
++itr;
}
debug_printf(" [%d : %d] \n", line, column);
}
/* Parse shader header.
* Return TRUE for one of the following headers.
* FRAG
* GEOM
* VERT
*/
static boolean parse_header( struct translate_ctx *ctx )
{
uint processor;
if (str_match_nocase_whole( &ctx->cur, "FRAG" ))
processor = TGSI_PROCESSOR_FRAGMENT;
else if (str_match_nocase_whole( &ctx->cur, "VERT" ))
processor = TGSI_PROCESSOR_VERTEX;
else if (str_match_nocase_whole( &ctx->cur, "GEOM" ))
processor = TGSI_PROCESSOR_GEOMETRY;
else if (str_match_nocase_whole( &ctx->cur, "TESS_CTRL" ))
processor = TGSI_PROCESSOR_TESS_CTRL;
else if (str_match_nocase_whole( &ctx->cur, "TESS_EVAL" ))
processor = TGSI_PROCESSOR_TESS_EVAL;
else if (str_match_nocase_whole( &ctx->cur, "COMP" ))
processor = TGSI_PROCESSOR_COMPUTE;
else {
report_error( ctx, "Unknown header" );
return FALSE;
}
if (ctx->tokens_cur >= ctx->tokens_end)
return FALSE;
ctx->header = (struct tgsi_header *) ctx->tokens_cur++;
*ctx->header = tgsi_build_header();
if (ctx->tokens_cur >= ctx->tokens_end)
return FALSE;
*(struct tgsi_processor *) ctx->tokens_cur++ = tgsi_build_processor( processor, ctx->header );
ctx->processor = processor;
return TRUE;
}
static boolean parse_label( struct translate_ctx *ctx, uint *val )
{
const char *cur = ctx->cur;
if (parse_uint( &cur, val )) {
eat_opt_white( &cur );
if (*cur == ':') {
cur++;
ctx->cur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_file( const char **pcur, uint *file )
{
uint i;
for (i = 0; i < TGSI_FILE_COUNT; i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_file_name(i) )) {
*pcur = cur;
*file = i;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_opt_writemask(
struct translate_ctx *ctx,
uint *writemask )
{
const char *cur;
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == '.') {
cur++;
*writemask = TGSI_WRITEMASK_NONE;
eat_opt_white( &cur );
if (uprcase( *cur ) == 'X') {
cur++;
*writemask |= TGSI_WRITEMASK_X;
}
if (uprcase( *cur ) == 'Y') {
cur++;
*writemask |= TGSI_WRITEMASK_Y;
}
if (uprcase( *cur ) == 'Z') {
cur++;
*writemask |= TGSI_WRITEMASK_Z;
}
if (uprcase( *cur ) == 'W') {
cur++;
*writemask |= TGSI_WRITEMASK_W;
}
if (*writemask == TGSI_WRITEMASK_NONE) {
report_error( ctx, "Writemask expected" );
return FALSE;
}
ctx->cur = cur;
}
else {
*writemask = TGSI_WRITEMASK_XYZW;
}
return TRUE;
}
/* <register_file_bracket> ::= <file> `['
*/
static boolean
parse_register_file_bracket(
struct translate_ctx *ctx,
uint *file )
{
if (!parse_file( &ctx->cur, file )) {
report_error( ctx, "Unknown register file" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != '[') {
report_error( ctx, "Expected `['" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
/* <register_file_bracket_index> ::= <register_file_bracket> <uint>
*/
static boolean
parse_register_file_bracket_index(
struct translate_ctx *ctx,
uint *file,
int *index )
{
uint uindex;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
*index = (int) uindex;
return TRUE;
}
/* Parse simple 1d register operand.
* <register_dst> ::= <register_file_bracket_index> `]'
*/
static boolean
parse_register_1d(struct translate_ctx *ctx,
uint *file,
int *index )
{
if (!parse_register_file_bracket_index( ctx, file, index ))
return FALSE;
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
struct parsed_bracket {
int index;
uint ind_file;
int ind_index;
uint ind_comp;
uint ind_array;
};
static boolean
parse_register_bracket(
struct translate_ctx *ctx,
struct parsed_bracket *brackets)
{
const char *cur;
uint uindex;
memset(brackets, 0, sizeof(struct parsed_bracket));
eat_opt_white( &ctx->cur );
cur = ctx->cur;
if (parse_file( &cur, &brackets->ind_file )) {
if (!parse_register_1d( ctx, &brackets->ind_file,
&brackets->ind_index ))
return FALSE;
eat_opt_white( &ctx->cur );
if (*ctx->cur == '.') {
ctx->cur++;
eat_opt_white(&ctx->cur);
switch (uprcase(*ctx->cur)) {
case 'X':
brackets->ind_comp = TGSI_SWIZZLE_X;
break;
case 'Y':
brackets->ind_comp = TGSI_SWIZZLE_Y;
break;
case 'Z':
brackets->ind_comp = TGSI_SWIZZLE_Z;
break;
case 'W':
brackets->ind_comp = TGSI_SWIZZLE_W;
break;
default:
report_error(ctx, "Expected indirect register swizzle component `x', `y', `z' or `w'");
return FALSE;
}
ctx->cur++;
eat_opt_white(&ctx->cur);
}
if (*ctx->cur == '+' || *ctx->cur == '-')
parse_int( &ctx->cur, &brackets->index );
else
brackets->index = 0;
}
else {
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
brackets->index = (int) uindex;
brackets->ind_file = TGSI_FILE_NULL;
brackets->ind_index = 0;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
if (*ctx->cur == '(') {
ctx->cur++;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &brackets->ind_array )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
return TRUE;
}
static boolean
parse_opt_register_src_bracket(
struct translate_ctx *ctx,
struct parsed_bracket *brackets,
int *parsed_brackets)
{
const char *cur = ctx->cur;
*parsed_brackets = 0;
eat_opt_white( &cur );
if (cur[0] == '[') {
++cur;
ctx->cur = cur;
if (!parse_register_bracket(ctx, brackets))
return FALSE;
*parsed_brackets = 1;
}
return TRUE;
}
/* Parse source register operand.
* <register_src> ::= <register_file_bracket_index> `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `+' <uint> `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `-' <uint> `]'
*/
static boolean
parse_register_src(
struct translate_ctx *ctx,
uint *file,
struct parsed_bracket *brackets)
{
brackets->ind_comp = TGSI_SWIZZLE_X;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_bracket( ctx, brackets ))
return FALSE;
return TRUE;
}
struct parsed_dcl_bracket {
uint first;
uint last;
};
static boolean
parse_register_dcl_bracket(
struct translate_ctx *ctx,
struct parsed_dcl_bracket *bracket)
{
uint uindex;
memset(bracket, 0, sizeof(struct parsed_dcl_bracket));
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
/* it can be an empty bracket [] which means its range
* is from 0 to some implied size */
if (ctx->cur[0] == ']' && ctx->implied_array_size != 0) {
bracket->first = 0;
bracket->last = ctx->implied_array_size - 1;
goto cleanup;
}
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
bracket->first = uindex;
eat_opt_white( &ctx->cur );
if (ctx->cur[0] == '.' && ctx->cur[1] == '.') {
uint uindex;
ctx->cur += 2;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal integer" );
return FALSE;
}
bracket->last = (int) uindex;
eat_opt_white( &ctx->cur );
}
else {
bracket->last = bracket->first;
}
cleanup:
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]' or `..'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
/* Parse register declaration.
* <register_dcl> ::= <register_file_bracket_index> `]' |
* <register_file_bracket_index> `..' <index> `]'
*/
static boolean
parse_register_dcl(
struct translate_ctx *ctx,
uint *file,
struct parsed_dcl_bracket *brackets,
int *num_brackets)
{
const char *cur;
*num_brackets = 0;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_dcl_bracket( ctx, &brackets[0] ))
return FALSE;
*num_brackets = 1;
cur = ctx->cur;
eat_opt_white( &cur );
if (cur[0] == '[') {
bool is_in = *file == TGSI_FILE_INPUT;
bool is_out = *file == TGSI_FILE_OUTPUT;
++cur;
ctx->cur = cur;
if (!parse_register_dcl_bracket( ctx, &brackets[1] ))
return FALSE;
/* for geometry shader we don't really care about
* the first brackets it's always the size of the
* input primitive. so we want to declare just
* the index relevant to the semantics which is in
* the second bracket */
/* tessellation has similar constraints to geometry shader */
if ((ctx->processor == TGSI_PROCESSOR_GEOMETRY && is_in) ||
(ctx->processor == TGSI_PROCESSOR_TESS_EVAL && is_in) ||
(ctx->processor == TGSI_PROCESSOR_TESS_CTRL && (is_in || is_out))) {
brackets[0] = brackets[1];
*num_brackets = 1;
} else {
*num_brackets = 2;
}
}
return TRUE;
}
/* Parse destination register operand.*/
static boolean
parse_register_dst(
struct translate_ctx *ctx,
uint *file,
struct parsed_bracket *brackets)
{
brackets->ind_comp = TGSI_SWIZZLE_X;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_bracket( ctx, brackets ))
return FALSE;
return TRUE;
}
static boolean
parse_dst_operand(
struct translate_ctx *ctx,
struct tgsi_full_dst_register *dst )
{
uint file;
uint writemask;
const char *cur;
struct parsed_bracket bracket[2];
int parsed_opt_brackets;
if (!parse_register_dst( ctx, &file, &bracket[0] ))
return FALSE;
if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
if (!parse_opt_writemask( ctx, &writemask ))
return FALSE;
dst->Register.File = file;
if (parsed_opt_brackets) {
dst->Register.Dimension = 1;
dst->Dimension.Indirect = 0;
dst->Dimension.Dimension = 0;
dst->Dimension.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
dst->Dimension.Indirect = 1;
dst->DimIndirect.File = bracket[0].ind_file;
dst->DimIndirect.Index = bracket[0].ind_index;
dst->DimIndirect.Swizzle = bracket[0].ind_comp;
dst->DimIndirect.ArrayID = bracket[0].ind_array;
}
bracket[0] = bracket[1];
}
dst->Register.Index = bracket[0].index;
dst->Register.WriteMask = writemask;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
dst->Register.Indirect = 1;
dst->Indirect.File = bracket[0].ind_file;
dst->Indirect.Index = bracket[0].ind_index;
dst->Indirect.Swizzle = bracket[0].ind_comp;
dst->Indirect.ArrayID = bracket[0].ind_array;
}
return TRUE;
}
static boolean
parse_optional_swizzle(
struct translate_ctx *ctx,
uint *swizzle,
boolean *parsed_swizzle,
int components)
{
const char *cur = ctx->cur;
*parsed_swizzle = FALSE;
eat_opt_white( &cur );
if (*cur == '.') {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < components; i++) {
if (uprcase( *cur ) == 'X')
swizzle[i] = TGSI_SWIZZLE_X;
else if (uprcase( *cur ) == 'Y')
swizzle[i] = TGSI_SWIZZLE_Y;
else if (uprcase( *cur ) == 'Z')
swizzle[i] = TGSI_SWIZZLE_Z;
else if (uprcase( *cur ) == 'W')
swizzle[i] = TGSI_SWIZZLE_W;
else {
report_error( ctx, "Expected register swizzle component `x', `y', `z' or `w'" );
return FALSE;
}
cur++;
}
*parsed_swizzle = TRUE;
ctx->cur = cur;
}
return TRUE;
}
static boolean
parse_src_operand(
struct translate_ctx *ctx,
struct tgsi_full_src_register *src )
{
uint file;
uint swizzle[4];
boolean parsed_swizzle;
struct parsed_bracket bracket[2];
int parsed_opt_brackets;
if (*ctx->cur == '-') {
ctx->cur++;
eat_opt_white( &ctx->cur );
src->Register.Negate = 1;
}
if (*ctx->cur == '|') {
ctx->cur++;
eat_opt_white( &ctx->cur );
src->Register.Absolute = 1;
}
if (!parse_register_src(ctx, &file, &bracket[0]))
return FALSE;
if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets))
return FALSE;
src->Register.File = file;
if (parsed_opt_brackets) {
src->Register.Dimension = 1;
src->Dimension.Indirect = 0;
src->Dimension.Dimension = 0;
src->Dimension.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
src->Dimension.Indirect = 1;
src->DimIndirect.File = bracket[0].ind_file;
src->DimIndirect.Index = bracket[0].ind_index;
src->DimIndirect.Swizzle = bracket[0].ind_comp;
src->DimIndirect.ArrayID = bracket[0].ind_array;
}
bracket[0] = bracket[1];
}
src->Register.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
src->Register.Indirect = 1;
src->Indirect.File = bracket[0].ind_file;
src->Indirect.Index = bracket[0].ind_index;
src->Indirect.Swizzle = bracket[0].ind_comp;
src->Indirect.ArrayID = bracket[0].ind_array;
}
/* Parse optional swizzle.
*/
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
src->Register.SwizzleX = swizzle[0];
src->Register.SwizzleY = swizzle[1];
src->Register.SwizzleZ = swizzle[2];
src->Register.SwizzleW = swizzle[3];
}
}
if (src->Register.Absolute) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != '|') {
report_error( ctx, "Expected `|'" );
return FALSE;
}
ctx->cur++;
}
return TRUE;
}
static boolean
parse_texoffset_operand(
struct translate_ctx *ctx,
struct tgsi_texture_offset *src )
{
uint file;
uint swizzle[3];
boolean parsed_swizzle;
struct parsed_bracket bracket;
if (!parse_register_src(ctx, &file, &bracket))
return FALSE;
src->File = file;
src->Index = bracket.index;
/* Parse optional swizzle.
*/
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 3 )) {
if (parsed_swizzle) {
src->SwizzleX = swizzle[0];
src->SwizzleY = swizzle[1];
src->SwizzleZ = swizzle[2];
}
}
return TRUE;
}
static boolean
match_inst(const char **pcur,
unsigned *saturate,
const struct tgsi_opcode_info *info)
{
const char *cur = *pcur;
/* simple case: the whole string matches the instruction name */
if (str_match_nocase_whole(&cur, info->mnemonic)) {
*pcur = cur;
*saturate = 0;
return TRUE;
}
if (str_match_no_case(&cur, info->mnemonic)) {
/* the instruction has a suffix, figure it out */
if (str_match_nocase_whole(&cur, "_SAT")) {
*pcur = cur;
*saturate = 1;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_instruction(
struct translate_ctx *ctx,
boolean has_label )
{
uint i;
uint saturate = 0;
const struct tgsi_opcode_info *info;
struct tgsi_full_instruction inst;
const char *cur;
uint advance;
inst = tgsi_default_full_instruction();
/* Parse predicate.
*/
eat_opt_white( &ctx->cur );
if (*ctx->cur == '(') {
uint file;
int index;
uint swizzle[4];
boolean parsed_swizzle;
inst.Instruction.Predicate = 1;
ctx->cur++;
if (*ctx->cur == '!') {
ctx->cur++;
inst.Predicate.Negate = 1;
}
if (!parse_register_1d( ctx, &file, &index ))
return FALSE;
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
inst.Predicate.SwizzleX = swizzle[0];
inst.Predicate.SwizzleY = swizzle[1];
inst.Predicate.SwizzleZ = swizzle[2];
inst.Predicate.SwizzleW = swizzle[3];
}
}
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
/* Parse instruction name.
*/
eat_opt_white( &ctx->cur );
for (i = 0; i < TGSI_OPCODE_LAST; i++) {
cur = ctx->cur;
info = tgsi_get_opcode_info( i );
if (match_inst(&cur, &saturate, info)) {
if (info->num_dst + info->num_src + info->is_tex == 0) {
ctx->cur = cur;
break;
}
else if (*cur == '\0' || eat_white( &cur )) {
ctx->cur = cur;
break;
}
}
}
if (i == TGSI_OPCODE_LAST) {
if (has_label)
report_error( ctx, "Unknown opcode" );
else
report_error( ctx, "Expected `DCL', `IMM' or a label" );
return FALSE;
}
inst.Instruction.Opcode = i;
inst.Instruction.Saturate = saturate;
inst.Instruction.NumDstRegs = info->num_dst;
inst.Instruction.NumSrcRegs = info->num_src;
if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) {
/*
* These are not considered tex opcodes here (no additional
* target argument) however we're required to set the Texture
* bit so we can set the number of tex offsets.
*/
inst.Instruction.Texture = 1;
inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN;
}
/* Parse instruction operands.
*/
for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) {
if (i > 0) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
if (i < info->num_dst) {
if (!parse_dst_operand( ctx, &inst.Dst[i] ))
return FALSE;
}
else if (i < info->num_dst + info->num_src) {
if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] ))
return FALSE;
}
else {
uint j;
for (j = 0; j < TGSI_TEXTURE_COUNT; j++) {
if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) {
inst.Instruction.Texture = 1;
inst.Texture.Texture = j;
break;
}
}
if (j == TGSI_TEXTURE_COUNT) {
report_error( ctx, "Expected texture target" );
return FALSE;
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
for (i = 0; inst.Instruction.Texture && *cur == ','; i++) {
cur++;
eat_opt_white( &cur );
ctx->cur = cur;
if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] ))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
}
inst.Texture.NumOffsets = i;
cur = ctx->cur;
eat_opt_white( &cur );
if (info->is_branch && *cur == ':') {
uint target;
cur++;
eat_opt_white( &cur );
if (!parse_uint( &cur, &target )) {
report_error( ctx, "Expected a label" );
return FALSE;
}
inst.Instruction.Label = 1;
inst.Label.Label = target;
ctx->cur = cur;
}
advance = tgsi_build_full_instruction(
&inst,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
/* parses a 4-touple of the form {x, y, z, w}
* where x, y, z, w are numbers */
static boolean parse_immediate_data(struct translate_ctx *ctx, unsigned type,
union tgsi_immediate_data *values)
{
unsigned i;
int ret;
eat_opt_white( &ctx->cur );
if (*ctx->cur != '{') {
report_error( ctx, "Expected `{'" );
return FALSE;
}
ctx->cur++;
for (i = 0; i < 4; i++) {
eat_opt_white( &ctx->cur );
if (i > 0) {
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
switch (type) {
case TGSI_IMM_FLOAT64:
ret = parse_double(&ctx->cur, &values[i].Uint, &values[i+1].Uint);
i++;
break;
case TGSI_IMM_FLOAT32:
ret = parse_float(&ctx->cur, &values[i].Float);
break;
case TGSI_IMM_UINT32:
ret = parse_uint(&ctx->cur, &values[i].Uint);
break;
case TGSI_IMM_INT32:
ret = parse_int(&ctx->cur, &values[i].Int);
break;
default:
assert(0);
ret = FALSE;
break;
}
if (!ret) {
report_error( ctx, "Expected immediate constant" );
return FALSE;
}
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != '}') {
report_error( ctx, "Expected `}'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
static boolean parse_declaration( struct translate_ctx *ctx )
{
struct tgsi_full_declaration decl;
uint file;
struct parsed_dcl_bracket brackets[2];
int num_brackets;
uint writemask;
const char *cur, *cur2;
uint advance;
boolean is_vs_input;
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
if (!parse_register_dcl( ctx, &file, brackets, &num_brackets))
return FALSE;
if (!parse_opt_writemask( ctx, &writemask ))
return FALSE;
decl = tgsi_default_full_declaration();
decl.Declaration.File = file;
decl.Declaration.UsageMask = writemask;
if (num_brackets == 1) {
decl.Range.First = brackets[0].first;
decl.Range.Last = brackets[0].last;
} else {
decl.Range.First = brackets[1].first;
decl.Range.Last = brackets[1].last;
decl.Declaration.Dimension = 1;
decl.Dim.Index2D = brackets[0].first;
}
is_vs_input = (file == TGSI_FILE_INPUT &&
ctx->processor == TGSI_PROCESSOR_VERTEX);
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',') {
cur2 = cur;
cur2++;
eat_opt_white( &cur2 );
if (str_match_nocase_whole( &cur2, "ARRAY" )) {
int arrayid;
if (*cur2 != '(') {
report_error( ctx, "Expected `('" );
return FALSE;
}
cur2++;
eat_opt_white( &cur2 );
if (!parse_int( &cur2, &arrayid )) {
report_error( ctx, "Expected `,'" );
return FALSE;
}
eat_opt_white( &cur2 );
if (*cur2 != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
cur2++;
decl.Declaration.Array = 1;
decl.Array.ArrayID = arrayid;
ctx->cur = cur = cur2;
}
}
if (*cur == ',' && !is_vs_input) {
uint i, j;
cur++;
eat_opt_white( &cur );
if (file == TGSI_FILE_RESOURCE) {
for (i = 0; i < TGSI_TEXTURE_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) {
decl.Resource.Resource = i;
break;
}
}
if (i == TGSI_TEXTURE_COUNT) {
report_error(ctx, "Expected texture target");
return FALSE;
}
cur2 = cur;
eat_opt_white(&cur2);
while (*cur2 == ',') {
cur2++;
eat_opt_white(&cur2);
if (str_match_nocase_whole(&cur2, "RAW")) {
decl.Resource.Raw = 1;
} else if (str_match_nocase_whole(&cur2, "WR")) {
decl.Resource.Writable = 1;
} else {
break;
}
cur = cur2;
eat_opt_white(&cur2);
}
ctx->cur = cur;
} else if (file == TGSI_FILE_SAMPLER_VIEW) {
for (i = 0; i < TGSI_TEXTURE_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) {
decl.SamplerView.Resource = i;
break;
}
}
if (i == TGSI_TEXTURE_COUNT) {
report_error(ctx, "Expected texture target");
return FALSE;
}
eat_opt_white( &cur );
if (*cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
++cur;
eat_opt_white( &cur );
for (j = 0; j < 4; ++j) {
for (i = 0; i < TGSI_RETURN_TYPE_COUNT; ++i) {
if (str_match_nocase_whole(&cur, tgsi_return_type_names[i])) {
switch (j) {
case 0:
decl.SamplerView.ReturnTypeX = i;
break;
case 1:
decl.SamplerView.ReturnTypeY = i;
break;
case 2:
decl.SamplerView.ReturnTypeZ = i;
break;
case 3:
decl.SamplerView.ReturnTypeW = i;
break;
default:
assert(0);
}
break;
}
}
if (i == TGSI_RETURN_TYPE_COUNT) {
if (j == 0 || j > 2) {
report_error(ctx, "Expected type name");
return FALSE;
}
break;
} else {
cur2 = cur;
eat_opt_white( &cur2 );
if (*cur2 == ',') {
cur2++;
eat_opt_white( &cur2 );
cur = cur2;
continue;
} else
break;
}
}
if (j < 4) {
decl.SamplerView.ReturnTypeY =
decl.SamplerView.ReturnTypeZ =
decl.SamplerView.ReturnTypeW =
decl.SamplerView.ReturnTypeX;
}
ctx->cur = cur;
} else {
if (str_match_nocase_whole(&cur, "LOCAL")) {
decl.Declaration.Local = 1;
ctx->cur = cur;
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',') {
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_SEMANTIC_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_semantic_names[i])) {
uint index;
cur2 = cur;
eat_opt_white( &cur2 );
if (*cur2 == '[') {
cur2++;
eat_opt_white( &cur2 );
if (!parse_uint( &cur2, &index )) {
report_error( ctx, "Expected literal integer" );
return FALSE;
}
eat_opt_white( &cur2 );
if (*cur2 != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
cur2++;
decl.Semantic.Index = index;
cur = cur2;
}
decl.Declaration.Semantic = 1;
decl.Semantic.Name = i;
ctx->cur = cur;
break;
}
}
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',' && !is_vs_input) {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_INTERPOLATE_COUNT; i++) {
if (str_match_nocase_whole( &cur, tgsi_interpolate_names[i] )) {
decl.Declaration.Interpolate = 1;
decl.Interp.Interpolate = i;
ctx->cur = cur;
break;
}
}
if (i == TGSI_INTERPOLATE_COUNT) {
report_error( ctx, "Expected semantic or interpolate attribute" );
return FALSE;
}
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',' && !is_vs_input) {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_INTERPOLATE_LOC_COUNT; i++) {
if (str_match_nocase_whole( &cur, tgsi_interpolate_locations[i] )) {
decl.Interp.Location = i;
ctx->cur = cur;
break;
}
}
}
advance = tgsi_build_full_declaration(
&decl,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
static boolean parse_immediate( struct translate_ctx *ctx )
{
struct tgsi_full_immediate imm;
uint advance;
int type;
if (*ctx->cur == '[') {
uint uindex;
++ctx->cur;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
if (uindex != ctx->num_immediates) {
report_error( ctx, "Immediates must be sorted" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
}
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
for (type = 0; type < Elements(tgsi_immediate_type_names); ++type) {
if (str_match_nocase_whole(&ctx->cur, tgsi_immediate_type_names[type]))
break;
}
if (type == Elements(tgsi_immediate_type_names)) {
report_error( ctx, "Expected immediate type" );
return FALSE;
}
imm = tgsi_default_full_immediate();
imm.Immediate.NrTokens += 4;
imm.Immediate.DataType = type;
parse_immediate_data(ctx, type, imm.u);
advance = tgsi_build_full_immediate(
&imm,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
ctx->num_immediates++;
return TRUE;
}
static boolean
parse_primitive( const char **pcur, uint *primitive )
{
uint i;
for (i = 0; i < PIPE_PRIM_MAX; i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_primitive_names[i])) {
*primitive = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_fs_coord_origin( const char **pcur, uint *fs_coord_origin )
{
uint i;
for (i = 0; i < Elements(tgsi_fs_coord_origin_names); i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_fs_coord_origin_names[i])) {
*fs_coord_origin = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_fs_coord_pixel_center( const char **pcur, uint *fs_coord_pixel_center )
{
uint i;
for (i = 0; i < Elements(tgsi_fs_coord_pixel_center_names); i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_fs_coord_pixel_center_names[i])) {
*fs_coord_pixel_center = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean parse_property( struct translate_ctx *ctx )
{
struct tgsi_full_property prop;
uint property_name;
uint values[8];
uint advance;
char id[64];
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
report_error( ctx, "Syntax error" );
return FALSE;
}
if (!parse_identifier( &ctx->cur, id )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
break;
}
}
|
static boolean parse_identifier( const char **pcur, char *ret )
static boolean parse_identifier( const char **pcur, char *ret, size_t len )
{
const char *cur = *pcur;
int i = 0;
if (is_alpha_underscore( cur )) {
ret[i++] = *cur++;
while (is_alpha_underscore( cur ) || is_digit( cur )) {
if (i == len - 1)
return FALSE;
ret[i++] = *cur++;
}
ret[i++] = '\0';
*pcur = cur;
return TRUE;
/* Parse floating point.
*/
static boolean parse_float( const char **pcur, float *val )
{
const char *cur = *pcur;
boolean integral_part = FALSE;
boolean fractional_part = FALSE;
if (*cur == '0' && *(cur + 1) == 'x') {
union fi fi;
fi.ui = strtoul(cur, NULL, 16);
*val = fi.f;
cur += 10;
goto out;
}
*val = (float) atof( cur );
if (*cur == '-' || *cur == '+')
cur++;
if (is_digit( cur )) {
cur++;
integral_part = TRUE;
while (is_digit( cur ))
cur++;
}
if (*cur == '.') {
cur++;
if (is_digit( cur )) {
cur++;
fractional_part = TRUE;
while (is_digit( cur ))
cur++;
}
}
if (!integral_part && !fractional_part)
return FALSE;
if (uprcase( *cur ) == 'E') {
cur++;
if (*cur == '-' || *cur == '+')
cur++;
if (is_digit( cur )) {
cur++;
while (is_digit( cur ))
cur++;
}
else
return FALSE;
}
out:
*pcur = cur;
return TRUE;
}
static boolean parse_double( const char **pcur, uint32_t *val0, uint32_t *val1)
{
const char *cur = *pcur;
union {
double dval;
uint32_t uval[2];
} v;
v.dval = strtod(cur, (char**)pcur);
if (*pcur == cur)
return FALSE;
*val0 = v.uval[0];
*val1 = v.uval[1];
return TRUE;
}
struct translate_ctx
{
const char *text;
const char *cur;
struct tgsi_token *tokens;
struct tgsi_token *tokens_cur;
struct tgsi_token *tokens_end;
struct tgsi_header *header;
unsigned processor : 4;
unsigned implied_array_size : 6;
unsigned num_immediates;
};
static void report_error(struct translate_ctx *ctx, const char *format, ...)
{
va_list args;
int line = 1;
int column = 1;
const char *itr = ctx->text;
debug_printf("\nTGSI asm error: ");
va_start(args, format);
_debug_vprintf(format, args);
va_end(args);
while (itr != ctx->cur) {
if (*itr == '\n') {
column = 1;
++line;
}
++column;
++itr;
}
debug_printf(" [%d : %d] \n", line, column);
}
/* Parse shader header.
* Return TRUE for one of the following headers.
* FRAG
* GEOM
* VERT
*/
static boolean parse_header( struct translate_ctx *ctx )
{
uint processor;
if (str_match_nocase_whole( &ctx->cur, "FRAG" ))
processor = TGSI_PROCESSOR_FRAGMENT;
else if (str_match_nocase_whole( &ctx->cur, "VERT" ))
processor = TGSI_PROCESSOR_VERTEX;
else if (str_match_nocase_whole( &ctx->cur, "GEOM" ))
processor = TGSI_PROCESSOR_GEOMETRY;
else if (str_match_nocase_whole( &ctx->cur, "TESS_CTRL" ))
processor = TGSI_PROCESSOR_TESS_CTRL;
else if (str_match_nocase_whole( &ctx->cur, "TESS_EVAL" ))
processor = TGSI_PROCESSOR_TESS_EVAL;
else if (str_match_nocase_whole( &ctx->cur, "COMP" ))
processor = TGSI_PROCESSOR_COMPUTE;
else {
report_error( ctx, "Unknown header" );
return FALSE;
}
if (ctx->tokens_cur >= ctx->tokens_end)
return FALSE;
ctx->header = (struct tgsi_header *) ctx->tokens_cur++;
*ctx->header = tgsi_build_header();
if (ctx->tokens_cur >= ctx->tokens_end)
return FALSE;
*(struct tgsi_processor *) ctx->tokens_cur++ = tgsi_build_processor( processor, ctx->header );
ctx->processor = processor;
return TRUE;
}
static boolean parse_label( struct translate_ctx *ctx, uint *val )
{
const char *cur = ctx->cur;
if (parse_uint( &cur, val )) {
eat_opt_white( &cur );
if (*cur == ':') {
cur++;
ctx->cur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_file( const char **pcur, uint *file )
{
uint i;
for (i = 0; i < TGSI_FILE_COUNT; i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_file_name(i) )) {
*pcur = cur;
*file = i;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_opt_writemask(
struct translate_ctx *ctx,
uint *writemask )
{
const char *cur;
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == '.') {
cur++;
*writemask = TGSI_WRITEMASK_NONE;
eat_opt_white( &cur );
if (uprcase( *cur ) == 'X') {
cur++;
*writemask |= TGSI_WRITEMASK_X;
}
if (uprcase( *cur ) == 'Y') {
cur++;
*writemask |= TGSI_WRITEMASK_Y;
}
if (uprcase( *cur ) == 'Z') {
cur++;
*writemask |= TGSI_WRITEMASK_Z;
}
if (uprcase( *cur ) == 'W') {
cur++;
*writemask |= TGSI_WRITEMASK_W;
}
if (*writemask == TGSI_WRITEMASK_NONE) {
report_error( ctx, "Writemask expected" );
return FALSE;
}
ctx->cur = cur;
}
else {
*writemask = TGSI_WRITEMASK_XYZW;
}
return TRUE;
}
/* <register_file_bracket> ::= <file> `['
*/
static boolean
parse_register_file_bracket(
struct translate_ctx *ctx,
uint *file )
{
if (!parse_file( &ctx->cur, file )) {
report_error( ctx, "Unknown register file" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != '[') {
report_error( ctx, "Expected `['" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
/* <register_file_bracket_index> ::= <register_file_bracket> <uint>
*/
static boolean
parse_register_file_bracket_index(
struct translate_ctx *ctx,
uint *file,
int *index )
{
uint uindex;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
*index = (int) uindex;
return TRUE;
}
/* Parse simple 1d register operand.
* <register_dst> ::= <register_file_bracket_index> `]'
*/
static boolean
parse_register_1d(struct translate_ctx *ctx,
uint *file,
int *index )
{
if (!parse_register_file_bracket_index( ctx, file, index ))
return FALSE;
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
struct parsed_bracket {
int index;
uint ind_file;
int ind_index;
uint ind_comp;
uint ind_array;
};
static boolean
parse_register_bracket(
struct translate_ctx *ctx,
struct parsed_bracket *brackets)
{
const char *cur;
uint uindex;
memset(brackets, 0, sizeof(struct parsed_bracket));
eat_opt_white( &ctx->cur );
cur = ctx->cur;
if (parse_file( &cur, &brackets->ind_file )) {
if (!parse_register_1d( ctx, &brackets->ind_file,
&brackets->ind_index ))
return FALSE;
eat_opt_white( &ctx->cur );
if (*ctx->cur == '.') {
ctx->cur++;
eat_opt_white(&ctx->cur);
switch (uprcase(*ctx->cur)) {
case 'X':
brackets->ind_comp = TGSI_SWIZZLE_X;
break;
case 'Y':
brackets->ind_comp = TGSI_SWIZZLE_Y;
break;
case 'Z':
brackets->ind_comp = TGSI_SWIZZLE_Z;
break;
case 'W':
brackets->ind_comp = TGSI_SWIZZLE_W;
break;
default:
report_error(ctx, "Expected indirect register swizzle component `x', `y', `z' or `w'");
return FALSE;
}
ctx->cur++;
eat_opt_white(&ctx->cur);
}
if (*ctx->cur == '+' || *ctx->cur == '-')
parse_int( &ctx->cur, &brackets->index );
else
brackets->index = 0;
}
else {
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
brackets->index = (int) uindex;
brackets->ind_file = TGSI_FILE_NULL;
brackets->ind_index = 0;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
if (*ctx->cur == '(') {
ctx->cur++;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &brackets->ind_array )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
return TRUE;
}
static boolean
parse_opt_register_src_bracket(
struct translate_ctx *ctx,
struct parsed_bracket *brackets,
int *parsed_brackets)
{
const char *cur = ctx->cur;
*parsed_brackets = 0;
eat_opt_white( &cur );
if (cur[0] == '[') {
++cur;
ctx->cur = cur;
if (!parse_register_bracket(ctx, brackets))
return FALSE;
*parsed_brackets = 1;
}
return TRUE;
}
/* Parse source register operand.
* <register_src> ::= <register_file_bracket_index> `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `+' <uint> `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `-' <uint> `]'
*/
static boolean
parse_register_src(
struct translate_ctx *ctx,
uint *file,
struct parsed_bracket *brackets)
{
brackets->ind_comp = TGSI_SWIZZLE_X;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_bracket( ctx, brackets ))
return FALSE;
return TRUE;
}
struct parsed_dcl_bracket {
uint first;
uint last;
};
static boolean
parse_register_dcl_bracket(
struct translate_ctx *ctx,
struct parsed_dcl_bracket *bracket)
{
uint uindex;
memset(bracket, 0, sizeof(struct parsed_dcl_bracket));
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
/* it can be an empty bracket [] which means its range
* is from 0 to some implied size */
if (ctx->cur[0] == ']' && ctx->implied_array_size != 0) {
bracket->first = 0;
bracket->last = ctx->implied_array_size - 1;
goto cleanup;
}
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
bracket->first = uindex;
eat_opt_white( &ctx->cur );
if (ctx->cur[0] == '.' && ctx->cur[1] == '.') {
uint uindex;
ctx->cur += 2;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal integer" );
return FALSE;
}
bracket->last = (int) uindex;
eat_opt_white( &ctx->cur );
}
else {
bracket->last = bracket->first;
}
cleanup:
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]' or `..'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
/* Parse register declaration.
* <register_dcl> ::= <register_file_bracket_index> `]' |
* <register_file_bracket_index> `..' <index> `]'
*/
static boolean
parse_register_dcl(
struct translate_ctx *ctx,
uint *file,
struct parsed_dcl_bracket *brackets,
int *num_brackets)
{
const char *cur;
*num_brackets = 0;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_dcl_bracket( ctx, &brackets[0] ))
return FALSE;
*num_brackets = 1;
cur = ctx->cur;
eat_opt_white( &cur );
if (cur[0] == '[') {
bool is_in = *file == TGSI_FILE_INPUT;
bool is_out = *file == TGSI_FILE_OUTPUT;
++cur;
ctx->cur = cur;
if (!parse_register_dcl_bracket( ctx, &brackets[1] ))
return FALSE;
/* for geometry shader we don't really care about
* the first brackets it's always the size of the
* input primitive. so we want to declare just
* the index relevant to the semantics which is in
* the second bracket */
/* tessellation has similar constraints to geometry shader */
if ((ctx->processor == TGSI_PROCESSOR_GEOMETRY && is_in) ||
(ctx->processor == TGSI_PROCESSOR_TESS_EVAL && is_in) ||
(ctx->processor == TGSI_PROCESSOR_TESS_CTRL && (is_in || is_out))) {
brackets[0] = brackets[1];
*num_brackets = 1;
} else {
*num_brackets = 2;
}
}
return TRUE;
}
/* Parse destination register operand.*/
static boolean
parse_register_dst(
struct translate_ctx *ctx,
uint *file,
struct parsed_bracket *brackets)
{
brackets->ind_comp = TGSI_SWIZZLE_X;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_bracket( ctx, brackets ))
return FALSE;
return TRUE;
}
static boolean
parse_dst_operand(
struct translate_ctx *ctx,
struct tgsi_full_dst_register *dst )
{
uint file;
uint writemask;
const char *cur;
struct parsed_bracket bracket[2];
int parsed_opt_brackets;
if (!parse_register_dst( ctx, &file, &bracket[0] ))
return FALSE;
if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
if (!parse_opt_writemask( ctx, &writemask ))
return FALSE;
dst->Register.File = file;
if (parsed_opt_brackets) {
dst->Register.Dimension = 1;
dst->Dimension.Indirect = 0;
dst->Dimension.Dimension = 0;
dst->Dimension.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
dst->Dimension.Indirect = 1;
dst->DimIndirect.File = bracket[0].ind_file;
dst->DimIndirect.Index = bracket[0].ind_index;
dst->DimIndirect.Swizzle = bracket[0].ind_comp;
dst->DimIndirect.ArrayID = bracket[0].ind_array;
}
bracket[0] = bracket[1];
}
dst->Register.Index = bracket[0].index;
dst->Register.WriteMask = writemask;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
dst->Register.Indirect = 1;
dst->Indirect.File = bracket[0].ind_file;
dst->Indirect.Index = bracket[0].ind_index;
dst->Indirect.Swizzle = bracket[0].ind_comp;
dst->Indirect.ArrayID = bracket[0].ind_array;
}
return TRUE;
}
static boolean
parse_optional_swizzle(
struct translate_ctx *ctx,
uint *swizzle,
boolean *parsed_swizzle,
int components)
{
const char *cur = ctx->cur;
*parsed_swizzle = FALSE;
eat_opt_white( &cur );
if (*cur == '.') {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < components; i++) {
if (uprcase( *cur ) == 'X')
swizzle[i] = TGSI_SWIZZLE_X;
else if (uprcase( *cur ) == 'Y')
swizzle[i] = TGSI_SWIZZLE_Y;
else if (uprcase( *cur ) == 'Z')
swizzle[i] = TGSI_SWIZZLE_Z;
else if (uprcase( *cur ) == 'W')
swizzle[i] = TGSI_SWIZZLE_W;
else {
report_error( ctx, "Expected register swizzle component `x', `y', `z' or `w'" );
return FALSE;
}
cur++;
}
*parsed_swizzle = TRUE;
ctx->cur = cur;
}
return TRUE;
}
static boolean
parse_src_operand(
struct translate_ctx *ctx,
struct tgsi_full_src_register *src )
{
uint file;
uint swizzle[4];
boolean parsed_swizzle;
struct parsed_bracket bracket[2];
int parsed_opt_brackets;
if (*ctx->cur == '-') {
ctx->cur++;
eat_opt_white( &ctx->cur );
src->Register.Negate = 1;
}
if (*ctx->cur == '|') {
ctx->cur++;
eat_opt_white( &ctx->cur );
src->Register.Absolute = 1;
}
if (!parse_register_src(ctx, &file, &bracket[0]))
return FALSE;
if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets))
return FALSE;
src->Register.File = file;
if (parsed_opt_brackets) {
src->Register.Dimension = 1;
src->Dimension.Indirect = 0;
src->Dimension.Dimension = 0;
src->Dimension.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
src->Dimension.Indirect = 1;
src->DimIndirect.File = bracket[0].ind_file;
src->DimIndirect.Index = bracket[0].ind_index;
src->DimIndirect.Swizzle = bracket[0].ind_comp;
src->DimIndirect.ArrayID = bracket[0].ind_array;
}
bracket[0] = bracket[1];
}
src->Register.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
src->Register.Indirect = 1;
src->Indirect.File = bracket[0].ind_file;
src->Indirect.Index = bracket[0].ind_index;
src->Indirect.Swizzle = bracket[0].ind_comp;
src->Indirect.ArrayID = bracket[0].ind_array;
}
/* Parse optional swizzle.
*/
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
src->Register.SwizzleX = swizzle[0];
src->Register.SwizzleY = swizzle[1];
src->Register.SwizzleZ = swizzle[2];
src->Register.SwizzleW = swizzle[3];
}
}
if (src->Register.Absolute) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != '|') {
report_error( ctx, "Expected `|'" );
return FALSE;
}
ctx->cur++;
}
return TRUE;
}
static boolean
parse_texoffset_operand(
struct translate_ctx *ctx,
struct tgsi_texture_offset *src )
{
uint file;
uint swizzle[3];
boolean parsed_swizzle;
struct parsed_bracket bracket;
if (!parse_register_src(ctx, &file, &bracket))
return FALSE;
src->File = file;
src->Index = bracket.index;
/* Parse optional swizzle.
*/
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 3 )) {
if (parsed_swizzle) {
src->SwizzleX = swizzle[0];
src->SwizzleY = swizzle[1];
src->SwizzleZ = swizzle[2];
}
}
return TRUE;
}
static boolean
match_inst(const char **pcur,
unsigned *saturate,
const struct tgsi_opcode_info *info)
{
const char *cur = *pcur;
/* simple case: the whole string matches the instruction name */
if (str_match_nocase_whole(&cur, info->mnemonic)) {
*pcur = cur;
*saturate = 0;
return TRUE;
}
if (str_match_no_case(&cur, info->mnemonic)) {
/* the instruction has a suffix, figure it out */
if (str_match_nocase_whole(&cur, "_SAT")) {
*pcur = cur;
*saturate = 1;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_instruction(
struct translate_ctx *ctx,
boolean has_label )
{
uint i;
uint saturate = 0;
const struct tgsi_opcode_info *info;
struct tgsi_full_instruction inst;
const char *cur;
uint advance;
inst = tgsi_default_full_instruction();
/* Parse predicate.
*/
eat_opt_white( &ctx->cur );
if (*ctx->cur == '(') {
uint file;
int index;
uint swizzle[4];
boolean parsed_swizzle;
inst.Instruction.Predicate = 1;
ctx->cur++;
if (*ctx->cur == '!') {
ctx->cur++;
inst.Predicate.Negate = 1;
}
if (!parse_register_1d( ctx, &file, &index ))
return FALSE;
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
inst.Predicate.SwizzleX = swizzle[0];
inst.Predicate.SwizzleY = swizzle[1];
inst.Predicate.SwizzleZ = swizzle[2];
inst.Predicate.SwizzleW = swizzle[3];
}
}
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
/* Parse instruction name.
*/
eat_opt_white( &ctx->cur );
for (i = 0; i < TGSI_OPCODE_LAST; i++) {
cur = ctx->cur;
info = tgsi_get_opcode_info( i );
if (match_inst(&cur, &saturate, info)) {
if (info->num_dst + info->num_src + info->is_tex == 0) {
ctx->cur = cur;
break;
}
else if (*cur == '\0' || eat_white( &cur )) {
ctx->cur = cur;
break;
}
}
}
if (i == TGSI_OPCODE_LAST) {
if (has_label)
report_error( ctx, "Unknown opcode" );
else
report_error( ctx, "Expected `DCL', `IMM' or a label" );
return FALSE;
}
inst.Instruction.Opcode = i;
inst.Instruction.Saturate = saturate;
inst.Instruction.NumDstRegs = info->num_dst;
inst.Instruction.NumSrcRegs = info->num_src;
if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) {
/*
* These are not considered tex opcodes here (no additional
* target argument) however we're required to set the Texture
* bit so we can set the number of tex offsets.
*/
inst.Instruction.Texture = 1;
inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN;
}
/* Parse instruction operands.
*/
for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) {
if (i > 0) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
if (i < info->num_dst) {
if (!parse_dst_operand( ctx, &inst.Dst[i] ))
return FALSE;
}
else if (i < info->num_dst + info->num_src) {
if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] ))
return FALSE;
}
else {
uint j;
for (j = 0; j < TGSI_TEXTURE_COUNT; j++) {
if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) {
inst.Instruction.Texture = 1;
inst.Texture.Texture = j;
break;
}
}
if (j == TGSI_TEXTURE_COUNT) {
report_error( ctx, "Expected texture target" );
return FALSE;
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
for (i = 0; inst.Instruction.Texture && *cur == ','; i++) {
cur++;
eat_opt_white( &cur );
ctx->cur = cur;
if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] ))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
}
inst.Texture.NumOffsets = i;
cur = ctx->cur;
eat_opt_white( &cur );
if (info->is_branch && *cur == ':') {
uint target;
cur++;
eat_opt_white( &cur );
if (!parse_uint( &cur, &target )) {
report_error( ctx, "Expected a label" );
return FALSE;
}
inst.Instruction.Label = 1;
inst.Label.Label = target;
ctx->cur = cur;
}
advance = tgsi_build_full_instruction(
&inst,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
/* parses a 4-touple of the form {x, y, z, w}
* where x, y, z, w are numbers */
static boolean parse_immediate_data(struct translate_ctx *ctx, unsigned type,
union tgsi_immediate_data *values)
{
unsigned i;
int ret;
eat_opt_white( &ctx->cur );
if (*ctx->cur != '{') {
report_error( ctx, "Expected `{'" );
return FALSE;
}
ctx->cur++;
for (i = 0; i < 4; i++) {
eat_opt_white( &ctx->cur );
if (i > 0) {
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
switch (type) {
case TGSI_IMM_FLOAT64:
ret = parse_double(&ctx->cur, &values[i].Uint, &values[i+1].Uint);
i++;
break;
case TGSI_IMM_FLOAT32:
ret = parse_float(&ctx->cur, &values[i].Float);
break;
case TGSI_IMM_UINT32:
ret = parse_uint(&ctx->cur, &values[i].Uint);
break;
case TGSI_IMM_INT32:
ret = parse_int(&ctx->cur, &values[i].Int);
break;
default:
assert(0);
ret = FALSE;
break;
}
if (!ret) {
report_error( ctx, "Expected immediate constant" );
return FALSE;
}
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != '}') {
report_error( ctx, "Expected `}'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
static boolean parse_declaration( struct translate_ctx *ctx )
{
struct tgsi_full_declaration decl;
uint file;
struct parsed_dcl_bracket brackets[2];
int num_brackets;
uint writemask;
const char *cur, *cur2;
uint advance;
boolean is_vs_input;
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
if (!parse_register_dcl( ctx, &file, brackets, &num_brackets))
return FALSE;
if (!parse_opt_writemask( ctx, &writemask ))
return FALSE;
decl = tgsi_default_full_declaration();
decl.Declaration.File = file;
decl.Declaration.UsageMask = writemask;
if (num_brackets == 1) {
decl.Range.First = brackets[0].first;
decl.Range.Last = brackets[0].last;
} else {
decl.Range.First = brackets[1].first;
decl.Range.Last = brackets[1].last;
decl.Declaration.Dimension = 1;
decl.Dim.Index2D = brackets[0].first;
}
is_vs_input = (file == TGSI_FILE_INPUT &&
ctx->processor == TGSI_PROCESSOR_VERTEX);
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',') {
cur2 = cur;
cur2++;
eat_opt_white( &cur2 );
if (str_match_nocase_whole( &cur2, "ARRAY" )) {
int arrayid;
if (*cur2 != '(') {
report_error( ctx, "Expected `('" );
return FALSE;
}
cur2++;
eat_opt_white( &cur2 );
if (!parse_int( &cur2, &arrayid )) {
report_error( ctx, "Expected `,'" );
return FALSE;
}
eat_opt_white( &cur2 );
if (*cur2 != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
cur2++;
decl.Declaration.Array = 1;
decl.Array.ArrayID = arrayid;
ctx->cur = cur = cur2;
}
}
if (*cur == ',' && !is_vs_input) {
uint i, j;
cur++;
eat_opt_white( &cur );
if (file == TGSI_FILE_RESOURCE) {
for (i = 0; i < TGSI_TEXTURE_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) {
decl.Resource.Resource = i;
break;
}
}
if (i == TGSI_TEXTURE_COUNT) {
report_error(ctx, "Expected texture target");
return FALSE;
}
cur2 = cur;
eat_opt_white(&cur2);
while (*cur2 == ',') {
cur2++;
eat_opt_white(&cur2);
if (str_match_nocase_whole(&cur2, "RAW")) {
decl.Resource.Raw = 1;
} else if (str_match_nocase_whole(&cur2, "WR")) {
decl.Resource.Writable = 1;
} else {
break;
}
cur = cur2;
eat_opt_white(&cur2);
}
ctx->cur = cur;
} else if (file == TGSI_FILE_SAMPLER_VIEW) {
for (i = 0; i < TGSI_TEXTURE_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) {
decl.SamplerView.Resource = i;
break;
}
}
if (i == TGSI_TEXTURE_COUNT) {
report_error(ctx, "Expected texture target");
return FALSE;
}
eat_opt_white( &cur );
if (*cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
++cur;
eat_opt_white( &cur );
for (j = 0; j < 4; ++j) {
for (i = 0; i < TGSI_RETURN_TYPE_COUNT; ++i) {
if (str_match_nocase_whole(&cur, tgsi_return_type_names[i])) {
switch (j) {
case 0:
decl.SamplerView.ReturnTypeX = i;
break;
case 1:
decl.SamplerView.ReturnTypeY = i;
break;
case 2:
decl.SamplerView.ReturnTypeZ = i;
break;
case 3:
decl.SamplerView.ReturnTypeW = i;
break;
default:
assert(0);
}
break;
}
}
if (i == TGSI_RETURN_TYPE_COUNT) {
if (j == 0 || j > 2) {
report_error(ctx, "Expected type name");
return FALSE;
}
break;
} else {
cur2 = cur;
eat_opt_white( &cur2 );
if (*cur2 == ',') {
cur2++;
eat_opt_white( &cur2 );
cur = cur2;
continue;
} else
break;
}
}
if (j < 4) {
decl.SamplerView.ReturnTypeY =
decl.SamplerView.ReturnTypeZ =
decl.SamplerView.ReturnTypeW =
decl.SamplerView.ReturnTypeX;
}
ctx->cur = cur;
} else {
if (str_match_nocase_whole(&cur, "LOCAL")) {
decl.Declaration.Local = 1;
ctx->cur = cur;
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',') {
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_SEMANTIC_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_semantic_names[i])) {
uint index;
cur2 = cur;
eat_opt_white( &cur2 );
if (*cur2 == '[') {
cur2++;
eat_opt_white( &cur2 );
if (!parse_uint( &cur2, &index )) {
report_error( ctx, "Expected literal integer" );
return FALSE;
}
eat_opt_white( &cur2 );
if (*cur2 != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
cur2++;
decl.Semantic.Index = index;
cur = cur2;
}
decl.Declaration.Semantic = 1;
decl.Semantic.Name = i;
ctx->cur = cur;
break;
}
}
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',' && !is_vs_input) {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_INTERPOLATE_COUNT; i++) {
if (str_match_nocase_whole( &cur, tgsi_interpolate_names[i] )) {
decl.Declaration.Interpolate = 1;
decl.Interp.Interpolate = i;
ctx->cur = cur;
break;
}
}
if (i == TGSI_INTERPOLATE_COUNT) {
report_error( ctx, "Expected semantic or interpolate attribute" );
return FALSE;
}
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',' && !is_vs_input) {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_INTERPOLATE_LOC_COUNT; i++) {
if (str_match_nocase_whole( &cur, tgsi_interpolate_locations[i] )) {
decl.Interp.Location = i;
ctx->cur = cur;
break;
}
}
}
advance = tgsi_build_full_declaration(
&decl,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
static boolean parse_immediate( struct translate_ctx *ctx )
{
struct tgsi_full_immediate imm;
uint advance;
int type;
if (*ctx->cur == '[') {
uint uindex;
++ctx->cur;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
if (uindex != ctx->num_immediates) {
report_error( ctx, "Immediates must be sorted" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
}
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
for (type = 0; type < Elements(tgsi_immediate_type_names); ++type) {
if (str_match_nocase_whole(&ctx->cur, tgsi_immediate_type_names[type]))
break;
}
if (type == Elements(tgsi_immediate_type_names)) {
report_error( ctx, "Expected immediate type" );
return FALSE;
}
imm = tgsi_default_full_immediate();
imm.Immediate.NrTokens += 4;
imm.Immediate.DataType = type;
parse_immediate_data(ctx, type, imm.u);
advance = tgsi_build_full_immediate(
&imm,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
ctx->num_immediates++;
return TRUE;
}
static boolean
parse_primitive( const char **pcur, uint *primitive )
{
uint i;
for (i = 0; i < PIPE_PRIM_MAX; i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_primitive_names[i])) {
*primitive = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_fs_coord_origin( const char **pcur, uint *fs_coord_origin )
{
uint i;
for (i = 0; i < Elements(tgsi_fs_coord_origin_names); i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_fs_coord_origin_names[i])) {
*fs_coord_origin = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_fs_coord_pixel_center( const char **pcur, uint *fs_coord_pixel_center )
{
uint i;
for (i = 0; i < Elements(tgsi_fs_coord_pixel_center_names); i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_fs_coord_pixel_center_names[i])) {
*fs_coord_pixel_center = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean parse_property( struct translate_ctx *ctx )
{
struct tgsi_full_property prop;
uint property_name;
uint values[8];
uint advance;
char id[64];
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
report_error( ctx, "Syntax error" );
return FALSE;
}
if (!parse_identifier( &ctx->cur, id, sizeof(id) )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
break;
}
}
|
CVE-2017-6209
|
Stack-based buffer overflow in the parse_identifier function in tgsi_text.c in the TGSI auxiliary module in the Gallium driver in virglrenderer before 0.6.0 allows local guest OS users to cause a denial of service (out-of-bounds array access and QEMU process crash) via vectors related to parsing properties.
|
[
"CWE-119"
] |
[
{
"line_no": 7,
"text": " while (is_alpha_underscore( cur ) || is_digit( cur ))",
"char_start": null,
"char_end": null
},
{
"line_no": 1411,
"text": " if (!parse_identifier( &ctx->cur, id )) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 2,
"text": "static boolean parse_identifier( const char **pcur, char *ret, size_t len )",
"char_start": null,
"char_end": null
},
{
"line_no": 8,
"text": " while (is_alpha_underscore( cur ) || is_digit( cur )) {",
"char_start": null,
"char_end": null
},
{
"line_no": 9,
"text": " if (i == len - 1)",
"char_start": null,
"char_end": null
},
{
"line_no": 10,
"text": " return FALSE;",
"char_start": null,
"char_end": null
},
{
"line_no": 12,
"text": " }",
"char_start": null,
"char_end": null
},
{
"line_no": 1415,
"text": " if (!parse_identifier( &ctx->cur, id, sizeof(id) )) {",
"char_start": null,
"char_end": null
}
] | 241
|
primevul
|
primevul_virglrenderer_114688c526fe45f341d75ccd1d85473c3b08f7a7
|
114688c526fe45f341d75ccd1d85473c3b08f7a7
|
virglrenderer
|
https://gitlab.freedesktop.org/virgl/virglrenderer
|
int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
|
int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
if (num_elements > PIPE_MAX_ATTRIBS)
return EINVAL;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
|
CVE-2017-5994
|
Heap-based buffer overflow in the vrend_create_vertex_elements_state function in vrend_renderer.c in virglrenderer before 0.6.0 allows local guest OS users to cause a denial of service (out-of-bounds array access and crash) via the num_elements parameter.
|
[
"CWE-119"
] |
[] |
[
{
"line_no": 15,
"text": " if (num_elements > PIPE_MAX_ATTRIBS)",
"char_start": null,
"char_end": null
},
{
"line_no": 16,
"text": " return EINVAL;",
"char_start": null,
"char_end": null
},
{
"line_no": 17,
"text": "",
"char_start": null,
"char_end": null
}
] | 242
|
primevul
|
primevul_virglrenderer_a5ac49940c40ae415eac0cf912eac7070b4ba95d
|
a5ac49940c40ae415eac0cf912eac7070b4ba95d
|
virglrenderer
|
https://gitlab.freedesktop.org/virgl/virglrenderer
|
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length)
{
struct pipe_vertex_element *ve = NULL;
int num_elements;
int i;
int ret;
if (length < 1)
return EINVAL;
if ((length - 1) % 4)
return EINVAL;
num_elements = (length - 1) / 4;
if (num_elements) {
ve = calloc(num_elements, sizeof(struct pipe_vertex_element));
if (!ve)
return ENOMEM;
for (i = 0; i < num_elements; i++) {
ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i));
ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i));
ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i));
ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i));
}
}
return ret;
}
|
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length)
{
struct pipe_vertex_element *ve = NULL;
int num_elements;
int i;
int ret;
if (length < 1)
return EINVAL;
if ((length - 1) % 4)
return EINVAL;
num_elements = (length - 1) / 4;
if (num_elements) {
ve = calloc(num_elements, sizeof(struct pipe_vertex_element));
if (!ve)
return ENOMEM;
for (i = 0; i < num_elements; i++) {
ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i));
ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i));
ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i));
if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS)
return EINVAL;
ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i));
}
}
return ret;
}
|
CVE-2017-5956
|
The vrend_draw_vbo function in virglrenderer before 0.6.0 allows local guest OS users to cause a denial of service (out-of-bounds array access and QEMU process crash) via vectors involving vertext_buffer_index.
|
[
"CWE-125"
] |
[] |
[
{
"line_no": 26,
"text": "",
"char_start": null,
"char_end": null
},
{
"line_no": 27,
"text": " if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS)",
"char_start": null,
"char_end": null
},
{
"line_no": 28,
"text": " return EINVAL;",
"char_start": null,
"char_end": null
},
{
"line_no": 29,
"text": "",
"char_start": null,
"char_end": null
}
] | 243
|
primevul
|
primevul_infradead_14cae65318d3ef1f7d449e463b72b6934e82f1c2
|
14cae65318d3ef1f7d449e463b72b6934e82f1c2
|
infradead
|
http://git.infradead.org/?p=mtd-2.6
|
static void set_banner(struct openconnect_info *vpninfo)
{
char *banner, *q;
const char *p;
if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) {
unsetenv("CISCO_BANNER");
return;
}
p = vpninfo->banner;
q = banner;
while (*p) {
if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
isxdigit((int)(unsigned char)p[2])) {
*(q++) = unhex(p + 1);
p += 3;
} else
*(q++) = *(p++);
}
*q = 0;
setenv("CISCO_BANNER", banner, 1);
free(banner);
}
|
static void set_banner(struct openconnect_info *vpninfo)
{
char *banner, *q;
const char *p;
if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)+1))) {
unsetenv("CISCO_BANNER");
return;
}
p = vpninfo->banner;
q = banner;
while (*p) {
if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
isxdigit((int)(unsigned char)p[2])) {
*(q++) = unhex(p + 1);
p += 3;
} else
*(q++) = *(p++);
}
*q = 0;
setenv("CISCO_BANNER", banner, 1);
free(banner);
}
|
CVE-2012-3291
|
Heap-based buffer overflow in OpenConnect 3.18 allows remote servers to cause a denial of service via a crafted greeting banner.
|
[
"CWE-119"
] |
[
{
"line_no": 6,
"text": " if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) {",
"char_start": null,
"char_end": null
}
] |
[
{
"line_no": 6,
"text": " if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)+1))) {",
"char_start": null,
"char_end": null
}
] | 246
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.