is_vulnerable
bool
2 classes
func
stringlengths
28
484k
cwe
sequencelengths
1
2
project
stringclasses
592 values
commit_id
stringlengths
7
44
hash
stringlengths
34
39
big_vul_idx
int64
4.09k
189k
idx
int64
0
522k
cwe_description
stringclasses
81 values
false
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; }
[ "CWE-310" ]
openssl
ca989269a2876bae79393bd54c3e72d49975fc75
255087747659226932756944884868284698117
177,739
0
This weakness pertains to the use of cryptographic functions that are weak, misconfigured, or outdated, which undermines the intended protection of encrypted data and communications.
true
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; }
[ "CWE-310" ]
openssl
ca989269a2876bae79393bd54c3e72d49975fc75
185448168336389579295943711163093638128
177,739
157,856
This weakness pertains to the use of cryptographic functions that are weak, misconfigured, or outdated, which undermines the intended protection of encrypted data and communications.
false
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; }
[ "CWE-119" ]
savannah
190cef6eed37d0e73a73c1e205eb31d45ab60a3c
266005388725654386397960628110885023158
177,741
1
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
savannah
190cef6eed37d0e73a73c1e205eb31d45ab60a3c
217937088037221829579003352102231694649
177,741
157,857
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-119" ]
savannah
e82ef4545e9e98cbcb032f55d7c750b81e3a0450
162619476999663411812822607346255778028
177,742
2
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
savannah
e82ef4545e9e98cbcb032f55d7c750b81e3a0450
282098968981021847575763555214602715866
177,742
157,858
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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 ([email protected]) 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 */ }
[ "CWE-200" ]
savannah
075d7556964f5a871a73c22ac4b69f5361295099
114753069609161113628525870463495041364
177,746
3
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
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 ([email protected]) 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 */ }
[ "CWE-200" ]
savannah
075d7556964f5a871a73c22ac4b69f5361295099
230484519226133503077096905290707768008
177,746
157,859
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
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 }
[ "CWE-416" ]
ghostscript
f597300439e62f5e921f0d7b1e880b5c1a1f1607
73361849657881456808355395187124534685
177,749
6
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory belongs to the code that operates on the new pointer.
true
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 }
[ "CWE-416" ]
ghostscript
f597300439e62f5e921f0d7b1e880b5c1a1f1607
124485393887214475174443050553758560429
177,749
157,862
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory belongs to the code that operates on the new pointer.
false
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 }
[ "CWE-416" ]
ghostscript
71ceebcf56e682504da22c4035b39a2d451e8ffd
72963719227623516762803191293835350908
177,751
8
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory belongs to the code that operates on the new pointer.
true
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 }
[ "CWE-416" ]
ghostscript
71ceebcf56e682504da22c4035b39a2d451e8ffd
146583299015225488764454157462983427672
177,751
157,863
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory belongs to the code that operates on the new pointer.
false
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); }
[ "CWE-20" ]
ghostscript
b2e7d38e845c7d4922d05e6e41f3a2dc1bc1b14a
327424409628836476675717770567987598130
177,752
9
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
true
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); }
[ "CWE-20" ]
ghostscript
b2e7d38e845c7d4922d05e6e41f3a2dc1bc1b14a
103996721370606474168467973808469707242
177,752
157,864
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
false
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; }
[ "CWE-835" ]
savannah
c15c42ccd1e2377945fd0414eca1a49294bff454
265039722963046446329719176641029797849
177,768
23
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
true
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; }
[ "CWE-835" ]
savannah
c15c42ccd1e2377945fd0414eca1a49294bff454
67919736298016751923724729486340465129
177,768
157,878
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
false
int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr, char *buf, int *len_ptr) { int len, iflags = 0; struct file_list *flist; uchar fnamecmp_type = FNAMECMP_FNAME; int ndx; read_loop: while (1) { ndx = read_ndx(f_in); if (ndx >= 0) break; if (ndx == NDX_DONE) return ndx; if (ndx == NDX_DEL_STATS) { read_del_stats(f_in); if (am_sender && am_server) write_del_stats(f_out); continue; } if (!inc_recurse || am_sender) { int last; if (first_flist) last = first_flist->prev->ndx_start + first_flist->prev->used - 1; else last = -1; rprintf(FERROR, "Invalid file index: %d (%d - %d) [%s]\n", ndx, NDX_DONE, last, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (ndx == NDX_FLIST_EOF) { flist_eof = 1; if (DEBUG_GTE(FLIST, 3)) rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i()); write_int(f_out, NDX_FLIST_EOF); continue; } ndx = NDX_FLIST_OFFSET - ndx; if (ndx < 0 || ndx >= dir_flist->used) { ndx = NDX_FLIST_OFFSET - ndx; rprintf(FERROR, "Invalid dir index: %d (%d - %d) [%s]\n", ndx, NDX_FLIST_OFFSET, NDX_FLIST_OFFSET - dir_flist->used + 1, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (DEBUG_GTE(FLIST, 2)) { rprintf(FINFO, "[%s] receiving flist for dir %d\n", who_am_i(), ndx); } /* Send all the data we read for this flist to the generator. */ start_flist_forward(ndx); flist = recv_file_list(f_in, ndx); flist->parent_ndx = ndx; stop_flist_forward(); } iflags = protocol_version >= 29 ? read_shortint(f_in) : ITEM_TRANSFER | ITEM_MISSING_DATA; /* Support the protocol-29 keep-alive style. */ if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) { if (am_sender) maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH); goto read_loop; } flist = flist_for_ndx(ndx, "read_ndx_and_attrs"); if (flist != cur_flist) { cur_flist = flist; if (am_sender) { file_old_total = cur_flist->used; for (flist = first_flist; flist != cur_flist; flist = flist->next) file_old_total += flist->used; } } if (iflags & ITEM_BASIS_TYPE_FOLLOWS) fnamecmp_type = read_byte(f_in); *type_ptr = fnamecmp_type; if (iflags & ITEM_XNAME_FOLLOWS) { if (iflags & ITEM_XNAME_FOLLOWS) { if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0) exit_cleanup(RERR_PROTOCOL); } else { *buf = '\0'; len = -1; rprintf(FERROR, "received request to transfer non-regular file: %d [%s]\n", ndx, who_am_i()); exit_cleanup(RERR_PROTOCOL); } } *iflag_ptr = iflags; return ndx; }
[ "Other" ]
samba
70aeb5fddd1b2f8e143276f8d5a085db16c593b9
218007185182567162788891557146038450271
177,770
25
Unknown
true
int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr, char *buf, int *len_ptr) { int len, iflags = 0; struct file_list *flist; uchar fnamecmp_type = FNAMECMP_FNAME; int ndx; read_loop: while (1) { ndx = read_ndx(f_in); if (ndx >= 0) break; if (ndx == NDX_DONE) return ndx; if (ndx == NDX_DEL_STATS) { read_del_stats(f_in); if (am_sender && am_server) write_del_stats(f_out); continue; } if (!inc_recurse || am_sender) { int last; if (first_flist) last = first_flist->prev->ndx_start + first_flist->prev->used - 1; else last = -1; rprintf(FERROR, "Invalid file index: %d (%d - %d) [%s]\n", ndx, NDX_DONE, last, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (ndx == NDX_FLIST_EOF) { flist_eof = 1; if (DEBUG_GTE(FLIST, 3)) rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i()); write_int(f_out, NDX_FLIST_EOF); continue; } ndx = NDX_FLIST_OFFSET - ndx; if (ndx < 0 || ndx >= dir_flist->used) { ndx = NDX_FLIST_OFFSET - ndx; rprintf(FERROR, "Invalid dir index: %d (%d - %d) [%s]\n", ndx, NDX_FLIST_OFFSET, NDX_FLIST_OFFSET - dir_flist->used + 1, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (DEBUG_GTE(FLIST, 2)) { rprintf(FINFO, "[%s] receiving flist for dir %d\n", who_am_i(), ndx); } /* Send all the data we read for this flist to the generator. */ start_flist_forward(ndx); flist = recv_file_list(f_in, ndx); flist->parent_ndx = ndx; stop_flist_forward(); } iflags = protocol_version >= 29 ? read_shortint(f_in) : ITEM_TRANSFER | ITEM_MISSING_DATA; /* Support the protocol-29 keep-alive style. */ if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) { if (am_sender) maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH); goto read_loop; } flist = flist_for_ndx(ndx, "read_ndx_and_attrs"); if (flist != cur_flist) { cur_flist = flist; if (am_sender) { file_old_total = cur_flist->used; for (flist = first_flist; flist != cur_flist; flist = flist->next) file_old_total += flist->used; } } if (iflags & ITEM_BASIS_TYPE_FOLLOWS) fnamecmp_type = read_byte(f_in); *type_ptr = fnamecmp_type; if (iflags & ITEM_XNAME_FOLLOWS) { if (iflags & ITEM_XNAME_FOLLOWS) { if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0) exit_cleanup(RERR_PROTOCOL); if (sanitize_paths) { sanitize_path(buf, buf, "", 0, SP_DEFAULT); len = strlen(buf); } } else { *buf = '\0'; len = -1; rprintf(FERROR, "received request to transfer non-regular file: %d [%s]\n", ndx, who_am_i()); exit_cleanup(RERR_PROTOCOL); } } *iflag_ptr = iflags; return ndx; }
[ "Other" ]
samba
70aeb5fddd1b2f8e143276f8d5a085db16c593b9
173509734569313928092432437809749954291
177,770
157,880
Unknown
false
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; }
[ "CWE-835" ]
haproxy
58df5aea0a0c926b2238f65908f5e9f83d1cca25
6381338430754950645676757195002300075
177,771
26
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
true
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; }
[ "CWE-835" ]
haproxy
58df5aea0a0c926b2238f65908f5e9f83d1cca25
89452639221463286839806233233037284865
177,771
157,881
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
false
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(); }
[ "CWE-189" ]
poppler
284a92899602daa4a7f429e61849e794569310b5
304076538021281751998637961089745244390
177,774
27
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
true
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(); }
[ "CWE-189" ]
poppler
284a92899602daa4a7f429e61849e794569310b5
238370966634441304873792337937568791030
177,774
157,883
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
false
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; }
[ "CWE-189" ]
poppler
7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
145223011821522984832787544024029108709
177,775
28
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
true
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; }
[ "CWE-189" ]
poppler
7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
328681969473388669211085267743237662516
177,775
157,884
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
false
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."); } }
[ "CWE-347" ]
shibboleth
b66cceb0e992c351ad5e2c665229ede82f261b16
11538925675754479849567947994472519439
177,795
40
The product does not verify, or incorrectly verifies, the cryptographic signature for data.
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."); } }
[ "CWE-347" ]
shibboleth
b66cceb0e992c351ad5e2c665229ede82f261b16
313820794002673879698519839177687302127
177,795
157,898
The product does not verify, or incorrectly verifies, the cryptographic signature for data.
false
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; }
[ "CWE-119" ]
pengutronix
574ce994016107ad8ab0f845a785f28d7eaa5208
165064796667373419921312233428470052444
177,796
41
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
pengutronix
574ce994016107ad8ab0f845a785f28d7eaa5208
52376305515786293225734978443916270796
177,796
157,899
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-119" ]
pengutronix
84986ca024462058574432b5483f4bf9136c538d
197742048742816713437466148600234690021
177,797
42
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
pengutronix
84986ca024462058574432b5483f4bf9136c538d
206056256559243150120680816426898705118
177,797
157,900
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *dev = gs_currentdevice(igs); os_ptr op = osp; int code = 0; check_write_type(*op, t_device); if (dev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != dev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
[ "Other" ]
ghostscript
661e8d8fb8248c38d67958beda32f3a5876d0c3f
340004772641014275916898545695953737482
177,810
52
Unknown
true
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *odev = NULL, *dev = gs_currentdevice(igs); os_ptr op = osp; int code = dev_proc(dev, dev_spec_op)(dev, gxdso_current_output_device, (void *)&odev, 0); if (code < 0) return code; check_write_type(*op, t_device); if (odev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != odev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
[ "Other" ]
ghostscript
661e8d8fb8248c38d67958beda32f3a5876d0c3f
59315764021980318626003459290825520793
177,810
157,910
Unknown
false
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; } }
[ "CWE-354" ]
samba
c252546ceeb0925eb8a4061315e3ff0a8c55b48b
337655106013087126363639454838638190943
177,812
54
The product does not validate or incorrectly validates the integrity check values or checksums of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
true
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; } }
[ "CWE-354" ]
samba
c252546ceeb0925eb8a4061315e3ff0a8c55b48b
127195280572279640618380038836318413135
177,812
157,912
The product does not validate or incorrectly validates the integrity check values or checksums of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
false
char *auth_server(int f_in, int f_out, int module, const char *host, const char *addr, const char *leader) { char *users = lp_auth_users(module); char challenge[MAX_DIGEST_LEN*2]; char line[BIGPATHBUFLEN]; char **auth_uid_groups = NULL; int auth_uid_groups_cnt = -1; const char *err = NULL; int group_match = -1; char *tok, *pass; char opt_ch = '\0'; /* if no auth list then allow anyone in! */ if (!users || !*users) if (!users || !*users) return ""; gen_challenge(addr, challenge); io_printf(f_out, "%s%s\n", leader, challenge); return NULL; }
[ "CWE-354" ]
samba
9a480deec4d20277d8e20bc55515ef0640ca1e55
98721516615150795159214070101872089036
177,813
55
The product does not validate or incorrectly validates the integrity check values or checksums of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
true
char *auth_server(int f_in, int f_out, int module, const char *host, const char *addr, const char *leader) { char *users = lp_auth_users(module); char challenge[MAX_DIGEST_LEN*2]; char line[BIGPATHBUFLEN]; char **auth_uid_groups = NULL; int auth_uid_groups_cnt = -1; const char *err = NULL; int group_match = -1; char *tok, *pass; char opt_ch = '\0'; /* if no auth list then allow anyone in! */ if (!users || !*users) if (!users || !*users) return ""; if (protocol_version < 21) { /* Don't allow a weak checksum for the password. */ rprintf(FERROR, "ERROR: protocol version is too old!\n"); exit_cleanup(RERR_PROTOCOL); } gen_challenge(addr, challenge); io_printf(f_out, "%s%s\n", leader, challenge); return NULL; }
[ "CWE-354" ]
samba
9a480deec4d20277d8e20bc55515ef0640ca1e55
143115557888664430123988818349954566324
177,813
157,913
The product does not validate or incorrectly validates the integrity check values or checksums of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
false
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; }
[ "CWE-190" ]
busybox
0402cb32df015d9372578e3db27db47b33d5c7b0
238413816495536863232825191293924303166
177,822
62
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
true
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; }
[ "CWE-190" ]
busybox
0402cb32df015d9372578e3db27db47b33d5c7b0
312101605599426186472577359417874735416
177,822
157,918
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
false
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]; }
[ "CWE-119" ]
libxfont
d11ee5886e9d9ec610051a206b135a4cdc1e09a0
314816336443270992925734214319385584087
177,823
63
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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]; }
[ "CWE-119" ]
libxfont
d11ee5886e9d9ec610051a206b135a4cdc1e09a0
176288859918527814344787198280161772156
177,823
157,919
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-119" ]
musl
45ca5d3fcb6f874bf5ba55d0e9651cef68515395
212099417602244187828055587331477277729
177,824
64
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
musl
45ca5d3fcb6f874bf5ba55d0e9651cef68515395
60029525500602919860744776503907800398
177,824
157,920
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-20" ]
poppler
61f79b8447c3ac8ab5a26e79e0c28053ffdccf75
41887122719404523174993334902149265910
177,825
65
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
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) 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; }
[ "CWE-20" ]
poppler
61f79b8447c3ac8ab5a26e79e0c28053ffdccf75
226017378882353720793476700179562068873
177,825
157,921
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
false
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; }
[ "CWE-119" ]
poppler
b8682d868ddf7f741e93b791588af0932893f95c
244634780333143587019078565382798831655
177,826
66
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
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; }
[ "CWE-119" ]
poppler
b8682d868ddf7f741e93b791588af0932893f95c
151037751520527895735005785354898270248
177,826
157,922
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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); }
[ "CWE-125" ]
ghostscript
97096297d409ec6f206298444ba00719607e8ba8
260933823413348392755539962564037161558
177,832
70
The product reads data past the end, or before the beginning, of the intended buffer.
true
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); }
[ "CWE-125" ]
ghostscript
97096297d409ec6f206298444ba00719607e8ba8
258102495955873121265660327401992670615
177,832
157,926
The product reads data past the end, or before the beginning, of the intended buffer.
false
void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type) { RingItem *link; RING_FOREACH(link, &channel->clients) { red_channel_client_pipe_add_empty_msg( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), msg_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
246859488383496619201376958064716490992
177,835
71
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
true
void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type) { RingItem *link, *next; RING_FOREACH_SAFE(link, next, &channel->clients) { red_channel_client_pipe_add_empty_msg( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), msg_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
335972113688640103719320370363622760524
177,835
157,928
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
false
void red_channel_pipes_add_type(RedChannel *channel, int pipe_item_type) { RingItem *link; RING_FOREACH(link, &channel->clients) { red_channel_client_pipe_add_type( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), pipe_item_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
261946911680290370969616922085083966153
177,836
72
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
true
void red_channel_pipes_add_type(RedChannel *channel, int pipe_item_type) { RingItem *link, *next; RING_FOREACH_SAFE(link, next, &channel->clients) { red_channel_client_pipe_add_type( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), pipe_item_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
190053951808043701869694332992364951708
177,836
157,929
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
false
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; }
[ "CWE-264" ]
mindrot
1bf477d3cdf1a864646d59820878783d42357a1d
186655838205464964819117737453872627903
177,838
73
This category addresses vulnerabilities caused by flawed access control mechanisms, where incorrect permission settings allow unauthorized users to access restricted resources.
true
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; }
[ "CWE-264" ]
mindrot
1bf477d3cdf1a864646d59820878783d42357a1d
16527654010321763311742650376565564635
177,838
157,931
This category addresses vulnerabilities caused by flawed access control mechanisms, where incorrect permission settings allow unauthorized users to access restricted resources.
false
_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; }
[ "CWE-200" ]
samba
538d305de91e34a2938f5f219f18bf0e1918763f
7537344539298054773758251251687254208
177,839
74
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
_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; }
[ "CWE-200" ]
samba
538d305de91e34a2938f5f219f18bf0e1918763f
255868036276361989234981047681917157130
177,839
157,932
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
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 */ }
[ "CWE-200" ]
samba
7f51ec8c4ed9ba1f53d722e44fb6fb3cde933b72
165702818458270596859790967970868439168
177,840
75
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
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; } }
[ "CWE-200" ]
samba
7f51ec8c4ed9ba1f53d722e44fb6fb3cde933b72
317106333919448304744541648192653602778
177,840
157,933
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
_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; }
[ "CWE-200" ]
samba
a118d4220ed85749c07fb43c1229d9e2fecbea6b
133076053301010291311483906719742687999
177,841
76
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
_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; }
[ "CWE-200" ]
samba
a118d4220ed85749c07fb43c1229d9e2fecbea6b
36254057942599479296824956404810979025
177,841
157,934
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
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; } } }
[ "CWE-200" ]
samba
f36cb71c330a52106e36028b3029d952257baf15
56521152564463965686656149103554582573
177,845
80
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
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; } } }
[ "CWE-200" ]
samba
f36cb71c330a52106e36028b3029d952257baf15
151391885881791518561509644947335222102
177,845
157,938
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
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); } }
[ "CWE-209" ]
ghostscript
a6807394bd94b708be24758287b606154daaaed9
158176379266765825681809562263566380830
177,854
81
The product generates an error message that includes sensitive information about its environment, users, or associated data.
true
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); } } }
[ "CWE-209" ]
ghostscript
a6807394bd94b708be24758287b606154daaaed9
121685247830698431863866645627437588475
177,854
157,940
The product generates an error message that includes sensitive information about its environment, users, or associated data.
false
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; } }
[ "CWE-264" ]
samba
4278ef25f64d5fdbf432ff1534e275416ec9561e
1187391106808919572589646338804645949
177,855
82
This category addresses vulnerabilities caused by flawed access control mechanisms, where incorrect permission settings allow unauthorized users to access restricted resources.
true
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; } }
[ "CWE-264" ]
samba
4278ef25f64d5fdbf432ff1534e275416ec9561e
205771650439669619349097817231899606612
177,855
157,941
This category addresses vulnerabilities caused by flawed access control mechanisms, where incorrect permission settings allow unauthorized users to access restricted resources.
false
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 (); }
[ "CWE-59" ]
savannah
dce4683cbbe107a95f1f0d45fabc304acfb5d71a
8366090498822481813911553841981995710
177,857
83
The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
true
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 (); }
[ "CWE-59" ]
savannah
dce4683cbbe107a95f1f0d45fabc304acfb5d71a
208309111606883428843432673009365368758
177,857
157,942
The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
false
_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; }
[ "CWE-20" ]
dbus
c3223ba6c401ba81df1305851312a47c485e6cd7
9228036298590962222843680821307727463
177,858
84
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
true
_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; }
[ "CWE-20" ]
dbus
c3223ba6c401ba81df1305851312a47c485e6cd7
171873919518716570145042987364216001209
177,858
157,943
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
false
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; }
[ "CWE-78" ]
ghostscript
79cccf641486a6595c43f1de1cd7ade696020a31
84413200937845432393453109331654543792
177,859
85
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
true
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; }
[ "CWE-78" ]
ghostscript
79cccf641486a6595c43f1de1cd7ade696020a31
212959667910932412736569570385002997093
177,859
157,944
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
false
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); }
[ "CWE-78" ]
ghostscript
5516c614dc33662a2afdc377159f70218e67bde5
243122500252437636802158481572566726525
177,860
86
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
true
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); }
[ "CWE-78" ]
ghostscript
5516c614dc33662a2afdc377159f70218e67bde5
286298531521520139137532598340258135965
177,860
157,945
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
false
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); }
[ "CWE-200" ]
NetworkManager
78ce088843d59d4494965bfc40b30a2e63d065f6
1138568555668242760358654543466979215
177,861
87
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
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); }
[ "CWE-200" ]
NetworkManager
78ce088843d59d4494965bfc40b30a2e63d065f6
136510234881215550072789075769262394565
177,861
157,946
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
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; } }
[ "CWE-125" ]
libxfont
d1e670a4a8704b8708e493ab6155589bcd570608
235016592504912789309291169579431913614
177,865
90
The product reads data past the end, or before the beginning, of the intended buffer.
true
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; } }
[ "CWE-125" ]
libxfont
d1e670a4a8704b8708e493ab6155589bcd570608
335732905628135922039393462052987124214
177,865
157,948
The product reads data past the end, or before the beginning, of the intended buffer.
false
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; }
[ "CWE-388" ]
ghostscript
b575e1ec42cc86f6a58c603f2a88fcc2af699cc8
56777007913799829721432476707011479257
177,866
91
This obsolete category once captured errors related to system feedback management, such as overly detailed error messages that might inadvertently disclose sensitive internal information.
true
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; }
[ "CWE-388" ]
ghostscript
b575e1ec42cc86f6a58c603f2a88fcc2af699cc8
276163117354160345948359399254998318074
177,866
157,949
This obsolete category once captured errors related to system feedback management, such as overly detailed error messages that might inadvertently disclose sensitive internal information.
false
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; }
[ "CWE-416" ]
ghostscript
241d91112771a6104de10b3948c3f350d6690c1d
143975174954705637984220412120331580143
177,867
92
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory belongs to the code that operates on the new pointer.
true
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; }
[ "CWE-416" ]
ghostscript
241d91112771a6104de10b3948c3f350d6690c1d
65559169527903508610670362820860424615
177,867
157,950
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory belongs to the code that operates on the new pointer.
false
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; }
[ "CWE-704" ]
ghostscript
b326a71659b7837d3acde954b18bda1a6f5e9498
204275868331229737175629924419598292681
177,869
93
The product does not correctly convert an object, resource, or structure from one type to a different type.
true
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; }
[ "CWE-704" ]
ghostscript
b326a71659b7837d3acde954b18bda1a6f5e9498
34376628731007990509857302521992081996
177,869
157,951
The product does not correctly convert an object, resource, or structure from one type to a different type.
false
fd_read_body (const char *downloaded_filename, int fd, FILE *out, wgint toread, wgint startpos, wgint *qtyread, wgint *qtywritten, double *elapsed, int flags, FILE *out2) { int ret = 0; #undef max #define max(a,b) ((a) > (b) ? (a) : (b)) int dlbufsize = max (BUFSIZ, 8 * 1024); char *dlbuf = xmalloc (dlbufsize); struct ptimer *timer = NULL; double last_successful_read_tm = 0; /* The progress gauge, set according to the user preferences. */ void *progress = NULL; /* Non-zero if the progress gauge is interactive, i.e. if it can continually update the display. When true, smaller timeout values are used so that the gauge can update the display when data arrives slowly. */ bool progress_interactive = false; bool exact = !!(flags & rb_read_exactly); /* Used only by HTTP/HTTPS chunked transfer encoding. */ bool chunked = flags & rb_chunked_transfer_encoding; wgint skip = 0; /* How much data we've read/written. */ wgint sum_read = 0; wgint sum_written = 0; wgint remaining_chunk_size = 0; #ifdef HAVE_LIBZ /* try to minimize the number of calls to inflate() and write_data() per call to fd_read() */ unsigned int gzbufsize = dlbufsize * 4; char *gzbuf = NULL; z_stream gzstream; if (flags & rb_compressed_gzip) { gzbuf = xmalloc (gzbufsize); if (gzbuf != NULL) { gzstream.zalloc = zalloc; gzstream.zfree = zfree; gzstream.opaque = Z_NULL; gzstream.next_in = Z_NULL; gzstream.avail_in = 0; #define GZIP_DETECT 32 /* gzip format detection */ #define GZIP_WINDOW 15 /* logarithmic window size (default: 15) */ ret = inflateInit2 (&gzstream, GZIP_DETECT | GZIP_WINDOW); if (ret != Z_OK) { xfree (gzbuf); errno = (ret == Z_MEM_ERROR) ? ENOMEM : EINVAL; ret = -1; goto out; } } else { errno = ENOMEM; ret = -1; goto out; } } #endif if (flags & rb_skip_startpos) skip = startpos; if (opt.show_progress) { const char *filename_progress; /* If we're skipping STARTPOS bytes, pass 0 as the INITIAL argument to progress_create because the indicator doesn't (yet) know about "skipping" data. */ wgint start = skip ? 0 : startpos; if (opt.dir_prefix) filename_progress = downloaded_filename + strlen (opt.dir_prefix) + 1; else filename_progress = downloaded_filename; progress = progress_create (filename_progress, start, start + toread); progress_interactive = progress_interactive_p (progress); } if (opt.limit_rate) limit_bandwidth_reset (); /* A timer is needed for tracking progress, for throttling, and for tracking elapsed time. If either of these are requested, start the timer. */ if (progress || opt.limit_rate || elapsed) { timer = ptimer_new (); last_successful_read_tm = 0; } /* Use a smaller buffer for low requested bandwidths. For example, with --limit-rate=2k, it doesn't make sense to slurp in 16K of data and then sleep for 8s. With buffer size equal to the limit, we never have to sleep for more than one second. */ if (opt.limit_rate && opt.limit_rate < dlbufsize) dlbufsize = opt.limit_rate; /* Read from FD while there is data to read. Normally toread==0 means that it is unknown how much data is to arrive. However, if EXACT is set, then toread==0 means what it says: that no data should be read. */ while (!exact || (sum_read < toread)) { int rdsize; double tmout = opt.read_timeout; if (chunked) { if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); char *endl; if (line == NULL) { ret = -1; break; } else if (out2 != NULL) fwrite (line, 1, strlen (line), out2); remaining_chunk_size = strtol (line, &endl, 16); xfree (line); if (remaining_chunk_size == 0) { ret = 0; fwrite (line, 1, strlen (line), out2); xfree (line); } break; } } rdsize = MIN (remaining_chunk_size, dlbufsize); } else rdsize = exact ? MIN (toread - sum_read, dlbufsize) : dlbufsize; if (progress_interactive) { /* For interactive progress gauges, always specify a ~1s timeout, so that the gauge can be updated regularly even when the data arrives very slowly or stalls. */ tmout = 0.95; if (opt.read_timeout) { double waittm; waittm = ptimer_read (timer) - last_successful_read_tm; if (waittm + tmout > opt.read_timeout) { /* Don't let total idle time exceed read timeout. */ tmout = opt.read_timeout - waittm; if (tmout < 0) { /* We've already exceeded the timeout. */ ret = -1, errno = ETIMEDOUT; break; } } } } ret = fd_read (fd, dlbuf, rdsize, tmout); if (progress_interactive && ret < 0 && errno == ETIMEDOUT) ret = 0; /* interactive timeout, handled above */ else if (ret <= 0) break; /* EOF or read error */ if (progress || opt.limit_rate || elapsed) { ptimer_measure (timer); if (ret > 0) last_successful_read_tm = ptimer_read (timer); } if (ret > 0) { int write_res; sum_read += ret; #ifdef HAVE_LIBZ if (gzbuf != NULL) { int err; int towrite; gzstream.avail_in = ret; gzstream.next_in = (unsigned char *) dlbuf; do { gzstream.avail_out = gzbufsize; gzstream.next_out = (unsigned char *) gzbuf; err = inflate (&gzstream, Z_NO_FLUSH); switch (err) { case Z_MEM_ERROR: errno = ENOMEM; ret = -1; goto out; case Z_NEED_DICT: case Z_DATA_ERROR: errno = EINVAL; ret = -1; goto out; case Z_STREAM_END: if (exact && sum_read != toread) { DEBUGP(("zlib stream ended unexpectedly after " "%ld/%ld bytes\n", sum_read, toread)); } } towrite = gzbufsize - gzstream.avail_out; write_res = write_data (out, out2, gzbuf, towrite, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } while (gzstream.avail_out == 0); } else #endif { write_res = write_data (out, out2, dlbuf, ret, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } if (chunked) { remaining_chunk_size -= ret; if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); if (line == NULL) { ret = -1; break; } else { if (out2 != NULL) fwrite (line, 1, strlen (line), out2); xfree (line); } } } } if (opt.limit_rate) limit_bandwidth (ret, timer); if (progress) progress_update (progress, ret, ptimer_read (timer)); #ifdef WINDOWS if (toread > 0 && opt.show_progress) ws_percenttitle (100.0 * (startpos + sum_read) / (startpos + toread)); #endif }
[ "CWE-119" ]
savannah
ba6b44f6745b14dce414761a8e4b35d31b176bba
323589515235597079129994725046166819711
177,873
96
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
fd_read_body (const char *downloaded_filename, int fd, FILE *out, wgint toread, wgint startpos, wgint *qtyread, wgint *qtywritten, double *elapsed, int flags, FILE *out2) { int ret = 0; #undef max #define max(a,b) ((a) > (b) ? (a) : (b)) int dlbufsize = max (BUFSIZ, 8 * 1024); char *dlbuf = xmalloc (dlbufsize); struct ptimer *timer = NULL; double last_successful_read_tm = 0; /* The progress gauge, set according to the user preferences. */ void *progress = NULL; /* Non-zero if the progress gauge is interactive, i.e. if it can continually update the display. When true, smaller timeout values are used so that the gauge can update the display when data arrives slowly. */ bool progress_interactive = false; bool exact = !!(flags & rb_read_exactly); /* Used only by HTTP/HTTPS chunked transfer encoding. */ bool chunked = flags & rb_chunked_transfer_encoding; wgint skip = 0; /* How much data we've read/written. */ wgint sum_read = 0; wgint sum_written = 0; wgint remaining_chunk_size = 0; #ifdef HAVE_LIBZ /* try to minimize the number of calls to inflate() and write_data() per call to fd_read() */ unsigned int gzbufsize = dlbufsize * 4; char *gzbuf = NULL; z_stream gzstream; if (flags & rb_compressed_gzip) { gzbuf = xmalloc (gzbufsize); if (gzbuf != NULL) { gzstream.zalloc = zalloc; gzstream.zfree = zfree; gzstream.opaque = Z_NULL; gzstream.next_in = Z_NULL; gzstream.avail_in = 0; #define GZIP_DETECT 32 /* gzip format detection */ #define GZIP_WINDOW 15 /* logarithmic window size (default: 15) */ ret = inflateInit2 (&gzstream, GZIP_DETECT | GZIP_WINDOW); if (ret != Z_OK) { xfree (gzbuf); errno = (ret == Z_MEM_ERROR) ? ENOMEM : EINVAL; ret = -1; goto out; } } else { errno = ENOMEM; ret = -1; goto out; } } #endif if (flags & rb_skip_startpos) skip = startpos; if (opt.show_progress) { const char *filename_progress; /* If we're skipping STARTPOS bytes, pass 0 as the INITIAL argument to progress_create because the indicator doesn't (yet) know about "skipping" data. */ wgint start = skip ? 0 : startpos; if (opt.dir_prefix) filename_progress = downloaded_filename + strlen (opt.dir_prefix) + 1; else filename_progress = downloaded_filename; progress = progress_create (filename_progress, start, start + toread); progress_interactive = progress_interactive_p (progress); } if (opt.limit_rate) limit_bandwidth_reset (); /* A timer is needed for tracking progress, for throttling, and for tracking elapsed time. If either of these are requested, start the timer. */ if (progress || opt.limit_rate || elapsed) { timer = ptimer_new (); last_successful_read_tm = 0; } /* Use a smaller buffer for low requested bandwidths. For example, with --limit-rate=2k, it doesn't make sense to slurp in 16K of data and then sleep for 8s. With buffer size equal to the limit, we never have to sleep for more than one second. */ if (opt.limit_rate && opt.limit_rate < dlbufsize) dlbufsize = opt.limit_rate; /* Read from FD while there is data to read. Normally toread==0 means that it is unknown how much data is to arrive. However, if EXACT is set, then toread==0 means what it says: that no data should be read. */ while (!exact || (sum_read < toread)) { int rdsize; double tmout = opt.read_timeout; if (chunked) { if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); char *endl; if (line == NULL) { ret = -1; break; } else if (out2 != NULL) fwrite (line, 1, strlen (line), out2); remaining_chunk_size = strtol (line, &endl, 16); xfree (line); if (remaining_chunk_size < 0) { ret = -1; break; } if (remaining_chunk_size == 0) { ret = 0; fwrite (line, 1, strlen (line), out2); xfree (line); } break; } } rdsize = MIN (remaining_chunk_size, dlbufsize); } else rdsize = exact ? MIN (toread - sum_read, dlbufsize) : dlbufsize; if (progress_interactive) { /* For interactive progress gauges, always specify a ~1s timeout, so that the gauge can be updated regularly even when the data arrives very slowly or stalls. */ tmout = 0.95; if (opt.read_timeout) { double waittm; waittm = ptimer_read (timer) - last_successful_read_tm; if (waittm + tmout > opt.read_timeout) { /* Don't let total idle time exceed read timeout. */ tmout = opt.read_timeout - waittm; if (tmout < 0) { /* We've already exceeded the timeout. */ ret = -1, errno = ETIMEDOUT; break; } } } } ret = fd_read (fd, dlbuf, rdsize, tmout); if (progress_interactive && ret < 0 && errno == ETIMEDOUT) ret = 0; /* interactive timeout, handled above */ else if (ret <= 0) break; /* EOF or read error */ if (progress || opt.limit_rate || elapsed) { ptimer_measure (timer); if (ret > 0) last_successful_read_tm = ptimer_read (timer); } if (ret > 0) { int write_res; sum_read += ret; #ifdef HAVE_LIBZ if (gzbuf != NULL) { int err; int towrite; gzstream.avail_in = ret; gzstream.next_in = (unsigned char *) dlbuf; do { gzstream.avail_out = gzbufsize; gzstream.next_out = (unsigned char *) gzbuf; err = inflate (&gzstream, Z_NO_FLUSH); switch (err) { case Z_MEM_ERROR: errno = ENOMEM; ret = -1; goto out; case Z_NEED_DICT: case Z_DATA_ERROR: errno = EINVAL; ret = -1; goto out; case Z_STREAM_END: if (exact && sum_read != toread) { DEBUGP(("zlib stream ended unexpectedly after " "%ld/%ld bytes\n", sum_read, toread)); } } towrite = gzbufsize - gzstream.avail_out; write_res = write_data (out, out2, gzbuf, towrite, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } while (gzstream.avail_out == 0); } else #endif { write_res = write_data (out, out2, dlbuf, ret, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } if (chunked) { remaining_chunk_size -= ret; if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); if (line == NULL) { ret = -1; break; } else { if (out2 != NULL) fwrite (line, 1, strlen (line), out2); xfree (line); } } } } if (opt.limit_rate) limit_bandwidth (ret, timer); if (progress) progress_update (progress, ret, ptimer_read (timer)); #ifdef WINDOWS if (toread > 0 && opt.show_progress) ws_percenttitle (100.0 * (startpos + sum_read) / (startpos + toread)); #endif }
[ "CWE-119" ]
savannah
ba6b44f6745b14dce414761a8e4b35d31b176bba
220093956480677323605982437392462496483
177,873
157,954
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len, gx_io_device *iodev, const char *permitgroup) { long i; ref *permitlist = NULL; /* an empty string (first character == 0) if '\' character is */ /* recognized as a file name separator as on DOS & Windows */ const char *win_sep2 = "\\"; bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1); uint plen = gp_file_name_parents(fname, len); /* we're protecting arbitrary file system accesses, not Postscript device accesses. * Although, note that %pipe% is explicitly checked for and disallowed elsewhere */ if (iodev != iodev_default(imemory)) { return 0; } /* Assuming a reduced file name. */ if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0) return 0; /* if Permissions not found, just allow access */ for (i=0; i<r_size(permitlist); i++) { ref permitstring; const string_match_params win_filename_params = { '*', '?', '\\', true, true /* ignore case & '/' == '\\' */ }; const byte *permstr; uint permlen; int cwd_len = 0; if (array_get(imemory, permitlist, i, &permitstring) < 0 || r_type(&permitstring) != t_string ) break; /* any problem, just fail */ permstr = permitstring.value.bytes; permlen = r_size(&permitstring); /* * Check if any file name is permitted with "*". */ if (permlen == 1 && permstr[0] == '*') return 0; /* success */ /* * If the filename starts with parent references, * the permission element must start with same number of parent references. */ if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen)) continue; cwd_len = gp_file_name_cwds((const char *)permstr, permlen); /* * If the permission starts with "./", absolute paths * are not permitted. */ if (cwd_len > 0 && gp_file_name_is_absolute(fname, len)) continue; /* * If the permission starts with "./", relative paths * with no "./" are allowed as well as with "./". * 'fname' has no "./" because it is reduced. */ if (string_match( (const unsigned char*) fname, len, permstr + cwd_len, permlen - cwd_len, use_windows_pathsep ? &win_filename_params : NULL)) return 0; /* success */ } /* not found */ return gs_error_invalidfileaccess; }
[ "Other" ]
ghostscript
0d3901189f245232f0161addf215d7268c4d05a3
69859639183316940625463158376184599878
177,880
101
Unknown
true
check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len, gx_io_device *iodev, const char *permitgroup) { long i; ref *permitlist = NULL; /* an empty string (first character == 0) if '\' character is */ /* recognized as a file name separator as on DOS & Windows */ const char *win_sep2 = "\\"; bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1); uint plen = gp_file_name_parents(fname, len); /* we're protecting arbitrary file system accesses, not Postscript device accesses. * Although, note that %pipe% is explicitly checked for and disallowed elsewhere */ if (iodev && iodev != iodev_default(imemory)) { return 0; } /* Assuming a reduced file name. */ if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0) return 0; /* if Permissions not found, just allow access */ for (i=0; i<r_size(permitlist); i++) { ref permitstring; const string_match_params win_filename_params = { '*', '?', '\\', true, true /* ignore case & '/' == '\\' */ }; const byte *permstr; uint permlen; int cwd_len = 0; if (array_get(imemory, permitlist, i, &permitstring) < 0 || r_type(&permitstring) != t_string ) break; /* any problem, just fail */ permstr = permitstring.value.bytes; permlen = r_size(&permitstring); /* * Check if any file name is permitted with "*". */ if (permlen == 1 && permstr[0] == '*') return 0; /* success */ /* * If the filename starts with parent references, * the permission element must start with same number of parent references. */ if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen)) continue; cwd_len = gp_file_name_cwds((const char *)permstr, permlen); /* * If the permission starts with "./", absolute paths * are not permitted. */ if (cwd_len > 0 && gp_file_name_is_absolute(fname, len)) continue; /* * If the permission starts with "./", relative paths * with no "./" are allowed as well as with "./". * 'fname' has no "./" because it is reduced. */ if (string_match( (const unsigned char*) fname, len, permstr + cwd_len, permlen - cwd_len, use_windows_pathsep ? &win_filename_params : NULL)) return 0; /* success */ } /* not found */ return gs_error_invalidfileaccess; }
[ "Other" ]
ghostscript
0d3901189f245232f0161addf215d7268c4d05a3
99054520864994696214682568839021118743
177,880
157,959
Unknown
false
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; }
[ "CWE-476" ]
drm
9f1f1a2dab38d4ce87a13565cf4dc1b73bef3a5f
277136060870051879610700105139465176140
177,881
102
The product dereferences a pointer that it expects to be valid but is NULL.
true
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; }
[ "CWE-476" ]
drm
9f1f1a2dab38d4ce87a13565cf4dc1b73bef3a5f
199051164919133436575414029938699656311
177,881
157,960
The product dereferences a pointer that it expects to be valid but is NULL.
false
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; }
[ "CWE-119" ]
haproxy
7ec765568883b2d4e5a2796adbeb492a22ec9bd4
110551955760274715015247345529003415581
177,886
106
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
haproxy
7ec765568883b2d4e5a2796adbeb492a22ec9bd4
93118898612400237957558909236733687601
177,886
157,964
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter) { u_char buf[OSPF_API_MAX_MSG_SIZE]; struct msg_register_event *emsg; int len; emsg = (struct msg_register_event *) buf; len = sizeof (struct msg_register_event) + filter->num_areas * sizeof (struct in_addr); emsg->filter.typemask = htons (filter->typemask); emsg->filter.origin = filter->origin; emsg->filter.num_areas = filter->num_areas; return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len); }
[ "CWE-119" ]
savannah
3f872fe60463a931c5c766dbf8c36870c0023e88
24569741928780254928487121835647969548
177,888
107
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter) { u_char buf[OSPF_API_MAX_MSG_SIZE]; struct msg_register_event *emsg; int len; emsg = (struct msg_register_event *) buf; len = sizeof (struct msg_register_event) + filter->num_areas * sizeof (struct in_addr); emsg->filter.typemask = htons (filter->typemask); emsg->filter.origin = filter->origin; emsg->filter.num_areas = filter->num_areas; if (len > sizeof (buf)) len = sizeof(buf); /* API broken - missing memcpy to fill data */ return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len); }
[ "CWE-119" ]
savannah
3f872fe60463a931c5c766dbf8c36870c0023e88
145214918048062551547513527429211682293
177,888
157,965
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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); }
[ "CWE-200" ]
openssl
cc598f321fbac9c04da5766243ed55d55948637d
262483489551334338648277862128153636042
177,890
108
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
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); }
[ "CWE-200" ]
openssl
cc598f321fbac9c04da5766243ed55d55948637d
20163778210230944681624599155479176309
177,890
157,966
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
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; }
[ "Other" ]
openssl
d8541d7e9e63bf5f343af24644046c8d96498c17
288105964239389158612588380167749525157
177,891
109
Unknown
true
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; }
[ "Other" ]
openssl
d8541d7e9e63bf5f343af24644046c8d96498c17
338718658446842935098442076237481568312
177,891
157,967
Unknown
false
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); }
[ "Other" ]
openssl
c394a488942387246653833359a5c94b5832674e
308019867511894862199468289587358810995
177,892
110
Unknown
true
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); }
[ "Other" ]
openssl
c394a488942387246653833359a5c94b5832674e
184183702878896057031381637225428687008
177,892
157,968
Unknown